|
| 1 | +"""Snowflake 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 SnowflakeResult: |
| 10 | + """Wrapper for Snowflake cursor to match DuckDB result API.""" |
| 11 | + |
| 12 | + def __init__(self, cursor): |
| 13 | + """Initialize Snowflake result wrapper. |
| 14 | +
|
| 15 | + Args: |
| 16 | + cursor: Snowflake 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 | + # Fetch all rows and convert to Arrow |
| 34 | + rows = self.cursor.fetchall() |
| 35 | + if not rows: |
| 36 | + # Empty result |
| 37 | + schema = pa.schema([(desc[0], pa.string()) for desc in self._description]) |
| 38 | + return pa.RecordBatchReader.from_batches(schema, []) |
| 39 | + |
| 40 | + # Build Arrow table from rows |
| 41 | + columns = {desc[0]: [row[i] for row in rows] for i, desc in enumerate(self._description)} |
| 42 | + table = pa.table(columns) |
| 43 | + return pa.RecordBatchReader.from_batches(table.schema, table.to_batches()) |
| 44 | + |
| 45 | + @property |
| 46 | + def description(self): |
| 47 | + """Get column descriptions.""" |
| 48 | + return self._description |
| 49 | + |
| 50 | + |
| 51 | +class SnowflakeAdapter(BaseDatabaseAdapter): |
| 52 | + """Snowflake database adapter. |
| 53 | +
|
| 54 | + Example: |
| 55 | + >>> adapter = SnowflakeAdapter( |
| 56 | + ... account="myaccount", |
| 57 | + ... user="myuser", |
| 58 | + ... password="mypass", |
| 59 | + ... database="mydb", |
| 60 | + ... schema="myschema" |
| 61 | + ... ) |
| 62 | + >>> result = adapter.execute("SELECT * FROM table") |
| 63 | + """ |
| 64 | + |
| 65 | + def __init__( |
| 66 | + self, |
| 67 | + account: str | None = None, |
| 68 | + user: str | None = None, |
| 69 | + password: str | None = None, |
| 70 | + database: str | None = None, |
| 71 | + schema: str | None = None, |
| 72 | + warehouse: str | None = None, |
| 73 | + role: str | None = None, |
| 74 | + **kwargs, |
| 75 | + ): |
| 76 | + """Initialize Snowflake adapter. |
| 77 | +
|
| 78 | + Args: |
| 79 | + account: Snowflake account identifier |
| 80 | + user: Username |
| 81 | + password: Password |
| 82 | + database: Database name |
| 83 | + schema: Schema name |
| 84 | + warehouse: Warehouse name |
| 85 | + role: Role name |
| 86 | + **kwargs: Additional arguments passed to snowflake.connector.connect |
| 87 | + """ |
| 88 | + try: |
| 89 | + import snowflake.connector |
| 90 | + except ImportError as e: |
| 91 | + raise ImportError( |
| 92 | + "Snowflake support requires snowflake-connector-python. " |
| 93 | + "Install with: pip install sidemantic[snowflake] or pip install snowflake-connector-python" |
| 94 | + ) from e |
| 95 | + |
| 96 | + # Build connection params |
| 97 | + conn_params = {} |
| 98 | + if account: |
| 99 | + conn_params["account"] = account |
| 100 | + if user: |
| 101 | + conn_params["user"] = user |
| 102 | + if password: |
| 103 | + conn_params["password"] = password |
| 104 | + if database: |
| 105 | + conn_params["database"] = database |
| 106 | + if schema: |
| 107 | + conn_params["schema"] = schema |
| 108 | + if warehouse: |
| 109 | + conn_params["warehouse"] = warehouse |
| 110 | + if role: |
| 111 | + conn_params["role"] = role |
| 112 | + |
| 113 | + # Merge with additional kwargs |
| 114 | + conn_params.update(kwargs) |
| 115 | + |
| 116 | + self.conn = snowflake.connector.connect(**conn_params) |
| 117 | + self.database = database |
| 118 | + self.schema = schema |
| 119 | + |
| 120 | + def execute(self, sql: str) -> SnowflakeResult: |
| 121 | + """Execute SQL query.""" |
| 122 | + cursor = self.conn.cursor() |
| 123 | + cursor.execute(sql) |
| 124 | + return SnowflakeResult(cursor) |
| 125 | + |
| 126 | + def executemany(self, sql: str, params: list) -> SnowflakeResult: |
| 127 | + """Execute SQL with multiple parameter sets.""" |
| 128 | + cursor = self.conn.cursor() |
| 129 | + cursor.executemany(sql, params) |
| 130 | + return SnowflakeResult(cursor) |
| 131 | + |
| 132 | + def fetchone(self, result: SnowflakeResult) -> tuple | None: |
| 133 | + """Fetch one row from result.""" |
| 134 | + return result.fetchone() |
| 135 | + |
| 136 | + def fetch_record_batch(self, result: SnowflakeResult) -> Any: |
| 137 | + """Fetch result as PyArrow RecordBatchReader.""" |
| 138 | + return result.fetch_record_batch() |
| 139 | + |
| 140 | + def get_tables(self) -> list[dict]: |
| 141 | + """List all tables in the database/schema.""" |
| 142 | + if self.schema: |
| 143 | + sql = f""" |
| 144 | + SELECT table_name, table_schema as schema |
| 145 | + FROM information_schema.tables |
| 146 | + WHERE table_schema = '{self.schema}' |
| 147 | + AND table_type = 'BASE TABLE' |
| 148 | + """ |
| 149 | + elif self.database: |
| 150 | + sql = """ |
| 151 | + SELECT table_name, table_schema as schema |
| 152 | + FROM information_schema.tables |
| 153 | + WHERE table_type = 'BASE TABLE' |
| 154 | + """ |
| 155 | + else: |
| 156 | + sql = """ |
| 157 | + SELECT table_name, table_schema as schema |
| 158 | + FROM information_schema.tables |
| 159 | + WHERE table_type = 'BASE TABLE' |
| 160 | + """ |
| 161 | + |
| 162 | + result = self.execute(sql) |
| 163 | + rows = result.fetchall() |
| 164 | + return [{"table_name": row[0], "schema": row[1]} for row in rows] |
| 165 | + |
| 166 | + def get_columns(self, table_name: str, schema: str | None = None) -> list[dict]: |
| 167 | + """Get column information for a table.""" |
| 168 | + schema = schema or self.schema |
| 169 | + schema_filter = f"AND table_schema = '{schema}'" if schema else "" |
| 170 | + |
| 171 | + sql = f""" |
| 172 | + SELECT column_name, data_type |
| 173 | + FROM information_schema.columns |
| 174 | + WHERE table_name = '{table_name}' {schema_filter} |
| 175 | + """ |
| 176 | + result = self.execute(sql) |
| 177 | + rows = result.fetchall() |
| 178 | + return [{"column_name": row[0], "data_type": row[1]} for row in rows] |
| 179 | + |
| 180 | + def close(self) -> None: |
| 181 | + """Close the Snowflake connection.""" |
| 182 | + self.conn.close() |
| 183 | + |
| 184 | + @property |
| 185 | + def dialect(self) -> str: |
| 186 | + """Return SQL dialect.""" |
| 187 | + return "snowflake" |
| 188 | + |
| 189 | + @property |
| 190 | + def raw_connection(self) -> Any: |
| 191 | + """Return raw Snowflake connection.""" |
| 192 | + return self.conn |
| 193 | + |
| 194 | + @classmethod |
| 195 | + def from_url(cls, url: str) -> "SnowflakeAdapter": |
| 196 | + """Create adapter from connection URL. |
| 197 | +
|
| 198 | + URL format: snowflake://user:password@account/database/schema?warehouse=wh&role=myrole |
| 199 | + Minimal: snowflake://user:password@account |
| 200 | +
|
| 201 | + Args: |
| 202 | + url: Connection URL |
| 203 | +
|
| 204 | + Returns: |
| 205 | + SnowflakeAdapter instance |
| 206 | + """ |
| 207 | + if not url.startswith("snowflake://"): |
| 208 | + raise ValueError(f"Invalid Snowflake URL: {url}") |
| 209 | + |
| 210 | + parsed = urlparse(url) |
| 211 | + |
| 212 | + # Parse path: /database/schema |
| 213 | + path_parts = [p for p in parsed.path.split("/") if p] |
| 214 | + database = path_parts[0] if len(path_parts) > 0 else None |
| 215 | + schema = path_parts[1] if len(path_parts) > 1 else None |
| 216 | + |
| 217 | + # Parse query parameters |
| 218 | + params = {} |
| 219 | + if parsed.query: |
| 220 | + params = {k: v[0] if len(v) == 1 else v for k, v in parse_qs(parsed.query).items()} |
| 221 | + |
| 222 | + return cls( |
| 223 | + account=parsed.hostname, |
| 224 | + user=unquote(parsed.username) if parsed.username else None, |
| 225 | + password=unquote(parsed.password) if parsed.password else None, |
| 226 | + database=database, |
| 227 | + schema=schema, |
| 228 | + warehouse=params.pop("warehouse", None), |
| 229 | + role=params.pop("role", None), |
| 230 | + **params, |
| 231 | + ) |
0 commit comments