analytics-query-analyzer 0.6.0__tar.gz → 0.7.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.
Files changed (32) hide show
  1. analytics_query_analyzer-0.7.0/.github/dependabot.yml +10 -0
  2. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/.github/workflows/pytest.yml +2 -1
  3. {analytics_query_analyzer-0.6.0/src/analytics_query_analyzer.egg-info → analytics_query_analyzer-0.7.0}/PKG-INFO +14 -5
  4. analytics_query_analyzer-0.6.0/PKG-INFO → analytics_query_analyzer-0.7.0/README.md +10 -19
  5. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/pyproject.toml +2 -1
  6. analytics_query_analyzer-0.7.0/src/analytics_query_analyzer/analyzer.py +216 -0
  7. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/src/analytics_query_analyzer/references_analyzer.py +32 -1
  8. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/src/analytics_query_analyzer/schema_builder.py +3 -1
  9. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/src/analytics_query_analyzer/timebounds_analyzer.py +350 -77
  10. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/src/analytics_query_analyzer/types.py +3 -3
  11. analytics_query_analyzer-0.6.0/README.md → analytics_query_analyzer-0.7.0/src/analytics_query_analyzer.egg-info/PKG-INFO +28 -3
  12. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/src/analytics_query_analyzer.egg-info/SOURCES.txt +7 -1
  13. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/src/analytics_query_analyzer.egg-info/requires.txt +4 -1
  14. analytics_query_analyzer-0.7.0/src/analytics_query_analyzer.egg-info/scm_file_list.json +26 -0
  15. analytics_query_analyzer-0.7.0/src/analytics_query_analyzer.egg-info/scm_version.json +8 -0
  16. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/tests/test_analyze_bigquery.py +4 -3
  17. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/tests/test_analyze_redshift.py +2 -2
  18. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/tests/test_analyze_with_timebounds_bigquery.py +3 -3
  19. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/tests/test_analyze_with_timebounds_redshift.py +3 -3
  20. analytics_query_analyzer-0.7.0/tests/test_api_validation.py +49 -0
  21. analytics_query_analyzer-0.7.0/tests/test_bigquery_special_tables.py +173 -0
  22. analytics_query_analyzer-0.7.0/tests/test_timebounds_safety.py +253 -0
  23. analytics_query_analyzer-0.6.0/src/analytics_query_analyzer/analyzer.py +0 -90
  24. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/.github/workflows/publish-pypi.yml +0 -0
  25. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/.github/workflows/publish-testpypi.yml +0 -0
  26. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/.gitignore +0 -0
  27. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/LICENSE +0 -0
  28. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/setup.cfg +0 -0
  29. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/src/analytics_query_analyzer/__init__.py +0 -0
  30. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/src/analytics_query_analyzer/column_resolver.py +0 -0
  31. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/src/analytics_query_analyzer.egg-info/dependency_links.txt +0 -0
  32. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.0}/src/analytics_query_analyzer.egg-info/top_level.txt +0 -0
@@ -0,0 +1,10 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: pip
4
+ directory: /
5
+ schedule:
6
+ interval: weekly
7
+ - package-ecosystem: github-actions
8
+ directory: /
9
+ schedule:
10
+ interval: weekly
@@ -11,6 +11,7 @@ jobs:
11
11
  strategy:
12
12
  matrix:
13
13
  python-version: ["3.11", "3.12", "3.13", "3.14"]
14
+ sqlglot: ["sqlglot==28.0.0", "sqlglot>=28,<31"]
14
15
 
15
16
  steps:
16
17
  - name: Checkout
@@ -24,7 +25,7 @@ jobs:
24
25
  - name: Install dependencies
25
26
  run: |
26
27
  python -m pip install --upgrade pip
27
- python -m pip install -e . pytest
28
+ python -m pip install -e ".[dev]" "${{ matrix.sqlglot }}"
28
29
 
29
30
  - name: Run pytest
30
31
  run: pytest
@@ -1,13 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: analytics-query-analyzer
3
- Version: 0.6.0
3
+ Version: 0.7.0
4
4
  Summary: Analytics Query Analyzer
5
5
  License: MIT
6
6
  Classifier: License :: OSI Approved :: MIT License
7
7
  Requires-Python: >=3.11
8
8
  Description-Content-Type: text/markdown
