analytics-query-analyzer 0.6.0__tar.gz → 0.7.1__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 (33) hide show
  1. analytics_query_analyzer-0.7.1/.github/dependabot.yml +10 -0
  2. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/.github/workflows/pytest.yml +2 -1
  3. {analytics_query_analyzer-0.6.0/src/analytics_query_analyzer.egg-info → analytics_query_analyzer-0.7.1}/PKG-INFO +14 -5
  4. analytics_query_analyzer-0.6.0/PKG-INFO → analytics_query_analyzer-0.7.1/README.md +10 -19
  5. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/pyproject.toml +2 -1
  6. analytics_query_analyzer-0.7.1/src/analytics_query_analyzer/analyzer.py +216 -0
  7. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/src/analytics_query_analyzer/column_resolver.py +45 -6
  8. analytics_query_analyzer-0.7.1/src/analytics_query_analyzer/references_analyzer.py +146 -0
  9. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/src/analytics_query_analyzer/schema_builder.py +3 -1
  10. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/src/analytics_query_analyzer/timebounds_analyzer.py +354 -77
  11. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/src/analytics_query_analyzer/types.py +3 -3
  12. analytics_query_analyzer-0.6.0/README.md → analytics_query_analyzer-0.7.1/src/analytics_query_analyzer.egg-info/PKG-INFO +28 -3
  13. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/src/analytics_query_analyzer.egg-info/SOURCES.txt +7 -1
  14. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/src/analytics_query_analyzer.egg-info/requires.txt +4 -1
  15. analytics_query_analyzer-0.7.1/src/analytics_query_analyzer.egg-info/scm_file_list.json +26 -0
  16. analytics_query_analyzer-0.7.1/src/analytics_query_analyzer.egg-info/scm_version.json +8 -0
  17. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/tests/test_analyze_bigquery.py +67 -3
  18. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/tests/test_analyze_redshift.py +2 -2
  19. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/tests/test_analyze_with_timebounds_bigquery.py +3 -3
  20. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/tests/test_analyze_with_timebounds_redshift.py +3 -3
  21. analytics_query_analyzer-0.7.1/tests/test_api_validation.py +49 -0
  22. analytics_query_analyzer-0.7.1/tests/test_bigquery_special_tables.py +173 -0
  23. analytics_query_analyzer-0.7.1/tests/test_timebounds_safety.py +277 -0
  24. analytics_query_analyzer-0.6.0/src/analytics_query_analyzer/analyzer.py +0 -90
  25. analytics_query_analyzer-0.6.0/src/analytics_query_analyzer/references_analyzer.py +0 -69
  26. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/.github/workflows/publish-pypi.yml +0 -0
  27. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/.github/workflows/publish-testpypi.yml +0 -0
  28. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/.gitignore +0 -0
  29. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/LICENSE +0 -0
  30. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/setup.cfg +0 -0
  31. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/src/analytics_query_analyzer/__init__.py +0 -0
  32. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/src/analytics_query_analyzer.egg-info/dependency_links.txt +0 -0
  33. {analytics_query_analyzer-0.6.0 → analytics_query_analyzer-0.7.1}/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.1
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"]
@@ -2,6 +2,26 @@ from sqlglot import exp
2
2
  from sqlglot.optimizer.scope import Scope
3
3
 
4
4
 
