analytics-query-analyzer 0.2.0__py3-none-any.whl

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.
@@ -0,0 +1,4 @@
1
+ from .analyzer import analyze, analyze_timespan
2
+ from .schema_builder import build_schema
3
+
4
+ __all__ = ["analyze", "analyze_timespan", "build_schema"]
@@ -0,0 +1,54 @@
1
+ from sqlglot import dialects, optimizer, parse_one
2
+
3
+ from .references_analyzer import ReferencesAnalyzer
4
+ from .timespan_analyzer import TimespanAnalyzer
5
+
6
+
7
+ def _resolve_dialect(
8
+ dialect: str | type[dialects.Dialect],
9
+ ) -> type[dialects.Dialect]:
10
+ if isinstance(dialect, str):
11
+ return dialects.get_or_raise(dialect.lower())
12
+ return dialect
13
+
14
+
15
+ def analyze(
16
+ dialect: str | type[dialects.Dialect],
17
+ sql: str,
18
+ schema: dict,
19
+ default_project: str,
20
+ ):
21
+ dialect = _resolve_dialect(dialect)
22
+ expression = parse_one(sql, read=dialect)
23
+
24
+ qualified = optimizer.qualify.qualify(
25
+ expression,
26
+ schema=schema,
27
+ catalog=default_project,
28
+ validate_qualify_columns=False,
29
+ )
30
+ analyzer = ReferencesAnalyzer(schema, default_project)
31
+ return analyzer.analyze(qualified)
32
+
33
+
34
+ def analyze_timespan(
35
+ dialect: str | type[dialects.Dialect],
36
+ sql: str,
37
+ schema: dict,
38
+ default_project: str,
39
+ current_date_provider=None,
40
+ ) -> dict:
41
+ dialect = _resolve_dialect(dialect)
42
+ expression = parse_one(sql, read=dialect)
43
+
44
+ qualified = optimizer.qualify.qualify(
45
+ expression,
46
+ schema=schema,
47
+ catalog=default_project,
48
+ validate_qualify_columns=False,
49
+ )
50
+ analyzer = TimespanAnalyzer(schema, default_project, current_date_provider)
51
+ return analyzer.analyze(qualified)
52
+
53
+
54
+ __all__ = ["analyze", "analyze_timespan"]
@@ -0,0 +1,62 @@
1
+ from sqlglot import exp
2
+ from sqlglot.optimizer.scope import Scope
3
+
4
+
5
+ def resolve_column_path(
6
+ column: exp.Column,
7
+ scope,
8
+ default_project: str,
9
+ schema: dict,
10
+ column_extractor,
11
+ ) -> tuple[str, str] | None:
12
+ table_alias = column.table
13
+ source = scope.sources.get(table_alias)
14
+ if isinstance(source, Scope):
15
+ select_expression = None
16
+ if source.expression:
17
+ named = source.expression.named_selects
18
+ if column.name in named:
19
+ select_expression = source.expression.selects[named.index(column.name)]
20
+ if not select_expression:
21
+ return None
22
+ if isinstance(select_expression, exp.Alias):
23
+ select_expression = select_expression.this
24
+ nested_column = column_extractor(select_expression)
25
+ if not nested_column:
26
+ return None
27
+ return resolve_column_path(
28
+ nested_column, source, default_project, schema, column_extractor
29
+ )
30
+ if not isinstance(source, exp.Table):
31
+ return None
32
+
33
+ project = source.catalog or default_project
34
+ dataset = source.db
35
+ table = source.name
36
+ if not dataset and project in schema:
37
+ matches = [
38
+ dataset_name
39
+ for dataset_name, tables in schema[project].items()
40
+ if table in tables
41
+ ]
42
+ if len(matches) == 1:
43
+ dataset = matches[0]
44
+ else:
45
+ return None
46
+ if not dataset:
47
+ return None
48
+
49
+ fields = []
50
+ parent = column.parent
51
+ while isinstance(parent, exp.Dot):
52
+ fields.append(parent.expression.name)
53
+ parent = parent.parent
54
+
55
+ if column.parts[0].name == column.table:
56
+ column_full_path = ".".join(p.name for p in column.parts[1:])
57
+ else:
58
+ column_full_path = ".".join(p.name for p in column.parts)
59
+ if fields:
60
+ column_full_path = column_full_path + "." + ".".join(fields)
61
+
62
+ return f"{project}.{dataset}.{table}.{column_full_path}", column_full_path
@@ -0,0 +1,49 @@
1
+ from sqlglot import exp
2
+ from sqlglot.optimizer.scope import traverse_scope
3
+
4
+ from .column_resolver import resolve_column_path
5
+
6
+
7
+ class ReferencesAnalyzer:
8
+ def __init__(self, schema: dict, default_project: str):
9
+ self.schema = schema
10
+ self.default_project = default_project
11
+
12
+ def analyze(self, expression: exp.Expression) -> dict:
13
+ references: dict[str, set[str]] = {}
14
+
15
+ for scope in traverse_scope(expression):
16
+ for column in scope.columns:
17
+ resolved = resolve_column_path(
18
+ column,
19
+ scope,
20
+ self.default_project,
21
+ self.schema,
22
+ _extract_column,
23
+ )
24
+ if not resolved:
25
+ continue
26
+ full_path, column_path = resolved
27
+ table_path = ".".join(full_path.split(".", 3)[:3])
28
+ _add(references, table_path, column_path)
29
+
30
+ return references
31
+
32
+ def _add(references: dict[str, set[str]], table: str, column: str):
33
+ if table in references:
34
+ references[table].add(column)
35
+ else:
36
+ references[table] = {column}
37
+
38
+
39
+ def _extract_column(expr: exp.Expression) -> exp.Column | None:
40
+ if isinstance(expr, exp.Column):
41
+ return expr
42
+ if isinstance(expr, exp.Cast):
43
+ return _extract_column(expr.this)
44
+ if isinstance(expr, exp.Paren):
45
+ return _extract_column(expr.this)
46
+ columns = list(expr.find_all(exp.Column))
47
+ if len(columns) == 1:
48
+ return columns[0]
49
+ return None
@@ -0,0 +1,71 @@
1
+ from sqlglot import dialects
2
+
3
+ SUPPORTED_DIALECTS = {dialects.BigQuery}
4
+
5
+
6
+ def build_schema(
7
+ dialect: str | type[dialects.Dialect],
8
+ database: str,
9
+ schema: str | None,
10
+ table: str | None,
11
+ ):
12
+ resolved = (
13
+ dialects.get_or_raise(dialect.lower()) if isinstance(dialect, str) else dialect
14
+ )
15
+ if resolved not in SUPPORTED_DIALECTS:
16
+ raise ValueError(f"Unsupported dialect for build_schema: {resolved.__name__}")
17
+ return _build_schema_bigquery(database, schema, table)
18
+
19
+
20
+ def _build_schema_bigquery(project: str, dataset: str | None, table: str | None):
21
+ try:
22
+ from google.cloud import bigquery # noqa: F401
23
+ except ImportError as e:
24
+ raise RuntimeError(
25
+ "BigQuery support is not installed. "
26
+ "Install with: pip install analytics-query-analyzer[bigquery]"
27
+ ) from e
28
+
29
+ def _format_field_type(field) -> str:
30
+ if field.field_type == "RECORD":
31
+ parts = [
32
+ f"{child.name} {_format_field_type(child)}" for child in field.fields
33
+ ]
34
+ return f"struct<{', '.join(parts)}>"
35
+ return field.field_type.lower()
36
+
37
+ def _field_to_schema(field) -> dict | str:
38
+ if field.mode == "REPEATED":
39
+ return f"array<{_format_field_type(field)}>"
40
+ if field.field_type == "RECORD":
41
+ return {child.name: _field_to_schema(child) for child in field.fields}
42
+ return field.field_type.lower()
43
+
44
+ def _table_to_schema(table_obj: bigquery.Table) -> dict:
45
+ return {
46
+ table_obj.table_id: {
47
+ field.name: _field_to_schema(field) for field in table_obj.schema
48
+ }
49
+ }
50
+
51
+ def _dataset_to_schema(dataset_id: str) -> dict:
52
+ dataset_ref = bigquery.DatasetReference(project, dataset_id)
53
+ table_schema = {}
54
+ for table_item in client.list_tables(dataset_ref):
55
+ table_obj = client.get_table(table_item)
56
+ table_schema.update(_table_to_schema(table_obj))
57
+ return {dataset_id: table_schema}
58
+
59
+ client = bigquery.Client(project=project)
60
+ if dataset is None:
61
+ result = {}
62
+ for ds in client.list_datasets():
63
+ result.update(_dataset_to_schema(ds.dataset_id))
64
+ return {project: result}
65
+ elif table is None:
66
+ return {project: _dataset_to_schema(dataset)}
67
+ else:
68
+ dataset_ref = bigquery.DatasetReference(project, dataset)
69
+ table_ref = dataset_ref.table(table)
70
+ table_obj = client.get_table(table_ref)
71
+ return {project: {dataset: _table_to_schema(table_obj)}}
@@ -0,0 +1,596 @@
1
+ import calendar
2
+ from datetime import date, datetime, timedelta, timezone
3
+ from typing import Callable, TypeAlias, TypedDict
4
+
5
+ from sqlglot import exp
6
+ from sqlglot.optimizer.scope import traverse_scope
7
+
8
+ from .column_resolver import resolve_column_path
9
+
10
+
11
+ class TimespanBounds(TypedDict):
12
+ lower: date | None
13
+ upper: date | None
14
+
15
+
16
+ TimespanResults: TypeAlias = dict[str, TimespanBounds]
17
+
18
+
19
+ class TimespanAnalyzer:
20
+ def __init__(
21
+ self,
22
+ schema: dict,
23
+ default_project: str,
24
+ current_date_provider: Callable[[], str | date | datetime] | None = None,
25
+ ):
26
+ self.schema = schema
27
+ self.default_project = default_project
28
+ self.current_date_provider = current_date_provider or date.today
29
+
30
+ def analyze(self, expression: exp.Expression) -> dict[str, dict[str, str | None]]:
31
+ return _stringify_results(self._analyze_internal(expression))
32
+
33
+ def _analyze_internal(self, expression: exp.Expression) -> TimespanResults:
34
+ if isinstance(expression, exp.Union):
35
+ with_expr = expression.args.get("with")
36
+ left = expression.this.copy()
37
+ right = expression.expression.copy()
38
+ if with_expr:
39
+ left.set("with", with_expr)
40
+ right.set("with", with_expr)
41
+ left_bounds = self._analyze_internal(left)
42
+ right_bounds = self._analyze_internal(right)
43
+ return self.merge_bounds_union(left_bounds, right_bounds)
44
+ return self.analyze_scopes(expression)
45
+
46
+ def analyze_scopes(self, expression: exp.Expression) -> TimespanResults:
47
+ scoped_results: TimespanResults = {}
48
+ for scope in traverse_scope(expression):
49
+ conditions = []
50
+ where = scope.expression.args.get("where")
51
+ if where and where.this:
52
+ conditions.append(where.this)
53
+
54
+ qualify = scope.expression.args.get("qualify")
55
+ if qualify and qualify.this:
56
+ conditions.append(qualify.this)
57
+
58
+ having = scope.expression.args.get("having")
59
+ if having and having.this:
60
+ conditions.append(having.this)
61
+
62
+ for join in scope.expression.args.get("joins", []):
63
+ on = join.args.get("on")
64
+ if not on:
65
+ continue
66
+ if isinstance(on, exp.Expression):
67
+ conditions.append(on)
68
+
69
+ bounds = {}
70
+ for condition in conditions:
71
+ bounds = self.merge_bounds_and(
72
+ bounds, self.bounds_for_condition(condition, scope)
73
+ )
74
+ scoped_results = self.merge_bounds_and(scoped_results, bounds)
75
+
76
+ for key, value in list(scoped_results.items()):
77
+ lower = value.get("lower")
78
+ upper = value.get("upper")
79
+ if lower is not None and upper is not None and lower > upper:
80
+ scoped_results[key] = {"lower": None, "upper": None}
81
+
82
+ return scoped_results
83
+
84
+ def bounds_for_condition(self, condition: exp.Expression, scope) -> TimespanResults:
85
+ if isinstance(condition, exp.Paren):
86
+ return self.bounds_for_condition(condition.this, scope)
87
+ if isinstance(condition, exp.Not):
88
+ inner = condition.this
89
+ if isinstance(inner, exp.Paren):
90
+ inner = inner.this
91
+ if isinstance(inner, exp.GT):
92
+ return self.bounds_for_comparison(
93
+ exp.LTE(this=inner.left, expression=inner.right), scope
94
+ )
95
+ if isinstance(inner, exp.GTE):
96
+ return self.bounds_for_comparison(
97
+ exp.LT(this=inner.left, expression=inner.right), scope
98
+ )
99
+ if isinstance(inner, exp.LT):
100
+ return self.bounds_for_comparison(
101
+ exp.GTE(this=inner.left, expression=inner.right), scope
102
+ )
103
+ if isinstance(inner, exp.LTE):
104
+ return self.bounds_for_comparison(
105
+ exp.GT(this=inner.left, expression=inner.right), scope
106
+ )
107
+ return {}
108
+ if isinstance(condition, exp.And):
109
+ return self.merge_bounds_and(
110
+ self.bounds_for_condition(condition.left, scope),
111
+ self.bounds_for_condition(condition.right, scope),
112
+ )
113
+ if isinstance(condition, exp.Or):
114
+ return self.merge_bounds_or(
115
+ self.bounds_for_condition(condition.left, scope),
116
+ self.bounds_for_condition(condition.right, scope),
117
+ )
118
+ if isinstance(
119
+ condition,
120
+ (
121
+ exp.GT,
122
+ exp.GTE,
123
+ exp.LT,
124
+ exp.LTE,
125
+ exp.Between,
126
+ exp.EQ,
127
+ exp.In,
128
+ exp.NEQ,
129
+ ),
130
+ ):
131
+ return self.bounds_for_comparison(condition, scope)
132
+ return {}
133
+
134
+ def bounds_for_comparison(
135
+ self, comparison: exp.Expression, scope
136
+ ) -> TimespanResults:
137
+ if isinstance(comparison, exp.Between):
138
+ column = self.extract_column(comparison.this)
139
+ low = self.extract_literal(comparison.args.get("low"))
140
+ high = self.extract_literal(comparison.args.get("high"))
141
+ if not column:
142
+ return {}
143
+ resolved = resolve_column_path(
144
+ column, scope, self.default_project, self.schema, self.extract_column
145
+ )
146
+ if not resolved:
147
+ return {}
148
+ full_path, column_path = resolved
149
+ project, dataset, table, _ = full_path.split(".", 3)
150
+ if not self.is_time_column(project, dataset, table, column_path):
151
+ return {}
152
+ if low is None and high is None:
153
+ return {full_path: {"lower": None, "upper": None}}
154
+ return {full_path: {"lower": low, "upper": high}}
155
+
156
+ if isinstance(comparison, exp.In):
157
+ column = self.extract_column(comparison.this)
158
+ if not column:
159
+ return {}
160
+ resolved = resolve_column_path(
161
+ column, scope, self.default_project, self.schema, self.extract_column
162
+ )
163
+ if not resolved:
164
+ return {}
165
+ full_path, column_path = resolved
166
+ project, dataset, table, _ = full_path.split(".", 3)
167
+ if not self.is_time_column(project, dataset, table, column_path):
168
+ return {}
169
+ literals = [self.extract_literal(value) for value in comparison.expressions]
170
+ literal_values = [value for value in literals if value is not None]
171
+ if not literal_values:
172
+ return {full_path: {"lower": None, "upper": None}}
173
+ if len(literal_values) == 1:
174
+ return {
175
+ full_path: {"lower": literal_values[0], "upper": literal_values[0]}
176
+ }
177
+ return {
178
+ full_path: {
179
+ "lower": min(literal_values),
180
+ "upper": max(literal_values),
181
+ }
182
+ }
183
+
184
+ left = comparison.left
185
+ right = comparison.right
186
+ left_column, left_trunc_unit = self._extract_trunc_column(left)
187
+ right_column, right_trunc_unit = self._extract_trunc_column(right)
188
+ if left_column is None:
189
+ left_column = self.extract_column(left)
190
+ if right_column is None:
191
+ right_column = self.extract_column(right)
192
+ column_side = None
193
+ column = None
194
+ trunc_unit = None
195
+ if left_column:
196
+ column = left_column
197
+ column_side = "left"
198
+ trunc_unit = left_trunc_unit
199
+ elif right_column:
200
+ column = right_column
201
+ column_side = "right"
202
+ trunc_unit = right_trunc_unit
203
+ else:
204
+ left_window_column = self.extract_window_column(left)
205
+ right_window_column = self.extract_window_column(right)
206
+ if left_window_column:
207
+ column = left_window_column
208
+ column_side = "left"
209
+ elif right_window_column:
210
+ column = right_window_column
211
+ column_side = "right"
212
+ literal = (
213
+ self.extract_literal(right)
214
+ if column_side == "left"
215
+ else self.extract_literal(left)
216
+ )
217
+ if not column:
218
+ return {}
219
+
220
+ resolved = resolve_column_path(
221
+ column, scope, self.default_project, self.schema, self.extract_column
222
+ )
223
+ if not resolved:
224
+ return {}
225
+ full_path, column_path = resolved
226
+ project, dataset, table, _ = full_path.split(".", 3)
227
+ if not self.is_time_column(project, dataset, table, column_path):
228
+ return {}
229
+ if trunc_unit and literal is not None:
230
+ literal = self._truncate_date(literal, trunc_unit)
231
+ if literal is None:
232
+ return {full_path: {"lower": None, "upper": None}}
233
+
234
+ if isinstance(comparison, exp.NEQ):
235
+ return {full_path: {"lower": None, "upper": None}}
236
+
237
+ if isinstance(comparison, exp.EQ):
238
+ return {full_path: {"lower": literal, "upper": literal}}
239
+
240
+ if isinstance(comparison, (exp.GT, exp.GTE)):
241
+ bound = "lower" if column_side == "left" else "upper"
242
+ else:
243
+ bound = "upper" if column_side == "left" else "lower"
244
+
245
+ if bound == "lower":
246
+ return {full_path: {"lower": literal, "upper": None}}
247
+ return {full_path: {"lower": None, "upper": literal}}
248
+
249
+ def extract_column(self, expr: exp.Expression) -> exp.Column | None:
250
+ if isinstance(expr, exp.Column):
251
+ return expr
252
+ if isinstance(expr, exp.Cast):
253
+ return self.extract_column(expr.this)
254
+ if isinstance(expr, exp.Paren):
255
+ return self.extract_column(expr.this)
256
+ if expr.find(exp.Window):
257
+ return None
258
+ columns = list(expr.find_all(exp.Column))
259
+ if len(columns) == 1:
260
+ return columns[0]
261
+ return None
262
+
263
+ def extract_window_column(self, expr: exp.Expression) -> exp.Column | None:
264
+ if not isinstance(expr, exp.Window):
265
+ return None
266
+ if expr.this is None:
267
+ return None
268
+ columns = list(expr.this.find_all(exp.Column))
269
+ if len(columns) == 1:
270
+ return columns[0]
271
+ return None
272
+
273
+ def extract_literal(self, expr: exp.Expression) -> date | None:
274
+ if isinstance(expr, exp.Literal):
275
+ if expr.is_string:
276
+ return _normalize_iso_date(expr.this)
277
+ return None
278
+ if isinstance(expr, exp.CurrentDate):
279
+ return self._evaluate_current_date()
280
+ if isinstance(expr, (exp.CurrentDatetime, exp.CurrentTimestamp)):
281
+ return self._evaluate_current_date()
282
+ if isinstance(expr, exp.TsOrDsToDatetime):
283
+ return self.extract_literal(expr.this)
284
+ if isinstance(expr, exp.Cast):
285
+ target = expr.args.get("to")
286
+ if isinstance(target, exp.DataType):
287
+ target_type = target.this
288
+ if isinstance(target_type, exp.DataType.Type):
289
+ target_name = target_type.value
290
+ else:
291
+ target_name = str(target_type)
292
+ if target_name in {"DATE", "DATETIME", "TIMESTAMP", "TIMESTAMPTZ"}:
293
+ return self.extract_literal(expr.this)
294
+ return None
295
+ return self.extract_literal(expr.this)
296
+ if isinstance(expr, exp.Paren):
297
+ return self.extract_literal(expr.this)
298
+ if isinstance(expr, (exp.Date, exp.Datetime, exp.Timestamp, exp.Time)):
299
+ return self.extract_literal(expr.this)
300
+ trunc_types = (exp.DateTrunc, exp.DatetimeTrunc, exp.TimestampTrunc)
301
+ if isinstance(expr, trunc_types):
302
+ return self._extract_trunc_date(expr)
303
+ parse_types = (
304
+ exp.ParseDatetime,
305
+ exp.StrToDate,
306
+ exp.StrToTime,
307
+ )
308
+ if isinstance(expr, parse_types):
309
+ return self._extract_parsed_date(expr)
310
+ parts_types = (
311
+ exp.DateFromParts,
312
+ exp.TimestampFromParts,
313
+ )
314
+ if isinstance(expr, parts_types):
315
+ return self._extract_parts_date(expr)
316
+ if isinstance(expr, exp.UnixToTime):
317
+ return self._extract_epoch_date(expr)
318
+ if isinstance(expr, (exp.DateAdd, exp.DateSub)):
319
+ return self._extract_date_arithmetic(expr)
320
+ return None
321
+
322
+ def _evaluate_current_date(self) -> date | None:
323
+ if self.current_date_provider is None:
324
+ return None
325
+ value = self.current_date_provider()
326
+ if isinstance(value, datetime):
327
+ return value.date()
328
+ if isinstance(value, date):
329
+ return value
330
+ if isinstance(value, str):
331
+ return _normalize_iso_date(value)
332
+ return None
333
+
334
+ def _extract_parts_date(self, expr: exp.Expression) -> date | None:
335
+ year = self._extract_int_literal(expr.args.get("year"))
336
+ month = self._extract_int_literal(expr.args.get("month"))
337
+ day = self._extract_int_literal(expr.args.get("day"))
338
+ if year is None or month is None or day is None:
339
+ return None
340
+ return self._format_date_parts(year, month, day)
341
+
342
+ @staticmethod
343
+ def _format_date_parts(year: int, month: int, day: int) -> date | None:
344
+ if not (1 <= month <= 12 and 1 <= day <= 31):
345
+ return None
346
+ return date(year, month, day)
347
+
348
+ def _extract_parsed_date(self, expr: exp.Expression) -> date | None:
349
+ format_expr = expr.args.get("format") or expr.args.get("format_string")
350
+ string_expr = expr.args.get("string") or expr.args.get("this")
351
+ if format_expr is None or string_expr is None:
352
+ expressions = expr.expressions
353
+ if len(expressions) >= 2:
354
+ string_expr = expressions[0]
355
+ format_expr = expressions[1]
356
+ format_str = self._extract_string_literal(format_expr)
357
+ value_str = self._extract_string_literal(string_expr)
358
+ if not format_str or not value_str:
359
+ return None
360
+ try:
361
+ return datetime.strptime(value_str, format_str).date()
362
+ except ValueError:
363
+ return None
364
+
365
+ def _extract_epoch_date(self, expr: exp.Expression) -> date | None:
366
+ value = self._extract_int_literal(expr.args.get("this") or expr.this)
367
+ if value is None:
368
+ return None
369
+ scale = self._extract_int_literal(expr.args.get("scale"))
370
+ if scale == 3:
371
+ value = value / 1000
372
+ try:
373
+ return datetime.fromtimestamp(value, tz=timezone.utc).date()
374
+ except (OverflowError, OSError, ValueError):
375
+ return None
376
+
377
+ def _extract_date_arithmetic(self, expr: exp.Expression) -> date | None:
378
+ base = self.extract_literal(expr.args.get("this") or expr.this)
379
+ if base is None:
380
+ return None
381
+ delta_value = self._extract_int_literal(expr.args.get("expression"))
382
+ if delta_value is None:
383
+ return None
384
+ unit = self._extract_unit_literal(expr.args.get("unit"))
385
+ if not unit:
386
+ return None
387
+ if isinstance(expr, exp.DateSub):
388
+ delta_value = -delta_value
389
+ return self._apply_date_delta(base, delta_value, unit)
390
+
391
+ def _extract_trunc_date(self, expr: exp.Expression) -> date | None:
392
+ target = expr.args.get("this") or expr.this
393
+ unit_expr = expr.args.get("unit") or expr.args.get("part")
394
+ value = self.extract_literal(target)
395
+ unit = self._extract_unit_literal(unit_expr)
396
+ if value is None or not unit:
397
+ return None
398
+ return self._truncate_date(value, unit)
399
+
400
+ def _extract_string_literal(self, expr: exp.Expression | None) -> str | None:
401
+ if expr is None:
402
+ return None
403
+ if isinstance(expr, exp.Literal) and expr.is_string:
404
+ return expr.this
405
+ if isinstance(expr, exp.Cast):
406
+ return self._extract_string_literal(expr.this)
407
+ if isinstance(expr, exp.Paren):
408
+ return self._extract_string_literal(expr.this)
409
+ return None
410
+
411
+ def _extract_unit_literal(self, expr: exp.Expression | None) -> str | None:
412
+ if expr is None:
413
+ return None
414
+ if isinstance(expr, exp.Var):
415
+ return expr.this.upper()
416
+ literal = self._extract_string_literal(expr)
417
+ if literal:
418
+ return literal.upper()
419
+ return str(expr).upper()
420
+
421
+ def _extract_int_literal(self, expr: exp.Expression | None) -> int | None:
422
+ if expr is None:
423
+ return None
424
+ if isinstance(expr, exp.Literal):
425
+ try:
426
+ return int(expr.this)
427
+ except (TypeError, ValueError):
428
+ return None
429
+ if isinstance(expr, exp.Cast):
430
+ return self._extract_int_literal(expr.this)
431
+ if isinstance(expr, exp.Paren):
432
+ return self._extract_int_literal(expr.this)
433
+ return None
434
+
435
+ def _extract_trunc_column(
436
+ self, expr: exp.Expression
437
+ ) -> tuple[exp.Column | None, str | None]:
438
+ trunc_types = (exp.DateTrunc, exp.DatetimeTrunc, exp.TimestampTrunc)
439
+ if not isinstance(expr, trunc_types):
440
+ return None, None
441
+ target = expr.args.get("this") or expr.this
442
+ unit_expr = expr.args.get("unit") or expr.args.get("part")
443
+ column = self.extract_column(target)
444
+ unit = self._extract_unit_literal(unit_expr)
445
+ return column, unit
446
+
447
+ def _truncate_date(self, value: date, unit: str) -> date | None:
448
+ parsed = value
449
+ unit = unit.strip().upper()
450
+ if unit in {"YEAR", "YYYY"}:
451
+ return date(parsed.year, 1, 1)
452
+ if unit in {"QUARTER", "QTR"}:
453
+ quarter_start = ((parsed.month - 1) // 3) * 3 + 1
454
+ return date(parsed.year, quarter_start, 1)
455
+ if unit in {"MONTH", "MON"}:
456
+ return date(parsed.year, parsed.month, 1)
457
+ if unit in {"WEEK"}:
458
+ monday = parsed - timedelta(days=parsed.weekday())
459
+ return monday
460
+ if unit in {"DAY"}:
461
+ return parsed
462
+ return None
463
+
464
+ def _apply_date_delta(self, value: date, delta: int, unit: str) -> date | None:
465
+ parsed = value
466
+ unit = unit.strip().upper()
467
+ if unit in {"DAY", "DAYS"}:
468
+ return parsed + timedelta(days=delta)
469
+ if unit in {"WEEK", "WEEKS"}:
470
+ return parsed + timedelta(weeks=delta)
471
+ if unit in {"MONTH", "MONTHS"}:
472
+ return self._shift_month(parsed, delta)
473
+ if unit in {"YEAR", "YEARS"}:
474
+ return self._shift_month(parsed, delta * 12)
475
+ return None
476
+
477
+ @staticmethod
478
+ def _shift_month(date_value: date, months: int) -> date | None:
479
+ year = date_value.year + (date_value.month - 1 + months) // 12
480
+ month = (date_value.month - 1 + months) % 12 + 1
481
+ last_day = calendar.monthrange(year, month)[1]
482
+ day = min(date_value.day, last_day)
483
+ return date(year, month, day)
484
+
485
+ def is_time_column(
486
+ self, project: str, dataset: str, table: str, column_name: str
487
+ ) -> bool:
488
+ column_root = column_name.split(".", 1)[0]
489
+ try:
490
+ column_type = self.schema[project][dataset][table][column_root]
491
+ except KeyError:
492
+ return False
493
+ return str(column_type).lower() in {"datetime", "date", "timestamp"}
494
+
495
+ @staticmethod
496
+ def merge_bounds_and(
497
+ left: TimespanResults, right: TimespanResults
498
+ ) -> TimespanResults:
499
+ merged: TimespanResults = {}
500
+ for key in set(left) | set(right):
501
+ if key in left and key in right:
502
+ lower_left = left[key]["lower"]
503
+ lower_right = right[key]["lower"]
504
+ if lower_left is None:
505
+ lower = lower_right
506
+ elif lower_right is None:
507
+ lower = lower_left
508
+ else:
509
+ lower = max(lower_left, lower_right)
510
+
511
+ upper_left = left[key]["upper"]
512
+ upper_right = right[key]["upper"]
513
+ if upper_left is None:
514
+ upper = upper_right
515
+ elif upper_right is None:
516
+ upper = upper_left
517
+ else:
518
+ upper = min(upper_left, upper_right)
519
+
520
+ merged[key] = {"lower": lower, "upper": upper}
521
+ else:
522
+ merged[key] = left.get(key, right.get(key))
523
+ return merged
524
+
525
+ @staticmethod
526
+ def merge_bounds_or(
527
+ left: TimespanResults, right: TimespanResults
528
+ ) -> TimespanResults:
529
+ merged: TimespanResults = {}
530
+ for key in set(left) & set(right):
531
+ lower_left = left[key]["lower"]
532
+ lower_right = right[key]["lower"]
533
+ if lower_left is None or lower_right is None:
534
+ lower = None
535
+ else:
536
+ lower = min(lower_left, lower_right)
537
+
538
+ upper_left = left[key]["upper"]
539
+ upper_right = right[key]["upper"]
540
+ if upper_left is None or upper_right is None:
541
+ upper = None
542
+ else:
543
+ upper = max(upper_left, upper_right)
544
+
545
+ merged[key] = {"lower": lower, "upper": upper}
546
+ return merged
547
+
548
+ @staticmethod
549
+ def merge_bounds_union(
550
+ left: TimespanResults, right: TimespanResults
551
+ ) -> TimespanResults:
552
+ if not left:
553
+ return right
554
+ if not right:
555
+ return left
556
+ merged: TimespanResults = {}
557
+ for key in set(left) | set(right):
558
+ if key not in left:
559
+ merged[key] = right[key]
560
+ continue
561
+ if key not in right:
562
+ merged[key] = left[key]
563
+ continue
564
+ lower_left = left[key]["lower"]
565
+ lower_right = right[key]["lower"]
566
+ if lower_left is None or lower_right is None:
567
+ lower = None
568
+ else:
569
+ lower = min(lower_left, lower_right)
570
+
571
+ upper_left = left[key]["upper"]
572
+ upper_right = right[key]["upper"]
573
+ if upper_left is None or upper_right is None:
574
+ upper = None
575
+ else:
576
+ upper = max(upper_left, upper_right)
577
+
578
+ merged[key] = {"lower": lower, "upper": upper}
579
+ return merged
580
+
581
+
582
+ def _normalize_iso_date(value: str) -> date | None:
583
+ try:
584
+ return datetime.fromisoformat(value).date()
585
+ except ValueError:
586
+ return None
587
+
588
+
589
+ def _stringify_results(results: TimespanResults) -> dict[str, dict[str, str | None]]:
590
+ output: dict[str, dict[str, str | None]] = {}
591
+ for key, bounds in results.items():
592
+ output[key] = {
593
+ "lower": bounds["lower"].isoformat() if bounds["lower"] else None,
594
+ "upper": bounds["upper"].isoformat() if bounds["upper"] else None,
595
+ }
596
+ return output
@@ -0,0 +1,149 @@
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
+ # analytics-query-analyzer
16
+
17
+ Analyze analytics SQL to extract referenced tables/columns and time bounds.
18
+
19
+ ## Install
20
+
21
+ Base install:
22
+
23
+ ```bash
24
+ pip install analytics-query-analyzer
25
+ ```
26
+
27
+ BigQuery extras (only needed for `build_schema`):
28
+
29
+ ```bash
30
+ pip install analytics-query-analyzer[bigquery]
31
+ ```
32
+
33
+ ## Support
34
+
35
+ BigQuery is currently supported and tested.
36
+
37
+ ## Schema format
38
+
39
+ Schemas follow sqlglot conventions, with nested fields represented as nested dicts.
40
+
41
+ ## Usage
42
+
43
+ ### analyze
44
+
45
+ Extract table/column references from a query.
46
+
47
+ ```python
48
+ from analytics_query_analyzer import analyze
49
+ from sqlglot import dialects
50
+
51
+ schema = {
52
+ "production": {
53
+ "shop": {
54
+ "orders": {
55
+ "id": "int64",
56
+ "ordered_at": "datetime",
57
+ "user_id": "int64",
58
+ "payment": {
59
+ "amount": "int64",
60
+ "method": "string",
61
+ },
62
+ },
63
+ },
64
+ },
65
+ }
66
+
67
+ sql = """
68
+ select
69
+ id,
70
+ user_id,
71
+ payment.amount
72
+ from
73
+ shop.orders
74
+ """
75
+
76
+ references = analyze(dialects.BigQuery, sql, schema, "production")
77
+ print(references)
78
+ # {"production.shop.orders": {"id", "user_id", "payment.amount"}}
79
+ ```
80
+
81
+ ### analyze_timespan
82
+
83
+ Extract time bounds from filters.
84
+
85
+ ```python
86
+ from analytics_query_analyzer import analyze_timespan
87
+ from sqlglot import dialects
88
+
89
+ schema = {
90
+ "production": {
91
+ "shop": {
92
+ "orders": {
93
+ "id": "int64",
94
+ "ordered_at": "datetime",
95
+ "user_id": "int64",
96
+ },
97
+ },
98
+ },
99
+ }
100
+
101
+ sql = """
102
+ select
103
+ *
104
+ from
105
+ shop.orders
106
+ where
107
+ ordered_at >= "2025-01-01"
108
+ and ordered_at < "2026-01-01"
109
+ """
110
+
111
+ timespans = analyze_timespan(dialects.BigQuery, sql, schema, "production")
112
+ print(timespans)
113
+ # {
114
+ # "production.shop.orders.ordered_at": {
115
+ # "lower": "2025-01-01",
116
+ # "upper": "2026-01-01"
117
+ # }
118
+ # }
119
+ ```
120
+
121
+ To make `current_date()` deterministic, pass a provider:
122
+
123
+ ```python
124
+ timespans = analyze_timespan(
125
+ dialects.BigQuery,
126
+ "select * from shop.orders where ordered_at >= current_date()",
127
+ schema,
128
+ "production",
129
+ current_date_provider=lambda: "2026-01-01",
130
+ )
131
+ ```
132
+
133
+ ### build_schema
134
+
135
+ Fetch a schema dictionary from BigQuery.
136
+
137
+ ```python
138
+ from analytics_query_analyzer import build_schema
139
+ from sqlglot import dialects
140
+
141
+ schema = build_schema(dialects.BigQuery, "my_project", "my_schema", "my_table")
142
+ print(schema)
143
+ ```
144
+
145
+ - Authentication uses Application Default Credentials (ADC).
146
+ - Only BigQuery is supported for `build_schema`.
147
+ - When `table` is omitted, it scans all tables in the dataset.
148
+ - When both `dataset` and `table` are omitted, it scans all datasets in the project.
149
+ - The returned `schema` can be passed directly to `analyze` and `analyze_timespan`.
@@ -0,0 +1,11 @@
1
+ analytics_query_analyzer/__init__.py,sha256=rNLr3A-3sW6GEKSePeOCmcafGxNs6VXAivAXrqEOTuk,148
2
+ analytics_query_analyzer/analyzer.py,sha256=mx6YegjjrLcAf3GTNqM6heffe8K1B4ijtuAtkpAv58I,1406
3
+ analytics_query_analyzer/column_resolver.py,sha256=0NWCe6QngEcfPY9Ip6hRMDDa_kQcXp5lZFuFZ7ojJ24,1983
4
+ analytics_query_analyzer/references_analyzer.py,sha256=gH0tYNM80PxqBHWqiScUCAdtoPv7PSIkdJTnx_nrG88,1556
5
+ analytics_query_analyzer/schema_builder.py,sha256=Dt0mZ34RMuNHrhMRc64McD70F6uNJFhDe406Zr63DZ8,2574
6
+ analytics_query_analyzer/timespan_analyzer.py,sha256=QO-k9_MopP-inwAJZz4FF8ddY3Z3xB_cqx_IkR382rw,23048
7
+ analytics_query_analyzer-0.2.0.dist-info/licenses/LICENSE,sha256=MsCNF9ITw7FpLzT4AjsJePOcsZJu1uRpZ1zkmg8L-b4,1068
8
+ analytics_query_analyzer-0.2.0.dist-info/METADATA,sha256=RHvdAoNNgOILHMTp2XmuwKJZs3Q4RWrua1Yy8xXBXYQ,3142
9
+ analytics_query_analyzer-0.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
10
+ analytics_query_analyzer-0.2.0.dist-info/top_level.txt,sha256=iqLavFx5cP4IW3unwBn9ed3UuUEZ71jawcomCgV21o0,25
11
+ analytics_query_analyzer-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ryo Iketani
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ analytics_query_analyzer