9
9
  License-File: LICENSE
10
- Requires-Dist: sqlglot>=28
10
+ Requires-Dist: sqlglot<31,>=28
11
+ Provides-Extra: dev
12
+ Requires-Dist: pytest>=8; extra == "dev"
11
13
  Provides-Extra: bigquery
12
14
  Requires-Dist: google-cloud-bigquery; extra == "bigquery"
13
15
  Provides-Extra: redshift
@@ -46,9 +48,10 @@ pip install analytics-query-analyzer[redshift]
46
48
 
47
49
  ### analyze
48
50
 
49
- Extract table/column references from a query.
51
+ Extract table/column references from a single SQL statement. Passing multiple statements raises `ValueError`. Dialects can be passed as classes or names such as `"bigquery"`.
50
52
 
51
53
  Schema format follows sqlglot conventions, with nested fields represented as nested dicts.
54
+ A table referenced without a specific column, such as in `COUNT(*)`, is returned with `column=None`.
52
55
 
53
56
  ```python
54
57
  from analytics_query_analyzer import analyze
@@ -108,6 +111,8 @@ print(references)
108
111
  Extract time bounds from filters by enabling `with_timebounds`.
109
112
 
110
113
  ```python
114
+ from datetime import date
115
+
111
116
  from analytics_query_analyzer import analyze
112
117
  from sqlglot import dialects
113
118
 
@@ -155,8 +160,8 @@ print(timebounds)
155
160
  # "schema": "shop",
156
161
  # "table": "orders",
157
162
  # "column": "ordered_at",
158
- # "lower": "2025-01-01",
159
- # "upper": "2026-01-01",
163
+ # "lower": date(2025, 1, 1),
164
+ # "upper": date(2026, 1, 1),
160
165
  # },
161
166
  # {
162
167
  # "database": "production",
@@ -169,6 +174,10 @@ print(timebounds)
169
174
  # ]
170
175
  ```
171
176
 
177
+ Bounds are inclusive, conservative `date` values inferred from SQL predicates, not the actual scan range. Time-of-day precision is lost, and timezone-aware literals are converted to UTC. `None` means unbounded or unknown. For example, `ordered_at < DATE '2026-02-01'` yields an upper bound of `date(2026, 2, 1)`.
178
+
179
+ For BigQuery, `_TABLE_SUFFIX` bounds are strings; `_PARTITIONDATE` and `_PARTITIONTIME` are also supported. Wildcard tables use the union of matching table schemas; conflicting field types and ambiguous references may be unknown. The default current date is evaluated in UTC.
180
+
172
181
  To make `current_date()` deterministic, pass a provider:
173
182
 
174
183
  ```python
@@ -1,19 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: analytics-query-analyzer
3
- Version: 0.6.0
4
- Summary: Analytics Query Analyzer
5
- License: MIT
6
- Classifier: License :: OSI Approved :: MIT License
7
- Requires-Python: >=3.11
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
- Provides-Extra: redshift
14
- Requires-Dist: redshift-connector; extra == "redshift"
15
- Dynamic: license-file
16
-
17
1
  # analytics-query-analyzer
18
2
 
19
3
  Analyze analytics SQL to extract referenced tables/columns and time bounds.
@@ -46,9 +30,10 @@ pip install analytics-query-analyzer[redshift]
46
30
 
47
31
  ### analyze
48
32
 
49
- Extract table/column references from a query.
33
+ Extract table/column references from a single SQL statement. Passing multiple statements raises `ValueError`. Dialects can be passed as classes or names such as `"bigquery"`.
50
34
 
51
35
  Schema format follows sqlglot conventions, with nested fields represented as nested dicts.
36
+ A table referenced without a specific column, such as in `COUNT(*)`, is returned with `column=None`.
52
37
 
53
38
  ```python
54
39
  from analytics_query_analyzer import analyze
@@ -108,6 +93,8 @@ print(references)
108
93
  Extract time bounds from filters by enabling `with_timebounds`.
109
94
 
110
95
  ```python
96
+ from datetime import date
97
+
111
98
  from analytics_query_analyzer import analyze
112
99
  from sqlglot import dialects
113
100
 
@@ -155,8 +142,8 @@ print(timebounds)
155
142
  # "schema": "shop",
156
143
  # "table": "orders",
