analytics-query-analyzer 0.2.1__tar.gz → 0.4.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/.github/workflows/publish-testpypi.yml +6 -0
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/PKG-INFO +58 -14
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/README.md +55 -13
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/pyproject.toml +1 -0
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/src/analytics_query_analyzer/analyzer.py +6 -6
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/src/analytics_query_analyzer/column_resolver.py +3 -3
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/src/analytics_query_analyzer/references_analyzer.py +22 -5
- analytics_query_analyzer-0.4.0/src/analytics_query_analyzer/schema_builder.py +189 -0
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/src/analytics_query_analyzer/timespan_analyzer.py +75 -10
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/src/analytics_query_analyzer.egg-info/PKG-INFO +58 -14
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/src/analytics_query_analyzer.egg-info/SOURCES.txt +4 -2
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/src/analytics_query_analyzer.egg-info/requires.txt +3 -0
- analytics_query_analyzer-0.4.0/tests/test_analyze_bigquery.py +247 -0
- analytics_query_analyzer-0.4.0/tests/test_analyze_redshift.py +253 -0
- analytics_query_analyzer-0.4.0/tests/test_analyze_timespan_bigquery.py +905 -0
- analytics_query_analyzer-0.4.0/tests/test_analyze_timespan_redshift.py +576 -0
- analytics_query_analyzer-0.2.1/src/analytics_query_analyzer/schema_builder.py +0 -71
- analytics_query_analyzer-0.2.1/tests/test_analyze.py +0 -142
- analytics_query_analyzer-0.2.1/tests/test_analyze_timespan.py +0 -588
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/.github/workflows/publish-pypi.yml +0 -0
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/.github/workflows/pytest.yml +0 -0
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/.gitignore +0 -0
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/LICENSE +0 -0
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/setup.cfg +0 -0
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/src/analytics_query_analyzer/__init__.py +0 -0
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/src/analytics_query_analyzer.egg-info/dependency_links.txt +0 -0
- {analytics_query_analyzer-0.2.1 → analytics_query_analyzer-0.4.0}/src/analytics_query_analyzer.egg-info/top_level.txt +0 -0
|
@@ -2,6 +2,11 @@ name: Publish to TestPyPI
|
|
|
2
2
|
|
|
3
3
|
on:
|
|
4
4
|
workflow_dispatch:
|
|
5
|
+
inputs:
|
|
6
|
+
ref:
|
|
7
|
+
description: "Git ref to publish (branch or tag)"
|
|
8
|
+
required: true
|
|
9
|
+
default: "main"
|
|
5
10
|
|
|
6
11
|
jobs:
|
|
7
12
|
build-and-publish:
|
|
@@ -14,6 +19,7 @@ jobs:
|
|
|
14
19
|
- name: Checkout
|
|
15
20
|
uses: actions/checkout@v4
|
|
16
21
|
with:
|
|
22
|
+
ref: ${{ inputs.ref }}
|
|
17
23
|
fetch-depth: 0
|
|
18
24
|
|
|
19
25
|
- name: Set up Python
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: analytics-query-analyzer
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Analytics Query Analyzer
|
|
5
5
|
License: MIT
|
|
6
6
|
Classifier: License :: OSI Approved :: MIT License
|
|
@@ -10,12 +10,18 @@ License-File: LICENSE
|
|
|
10
10
|
Requires-Dist: sqlglot>=28
|
|
11
11
|
Provides-Extra: bigquery
|
|
12
12
|
Requires-Dist: google-cloud-bigquery; extra == "bigquery"
|
|
13
|
+
Provides-Extra: redshift
|
|
14
|
+
Requires-Dist: redshift-connector; extra == "redshift"
|
|
13
15
|
Dynamic: license-file
|
|
14
16
|
|
|
15
17
|
# analytics-query-analyzer
|
|
16
18
|
|
|
17
19
|
Analyze analytics SQL to extract referenced tables/columns and time bounds.
|
|
18
20
|
|
|
21
|
+
## Support
|
|
22
|
+
|
|
23
|
+
BigQuery and Redshift are currently supported.
|
|
24
|
+
|
|
19
25
|
## Install
|
|
20
26
|
|
|
21
27
|
Base install:
|
|
@@ -30,13 +36,11 @@ BigQuery extras (only needed for `build_schema`):
|
|
|
30
36
|
pip install analytics-query-analyzer[bigquery]
|
|
31
37
|
```
|
|
32
38
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
BigQuery is currently supported and tested.
|
|
39
|
+
Redshift extras (only needed for `build_schema`):
|
|
36
40
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
41
|
+
```bash
|
|
42
|
+
pip install analytics-query-analyzer[redshift]
|
|
43
|
+
```
|
|
40
44
|
|
|
41
45
|
## Usage
|
|
42
46
|
|
|
@@ -44,6 +48,8 @@ Schemas follow sqlglot conventions, with nested fields represented as nested dic
|
|
|
44
48
|
|
|
45
49
|
Extract table/column references from a query.
|
|
46
50
|
|
|
51
|
+
Schema format follows sqlglot conventions, with nested fields represented as nested dicts.
|
|
52
|
+
|
|
47
53
|
```python
|
|
48
54
|
from analytics_query_analyzer import analyze
|
|
49
55
|
from sqlglot import dialects
|
|
@@ -75,7 +81,26 @@ from
|
|
|
75
81
|
|
|
76
82
|
references = analyze(dialects.BigQuery, sql, schema, "production")
|
|
77
83
|
print(references)
|
|
78
|
-
#
|
|
84
|
+
# [
|
|
85
|
+
# {
|
|
86
|
+
# "database": "production",
|
|
87
|
+
# "schema": "shop",
|
|
88
|
+
# "table": "orders",
|
|
89
|
+
# "column": "id",
|
|
90
|
+
# },
|
|
91
|
+
# {
|
|
92
|
+
# "database": "production",
|
|
93
|
+
# "schema": "shop",
|
|
94
|
+
# "table": "orders",
|
|
95
|
+
# "column": "payment.amount",
|
|
96
|
+
# },
|
|
97
|
+
# {
|
|
98
|
+
# "database": "production",
|
|
99
|
+
# "schema": "shop",
|
|
100
|
+
# "table": "orders",
|
|
101
|
+
# "column": "user_id",
|
|
102
|
+
# },
|
|
103
|
+
# ]
|
|
79
104
|
```
|
|
80
105
|
|
|
81
106
|
### analyze_timespan
|
|
@@ -110,12 +135,16 @@ where
|
|
|
110
135
|
|
|
111
136
|
timespans = analyze_timespan(dialects.BigQuery, sql, schema, "production")
|
|
112
137
|
print(timespans)
|
|
113
|
-
#
|
|
114
|
-
#
|
|
138
|
+
# [
|
|
139
|
+
# {
|
|
140
|
+
# "database": "production",
|
|
141
|
+
# "schema": "shop",
|
|
142
|
+
# "table": "orders",
|
|
143
|
+
# "column": "ordered_at",
|
|
115
144
|
# "lower": "2025-01-01",
|
|
116
|
-
# "upper": "2026-01-01"
|
|
145
|
+
# "upper": "2026-01-01",
|
|
117
146
|
# }
|
|
118
|
-
#
|
|
147
|
+
# ]
|
|
119
148
|
```
|
|
120
149
|
|
|
121
150
|
To make `current_date()` deterministic, pass a provider:
|
|
@@ -132,7 +161,7 @@ timespans = analyze_timespan(
|
|
|
132
161
|
|
|
133
162
|
### build_schema
|
|
134
163
|
|
|
135
|
-
Fetch a schema dictionary from BigQuery.
|
|
164
|
+
Fetch a schema dictionary from BigQuery or Redshift.
|
|
136
165
|
|
|
137
166
|
```python
|
|
138
167
|
from analytics_query_analyzer import build_schema
|
|
@@ -143,7 +172,22 @@ print(schema)
|
|
|
143
172
|
```
|
|
144
173
|
|
|
145
174
|
- Authentication uses Application Default Credentials (ADC).
|
|
146
|
-
- Only BigQuery is supported for `build_schema`.
|
|
147
175
|
- When `table` is omitted, it scans all tables in the dataset.
|
|
148
176
|
- When both `dataset` and `table` are omitted, it scans all datasets in the project.
|
|
149
177
|
- The returned `schema` can be passed directly to `analyze` and `analyze_timespan`.
|
|
178
|
+
|
|
179
|
+
Fetching from Redshift is also supported:
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
from analytics_query_analyzer import build_schema
|
|
183
|
+
from sqlglot import dialects
|
|
184
|
+
|
|
185
|
+
schema = build_schema(dialects.Redshift, "my_database", "public", "orders")
|
|
186
|
+
print(schema)
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
Redshift authentication supports two modes:
|
|
190
|
+
|
|
191
|
+
- Set `REDSHIFT_HOST`, `REDSHIFT_USER`, and `REDSHIFT_PASSWORD` (optional `REDSHIFT_PORT`).
|
|
192
|
+
- Set `REDSHIFT_CLUSTER_IDENTIFIER`, `REDSHIFT_REGION`, and `REDSHIFT_DB_USER` to use IAM (you can also set `REDSHIFT_HOST`/`REDSHIFT_PORT`).
|
|
193
|
+
- Use `AWS_PROFILE` if you want to select a non-default AWS profile.
|
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
Analyze analytics SQL to extract referenced tables/columns and time bounds.
|
|
4
4
|
|
|
5
|
+
## Support
|
|
6
|
+
|
|
7
|
+
BigQuery and Redshift are currently supported.
|
|
8
|
+
|
|
5
9
|
## Install
|
|
6
10
|
|
|
7
11
|
Base install:
|
|
@@ -16,13 +20,11 @@ BigQuery extras (only needed for `build_schema`):
|
|
|
16
20
|
pip install analytics-query-analyzer[bigquery]
|
|
17
21
|
```
|
|
18
22
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
BigQuery is currently supported and tested.
|
|
23
|
+
Redshift extras (only needed for `build_schema`):
|
|
22
24
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
25
|
+
```bash
|
|
26
|
+
pip install analytics-query-analyzer[redshift]
|
|
27
|
+
```
|
|
26
28
|
|
|
27
29
|
## Usage
|
|
28
30
|
|
|
@@ -30,6 +32,8 @@ Schemas follow sqlglot conventions, with nested fields represented as nested dic
|
|
|
30
32
|
|
|
31
33
|
Extract table/column references from a query.
|
|
32
34
|
|
|
35
|
+
Schema format follows sqlglot conventions, with nested fields represented as nested dicts.
|
|
36
|
+
|
|
33
37
|
```python
|
|
34
38
|
from analytics_query_analyzer import analyze
|
|
35
39
|
from sqlglot import dialects
|
|
@@ -61,7 +65,26 @@ from
|
|
|
61
65
|
|
|
62
66
|
references = analyze(dialects.BigQuery, sql, schema, "production")
|
|
63
67
|
print(references)
|
|
64
|
-
#
|
|
68
|
+
# [
|
|
69
|
+
# {
|
|
70
|
+
# "database": "production",
|
|
71
|
+
# "schema": "shop",
|
|
72
|
+
# "table": "orders",
|
|
73
|
+
# "column": "id",
|
|
74
|
+
# },
|
|
75
|
+
# {
|
|
76
|
+
# "database": "production",
|
|
77
|
+
# "schema": "shop",
|
|
78
|
+
# "table": "orders",
|
|
79
|
+
# "column": "payment.amount",
|
|
80
|
+
# },
|
|
81
|
+
# {
|
|
82
|
+
# "database": "production",
|
|
83
|
+
# "schema": "shop",
|
|
84
|
+
# "table": "orders",
|
|
85
|
+
# "column": "user_id",
|
|
86
|
+
# },
|
|
87
|
+
# ]
|
|
65
88
|
```
|
|
66
89
|
|
|
67
90
|
### analyze_timespan
|
|
@@ -96,12 +119,16 @@ where
|
|
|
96
119
|
|
|
97
120
|
timespans = analyze_timespan(dialects.BigQuery, sql, schema, "production")
|
|
98
121
|
print(timespans)
|
|
99
|
-
#
|
|
100
|
-
#
|
|
122
|
+
# [
|
|
123
|
+
# {
|
|
124
|
+
# "database": "production",
|
|
125
|
+
# "schema": "shop",
|
|
126
|
+
# "table": "orders",
|
|
127
|
+
# "column": "ordered_at",
|
|
101
128
|
# "lower": "2025-01-01",
|
|
102
|
-
# "upper": "2026-01-01"
|
|
129
|
+
# "upper": "2026-01-01",
|
|
103
130
|
# }
|
|
104
|
-
#
|
|
131
|
+
# ]
|
|
105
132
|
```
|
|
106
133
|
|
|
107
134
|
To make `current_date()` deterministic, pass a provider:
|
|
@@ -118,7 +145,7 @@ timespans = analyze_timespan(
|
|
|
118
145
|
|
|
119
146
|
### build_schema
|
|
120
147
|
|
|
121
|
-
Fetch a schema dictionary from BigQuery.
|
|
148
|
+
Fetch a schema dictionary from BigQuery or Redshift.
|
|
122
149
|
|
|
123
150
|
```python
|
|
124
151
|
from analytics_query_analyzer import build_schema
|
|
@@ -129,7 +156,22 @@ print(schema)
|
|
|
129
156
|
```
|
|
130
157
|
|
|
131
158
|
- Authentication uses Application Default Credentials (ADC).
|
|
132
|
-
- Only BigQuery is supported for `build_schema`.
|
|
133
159
|
- When `table` is omitted, it scans all tables in the dataset.
|
|
134
160
|
- When both `dataset` and `table` are omitted, it scans all datasets in the project.
|
|
135
161
|
- The returned `schema` can be passed directly to `analyze` and `analyze_timespan`.
|
|
162
|
+
|
|
163
|
+
Fetching from Redshift is also supported:
|
|
164
|
+
|
|
165
|
+
```python
|
|
166
|
+
from analytics_query_analyzer import build_schema
|
|
167
|
+
from sqlglot import dialects
|
|
168
|
+
|
|
169
|
+
schema = build_schema(dialects.Redshift, "my_database", "public", "orders")
|
|
170
|
+
print(schema)
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
Redshift authentication supports two modes:
|
|
174
|
+
|
|
175
|
+
- Set `REDSHIFT_HOST`, `REDSHIFT_USER`, and `REDSHIFT_PASSWORD` (optional `REDSHIFT_PORT`).
|
|
176
|
+
- Set `REDSHIFT_CLUSTER_IDENTIFIER`, `REDSHIFT_REGION`, and `REDSHIFT_DB_USER` to use IAM (you can also set `REDSHIFT_HOST`/`REDSHIFT_PORT`).
|
|
177
|
+
- Use `AWS_PROFILE` if you want to select a non-default AWS profile.
|
|
@@ -16,7 +16,7 @@ def analyze(
|
|
|
16
16
|
dialect: str | type[dialects.Dialect],
|
|
17
17
|
sql: str,
|
|
18
18
|
schema: dict,
|
|
19
|
-
|
|
19
|
+
default_catalog: str,
|
|
20
20
|
):
|
|
21
21
|
dialect = _resolve_dialect(dialect)
|
|
22
22
|
expression = parse_one(sql, read=dialect)
|
|
@@ -24,10 +24,10 @@ def analyze(
|
|
|
24
24
|
qualified = optimizer.qualify.qualify(
|
|
25
25
|
expression,
|
|
26
26
|
schema=schema,
|
|
27
|
-
catalog=
|
|
27
|
+
catalog=default_catalog,
|
|
28
28
|
validate_qualify_columns=False,
|
|
29
29
|
)
|
|
30
|
-
analyzer = ReferencesAnalyzer(schema,
|
|
30
|
+
analyzer = ReferencesAnalyzer(schema, default_catalog)
|
|
31
31
|
return analyzer.analyze(qualified)
|
|
32
32
|
|
|
33
33
|
|
|
@@ -35,7 +35,7 @@ def analyze_timespan(
|
|
|
35
35
|
dialect: str | type[dialects.Dialect],
|
|
36
36
|
sql: str,
|
|
37
37
|
schema: dict,
|
|
38
|
-
|
|
38
|
+
default_catalog: str,
|
|
39
39
|
current_date_provider=None,
|
|
40
40
|
) -> dict:
|
|
41
41
|
dialect = _resolve_dialect(dialect)
|
|
@@ -44,10 +44,10 @@ def analyze_timespan(
|
|
|
44
44
|
qualified = optimizer.qualify.qualify(
|
|
45
45
|
expression,
|
|
46
46
|
schema=schema,
|
|
47
|
-
catalog=
|
|
47
|
+
catalog=default_catalog,
|
|
48
48
|
validate_qualify_columns=False,
|
|
49
49
|
)
|
|
50
|
-
analyzer = TimespanAnalyzer(schema,
|
|
50
|
+
analyzer = TimespanAnalyzer(schema, default_catalog, current_date_provider)
|
|
51
51
|
return analyzer.analyze(qualified)
|
|
52
52
|
|
|
53
53
|
|
|
@@ -5,7 +5,7 @@ from sqlglot.optimizer.scope import Scope
|
|
|
5
5
|
def resolve_column_path(
|
|
6
6
|
column: exp.Column,
|
|
7
7
|
scope,
|
|
8
|
-
|
|
8
|
+
default_catalog: str,
|
|
9
9
|
schema: dict,
|
|
10
10
|
column_extractor,
|
|
11
11
|
) -> tuple[str, str] | None:
|
|
@@ -25,12 +25,12 @@ def resolve_column_path(
|
|
|
25
25
|
if not nested_column:
|
|
26
26
|
return None
|
|
27
27
|
return resolve_column_path(
|
|
28
|
-
nested_column, source,
|
|
28
|
+
nested_column, source, default_catalog, schema, column_extractor
|
|
29
29
|
)
|
|
30
30
|
if not isinstance(source, exp.Table):
|
|
31
31
|
return None
|
|
32
32
|
|
|
33
|
-
project = source.catalog or
|
|
33
|
+
project = source.catalog or default_catalog
|
|
34
34
|
dataset = source.db
|
|
35
35
|
table = source.name
|
|
36
36
|
if not dataset and project in schema:
|
|
@@ -5,11 +5,11 @@ from .column_resolver import resolve_column_path
|
|
|
5
5
|
|
|
6
6
|
|
|
7
7
|
class ReferencesAnalyzer:
|
|
8
|
-
def __init__(self, schema: dict,
|
|
8
|
+
def __init__(self, schema: dict, default_catalog: str):
|
|
9
9
|
self.schema = schema
|
|
10
|
-
self.
|
|
10
|
+
self.default_catalog = default_catalog
|
|
11
11
|
|
|
12
|
-
def analyze(self, expression: exp.Expression) -> dict:
|
|
12
|
+
def analyze(self, expression: exp.Expression) -> list[dict[str, str]]:
|
|
13
13
|
references: dict[str, set[str]] = {}
|
|
14
14
|
|
|
15
15
|
for scope in traverse_scope(expression):
|
|
@@ -17,7 +17,7 @@ class ReferencesAnalyzer:
|
|
|
17
17
|
resolved = resolve_column_path(
|
|
18
18
|
column,
|
|
19
19
|
scope,
|
|
20
|
-
self.
|
|
20
|
+
self.default_catalog,
|
|
21
21
|
self.schema,
|
|
22
22
|
_extract_column,
|
|
23
23
|
)
|
|
@@ -27,7 +27,7 @@ class ReferencesAnalyzer:
|
|
|
27
27
|
table_path = ".".join(full_path.split(".", 3)[:3])
|
|
28
28
|
_add(references, table_path, column_path)
|
|
29
29
|
|
|
30
|
-
return references
|
|
30
|
+
return _flatten_references(references)
|
|
31
31
|
|
|
32
32
|
def _add(references: dict[str, set[str]], table: str, column: str):
|
|
33
33
|
if table in references:
|
|
@@ -36,6 +36,23 @@ def _add(references: dict[str, set[str]], table: str, column: str):
|
|
|
36
36
|
references[table] = {column}
|
|
37
37
|
|
|
38
38
|
|
|
39
|
+
def _flatten_references(references: dict[str, set[str]]) -> list[dict[str, str]]:
|
|
40
|
+
rows: list[dict[str, str]] = []
|
|
41
|
+
for table_path, columns in references.items():
|
|
42
|
+
database, schema, table = table_path.split(".", 2)
|
|
43
|
+
for column in columns:
|
|
44
|
+
rows.append(
|
|
45
|
+
{
|
|
46
|
+
"database": database,
|
|
47
|
+
"schema": schema,
|
|
48
|
+
"table": table,
|
|
49
|
+
"column": column,
|
|
50
|
+
}
|
|
51
|
+
)
|
|
52
|
+
rows.sort(key=lambda row: (row["database"], row["schema"], row["table"], row["column"]))
|
|
53
|
+
return rows
|
|
54
|
+
|
|
55
|
+
|
|
39
56
|
def _extract_column(expr: exp.Expression) -> exp.Column | None:
|
|
40
57
|
if isinstance(expr, exp.Column):
|
|
41
58
|
return expr
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from sqlglot import dialects
|
|
4
|
+
|
|
5
|
+
SUPPORTED_DIALECTS = {dialects.BigQuery, dialects.Redshift}
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def build_schema(
|
|
9
|
+
dialect: str | type[dialects.Dialect],
|
|
10
|
+
database: str,
|
|
11
|
+
schema: str | None = None,
|
|
12
|
+
table: str | None = None,
|
|
13
|
+
):
|
|
14
|
+
resolved = (
|
|
15
|
+
dialects.get_or_raise(dialect.lower()) if isinstance(dialect, str) else dialect
|
|
16
|
+
)
|
|
17
|
+
if resolved not in SUPPORTED_DIALECTS:
|
|
18
|
+
raise ValueError(f"Unsupported dialect for build_schema: {resolved.__name__}")
|
|
19
|
+
if resolved is dialects.BigQuery:
|
|
20
|
+
return _build_schema_bigquery(database, schema, table)
|
|
21
|
+
if resolved is dialects.Redshift:
|
|
22
|
+
return _build_schema_redshift(database, schema, table)
|
|
23
|
+
raise ValueError(f"Unsupported dialect for build_schema: {resolved.__name__}")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _build_schema_bigquery(project: str, dataset: str | None, table: str | None):
|
|
27
|
+
try:
|
|
28
|
+
from google.cloud import bigquery # noqa: F401
|
|
29
|
+
except ImportError as e:
|
|
30
|
+
raise RuntimeError(
|
|
31
|
+
"BigQuery support is not installed. "
|
|
32
|
+
"Install with: pip install analytics-query-analyzer[bigquery]"
|
|
33
|
+
) from e
|
|
34
|
+
|
|
35
|
+
def _format_field_type(field) -> str:
|
|
36
|
+
if field.field_type == "RECORD":
|
|
37
|
+
parts = [
|
|
38
|
+
f"{child.name} {_format_field_type(child)}" for child in field.fields
|
|
39
|
+
]
|
|
40
|
+
return f"struct<{', '.join(parts)}>"
|
|
41
|
+
return field.field_type.lower()
|
|
42
|
+
|
|
43
|
+
def _field_to_schema(field) -> dict | str:
|
|
44
|
+
if field.mode == "REPEATED":
|
|
45
|
+
return f"array<{_format_field_type(field)}>"
|
|
46
|
+
if field.field_type == "RECORD":
|
|
47
|
+
return {child.name: _field_to_schema(child) for child in field.fields}
|
|
48
|
+
return field.field_type.lower()
|
|
49
|
+
|
|
50
|
+
def _table_to_schema(table_obj: bigquery.Table) -> dict:
|
|
51
|
+
return {
|
|
52
|
+
table_obj.table_id: {
|
|
53
|
+
field.name: _field_to_schema(field) for field in table_obj.schema
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
def _dataset_to_schema(dataset_id: str) -> dict:
|
|
58
|
+
dataset_ref = bigquery.DatasetReference(project, dataset_id)
|
|
59
|
+
table_schema = {}
|
|
60
|
+
for table_item in client.list_tables(dataset_ref):
|
|
61
|
+
table_obj = client.get_table(table_item)
|
|
62
|
+
table_schema.update(_table_to_schema(table_obj))
|
|
63
|
+
return {dataset_id: table_schema}
|
|
64
|
+
|
|
65
|
+
client = bigquery.Client(project=project)
|
|
66
|
+
if dataset is None:
|
|
67
|
+
result = {}
|
|
68
|
+
for ds in client.list_datasets():
|
|
69
|
+
result.update(_dataset_to_schema(ds.dataset_id))
|
|
70
|
+
return {project: result}
|
|
71
|
+
elif table is None:
|
|
72
|
+
return {project: _dataset_to_schema(dataset)}
|
|
73
|
+
else:
|
|
74
|
+
dataset_ref = bigquery.DatasetReference(project, dataset)
|
|
75
|
+
table_ref = dataset_ref.table(table)
|
|
76
|
+
table_obj = client.get_table(table_ref)
|
|
77
|
+
return {project: {dataset: _table_to_schema(table_obj)}}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _redshift_connection_kwargs(database: str) -> dict[str, str | int | bool]:
|
|
81
|
+
host = os.getenv("REDSHIFT_HOST")
|
|
82
|
+
port = os.getenv("REDSHIFT_PORT")
|
|
83
|
+
|
|
84
|
+
cluster_identifier = os.getenv("REDSHIFT_CLUSTER_IDENTIFIER")
|
|
85
|
+
region = os.getenv("REDSHIFT_REGION")
|
|
86
|
+
db_user = os.getenv("REDSHIFT_DB_USER")
|
|
87
|
+
|
|
88
|
+
user = os.getenv("REDSHIFT_USER")
|
|
89
|
+
password = os.getenv("REDSHIFT_PASSWORD")
|
|
90
|
+
|
|
91
|
+
if cluster_identifier and region and db_user:
|
|
92
|
+
kwargs = {
|
|
93
|
+
"cluster_identifier": cluster_identifier,
|
|
94
|
+
"database": database,
|
|
95
|
+
"db_user": db_user,
|
|
96
|
+
"region": region,
|
|
97
|
+
"iam": True,
|
|
98
|
+
}
|
|
99
|
+
if host:
|
|
100
|
+
kwargs["host"] = host
|
|
101
|
+
if port:
|
|
102
|
+
kwargs["port"] = int(port)
|
|
103
|
+
return kwargs
|
|
104
|
+
|
|
105
|
+
if host and user and password:
|
|
106
|
+
return {
|
|
107
|
+
"host": host,
|
|
108
|
+
"port": int(port) if port else 5439,
|
|
109
|
+
"database": database,
|
|
110
|
+
"user": user,
|
|
111
|
+
"password": password,
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
raise RuntimeError(
|
|
115
|
+
"Redshift connection configuration not found. "
|
|
116
|
+
"Set REDSHIFT_HOST/REDSHIFT_USER/REDSHIFT_PASSWORD or "
|
|
117
|
+
"REDSHIFT_CLUSTER_IDENTIFIER/REDSHIFT_REGION/REDSHIFT_DB_USER."
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _build_schema_redshift(database: str, schema: str | None, table: str | None):
|
|
122
|
+
try:
|
|
123
|
+
import redshift_connector
|
|
124
|
+
except ImportError as e:
|
|
125
|
+
raise RuntimeError(
|
|
126
|
+
"Redshift support is not installed. "
|
|
127
|
+
"Install with: pip install analytics-query-analyzer[redshift]"
|
|
128
|
+
) from e
|
|
129
|
+
|
|
130
|
+
connection_kwargs = _redshift_connection_kwargs(database)
|
|
131
|
+
conn = redshift_connector.connect(**connection_kwargs)
|
|
132
|
+
try:
|
|
133
|
+
cursor = conn.cursor()
|
|
134
|
+
try:
|
|
135
|
+
if schema is None:
|
|
136
|
+
cursor.execute(
|
|
137
|
+
"""
|
|
138
|
+
select schema_name
|
|
139
|
+
from information_schema.schemata
|
|
140
|
+
where schema_name not in ('information_schema', 'pg_catalog')
|
|
141
|
+
and schema_name not like 'pg_%'
|
|
142
|
+
order by schema_name
|
|
143
|
+
"""
|
|
144
|
+
)
|
|
145
|
+
schemas = [row[0] for row in cursor.fetchall()]
|
|
146
|
+
else:
|
|
147
|
+
schemas = [schema]
|
|
148
|
+
|
|
149
|
+
result: dict[str, dict] = {}
|
|
150
|
+
for schema_name in schemas:
|
|
151
|
+
if table is None:
|
|
152
|
+
cursor.execute(
|
|
153
|
+
"""
|
|
154
|
+
select table_name
|
|
155
|
+
from information_schema.tables
|
|
156
|
+
where table_schema = %s
|
|
157
|
+
and table_type = 'BASE TABLE'
|
|
158
|
+
order by table_name
|
|
159
|
+
""",
|
|
160
|
+
(schema_name,),
|
|
161
|
+
)
|
|
162
|
+
tables = [row[0] for row in cursor.fetchall()]
|
|
163
|
+
else:
|
|
164
|
+
tables = [table]
|
|
165
|
+
if not tables:
|
|
166
|
+
result[schema_name] = {}
|
|
167
|
+
continue
|
|
168
|
+
|
|
169
|
+
placeholders = ", ".join(["%s"] * len(tables))
|
|
170
|
+
cursor.execute(
|
|
171
|
+
f"""
|
|
172
|
+
select table_name, column_name, data_type, udt_name
|
|
173
|
+
from information_schema.columns
|
|
174
|
+
where table_schema = %s
|
|
175
|
+
and table_name in ({placeholders})
|
|
176
|
+
order by table_name, ordinal_position
|
|
177
|
+
""",
|
|
178
|
+
(schema_name, *tables),
|
|
179
|
+
)
|
|
180
|
+
table_schema: dict[str, dict[str, str]] = {name: {} for name in tables}
|
|
181
|
+
for table_name, column_name, data_type, udt_name in cursor.fetchall():
|
|
182
|
+
column_type = data_type or udt_name or "unknown"
|
|
183
|
+
table_schema.setdefault(table_name, {})[column_name] = column_type
|
|
184
|
+
result[schema_name] = table_schema
|
|
185
|
+
finally:
|
|
186
|
+
cursor.close()
|
|
187
|
+
finally:
|
|
188
|
+
conn.close()
|
|
189
|
+
return {database: result}
|