analytics-query-analyzer 0.2.0__tar.gz → 0.3.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.0 → analytics_query_analyzer-0.3.0}/.github/workflows/publish-testpypi.yml +6 -0
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/.github/workflows/pytest.yml +4 -1
- {analytics_query_analyzer-0.2.0/src/analytics_query_analyzer.egg-info → analytics_query_analyzer-0.3.0}/PKG-INFO +31 -10
- analytics_query_analyzer-0.2.0/PKG-INFO → analytics_query_analyzer-0.3.0/README.md +27 -22
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/pyproject.toml +2 -1
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/src/analytics_query_analyzer/analyzer.py +6 -6
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/src/analytics_query_analyzer/column_resolver.py +3 -3
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/src/analytics_query_analyzer/references_analyzer.py +3 -3
- analytics_query_analyzer-0.3.0/src/analytics_query_analyzer/schema_builder.py +189 -0
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/src/analytics_query_analyzer/timespan_analyzer.py +46 -8
- analytics_query_analyzer-0.2.0/README.md → analytics_query_analyzer-0.3.0/src/analytics_query_analyzer.egg-info/PKG-INFO +43 -8
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/src/analytics_query_analyzer.egg-info/SOURCES.txt +4 -2
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/src/analytics_query_analyzer.egg-info/requires.txt +3 -0
- analytics_query_analyzer-0.3.0/tests/test_analyze_redshift.py +142 -0
- analytics_query_analyzer-0.3.0/tests/test_analyze_timespan_redshift.py +608 -0
- analytics_query_analyzer-0.2.0/src/analytics_query_analyzer/schema_builder.py +0 -71
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/.github/workflows/publish-pypi.yml +0 -0
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/.gitignore +0 -0
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/LICENSE +0 -0
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/setup.cfg +0 -0
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/src/analytics_query_analyzer/__init__.py +0 -0
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/src/analytics_query_analyzer.egg-info/dependency_links.txt +0 -0
- {analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/src/analytics_query_analyzer.egg-info/top_level.txt +0 -0
- /analytics_query_analyzer-0.2.0/tests/test_analyze.py → /analytics_query_analyzer-0.3.0/tests/test_analyze_bigquery.py +0 -0
- /analytics_query_analyzer-0.2.0/tests/test_analyze_timespan.py → /analytics_query_analyzer-0.3.0/tests/test_analyze_timespan_bigquery.py +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
|
{analytics_query_analyzer-0.2.0 → analytics_query_analyzer-0.3.0}/.github/workflows/pytest.yml
RENAMED
|
@@ -8,6 +8,9 @@ on:
|
|
|
8
8
|
jobs:
|
|
9
9
|
pytest:
|
|
10
10
|
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python-version: ["3.11", "3.12", "3.13", "3.14"]
|
|
11
14
|
|
|
12
15
|
steps:
|
|
13
16
|
- name: Checkout
|
|
@@ -16,7 +19,7 @@ jobs:
|
|
|
16
19
|
- name: Set up Python
|
|
17
20
|
uses: actions/setup-python@v5
|
|
18
21
|
with:
|
|
19
|
-
python-version:
|
|
22
|
+
python-version: ${{ matrix.python-version }}
|
|
20
23
|
|
|
21
24
|
- name: Install dependencies
|
|
22
25
|
run: |
|
|
@@ -1,21 +1,27 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: analytics-query-analyzer
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Analytics Query Analyzer
|
|
5
5
|
License: MIT
|
|
6
6
|
Classifier: License :: OSI Approved :: MIT License
|
|
7
|
-
Requires-Python: >=3.
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
8
|
Description-Content-Type: text/markdown
|
|
9
9
|
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
|
|
@@ -132,7 +138,7 @@ timespans = analyze_timespan(
|
|
|
132
138
|
|
|
133
139
|
### build_schema
|
|
134
140
|
|
|
135
|
-
Fetch a schema dictionary from BigQuery.
|
|
141
|
+
Fetch a schema dictionary from BigQuery or Redshift.
|
|
136
142
|
|
|
137
143
|
```python
|
|
138
144
|
from analytics_query_analyzer import build_schema
|
|
@@ -143,7 +149,22 @@ print(schema)
|
|
|
143
149
|
```
|
|
144
150
|
|
|
145
151
|
- Authentication uses Application Default Credentials (ADC).
|
|
146
|
-
- Only BigQuery is supported for `build_schema`.
|
|
147
152
|
- When `table` is omitted, it scans all tables in the dataset.
|
|
148
153
|
- When both `dataset` and `table` are omitted, it scans all datasets in the project.
|
|
149
154
|
- The returned `schema` can be passed directly to `analyze` and `analyze_timespan`.
|
|
155
|
+
|
|
156
|
+
Fetching from Redshift is also supported:
|
|
157
|
+
|
|
158
|
+
```python
|
|
159
|
+
from analytics_query_analyzer import build_schema
|
|
160
|
+
from sqlglot import dialects
|
|
161
|
+
|
|
162
|
+
schema = build_schema(dialects.Redshift, "my_database", "public", "orders")
|
|
163
|
+
print(schema)
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Redshift authentication supports two modes:
|
|
167
|
+
|
|
168
|
+
- Set `REDSHIFT_HOST`, `REDSHIFT_USER`, and `REDSHIFT_PASSWORD` (optional `REDSHIFT_PORT`).
|
|
169
|
+
- Set `REDSHIFT_CLUSTER_IDENTIFIER`, `REDSHIFT_REGION`, and `REDSHIFT_DB_USER` to use IAM (you can also set `REDSHIFT_HOST`/`REDSHIFT_PORT`).
|
|
170
|
+
- Use `AWS_PROFILE` if you want to select a non-default AWS profile.
|
|
@@ -1,21 +1,11 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: analytics-query-analyzer
|
|
3
|
-
Version: 0.2.0
|
|
4
|
-
Summary: Analytics Query Analyzer
|
|
5
|
-
License: MIT
|
|
6
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
7
|
-
Requires-Python: >=3.13
|
|
8
|
-
Description-Content-Type: text/markdown
|
|
9
|
-
License-File: LICENSE
|
|
10
|
-
Requires-Dist: sqlglot>=28
|
|
11
|
-
Provides-Extra: bigquery
|
|
12
|
-
Requires-Dist: google-cloud-bigquery; extra == "bigquery"
|
|
13
|
-
Dynamic: license-file
|
|
14
|
-
|
|
15
1
|
# analytics-query-analyzer
|
|
16
2
|
|
|
17
3
|
Analyze analytics SQL to extract referenced tables/columns and time bounds.
|
|
18
4
|
|
|
5
|
+
## Support
|
|
6
|
+
|
|
7
|
+
BigQuery and Redshift are currently supported.
|
|
8
|
+
|
|
19
9
|
## Install
|
|
20
10
|
|
|
21
11
|
Base install:
|
|
@@ -30,13 +20,11 @@ BigQuery extras (only needed for `build_schema`):
|
|
|
30
20
|
pip install analytics-query-analyzer[bigquery]
|
|
31
21
|
```
|
|
32
22
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
BigQuery is currently supported and tested.
|
|
36
|
-
|
|
37
|
-
## Schema format
|
|
23
|
+
Redshift extras (only needed for `build_schema`):
|
|
38
24
|
|
|
39
|
-
|
|
25
|
+
```bash
|
|
26
|
+
pip install analytics-query-analyzer[redshift]
|
|
27
|
+
```
|
|
40
28
|
|
|
41
29
|
## Usage
|
|
42
30
|
|
|
@@ -44,6 +32,8 @@ Schemas follow sqlglot conventions, with nested fields represented as nested dic
|
|
|
44
32
|
|
|
45
33
|
Extract table/column references from a query.
|
|
46
34
|
|
|
35
|
+
Schema format follows sqlglot conventions, with nested fields represented as nested dicts.
|
|
36
|
+
|
|
47
37
|
```python
|
|
48
38
|
from analytics_query_analyzer import analyze
|
|
49
39
|
from sqlglot import dialects
|
|
@@ -132,7 +122,7 @@ timespans = analyze_timespan(
|
|
|
132
122
|
|
|
133
123
|
### build_schema
|
|
134
124
|
|
|
135
|
-
Fetch a schema dictionary from BigQuery.
|
|
125
|
+
Fetch a schema dictionary from BigQuery or Redshift.
|
|
136
126
|
|
|
137
127
|
```python
|
|
138
128
|
from analytics_query_analyzer import build_schema
|
|
@@ -143,7 +133,22 @@ print(schema)
|
|
|
143
133
|
```
|
|
144
134
|
|
|
145
135
|
- Authentication uses Application Default Credentials (ADC).
|
|
146
|
-
- Only BigQuery is supported for `build_schema`.
|
|
147
136
|
- When `table` is omitted, it scans all tables in the dataset.
|
|
148
137
|
- When both `dataset` and `table` are omitted, it scans all datasets in the project.
|
|
149
138
|
- The returned `schema` can be passed directly to `analyze` and `analyze_timespan`.
|
|
139
|
+
|
|
140
|
+
Fetching from Redshift is also supported:
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from analytics_query_analyzer import build_schema
|
|
144
|
+
from sqlglot import dialects
|
|
145
|
+
|
|
146
|
+
schema = build_schema(dialects.Redshift, "my_database", "public", "orders")
|
|
147
|
+
print(schema)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Redshift authentication supports two modes:
|
|
151
|
+
|
|
152
|
+
- Set `REDSHIFT_HOST`, `REDSHIFT_USER`, and `REDSHIFT_PASSWORD` (optional `REDSHIFT_PORT`).
|
|
153
|
+
- Set `REDSHIFT_CLUSTER_IDENTIFIER`, `REDSHIFT_REGION`, and `REDSHIFT_DB_USER` to use IAM (you can also set `REDSHIFT_HOST`/`REDSHIFT_PORT`).
|
|
154
|
+
- Use `AWS_PROFILE` if you want to select a non-default AWS profile.
|
|
@@ -6,7 +6,7 @@ build-backend = "setuptools.build_meta"
|
|
|
6
6
|
name = "analytics-query-analyzer"
|
|
7
7
|
description = "Analytics Query Analyzer"
|
|
8
8
|
readme = "README.md"
|
|
9
|
-
requires-python = ">=3.
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
10
|
license = {text = "MIT"}
|
|
11
11
|
classifiers = [
|
|
12
12
|
"License :: OSI Approved :: MIT License",
|
|
@@ -18,6 +18,7 @@ dynamic = ["version"]
|
|
|
18
18
|
|
|
19
19
|
[project.optional-dependencies]
|
|
20
20
|
bigquery = ["google-cloud-bigquery"]
|
|
21
|
+
redshift = ["redshift-connector"]
|
|
21
22
|
|
|
22
23
|
[tool.setuptools]
|
|
23
24
|
package-dir = {"" = "src"}
|
|
@@ -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,9 +5,9 @@ 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
12
|
def analyze(self, expression: exp.Expression) -> dict:
|
|
13
13
|
references: dict[str, set[str]] = {}
|
|
@@ -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
|
)
|
|
@@ -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}
|
|
@@ -20,11 +20,11 @@ class TimespanAnalyzer:
|
|
|
20
20
|
def __init__(
|
|
21
21
|
self,
|
|
22
22
|
schema: dict,
|
|
23
|
-
|
|
23
|
+
default_catalog: str,
|
|
24
24
|
current_date_provider: Callable[[], str | date | datetime] | None = None,
|
|
25
25
|
):
|
|
26
26
|
self.schema = schema
|
|
27
|
-
self.
|
|
27
|
+
self.default_catalog = default_catalog
|
|
28
28
|
self.current_date_provider = current_date_provider or date.today
|
|
29
29
|
|
|
30
30
|
def analyze(self, expression: exp.Expression) -> dict[str, dict[str, str | None]]:
|
|
@@ -141,7 +141,7 @@ class TimespanAnalyzer:
|
|
|
141
141
|
if not column:
|
|
142
142
|
return {}
|
|
143
143
|
resolved = resolve_column_path(
|
|
144
|
-
column, scope, self.
|
|
144
|
+
column, scope, self.default_catalog, self.schema, self.extract_column
|
|
145
145
|
)
|
|
146
146
|
if not resolved:
|
|
147
147
|
return {}
|
|
@@ -158,7 +158,7 @@ class TimespanAnalyzer:
|
|
|
158
158
|
if not column:
|
|
159
159
|
return {}
|
|
160
160
|
resolved = resolve_column_path(
|
|
161
|
-
column, scope, self.
|
|
161
|
+
column, scope, self.default_catalog, self.schema, self.extract_column
|
|
162
162
|
)
|
|
163
163
|
if not resolved:
|
|
164
164
|
return {}
|
|
@@ -218,7 +218,7 @@ class TimespanAnalyzer:
|
|
|
218
218
|
return {}
|
|
219
219
|
|
|
220
220
|
resolved = resolve_column_path(
|
|
221
|
-
column, scope, self.
|
|
221
|
+
column, scope, self.default_catalog, self.schema, self.extract_column
|
|
222
222
|
)
|
|
223
223
|
if not resolved:
|
|
224
224
|
return {}
|
|
@@ -315,8 +315,10 @@ class TimespanAnalyzer:
|
|
|
315
315
|
return self._extract_parts_date(expr)
|
|
316
316
|
if isinstance(expr, exp.UnixToTime):
|
|
317
317
|
return self._extract_epoch_date(expr)
|
|
318
|
-
if isinstance(expr, (exp.DateAdd, exp.DateSub)):
|
|
318
|
+
if isinstance(expr, (exp.DateAdd, exp.DateSub, exp.TsOrDsAdd)):
|
|
319
319
|
return self._extract_date_arithmetic(expr)
|
|
320
|
+
if isinstance(expr, (exp.Add, exp.Sub)):
|
|
321
|
+
return self._extract_interval_arithmetic(expr)
|
|
320
322
|
return None
|
|
321
323
|
|
|
322
324
|
def _evaluate_current_date(self) -> date | None:
|
|
@@ -388,6 +390,27 @@ class TimespanAnalyzer:
|
|
|
388
390
|
delta_value = -delta_value
|
|
389
391
|
return self._apply_date_delta(base, delta_value, unit)
|
|
390
392
|
|
|
393
|
+
def _extract_interval_arithmetic(self, expr: exp.Expression) -> date | None:
|
|
394
|
+
left = expr.args.get("this")
|
|
395
|
+
right = expr.args.get("expression")
|
|
396
|
+
if isinstance(right, exp.Interval):
|
|
397
|
+
base = self.extract_literal(left)
|
|
398
|
+
delta = self._extract_int_literal(right.args.get("this"))
|
|
399
|
+
unit = self._extract_unit_literal(right.args.get("unit"))
|
|
400
|
+
if base is None or delta is None or not unit:
|
|
401
|
+
return None
|
|
402
|
+
if isinstance(expr, exp.Sub):
|
|
403
|
+
delta = -delta
|
|
404
|
+
return self._apply_date_delta(base, delta, unit)
|
|
405
|
+
if isinstance(left, exp.Interval):
|
|
406
|
+
base = self.extract_literal(right)
|
|
407
|
+
delta = self._extract_int_literal(left.args.get("this"))
|
|
408
|
+
unit = self._extract_unit_literal(left.args.get("unit"))
|
|
409
|
+
if base is None or delta is None or not unit:
|
|
410
|
+
return None
|
|
411
|
+
return self._apply_date_delta(base, delta, unit)
|
|
412
|
+
return None
|
|
413
|
+
|
|
391
414
|
def _extract_trunc_date(self, expr: exp.Expression) -> date | None:
|
|
392
415
|
target = expr.args.get("this") or expr.this
|
|
393
416
|
unit_expr = expr.args.get("unit") or expr.args.get("part")
|
|
@@ -425,7 +448,13 @@ class TimespanAnalyzer:
|
|
|
425
448
|
try:
|
|
426
449
|
return int(expr.this)
|
|
427
450
|
except (TypeError, ValueError):
|
|
428
|
-
|
|
451
|
+
try:
|
|
452
|
+
return int(float(expr.this))
|
|
453
|
+
except (TypeError, ValueError):
|
|
454
|
+
return None
|
|
455
|
+
if isinstance(expr, exp.Neg):
|
|
456
|
+
value = self._extract_int_literal(expr.this)
|
|
457
|
+
return None if value is None else -value
|
|
429
458
|
if isinstance(expr, exp.Cast):
|
|
430
459
|
return self._extract_int_literal(expr.this)
|
|
431
460
|
if isinstance(expr, exp.Paren):
|
|
@@ -490,7 +519,16 @@ class TimespanAnalyzer:
|
|
|
490
519
|
column_type = self.schema[project][dataset][table][column_root]
|
|
491
520
|
except KeyError:
|
|
492
521
|
return False
|
|
493
|
-
|
|
522
|
+
normalized = str(column_type).lower()
|
|
523
|
+
if normalized in {
|
|
524
|
+
"datetime",
|
|
525
|
+
"date",
|
|
526
|
+
"timestamp",
|
|
527
|
+
"timestamp without time zone",
|
|
528
|
+
"timestamp with time zone",
|
|
529
|
+
}:
|
|
530
|
+
return True
|
|
531
|
+
return False
|
|
494
532
|
|
|
495
533
|
@staticmethod
|
|
496
534
|
def merge_bounds_and(
|