157
144
  # "column": "ordered_at",
158
- # "lower": "2025-01-01",
159
- # "upper": "2026-01-01",
145
+ # "lower": date(2025, 1, 1),
146
+ # "upper": date(2026, 1, 1),
160
147
  # },
161
148
  # {
162
149
  # "database": "production",
@@ -169,6 +156,10 @@ print(timebounds)
169
156
  # ]
170
157
  ```
171
158
 
159
+ Bounds are inclusive, conservative `date` values inferred from SQL predicates, not the actual scan range. Time-of-day precision is lost, and timezone-aware literals are converted to UTC. `None` means unbounded or unknown. For example, `ordered_at < DATE '2026-02-01'` yields an upper bound of `date(2026, 2, 1)`.
160
+
161
+ For BigQuery, `_TABLE_SUFFIX` bounds are strings; `_PARTITIONDATE` and `_PARTITIONTIME` are also supported. Wildcard tables use the union of matching table schemas; conflicting field types and ambiguous references may be unknown. The default current date is evaluated in UTC.
162
+
172
163
  To make `current_date()` deterministic, pass a provider:
173
164
 
174
165
  ```python
@@ -12,11 +12,12 @@ classifiers = [
12
12
  "License :: OSI Approved :: MIT License",
13
13
  ]
14
14
  dependencies = [
15
- "sqlglot>=28",
15
+ "sqlglot>=28,<31",
16
16
  ]
17
17
  dynamic = ["version"]
18
18
 
19
19
  [project.optional-dependencies]
20
+ dev = ["pytest>=8"]
20
21
  bigquery = ["google-cloud-bigquery"]
21
22
  redshift = ["redshift-connector"]
22
23
 