5
+ def _fields_after(column: exp.Column) -> list[str]:
6
+ fields = []
7
+ node = column
8
+ while node.parent is not None:
9
+ parent = node.parent
10
+ if isinstance(parent, exp.Dot) and parent.this is node:
11
+ fields.append(parent.expression.name)
12
+ elif (
13
+ isinstance(parent, exp.Bracket)
14
+ and parent.this is node
15
+ and isinstance(node.type, exp.DataType)
16
+ and node.type.this == exp.DataType.Type.ARRAY
17
+ ):
18
+ pass
19
+ else:
20
+ break
21
+ node = parent
22
+ return fields
23
+
24
+
5
25
  def resolve_column_path(
6
26
  column: exp.Column,
7
27
  scope,
@@ -12,6 +32,22 @@ def resolve_column_path(
12
32
  table_alias = column.table
13
33
  source = scope.sources.get(table_alias)
14
34
  if isinstance(source, Scope):
35
+ fields = _fields_after(column)
36
+ if isinstance(source.expression, exp.Unnest):
37
+ expressions = source.expression.expressions
38
+ nested_column = (
39
+ column_extractor(expressions[0]) if len(expressions) == 1 else None
40
+ )
41
+ if not nested_column:
42
+ return None
43
+ resolved = resolve_column_path(
44
+ nested_column, source, default_catalog, schema, column_extractor
45
+ )
46
+ if not resolved:
47
+ return None
48
+ full_path, column_path = resolved
49
+ suffix = ".".join(fields)
50
+ return (f"{full_path}.{suffix}", f"{column_path}.{suffix}") if suffix else resolved
15
51
  select_expression = None
16
52
  if source.expression:
17
53
  named = source.expression.named_selects
@@ -21,12 +57,19 @@ def resolve_column_path(
21
57
  return None
22
58
  if isinstance(select_expression, exp.Alias):
23
59
  select_expression = select_expression.this
60
+ if fields and not isinstance(select_expression, exp.Column):
61
+ return None
24
62
  nested_column = column_extractor(select_expression)
25
63
  if not nested_column:
26
64
  return None
27
- return resolve_column_path(
65
+ resolved = resolve_column_path(
28
66
  nested_column, source, default_catalog, schema, column_extractor
29
67
  )
68
+ if not resolved or not fields:
69
+ return resolved
70
+ full_path, column_path = resolved
71
+ suffix = ".".join(fields)
72
+ return f"{full_path}.{suffix}", f"{column_path}.{suffix}"
30
73
  if not isinstance(source, exp.Table):
31
74
  return None
32
75
 
@@ -46,11 +89,7 @@ def resolve_column_path(
46
89
  if not dataset:
47
90
  return None
48
91
 
49
- fields = []
50
- parent = column.parent
51
- while isinstance(parent, exp.Dot):
52
- fields.append(parent.expression.name)
53
- parent = parent.parent
92
+ fields = _fields_after(column)
54
93
 
55
94
  if column.parts[0].name == column.table:
56
95
  column_full_path = ".".join(p.name for p in column.parts[1:])
@@ -0,0 +1,146 @@
1
+ from sqlglot import exp
2
+ from sqlglot.optimizer.scope import traverse_scope
3
+
4
+ from .column_resolver import resolve_column_path
5
+ from .types import ReferenceRow
6
+
7
+
8
+ class ReferencesAnalyzer:
9
+ def __init__(self, schema: dict, default_catalog: str):
10
+ self.schema = schema
11
+ self.default_catalog = default_catalog
12
+
13
+ def analyze(self, expression: exp.Expression) -> list[ReferenceRow]:
14
+ references: dict[str, set[str]] = {}
15
+ tables: set[str] = set()
16
+
17
+ scopes = list(traverse_scope(expression))
18
+ intermediate: dict[str, set[str]] = {}
19
+ explicit: dict[str, set[str]] = {}
20
+ # Only narrow passthroughs in simple queries. In other query shapes,
21
+ # projections can affect results even if only a field is read later
22
+ # (for example, DISTINCT, grouping, ordering, and scalar subqueries).
23
+ may_narrow = not any(
24
+ expression.find(kind)
25
+ for kind in (
26
+ exp.SetOperation,
27
+ exp.Distinct,
28
+ exp.Group,
29
+ exp.Having,
30
+ exp.Order,
31
+ exp.Limit,
32
+ exp.Qualify,
33
+ exp.Subquery,
34
+ exp.AggFunc,
35
+ exp.Window,
36
+ exp.Array,
37
+ exp.Struct,
38
+ )
39
+ ) and all(
40
+ isinstance(join.this, exp.Unnest) for join in expression.find_all(exp.Join)
41
+ ) and all(
42
+ not select.args.get("kind") for select in expression.find_all(exp.Select)
43
+ )
44
+ for scope in scopes:
45
+ for _, source in scope.selected_sources.values():
46
+ if not isinstance(source, exp.Table):
47
+ continue
48
+ project = source.catalog or self.default_catalog
49
+ dataset = source.db
50
+ if not dataset:
51
+ matches = [
52
+ name
53
+ for name, values in self.schema.get(project, {}).items()
54
+ if source.name in values
55
+ ]
56
+ if len(matches) != 1:
57
+ continue
58
+ dataset = matches[0]
59
+ tables.add(f"{project}.{dataset}.{source.name}")
60
+ for column in scope.columns:
61
+ resolved = resolve_column_path(
62
+ column,
63
+ scope,
64
+ self.default_catalog,
65
+ self.schema,
66
+ _extract_column,
67
+ )
68
+ if not resolved:
69
+ continue
70
+ full_path, column_path = resolved
71
+ table_path = ".".join(full_path.split(".", 3)[:3])
72
+ _add(references, table_path, column_path)
73
+ is_projection = (
74
+ isinstance(column.parent, exp.Alias)
75
+ and column.parent.parent is scope.expression
76
+ )
77
+ is_intermediate = may_narrow and (
78
+ (
79
+ scope is not scopes[-1]
80
+ and is_projection
81
+ )
82
+ or column.find_ancestor(exp.Unnest) is not None
83
+ )
84
+ _add(intermediate if is_intermediate else explicit, table_path, column_path)
85
+
86
+ for table_path, columns in intermediate.items():
87
+ for column in columns - explicit.get(table_path, set()):
88
+ if any(
89
+ other.startswith(column + ".") for other in references[table_path]
90
+ ):
91
+ references[table_path].discard(column)
92
+
93
+ rows = _flatten_references(references)
94
+ for table_path in tables - references.keys():
95
+ database, schema, table = table_path.split(".", 2)
96
+ rows.append(
97
+ ReferenceRow(database=database, schema=schema, table=table, column=None)
98
+ )
99
+ return sorted(
100
+ rows,
101
+ key=lambda row: (
102
+ row["database"],
103
+ row["schema"],
104
+ row["table"],
105
+ row["column"] or "",
106
+ ),
107
+ )
108
+
109
+
110
+ def _add(references: dict[str, set[str]], table: str, column: str):
111
+ if table in references:
112
+ references[table].add(column)
113
+ else:
114
+ references[table] = {column}
115
+
116
+
117
+ def _flatten_references(references: dict[str, set[str]]) -> list[ReferenceRow]:
118
+ rows: list[ReferenceRow] = []
119
+ for table_path, columns in references.items():
120
+ database, schema, table = table_path.split(".", 2)
121
+ for column in columns:
122
+ rows.append(
123
+ ReferenceRow(
124
+ database=database,
125
+ schema=schema,
126
+ table=table,
127
+ column=column,
128
+ )
129
+ )
130
+ rows.sort(
131
+ key=lambda row: (row["database"], row["schema"], row["table"], row["column"])
132
+ )
133
+ return rows
134
+
135
+
136
+ def _extract_column(expr: exp.Expression) -> exp.Column | None:
137
+ if isinstance(expr, exp.Column):
138
+ return expr
139
+ if isinstance(expr, exp.Cast):
140
+ return _extract_column(expr.this)
141
+ if isinstance(expr, exp.Paren):
142
+ return _extract_column(expr.this)
143
+ columns = list(expr.find_all(exp.Column))
144
+ if len(columns) == 1:
145
+ return columns[0]
146
+ return None
@@ -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__}")