Skip to content

Commit 14ce777

Browse files
authored
Merge pull request #9 from mportdata/codex/add-snowflake-connector
[codex] add snowflake database connector
2 parents ca44812 + 0e7726c commit 14ce777

7 files changed

Lines changed: 111 additions & 69 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ from piglets import DatabaseConnector
8888

8989
database_connector = DatabaseConnector(
9090
database_type="bigquery",
91-
database_name="my_bigquery_dataset",
91+
bq_dataset="my_bigquery_dataset",
9292
)
9393

9494
database = database_connector.get_database_schema()
@@ -112,20 +112,6 @@ database_connector = DatabaseConnector(
112112

113113
### Supported Databases
114114

115-
Arguments passed to the `DatabaseConnector` are used to create a url of the form:
116-
```
117-
dialect+driver://username:password@host:port/database
118-
```
119-
or in the case of `bigquery`
120-
```
121-
bigquery://project_id/dataset
122-
```
123-
and in the case of `snowflake`
124-
```
125-
snowflake://username:password@account/database
126-
```
127-
more intuitive paramater names and optional dependencies will be added shortly for all major cloud datawarehouse and lakehouses.
128-
129115
| Database type | `database_type` value | Install requirement | Notes |
130116
| --- | --- | --- | --- |
131117
| SQLite | `sqlite` | Included by default | Uses SQLAlchemy's built-in SQLite dialect. |
@@ -134,7 +120,7 @@ more intuitive paramater names and optional dependencies will be added shortly f
134120
| Oracle | `oracle` | SQLAlchemy dialect included by default | Requires a compatible Oracle DBAPI driver. |
135121
| Microsoft SQL Server | `mssql` | SQLAlchemy dialect included by default | Requires a compatible SQL Server DBAPI driver. |
136122
| BigQuery | `bigquery` | `piglets[bigquery]` | Uses `GOOGLE_CLOUD_PROJECT_ID` or `gcp_project_id` for the GCP project. |
137-
| Snowflake | `snowflake` | `piglets[snowflake]` | Uses the Snowflake SQLAlchemy dialect and Snowflake Connector for Python. |
123+
| Snowflake | `snowflake` | `piglets[snowflake]` | Uses `SNOWFLAKE_ACCOUNT`, `SNOWFLAKE_USER` and `SNOWFLAKE_PASSWORD` environment variables. |
138124

139125
### Dual-pathway pruning
140126

@@ -153,7 +139,7 @@ logical_plan = logical_planner.plan(
153139

154140
database_connector = DatabaseConnector(
155141
database_type="bigquery",
156-
database_name="stack_overflow",
142+
bq_dataset="stack_overflow",
157143
)
158144
database = database_connector.get_database_schema()
159145

@@ -165,23 +151,4 @@ pruned_database = pruner.dual_pathway_pruning(
165151
)
166152

167153
print(pruned_database.export_as_string())
168-
```
169-
170-
## Current scope
171-
172-
### Database
173-
174-
`DatabaseConnector` currently supports BigQuery. It connects to a database by `database_name` and returns a `Database` object containing `Table` and `Column` objects.
175-
176-
### Planning
177-
178-
The first included primitive is a `LogicalPlanner` that turns a natural-language analytics question into an ordered list of abstract logical steps.
179-
180-
The `LogicalPlanner` has a `plan` method that can generate one plan or sample multiple plans and aggregate them with `num_samples`.
181-
182-
Plan aggregation is available through `LogicalPlans.aggregate()`.
183-
Aggregated plans include a `sample_plans` attribute containing the candidate `LogicalPlan` objects used to produce the final plan.
184-
185-
### Pruning
186-
187-
`Pruner` supports preservation pruning, deletion pruning, and dual-pathway pruning. Preservation pruning returns a `PreservationSet` of useful tables and columns. Deletion pruning returns a `DeletionSet` of irrelevant tables and columns. Dual-pathway pruning combines both into a final pruned `Database`.
154+
```

‎examples/dual-pathway-pruning-open-ai-bigquery-example.ipynb‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373
"source": [
7474
"MODEL_NAME = \"gpt-5.2\"\n",
7575
"DATABASE_TYPE = \"bigquery\"\n",
76-
"DATABASE_NAME = \"stack_overflow\"\n",
76+
"BQ_DATASET = \"stack_overflow\"\n",
7777
"QUESTION = \"\"\"\n",
7878
" Which tags saw the largest increase in average answer score from 2022 to 2023, \n",
7979
" considering only questions with at least 5 answers?\n",
@@ -180,7 +180,7 @@
180180
"\n",
181181
"database_connector = DatabaseConnector(\n",
182182
" database_type=DATABASE_TYPE,\n",
183-
" database_name=DATABASE_NAME,\n",
183+
" bq_dataset=BQ_DATASET,\n",
184184
")\n",
185185
"database = database_connector.get_database_schema()"
186186
]

‎pyproject.toml‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,6 @@ snowflake = [
101101
]
102102
# for use with example jupyter notebooks
103103
examples = [
104-
# "notebook>=7.0",
105-
# "jupyterlab>=4.0",
106104
"ipykernel>=6.0",
107105
]
108106

@@ -116,7 +114,8 @@ dev = [
116114
test = [
117115
"pytest>=8.0",
118116
"langchain-openai>=1.0",
119-
"sqlalchemy-bigquery>=1.0.0"
117+
"sqlalchemy-bigquery>=1.0.0",
118+
"snowflake-sqlalchemy>=1.9.0"
120119
]
121120

122121
[tool.setuptools]

‎src/piglets/database/database_connector.py‎

Lines changed: 76 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -12,37 +12,89 @@ class DatabaseConnector():
1212
def __init__(
1313
self,
1414
database_type: str,
15-
database_name: str,
15+
database: str = None,
1616
username: str = None,
1717
password: str = None,
1818
host: str = None,
1919
port: int = None,
20-
database: str = None,
21-
gcp_project_id: str = None
20+
21+
gcp_project_id: str = None,
22+
bq_dataset: str = None,
23+
24+
snowflake_account: str = None,
25+
snowflake_region: str = None,
26+
snowflake_database: str = None,
27+
snowflake_schema: str = None,
28+
29+
protocol: str = None
2230
):
23-
if database_type == "bigquery":
24-
if not host:
25-
if gcp_project_id:
26-
host = gcp_project_id
27-
else:
28-
load_dotenv()
29-
google_cloud_project_id = os.getenv("GOOGLE_CLOUD_PROJECT_ID", None)
30-
host = google_cloud_project_id
31-
if not host:
32-
raise ValueError("gcp_project_id must be provided for BigQuery databases.")
33-
34-
connection_url = URL.create(
35-
drivername=database_type,
36-
username=username,
37-
password=password,
38-
host=host,
39-
port=port,
40-
database=database_name
41-
)
42-
logger.info(f"Connecting to database with URL: {connection_url}")
31+
if database_type == "snowflake":
32+
from snowflake.sqlalchemy import URL as sf_url
33+
if not snowflake_account:
34+
load_dotenv()
35+
snowflake_account = os.getenv("SNOWFLAKE_ACCOUNT", None)
36+
if not snowflake_account:
37+
raise ValueError("snowflake_account must be provided for Snowflake databases.")
38+
if not snowflake_database:
39+
raise ValueError("snowflake_database must be provided for Snowflake databases.")
40+
if not username:
41+
load_dotenv()
42+
username = os.getenv("SNOWFLAKE_USER", None)
43+
if not username:
44+
raise ValueError("Username must be provided for Snowflake databases, either as an argument or as SNOWFLAKE_USER in environment variables.")
45+
if not password:
46+
load_dotenv()
47+
password = os.getenv("SNOWFLAKE_PASSWORD", None)
48+
if not password:
49+
raise ValueError("Password must be provided for Snowflake databases, either as an argument or as SNOWFLAKE_PASSWORD in environment variables.")
50+
51+
connection_url = sf_url(
52+
account=snowflake_account,
53+
region=snowflake_region or "",
54+
user=username,
55+
password=password,
56+
database=snowflake_database,
57+
schema=snowflake_schema,
58+
port=port or 443,
59+
protocol=protocol or "https",
60+
host=host or f"{snowflake_account}.snowflakecomputing.com"
61+
)
62+
63+
if snowflake_schema:
64+
self.database_name = f"{snowflake_database}.{snowflake_schema}"
65+
else:
66+
self.database_name = snowflake_database
67+
68+
else:
69+
if database_type == "bigquery":
70+
if not host:
71+
if gcp_project_id:
72+
host = gcp_project_id
73+
else:
74+
load_dotenv()
75+
google_cloud_project_id = os.getenv("GOOGLE_CLOUD_PROJECT_ID", None)
76+
host = google_cloud_project_id
77+
if not host:
78+
raise ValueError("gcp_project_id must be provided for BigQuery databases.")
79+
if not database:
80+
database = bq_dataset
81+
if not database:
82+
raise ValueError("bq_dataset must be provided for BigQuery databases.")
83+
84+
connection_url = URL.create(
85+
drivername=database_type,
86+
username=username,
87+
password=password,
88+
host=host,
89+
port=port,
90+
database=database
91+
)
92+
93+
self.database_name = database
94+
95+
logger.info("Connecting to %s database %s", database_type, self.database_name)
4396
self.engine = create_engine(connection_url)
4497
self.inspector = inspect(self.engine)
45-
self.database_name = database_name
4698

4799
def get_database_schema(self) -> Database:
48100
"""Returns the schema of the database."""

‎tests/conftest.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,6 @@ def logical_planner(model_name) -> LogicalPlanner:
5050
def bigquery_connector():
5151
database_connector = DatabaseConnector(
5252
database_type="bigquery",
53-
database_name="stack_overflow",
53+
bq_dataset="stack_overflow",
5454
)
5555
return database_connector

‎tests/integration/database/test_database_connection_int.py‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,16 @@
1010
def biquery_connector():
1111
database_connector = DatabaseConnector(
1212
database_type="bigquery",
13-
database_name="stack_overflow",
13+
bq_dataset="stack_overflow",
14+
)
15+
return database_connector
16+
17+
@pytest.fixture
18+
def snowflake_connector():
19+
database_connector = DatabaseConnector(
20+
database_type="snowflake",
21+
snowflake_database="SNOWFLAKE_SAMPLE_DATA",
22+
snowflake_schema="TPCH_SF1",
1423
)
1524
return database_connector
1625

@@ -31,4 +40,17 @@ def test_bigquery_connector_export_database_as_string(biquery_connector):
3140
database_schema: Database = biquery_connector.get_database_schema()
3241
database_string = database_schema.export_as_string()
3342
assert isinstance(database_string, str)
34-
assert "Database: stack_overflow" in database_string
43+
assert "Database: stack_overflow" in database_string
44+
45+
def test_snowflake_connector_get_database_schema(snowflake_connector):
46+
database_schema: Database = snowflake_connector.get_database_schema()
47+
48+
assert isinstance(database_schema, Database)
49+
assert database_schema.name == "SNOWFLAKE_SAMPLE_DATA.TPCH_SF1"
50+
assert len(database_schema.tables) > 0
51+
assert all(isinstance(table, Table) for table in database_schema.tables)
52+
for table in database_schema.tables:
53+
assert len(table.columns) > 0
54+
assert all(isinstance(column, Column) for column in table.columns)
55+
assert all(isinstance(column.name, str) for column in table.columns)
56+
assert all(isinstance(column.data_type, str) for column in table.columns)

‎uv.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)