@@ -0,0 +1,216 @@
1
+ from copy import deepcopy
2
+ from typing import Literal, overload
3
+
4
+ from sqlglot import dialects, exp, optimizer, parse
5
+ from sqlglot.optimizer.scope import traverse_scope
6
+
7
+ from .references_analyzer import ReferencesAnalyzer
8
+ from .timebounds_analyzer import TimeboundsAnalyzer
9
+ from .types import ReferenceRow, TimeboundsRow
10
+
11
+
12
+ def _resolve_dialect(
13
+ dialect: str | type[dialects.Dialect],
14
+ ) -> type[dialects.Dialect]:
15
+ if isinstance(dialect, str):
16
+ return type(dialects.Dialect.get_or_raise(dialect.lower()))
17
+ return dialect
18
+
19
+
20
+ @overload
21
+ def analyze(
22
+ dialect: str | type[dialects.Dialect],
23
+ sql: str,
24
+ schema: dict,
25
+ default_catalog: str,
26
+ with_timebounds: Literal[False] = False,
27
+ current_date_provider=None,
28
+ ) -> list[ReferenceRow]: ...
29
+
30
+
31
+ @overload
32
+ def analyze(
33
+ dialect: str | type[dialects.Dialect],
34
+ sql: str,
35
+ schema: dict,
36
+ default_catalog: str,
37
+ with_timebounds: Literal[True],
38
+ current_date_provider=None,
39
+ ) -> list[TimeboundsRow]: ...
40
+
41
+
42
+ def analyze(
43
+ dialect: str | type[dialects.Dialect],
44
+ sql: str,
45
+ schema: dict,
46
+ default_catalog: str,
47
+ with_timebounds: bool = False,
48
+ current_date_provider=None,
49
+ ) -> list[ReferenceRow] | list[TimeboundsRow]:
50
+ dialect = _resolve_dialect(dialect)
51
+ statements = [
52
+ statement for statement in parse(sql, read=dialect) if statement is not None
53
+ ]
54
+ if len(statements) != 1:
55
+ raise ValueError("Expected a single SQL statement")
56
+ expression = statements[0]
57
+
58
+ if dialect is dialects.BigQuery:
59
+ schema = _bigquery_schema(schema, expression, default_catalog)
60
+
61
+ # sqlglot rejects empty schema branches; an empty branch supplies no types.
62
+ optimizer_schema = {
63
+ catalog: {
64
+ dataset: {table: fields for table, fields in tables.items() if fields}
65
+ for dataset, tables in datasets.items()
66
+ if any(tables.values())
67
+ }
68
+ for catalog, datasets in schema.items()
69
+ if any(any(tables.values()) for tables in datasets.values())
70
+ }
71
+ if dialect is dialects.BigQuery:
72
+ for datasets in optimizer_schema.values():
73
+ for tables in datasets.values():
74
+ for table, fields in tables.items():
75
+ tables[table] = {
76
+ name: _bigquery_struct_type(value)
77
+ for name, value in fields.items()
78
+ }
79
+ qualified = optimizer.qualify.qualify(
80
+ expression,
81
+ dialect=dialect,
82
+ schema=optimizer_schema,
83
+ catalog=default_catalog,
84
+ validate_qualify_columns=False,
85
+ allow_partial_qualification=True,
86
+ )
87
+ if dialect is dialects.BigQuery:
88
+ _qualify_bigquery_pseudocolumns(qualified)
89
+ analyzer = ReferencesAnalyzer(schema, default_catalog)
90
+ references: list[ReferenceRow] = analyzer.analyze(qualified)
91
+ if not with_timebounds:
92
+ return references
93
+ return _merge_timebounds(
94
+ references,
95
+ TimeboundsAnalyzer(
96
+ schema, default_catalog, current_date_provider, dialect
97
+ ).analyze(qualified),
98
+ )
99
+
100
+
101
+ def _bigquery_struct_type(value):
102
+ if not isinstance(value, dict):
103
+ return value
104
+ fields = [
105
+ f"{exp.to_identifier(name, quoted=True).sql(dialect='bigquery')} {_bigquery_struct_type(field_type)}"
106
+ for name, field_type in value.items()
107
+ ]
108
+ return f"STRUCT<{', '.join(fields)}>"
109
+
110
+
111
+ def _qualify_bigquery_pseudocolumns(expression: exp.Expression) -> None:
112
+ for scope in traverse_scope(expression):
113
+ sources = scope.selected_sources
114
+ if len(sources) != 1:
115
+ continue
116
+ alias, (_, source) = next(iter(sources.items()))
117
+ if not isinstance(source, exp.Table):
118
+ continue
119
+ if source.name.endswith("*") and not scope.can_be_correlated:
120
+ for column in scope.columns:
121
+ if not column.table and not isinstance(column.this, exp.Star):
122
+ column.set("table", exp.to_identifier(alias))
123
+ for pseudo in list(scope.expression.find_all(exp.Pseudocolumn)):
124
+ if pseudo.find_ancestor(
125
+ exp.Select
126
+ ) is scope.expression and pseudo.name.lower() in {
127
+ "_partitiondate",
128
+ "_partitiontime",
129
+ "_table_suffix",
130
+ }:
131
+ pseudo.replace(exp.column(pseudo.name.lower(), table=alias))
132
+
133
+
134
+ def _bigquery_schema(
135
+ schema: dict, expression: exp.Expression, default_catalog: str
136
+ ) -> dict:
137
+ """Provide schemas for referenced wildcard tables and pseudo-columns."""
138
+ schema = deepcopy(schema)
139
+ pseudo_types = {
140
+ "_partitiondate": "date",
141
+ "_partitiontime": "timestamp",
142
+ "_table_suffix": "string",
143
+ }
144
+ used_pseudos = {
145
+ column.name.lower() for column in expression.find_all(exp.Column)
146
+ } & pseudo_types.keys()
147
+ for table in expression.find_all(exp.Table):
148
+ project = table.catalog or default_catalog
149
+ datasets = schema.get(project, {})
150
+ dataset = table.db
151
+ if not dataset:
152
+ matches = [
153
+ name
154
+ for name, tables in datasets.items()
155
+ if table.name in tables
156
+ or (
157
+ table.name.endswith("*")
158
+ and any(t.startswith(table.name[:-1]) for t in tables)
159
+ )
160
+ ]
161
+ if len(matches) != 1:
162
+ continue
163
+ dataset = matches[0]
164
+ tables = datasets.get(dataset, {})
165
+ if table.name.endswith("*") and table.name not in tables:
166
+ matches = sorted(
167
+ name for name in tables if name.startswith(table.name[:-1])
168
+ )
169
+ if matches:
170
+ merged_fields = {}
171
+ for match in matches:
172
+ merged_fields = _merge_wildcard_fields(merged_fields, tables[match])
173
+ tables[table.name] = merged_fields
174
+ fields = tables.get(table.name)
175
+ if isinstance(fields, dict):
176
+ for name in used_pseudos:
177
+ if name != "_table_suffix" or table.name.endswith("*"):
178
+ fields.setdefault(name, pseudo_types[name])
179
+ return schema
180
+
181
+
182
+ def _merge_wildcard_fields(left: dict, right: dict) -> dict:
183
+ """Keep every possible field; conflicting types have no reliable type."""
184
+ result = deepcopy(left)
185
+ for name, right_type in right.items():
186
+ if name not in result:
187
+ result[name] = deepcopy(right_type)
188
+ elif isinstance(result[name], dict) and isinstance(right_type, dict):
189
+ result[name] = _merge_wildcard_fields(result[name], right_type)
190
+ elif result[name] != right_type:
191
+ result[name] = "unknown"
192
+ return result
193
+
194
+
195
+ def _merge_timebounds(
196
+ references: list[ReferenceRow],
197
+ timebounds: list[TimeboundsRow],
198
+ ) -> list[TimeboundsRow]:
199
+ merged: dict[tuple[str, str, str, str | None], TimeboundsRow] = {}
200
+ for row in references:
201
+ key = (row["database"], row["schema"], row["table"], row["column"])
202
+ merged[key] = {**row, "lower": None, "upper": None}
203
+ for row in timebounds:
204
+ key = (row["database"], row["schema"], row["table"], row["column"])
205
+ if key in merged:
206
+ merged[key]["lower"] = row.get("lower")
207
+ merged[key]["upper"] = row.get("upper")
208
+ else:
209
+ merged[key] = row
210
+ return [
211
+ merged[key]
212
+ for key in sorted(merged.keys(), key=lambda k: (k[0], k[1], k[2], k[3] or ""))
213
+ ]
214
+
215
+
216
+ __all__ = ["analyze"]
@@ -12,8 +12,24 @@ class ReferencesAnalyzer:
12
12
 
