|
| 1 | +"""ClickHouse database adapter.""" |
| 2 | + |
| 3 | +from typing import Any |
| 4 | +from urllib.parse import parse_qs, unquote, urlparse |
| 5 | + |
| 6 | +from sidemantic.db.base import BaseDatabaseAdapter |
| 7 | + |
| 8 | + |
| 9 | +class ClickHouseResult: |
| 10 | + """Wrapper for ClickHouse query result to match DuckDB result API.""" |
| 11 | + |
| 12 | + def __init__(self, result): |
| 13 | + """Initialize ClickHouse result wrapper. |
| 14 | +
|
| 15 | + Args: |
| 16 | + result: ClickHouse query result from clickhouse-connect |
| 17 | + """ |
| 18 | + self._result = result |
| 19 | + self._row_index = 0 |
| 20 | + |
| 21 | + def fetchone(self) -> tuple | None: |
| 22 | + """Fetch one row from the result.""" |
| 23 | + if self._row_index >= self._result.row_count: |
| 24 | + return None |
| 25 | + row = self._result.result_rows[self._row_index] |
| 26 | + self._row_index += 1 |
| 27 | + return row |
| 28 | + |
| 29 | + def fetchall(self) -> list[tuple]: |
| 30 | + """Fetch all remaining rows.""" |
| 31 | + remaining = self._result.result_rows[self._row_index :] |
| 32 | + self._row_index = self._result.row_count |
| 33 | + return remaining |
| 34 | + |
| 35 | + def fetch_record_batch(self) -> Any: |
| 36 | + """Convert result to PyArrow RecordBatchReader.""" |
| 37 | + import pyarrow as pa |
| 38 | + |
| 39 | + # Convert ClickHouse result to Arrow |
| 40 | + rows = self._result.result_rows |
| 41 | + if not rows: |
| 42 | + # Empty result |
| 43 | + schema = pa.schema([(name, pa.string()) for name in self._result.column_names]) |
| 44 | + return pa.RecordBatchReader.from_batches(schema, []) |
| 45 | + |
| 46 | + # Build Arrow table from rows |
| 47 | + columns = {name: [row[i] for row in rows] for i, name in enumerate(self._result.column_names)} |
| 48 | + table = pa.table(columns) |
| 49 | + return pa.RecordBatchReader.from_batches(table.schema, table.to_batches()) |
| 50 | + |
| 51 | + @property |
| 52 | + def description(self): |
| 53 | + """Get column descriptions.""" |
| 54 | + return [(name, None) for name in self._result.column_names] |
| 55 | + |
| 56 | + |
| 57 | +class ClickHouseAdapter(BaseDatabaseAdapter): |
| 58 | + """ClickHouse database adapter. |
| 59 | +
|
| 60 | + Example: |
| 61 | + >>> adapter = ClickHouseAdapter( |
| 62 | + ... host="localhost", |
| 63 | + ... port=8123, |
| 64 | + ... database="default", |
| 65 | + ... user="default", |
| 66 | + ... password="" |
| 67 | + ... ) |
| 68 | + >>> result = adapter.execute("SELECT * FROM table") |
| 69 | + """ |
| 70 | + |
| 71 | + def __init__( |
| 72 | + self, |
| 73 | + host: str = "localhost", |
| 74 | + port: int = 8123, |
| 75 | + database: str = "default", |
| 76 | + user: str | None = None, |
| 77 | + password: str | None = None, |
| 78 | + secure: bool = False, |
| 79 | + **kwargs, |
| 80 | + ): |
| 81 | + """Initialize ClickHouse adapter. |
| 82 | +
|
| 83 | + Args: |
| 84 | + host: ClickHouse host |
| 85 | + port: ClickHouse HTTP port (default: 8123) |
| 86 | + database: Database name |
| 87 | + user: Username |
| 88 | + password: Password |
| 89 | + secure: Use HTTPS instead of HTTP |
| 90 | + **kwargs: Additional arguments passed to clickhouse_connect.get_client |
| 91 | + """ |
| 92 | + try: |
| 93 | + import clickhouse_connect |
| 94 | + except ImportError as e: |
| 95 | + raise ImportError( |
| 96 | + "ClickHouse support requires clickhouse-connect. " |
| 97 | + "Install with: pip install sidemantic[clickhouse] or pip install clickhouse-connect" |
| 98 | + ) from e |
| 99 | + |
| 100 | + # Build connection params |
| 101 | + self.client = clickhouse_connect.get_client( |
| 102 | + host=host, |
| 103 | + port=port, |
| 104 | + database=database, |
| 105 | + username=user, |
| 106 | + password=password, |
| 107 | + secure=secure, |
| 108 | + **kwargs, |
| 109 | + ) |
| 110 | + self.database = database |
| 111 | + |
| 112 | + def execute(self, sql: str) -> ClickHouseResult: |
| 113 | + """Execute SQL query.""" |
| 114 | + result = self.client.query(sql) |
| 115 | + return ClickHouseResult(result) |
| 116 | + |
| 117 | + def executemany(self, sql: str, params: list) -> ClickHouseResult: |
| 118 | + """Execute SQL with multiple parameter sets. |
| 119 | +
|
| 120 | + Note: ClickHouse doesn't have native executemany, so we run queries sequentially. |
| 121 | + """ |
| 122 | + results = [] |
| 123 | + for param_set in params: |
| 124 | + result = self.client.query(sql, parameters=param_set) |
| 125 | + results.append(ClickHouseResult(result)) |
| 126 | + # Return last result for compatibility |
| 127 | + return results[-1] if results else ClickHouseResult(self.client.query("SELECT 1")) |
| 128 | + |
| 129 | + def fetchone(self, result: ClickHouseResult) -> tuple | None: |
| 130 | + """Fetch one row from result.""" |
| 131 | + return result.fetchone() |
| 132 | + |
| 133 | + def fetch_record_batch(self, result: ClickHouseResult) -> Any: |
| 134 | + """Fetch result as PyArrow RecordBatchReader.""" |
| 135 | + return result.fetch_record_batch() |
| 136 | + |
| 137 | + def get_tables(self) -> list[dict]: |
| 138 | + """List all tables in the database.""" |
| 139 | + sql = """ |
| 140 | + SELECT name as table_name, database as schema |
| 141 | + FROM system.tables |
| 142 | + WHERE database = %(database)s |
| 143 | + AND engine NOT LIKE '%View%' |
| 144 | + """ |
| 145 | + result = self.client.query(sql, parameters={"database": self.database}) |
| 146 | + return [{"table_name": row[0], "schema": row[1]} for row in result.result_rows] |
| 147 | + |
| 148 | + def get_columns(self, table_name: str, schema: str | None = None) -> list[dict]: |
| 149 | + """Get column information for a table.""" |
| 150 | + schema = schema or self.database |
| 151 | + |
| 152 | + sql = """ |
| 153 | + SELECT name as column_name, type as data_type |
| 154 | + FROM system.columns |
| 155 | + WHERE database = %(schema)s |
| 156 | + AND table = %(table)s |
| 157 | + """ |
| 158 | + result = self.client.query(sql, parameters={"schema": schema, "table": table_name}) |
| 159 | + return [{"column_name": row[0], "data_type": row[1]} for row in result.result_rows] |
| 160 | + |
| 161 | + def close(self) -> None: |
| 162 | + """Close the ClickHouse client.""" |
| 163 | + self.client.close() |
| 164 | + |
| 165 | + @property |
| 166 | + def dialect(self) -> str: |
| 167 | + """Return SQL dialect.""" |
| 168 | + return "clickhouse" |
| 169 | + |
| 170 | + @property |
| 171 | + def raw_connection(self) -> Any: |
| 172 | + """Return raw ClickHouse client.""" |
| 173 | + return self.client |
| 174 | + |
| 175 | + @classmethod |
| 176 | + def from_url(cls, url: str) -> "ClickHouseAdapter": |
| 177 | + """Create adapter from connection URL. |
| 178 | +
|
| 179 | + URL format: clickhouse://user:password@host:port/database |
| 180 | + or: clickhouse://host/database (default user/password) |
| 181 | +
|
| 182 | + Args: |
| 183 | + url: Connection URL |
| 184 | +
|
| 185 | + Returns: |
| 186 | + ClickHouseAdapter instance |
| 187 | + """ |
| 188 | + if not url.startswith("clickhouse://"): |
| 189 | + raise ValueError(f"Invalid ClickHouse URL: {url}") |
| 190 | + |
| 191 | + parsed = urlparse(url) |
| 192 | + |
| 193 | + # Parse path: /database |
| 194 | + database = parsed.path.lstrip("/") if parsed.path else "default" |
| 195 | + |
| 196 | + # Parse query parameters |
| 197 | + params = {} |
| 198 | + if parsed.query: |
| 199 | + params = {k: v[0] if len(v) == 1 else v for k, v in parse_qs(parsed.query).items()} |
| 200 | + |
| 201 | + # Check for secure parameter |
| 202 | + secure = params.pop("secure", "false").lower() in ("true", "1", "yes") |
| 203 | + |
| 204 | + return cls( |
| 205 | + host=parsed.hostname or "localhost", |
| 206 | + port=parsed.port or 8123, |
| 207 | + database=database, |
| 208 | + user=unquote(parsed.username) if parsed.username else "default", |
| 209 | + password=unquote(parsed.password) if parsed.password else "", |
| 210 | + secure=secure, |
| 211 | + **params, |
| 212 | + ) |
0 commit comments