|
| 1 | +"""Spark SQL database adapter using PyHive.""" |
| 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 SparkResult: |
| 10 | + """Wrapper for PyHive cursor to match DuckDB result API.""" |
| 11 | + |
| 12 | + def __init__(self, cursor): |
| 13 | + """Initialize Spark result wrapper. |
| 14 | +
|
| 15 | + Args: |
| 16 | + cursor: PyHive cursor object |
| 17 | + """ |
| 18 | + self.cursor = cursor |
| 19 | + self._description = cursor.description |
| 20 | + |
| 21 | + def fetchone(self) -> tuple | None: |
| 22 | + """Fetch one row from the result.""" |
| 23 | + return self.cursor.fetchone() |
| 24 | + |
| 25 | + def fetchall(self) -> list[tuple]: |
| 26 | + """Fetch all remaining rows.""" |
| 27 | + return self.cursor.fetchall() |
| 28 | + |
| 29 | + def fetch_record_batch(self) -> Any: |
| 30 | + """Convert result to PyArrow RecordBatchReader.""" |
| 31 | + import pyarrow as pa |
| 32 | + |
| 33 | + rows = self.cursor.fetchall() |
| 34 | + if not rows: |
| 35 | + # Empty result |
| 36 | + schema = pa.schema([(desc[0], pa.string()) for desc in self._description]) |
| 37 | + return pa.RecordBatchReader.from_batches(schema, []) |
| 38 | + |
| 39 | + # Build Arrow table from rows |
| 40 | + columns = {desc[0]: [row[i] for row in rows] for i, desc in enumerate(self._description)} |
| 41 | + table = pa.table(columns) |
| 42 | + return pa.RecordBatchReader.from_batches(table.schema, table.to_batches()) |
| 43 | + |
| 44 | + @property |
| 45 | + def description(self): |
| 46 | + """Get column descriptions.""" |
| 47 | + return self._description |
| 48 | + |
| 49 | + |
| 50 | +class SparkAdapter(BaseDatabaseAdapter): |
| 51 | + """Spark SQL database adapter using PyHive for Thrift server connections. |
| 52 | +
|
| 53 | + Example: |
| 54 | + >>> adapter = SparkAdapter( |
| 55 | + ... host="localhost", |
| 56 | + ... port=10000, |
| 57 | + ... database="default" |
| 58 | + ... ) |
| 59 | + >>> result = adapter.execute("SELECT * FROM table") |
| 60 | + """ |
| 61 | + |
| 62 | + def __init__( |
| 63 | + self, |
| 64 | + host: str = "localhost", |
| 65 | + port: int = 10000, |
| 66 | + database: str = "default", |
| 67 | + username: str | None = None, |
| 68 | + **kwargs, |
| 69 | + ): |
| 70 | + """Initialize Spark adapter. |
| 71 | +
|
| 72 | + Args: |
| 73 | + host: Spark Thrift server hostname |
| 74 | + port: Thrift server port (default: 10000) |
| 75 | + database: Database name (default: "default") |
| 76 | + username: Username (optional) |
| 77 | + **kwargs: Additional arguments passed to pyhive.hive.connect |
| 78 | + """ |
| 79 | + try: |
| 80 | + from pyhive import hive |
| 81 | + except ImportError as e: |
| 82 | + raise ImportError( |
| 83 | + "Spark support requires PyHive. " |
| 84 | + "Install with: pip install sidemantic[spark] or pip install 'PyHive[hive]'" |
| 85 | + ) from e |
| 86 | + |
| 87 | + # Build connection params |
| 88 | + conn_params = { |
| 89 | + "host": host, |
| 90 | + "port": port, |
| 91 | + "database": database, |
| 92 | + } |
| 93 | + |
| 94 | + if username: |
| 95 | + conn_params["username"] = username |
| 96 | + |
| 97 | + # Merge with additional kwargs |
| 98 | + conn_params.update(kwargs) |
| 99 | + |
| 100 | + self.conn = hive.connect(**conn_params) |
| 101 | + self.database = database |
| 102 | + |
| 103 | + def execute(self, sql: str) -> SparkResult: |
| 104 | + """Execute SQL query.""" |
| 105 | + cursor = self.conn.cursor() |
| 106 | + cursor.execute(sql) |
| 107 | + return SparkResult(cursor) |
| 108 | + |
| 109 | + def executemany(self, sql: str, params: list) -> SparkResult: |
| 110 | + """Execute SQL with multiple parameter sets.""" |
| 111 | + cursor = self.conn.cursor() |
| 112 | + cursor.executemany(sql, params) |
| 113 | + return SparkResult(cursor) |
| 114 | + |
| 115 | + def fetchone(self, result: SparkResult) -> tuple | None: |
| 116 | + """Fetch one row from result.""" |
| 117 | + return result.fetchone() |
| 118 | + |
| 119 | + def fetch_record_batch(self, result: SparkResult) -> Any: |
| 120 | + """Fetch result as PyArrow RecordBatchReader.""" |
| 121 | + return result.fetch_record_batch() |
| 122 | + |
| 123 | + def get_tables(self) -> list[dict]: |
| 124 | + """List all tables in the database.""" |
| 125 | + sql = f"SHOW TABLES IN {self.database}" |
| 126 | + result = self.execute(sql) |
| 127 | + rows = result.fetchall() |
| 128 | + return [{"table_name": row[1], "schema": row[0]} for row in rows] |
| 129 | + |
| 130 | + def get_columns(self, table_name: str, schema: str | None = None) -> list[dict]: |
| 131 | + """Get column information for a table.""" |
| 132 | + schema = schema or self.database |
| 133 | + table_ref = f"{schema}.{table_name}" if schema else table_name |
| 134 | + |
| 135 | + sql = f"DESCRIBE {table_ref}" |
| 136 | + result = self.execute(sql) |
| 137 | + rows = result.fetchall() |
| 138 | + return [{"column_name": row[0], "data_type": row[1]} for row in rows] |
| 139 | + |
| 140 | + def close(self) -> None: |
| 141 | + """Close the Spark connection.""" |
| 142 | + self.conn.close() |
| 143 | + |
| 144 | + @property |
| 145 | + def dialect(self) -> str: |
| 146 | + """Return SQL dialect.""" |
| 147 | + return "spark" |
| 148 | + |
| 149 | + @property |
| 150 | + def raw_connection(self) -> Any: |
| 151 | + """Return raw PyHive connection.""" |
| 152 | + return self.conn |
| 153 | + |
| 154 | + @classmethod |
| 155 | + def from_url(cls, url: str) -> "SparkAdapter": |
| 156 | + """Create adapter from connection URL. |
| 157 | +
|
| 158 | + URL format: spark://host:port/database |
| 159 | + Example: spark://localhost:10000/default |
| 160 | +
|
| 161 | + Args: |
| 162 | + url: Connection URL |
| 163 | +
|
| 164 | + Returns: |
| 165 | + SparkAdapter instance |
| 166 | + """ |
| 167 | + if not url.startswith("spark://"): |
| 168 | + raise ValueError(f"Invalid Spark URL: {url}") |
| 169 | + |
| 170 | + parsed = urlparse(url) |
| 171 | + |
| 172 | + # Parse hostname and port |
| 173 | + host = parsed.hostname or "localhost" |
| 174 | + port = parsed.port or 10000 |
| 175 | + |
| 176 | + # Parse database from path |
| 177 | + database = parsed.path.lstrip("/") if parsed.path else "default" |
| 178 | + |
| 179 | + # Parse username |
| 180 | + username = unquote(parsed.username) if parsed.username else None |
| 181 | + |
| 182 | + # Parse query parameters |
| 183 | + params = {} |
| 184 | + if parsed.query: |
| 185 | + params = {k: v[0] if len(v) == 1 else v for k, v in parse_qs(parsed.query).items()} |
| 186 | + |
| 187 | + return cls( |
| 188 | + host=host, |
| 189 | + port=port, |
| 190 | + database=database, |
| 191 | + username=username, |
| 192 | + **params, |
| 193 | + ) |
0 commit comments