13
13
  def analyze(self, expression: exp.Expression) -> list[ReferenceRow]:
14
14
  references: dict[str, set[str]] = {}
15
+ tables: set[str] = set()
15
16
 
16
17
  for scope in traverse_scope(expression):
18
+ for _, source in scope.selected_sources.values():
19
+ if not isinstance(source, exp.Table):
20
+ continue
21
+ project = source.catalog or self.default_catalog
22
+ dataset = source.db
23
+ if not dataset:
24
+ matches = [
25
+ name
26
+ for name, values in self.schema.get(project, {}).items()
27
+ if source.name in values
28
+ ]
29
+ if len(matches) != 1:
30
+ continue
31
+ dataset = matches[0]
32
+ tables.add(f"{project}.{dataset}.{source.name}")
17
33
  for column in scope.columns:
18
34
  resolved = resolve_column_path(
19
35
  column,
@@ -28,7 +44,22 @@ class ReferencesAnalyzer:
28
44
  table_path = ".".join(full_path.split(".", 3)[:3])
29
45
  _add(references, table_path, column_path)
30
46
 
31
- return _flatten_references(references)
47
+ rows = _flatten_references(references)
48
+ for table_path in tables - references.keys():
49
+ database, schema, table = table_path.split(".", 2)
50
+ rows.append(
51
+ ReferenceRow(database=database, schema=schema, table=table, column=None)
52
+ )
53
+ return sorted(
54
+ rows,
55
+ key=lambda row: (
56
+ row["database"],
57
+ row["schema"],
58
+ row["table"],
59
+ row["column"] or "",
60
+ ),
61
+ )
62
+
32
63
 
33
64
  def _add(references: dict[str, set[str]], table: str, column: str):
34
65
  if table in references:
@@ -12,7 +12,9 @@ def build_schema(
12
12
  table: str | None = None,
13
13
  ):
14
14
  resolved = (
15
- dialects.get_or_raise(dialect.lower()) if isinstance(dialect, str) else dialect
15
+ type(dialects.Dialect.get_or_raise(dialect.lower()))
16
+ if isinstance(dialect, str)
17
+ else dialect
16
18
  )
17
19
  if resolved not in SUPPORTED_DIALECTS:
18
20
  raise ValueError(f"Unsupported dialect for build_schema: {resolved.__name__}")