|
| 1 | +"""BigQuery database adapter.""" |
| 2 | + |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from sidemantic.db.base import BaseDatabaseAdapter |
| 6 | + |
| 7 | + |
| 8 | +class BigQueryResult: |
| 9 | + """Wrapper for BigQuery query result to match DuckDB result API.""" |
| 10 | + |
| 11 | + def __init__(self, query_job): |
| 12 | + """Initialize BigQuery result wrapper. |
| 13 | +
|
| 14 | + Args: |
| 15 | + query_job: BigQuery query job result |
| 16 | + """ |
| 17 | + self.query_job = query_job |
| 18 | + self._result = query_job.result() |
| 19 | + self._rows_iter = iter(self._result) |
| 20 | + |
| 21 | + def fetchone(self) -> tuple | None: |
| 22 | + """Fetch one row from the result.""" |
| 23 | + try: |
| 24 | + row = next(self._rows_iter) |
| 25 | + return tuple(row.values()) |
| 26 | + except StopIteration: |
| 27 | + return None |
| 28 | + |
| 29 | + def fetchall(self) -> list[tuple]: |
| 30 | + """Fetch all remaining rows.""" |
| 31 | + return [tuple(row.values()) for row in self._rows_iter] |
| 32 | + |
| 33 | + def fetch_record_batch(self) -> Any: |
| 34 | + """Convert result to PyArrow RecordBatchReader.""" |
| 35 | + import pyarrow as pa |
| 36 | + |
| 37 | + # BigQuery can return Arrow tables directly |
| 38 | + arrow_table = self._result.to_arrow() |
| 39 | + return pa.RecordBatchReader.from_batches(arrow_table.schema, arrow_table.to_batches()) |
| 40 | + |
| 41 | + @property |
| 42 | + def description(self): |
| 43 | + """Get column descriptions.""" |
| 44 | + return [(field.name, field.field_type) for field in self._result.schema] |
| 45 | + |
| 46 | + |
| 47 | +class BigQueryAdapter(BaseDatabaseAdapter): |
| 48 | + """BigQuery database adapter. |
| 49 | +
|
| 50 | + Example: |
| 51 | + >>> adapter = BigQueryAdapter(project_id="my-project", dataset_id="my_dataset") |
| 52 | + >>> result = adapter.execute("SELECT * FROM table") |
| 53 | + """ |
| 54 | + |
| 55 | + def __init__( |
| 56 | + self, |
| 57 | + project_id: str | None = None, |
| 58 | + dataset_id: str | None = None, |
| 59 | + credentials: Any | None = None, |
| 60 | + location: str = "US", |
| 61 | + **kwargs, |
| 62 | + ): |
| 63 | + """Initialize BigQuery adapter. |
| 64 | +
|
| 65 | + Args: |
| 66 | + project_id: GCP project ID (if None, uses default credentials project) |
| 67 | + dataset_id: Default dataset ID (optional) |
| 68 | + credentials: Google Cloud credentials (if None, uses default credentials) |
| 69 | + location: BigQuery location (default: US) |
| 70 | + **kwargs: Additional arguments passed to bigquery.Client |
| 71 | + """ |
| 72 | + try: |
| 73 | + from google.cloud import bigquery |
| 74 | + except ImportError as e: |
| 75 | + raise ImportError( |
| 76 | + "BigQuery support requires google-cloud-bigquery. " |
| 77 | + "Install with: pip install sidemantic[bigquery] or pip install google-cloud-bigquery" |
| 78 | + ) from e |
| 79 | + |
| 80 | + self.client = bigquery.Client(project=project_id, credentials=credentials, location=location, **kwargs) |
| 81 | + self.project_id = project_id or self.client.project |
| 82 | + self.dataset_id = dataset_id |
| 83 | + |
| 84 | + def execute(self, sql: str) -> BigQueryResult: |
| 85 | + """Execute SQL query.""" |
| 86 | + query_job = self.client.query(sql) |
| 87 | + return BigQueryResult(query_job) |
| 88 | + |
| 89 | + def executemany(self, sql: str, params: list) -> Any: |
| 90 | + """Execute SQL with multiple parameter sets. |
| 91 | +
|
| 92 | + Note: BigQuery doesn't have native executemany, so we run queries sequentially. |
| 93 | + """ |
| 94 | + results = [] |
| 95 | + for param_set in params: |
| 96 | + # BigQuery uses @param syntax for parameters |
| 97 | + query_job = self.client.query(sql, job_config={"query_parameters": param_set}) |
| 98 | + results.append(BigQueryResult(query_job)) |
| 99 | + return results |
| 100 | + |
| 101 | + def fetchone(self, result: BigQueryResult) -> tuple | None: |
| 102 | + """Fetch one row from result.""" |
| 103 | + return result.fetchone() |
| 104 | + |
| 105 | + def fetch_record_batch(self, result: BigQueryResult) -> Any: |
| 106 | + """Fetch result as PyArrow RecordBatchReader.""" |
| 107 | + return result.fetch_record_batch() |
| 108 | + |
| 109 | + def get_tables(self) -> list[dict]: |
| 110 | + """List all tables in the dataset.""" |
| 111 | + if not self.dataset_id: |
| 112 | + # If no dataset specified, list tables from all datasets |
| 113 | + tables = [] |
| 114 | + for dataset in self.client.list_datasets(): |
| 115 | + dataset_ref = self.client.dataset(dataset.dataset_id) |
| 116 | + for table in self.client.list_tables(dataset_ref): |
| 117 | + tables.append({"table_name": table.table_id, "schema": dataset.dataset_id}) |
| 118 | + return tables |
| 119 | + |
| 120 | + # List tables in specific dataset |
| 121 | + dataset_ref = self.client.dataset(self.dataset_id) |
| 122 | + tables = [] |
| 123 | + for table in self.client.list_tables(dataset_ref): |
| 124 | + tables.append({"table_name": table.table_id, "schema": self.dataset_id}) |
| 125 | + return tables |
| 126 | + |
| 127 | + def get_columns(self, table_name: str, schema: str | None = None) -> list[dict]: |
| 128 | + """Get column information for a table.""" |
| 129 | + schema = schema or self.dataset_id |
| 130 | + if not schema: |
| 131 | + raise ValueError("schema (dataset_id) required for get_columns") |
| 132 | + |
| 133 | + table_ref = self.client.dataset(schema).table(table_name) |
| 134 | + table = self.client.get_table(table_ref) |
| 135 | + |
| 136 | + columns = [] |
| 137 | + for field in table.schema: |
| 138 | + columns.append( |
| 139 | + { |
| 140 | + "column_name": field.name, |
| 141 | + "data_type": field.field_type, |
| 142 | + "is_nullable": field.mode != "REQUIRED", |
| 143 | + } |
| 144 | + ) |
| 145 | + return columns |
| 146 | + |
| 147 | + def close(self) -> None: |
| 148 | + """Close the BigQuery client.""" |
| 149 | + self.client.close() |
| 150 | + |
| 151 | + @property |
| 152 | + def dialect(self) -> str: |
| 153 | + """Return SQL dialect.""" |
| 154 | + return "bigquery" |
| 155 | + |
| 156 | + @property |
| 157 | + def raw_connection(self) -> Any: |
| 158 | + """Return raw BigQuery client.""" |
| 159 | + return self.client |
| 160 | + |
| 161 | + @classmethod |
| 162 | + def from_url(cls, url: str) -> "BigQueryAdapter": |
| 163 | + """Create adapter from connection URL. |
| 164 | +
|
| 165 | + URL format: bigquery://project_id/dataset_id |
| 166 | + or: bigquery://project_id (no default dataset) |
| 167 | +
|
| 168 | + Args: |
| 169 | + url: Connection URL |
| 170 | +
|
| 171 | + Returns: |
| 172 | + BigQueryAdapter instance |
| 173 | + """ |
| 174 | + if not url.startswith("bigquery://"): |
| 175 | + raise ValueError(f"Invalid BigQuery URL: {url}") |
| 176 | + |
| 177 | + # Parse URL: bigquery://project_id/dataset_id |
| 178 | + path = url[len("bigquery://") :] |
| 179 | + if not path: |
| 180 | + raise ValueError("BigQuery URL must include project_id: bigquery://project_id/dataset_id") |
| 181 | + |
| 182 | + parts = path.split("/") |
| 183 | + project_id = parts[0] |
| 184 | + dataset_id = parts[1] if len(parts) > 1 else None |
| 185 | + |
| 186 | + return cls(project_id=project_id, dataset_id=dataset_id) |
0 commit comments