metricflow-sql 0.5.3__tar.gz → 0.5.4__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 (70) hide show
  1. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/PKG-INFO +2 -2
  2. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/pyproject.toml +2 -2
  3. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/compiler.py +2 -0
  4. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/expand_datasets.py +296 -53
  5. metricflow_sql-0.5.4/src/metricflow_sql/compiler/rules/nest_windows.py +145 -0
  6. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/.gitignore +0 -0
  7. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/LICENSE +0 -0
  8. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/PYPI.md +0 -0
  9. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/README.md +0 -0
  10. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/__init__.py +0 -0
  11. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/__init__.py +0 -0
  12. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/__init__.py +0 -0
  13. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/cluster.py +0 -0
  14. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/information_schema.py +0 -0
  15. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/metadata.py +0 -0
  16. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/passthrough.py +0 -0
  17. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/protocols.py +0 -0
  18. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/semantic.py +0 -0
  19. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/guard.py +0 -0
  20. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/__init__.py +0 -0
  21. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/constellation_permissions.py +0 -0
  22. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/expand_constellations.py +0 -0
  23. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/expand_fill.py +0 -0
  24. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/expand_metadata.py +0 -0
  25. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/expand_per.py +0 -0
  26. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/isolate_fragments.py +0 -0
  27. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/passthrough_tables.py +0 -0
  28. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/table_arguments.py +0 -0
  29. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/converters/__init__.py +0 -0
  30. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/converters/legacy.py +0 -0
  31. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/converters/lookml.py +0 -0
  32. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/__init__.py +0 -0
  33. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/base.py +0 -0
  34. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/constellation.py +0 -0
  35. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/dataset.py +0 -0
  36. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/entity.py +0 -0
  37. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/reference.py +0 -0
  38. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/wiki.py +0 -0
  39. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/py.typed +0 -0
  40. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/__init__.py +0 -0
  41. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/dao.py +0 -0
  42. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/dependency_resolution.py +0 -0
  43. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/memory.py +0 -0
  44. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/operation.py +0 -0
  45. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/reference_resolution.py +0 -0
  46. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/registry.py +0 -0
  47. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/resolved.py +0 -0
  48. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/type_resolver.py +0 -0
  49. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/__init__.py +0 -0
  50. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/bundle.py +0 -0
  51. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/fragment.schema.json +0 -0
  52. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/generate.py +0 -0
  53. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/load.py +0 -0
  54. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/markdown.py +0 -0
  55. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/v1/__init__.py +0 -0
  56. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/v1/fragment.py +0 -0
  57. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/server/__init__.py +0 -0
  58. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/server/app.py +0 -0
  59. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/server/compile.py +0 -0
  60. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/server/errors.py +0 -0
  61. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/server/http.py +0 -0
  62. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/server/registry.py +0 -0
  63. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/server/serde.py +0 -0
  64. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/server/serve.py +0 -0
  65. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/utils/__init__.py +0 -0
  66. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/utils/composed_set.py +0 -0
  67. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/utils/normalize.py +0 -0
  68. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/utils/ordered_set.py +0 -0
  69. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/utils/sql.py +0 -0
  70. {metricflow_sql-0.5.3 → metricflow_sql-0.5.4}/src/metricflow_sql/utils/template.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: metricflow-sql
3
- Version: 0.5.3
3
+ Version: 0.5.4
4
4
  Summary: MetricFlow's core semantic layer engine
5
5
  Project-URL: Documentation, https://docs-internal-git-mfsql-dbt-labs.vercel.app/metricflow
6
6
  License-Expression: LicenseRef-Fivetran
@@ -12,7 +12,7 @@ Classifier: Programming Language :: Python :: 3.14
12
12
  Requires-Python: >=3.12
13
13
  Requires-Dist: jinja2>=3.1
14
14
  Requires-Dist: msgspec>=0.19
15
- Requires-Dist: sqlglot[c]>=30.32.0
15
+ Requires-Dist: sqlglot[c]>=30.33.0
16
16
  Requires-Dist: wenmode>=0.15.2
17
17
  Provides-Extra: lookml
18
18
  Requires-Dist: lkml>=1.3.7; extra == 'lookml'
@@ -1,7 +1,7 @@
1
1
  [project]
2
2
  name = "metricflow-sql"
3
3
  # A placeholder: a release sets its tag's version, with scripts/set_version.py.
4
- version = "0.5.3"
4
+ version = "0.5.4"
5
5
  description = "MetricFlow's core semantic layer engine"
6
6
  # Its PyPI page: README.md is for this repository.
7
7
  readme = "PYPI.md"
@@ -17,7 +17,7 @@ classifiers = [
17
17
  dependencies = [
18
18
  "jinja2>=3.1",
19
19
  "msgspec>=0.19",
20
- "sqlglot[c]>=30.32.0",
20
+ "sqlglot[c]>=30.33.0",
21
21
  "wenmode>=0.15.2",
22
22
  ]
23
23
 
@@ -34,6 +34,7 @@ from metricflow_sql.compiler.rules.expand_fill import expand_fills
34
34
  from metricflow_sql.compiler.rules.expand_metadata import ENGINE, ExpandMetadataRule
35
35
  from metricflow_sql.compiler.rules.expand_per import expand_per
36
36
  from metricflow_sql.compiler.rules.isolate_fragments import isolate_fragments
37
+ from metricflow_sql.compiler.rules.nest_windows import nest_windows
37
38
  from metricflow_sql.compiler.rules.passthrough_tables import name_passthrough_tables
38
39
  from metricflow_sql.compiler.table_arguments import bind_table_arguments
39
40
  from metricflow_sql.utils.normalize import normalizing_dialect
@@ -98,6 +99,7 @@ PLANNER_RULES: Sequence[OptimizerFn] = (
98
99
  ExpandDatasetsRule(),
99
100
  expand_per,
100
101
  expand_fills,
102
+ nest_windows,
101
103
  )
102
104
 
103
105
 
@@ -10,6 +10,7 @@ from sqlglot.dialects.dialect import DialectType
10
10
  from sqlglot.errors import SchemaError
11
11
  from sqlglot.optimizer.helpers import projection_has_aggregate
12
12
  from sqlglot.optimizer.optimize_joins import other_table_names
13
+ from sqlglot.optimizer.scope import find_all_in_scope
13
14
  from sqlglot.optimizer.simplify import simplify, simplify_parens
14
15
 
15
16
  from metricflow_sql.compiler.catalog.cluster import Cluster
@@ -95,6 +96,51 @@ def _is_outer_reference(
95
96
  return qualifier.name == ctx.alias or qualifier.name in ctx.datasets_by_alias
96
97
 
97
98
 
99
+ def _is_own_column(column: exp.Column, names: list[exp.Identifier]) -> bool:
100
+ """
101
+ Whether `column` may read a source of a subquery around it: its first name is a source's
102
+ alias, e.g. BigQuery's `UNNEST(periods) AS periods`, or, unqualified, a table's column.
103
+ """
104
+ head = names[0].name
105
+ # An UNNEST's own arguments can't read its alias.
106
+ unnest = column.find_ancestor(exp.Unnest)
107
+ select = column.find_ancestor(exp.Select)
108
+ while select is not None:
109
+ for source in [select.args.get("from_"), *(select.args.get("joins") or [])]:
110
+ if source is None or source.this is unnest:
111
+ continue
112
+ alias = source.this.args.get("alias")
113
+ if alias is not None and head in (alias.name, *(c.name for c in alias.columns)):
114
+ return True
115
+ if len(names) == 1 and not isinstance(source.this, exp.Unnest):
116
+ return True
117
+ select = select.find_ancestor(exp.Select)
118
+ return False
119
+
120
+
121
+ def _qualify_subquery_fields(root: exp.Expr, ctx: ExpandContext) -> None:
122
+ """
123
+ Qualifies the dataset's fields that subqueries in a calculation read, as qualify does a
124
+ query's, since inside a subquery only outer references are expanded.
125
+ """
126
+ if root.find(exp.Query) is None:
127
+ return
128
+ for column in list(root.find_all(exp.Column)):
129
+ if column.is_star or not _in_subquery(column):
130
+ continue
131
+ names = [name.copy() for name in path_names(column)]
132
+ if (
133
+ not is_shadowed(column, names[0].name)
134
+ and ctx.dataset.get_column(names[0]) is not None
135
+ and not _is_own_column(column, names)
136
+ ):
137
+ names.insert(0, exp.to_identifier(ctx.alias, quoted=True))
138
+ elif len(names) < 3:
139
+ continue
140
+ qualified = exp.column(names[1], table=names[0])
141
+ column.replace(exp.Dot.build([qualified, *names[2:]]) if len(names) > 2 else qualified)
142
+
143
+
98
144
  @dataclass
99
145
  class ExpandContext:
100
146
  registry: Registry
@@ -117,6 +163,14 @@ class ExpandContext:
117
163
  fanout_grain_by_alias: dict[str, str] = field(default_factory=dict)
118
164
  # One-to-many joins, keyed by alias, mapped to the alias of the join they fan out from.
119
165
  fanout_parents: dict[str, str] = field(default_factory=dict)
166
+ # The query's own joins on the joined dataset's whole key, which repeat no rows, mapped to
167
+ # the source whose row determines theirs, if one does.
168
+ to_one_joins: dict[str, str | None] = field(default_factory=dict)
169
+ # The query's other joins, which may repeat rows, mapped to the root if each row matches one
170
+ # of the root's.
171
+ fanout_joins: dict[str, str | None] = field(default_factory=dict)
172
+ # The query's own RIGHT and FULL joins, which add rows the root has none of.
173
+ outer_joins: set[str] = field(default_factory=set)
120
174
  aggregate_grains: dict[int, str] = field(default_factory=dict)
121
175
  dialect: DialectType = None
122
176
  # The root table's table function arguments, passed to every dataset its relationships reach.
@@ -311,6 +365,15 @@ class ExpandDatasetsRule:
311
365
  return filtered.subquery(alias, copy=False)
312
366
 
313
367
  def _expand_scope(self, select: exp.Select, ctx: ExpandContext) -> exp.Query:
368
+ joined_sources = [join.this for join in select.args.get("joins") or []]
369
+ for source in [*joined_sources, *(select.args.get("laterals") or [])]:
370
+ if isinstance(source, exp.Lateral):
371
+ self._fail(
372
+ ctx,
373
+ "Unsupported query - JOIN LATERAL onto a dataset: model it as a dataset of "
374
+ "its own, joined by a relationship",
375
+ source,
376
+ )
314
377
  order = select.args.get("order")
315
378
  # qualify writes a grouped ORDER BY key as its projection's alias, so the projection
316
379
  # writes the spine.
@@ -334,6 +397,27 @@ class ExpandDatasetsRule:
334
397
  join.set("on", self._expand_expr(on, ctx))
335
398
 
336
399
  table = join.this
400
+ joined = None
401
+ if isinstance(table, exp.Unnest):
402
+ # An array's elements repeat the dataset's rows, which only its key counts once.
403
+ if self._grain_or_none(ctx, ctx.root_alias) is None:
404
+ self._fail(
405
+ ctx,
406
+ "Unsupported query - JOIN UNNEST repeats the rows of "
407
+ f"{self._sql(ctx, ctx.dataset.name)}, which has no key: give it one, or "
408
+ "read the array in a subquery",
409
+ table,
410
+ )
411
+ arrays = [self._expand_expr(array, ctx) for array in table.expressions]
412
+ # A relationship expands to NULL, see _expand_path.
413
+ if any(isinstance(array, exp.Null) for array in arrays):
414
+ self._fail(
415
+ ctx,
416
+ "Unsupported query - JOIN UNNEST of a relationship: read its rows in a "
417
+ "subquery",
418
+ table,
419
+ )
420
+ table.set("expressions", arrays)
337
421
  if isinstance(table, exp.Table):
338
422
  joined = ctx.datasets_by_alias.get(table.alias_or_name)
339
423
  if joined:
@@ -344,6 +428,7 @@ class ExpandDatasetsRule:
344
428
  self._joined(ctx, joined[1], alias, ctx.arguments_by_alias[alias]),
345
429
  )
346
430
  prior[table.alias_or_name] = joined
431
+ self._classify_user_join(ctx, join, joined[1] if joined else None)
347
432
 
348
433
  where = select.args.get("where")
349
434
  if where is not None:
@@ -379,7 +464,7 @@ class ExpandDatasetsRule:
379
464
  # The query's PERs, calculations' included, come first: the fan-out dedup is a PER on the
380
465
  # scan's aggregates.
381
466
  scan = expand_select(select, ctx.dialect)
382
- self._fanout_per(scan.expressions, ctx, bool(user_joins))
467
+ self._fanout_per(scan.expressions, ctx)
383
468
  if havings:
384
469
  # HAVING runs before windows, unlike a filter around the query, and its fan-out PERs
385
470
  # must be expanded first, since only projections are.
@@ -555,44 +640,115 @@ class ExpandDatasetsRule:
555
640
  source_ctx = replace(ctx, dataset=dataset, alias=alias, trusted=True)
556
641
  return self._expand_expr(permission.having, source_ctx, calculation=True, agg=True)
557
642
 
558
- def _fanout_per(
559
- self,
560
- projections: list[exp.Expr],
561
- ctx: ExpandContext,
562
- user_joins: bool = False,
643
+ def _classify_user_join(
644
+ self, ctx: ExpandContext, join: exp.Join, dataset: DatasetProxy | None
563
645
  ) -> None:
646
+ """
647
+ Records whether the query's own `join` can repeat the rows before it: only a join of
648
+ `dataset` whose ON equates each field of its key to a value read from other sources
649
+ can't, e.g. `JOIN advertisers AS a ON a.advertiser_id = r.advertiser_id`.
650
+ """
651
+ # A semi or anti join only keeps or drops rows.
652
+ if join.args.get("kind") in ("SEMI", "ANTI"):
653
+ return
654
+ alias = join.alias_or_name
655
+ if join.side in ("RIGHT", "FULL"):
656
+ ctx.outer_joins.add(alias)
657
+ on = join.args.get("on")
658
+ terms = [] if on is None else _conjuncts(on)
659
+ parents = self._key_matched(ctx, terms, dataset, alias) if dataset is not None else None
660
+ if parents is not None:
661
+ ctx.to_one_joins[alias] = next(iter(parents)) if len(parents) == 1 else None
662
+ return
663
+ matched = self._key_matched(ctx, terms, ctx.dataset, ctx.root_alias)
664
+ ctx.fanout_joins[alias] = ctx.root_alias if matched == {alias} else None
665
+
666
+ def _key_matched(
667
+ self, ctx: ExpandContext, terms: list[exp.Expr], dataset: DatasetProxy, alias: str
668
+ ) -> set[str] | None:
669
+ """
670
+ The sources `terms` read to equate each field of `dataset`'s key, read as `alias`, to a
671
+ value of other sources, if they do.
672
+ """
673
+ fields = set(self._key_columns(ctx, dataset, alias) or ())
674
+ if not fields:
675
+ return None
676
+ matched: set[exp.Expr] = set()
677
+ parents: set[str] = set()
678
+ for term in terms:
679
+ if not isinstance(term, exp.EQ):
680
+ continue
681
+ for side, value in ((term.this, term.expression), (term.expression, term.this)):
682
+ read = exp.column_table_names(value)
683
+ if side in fields and alias not in read:
684
+ matched.add(side)
685
+ parents |= read
686
+ return parents if matched == fields else None
687
+
688
+ def _countable_grain(
689
+ self, ctx: ExpandContext, alias: str, aggregate: exp.AggFunc
690
+ ) -> tuple[exp.Expr, ...]:
691
+ """The grain of the source `alias`, which a join of the query's own may repeat."""
692
+ if alias != ctx.root_alias and alias not in ctx.datasets_by_alias:
693
+ self._fail(ctx, f"Aggregate crosses a fan-out join: {alias} has no key", aggregate)
694
+ grain = self._grain_or_none(ctx, alias)
695
+ if grain is None:
696
+ name = self._sql(ctx, self._dataset_at(ctx, alias).name)
697
+ self._fail(ctx, f"Aggregate crosses a fan-out join: give {name} a key", aggregate)
698
+ return grain
699
+
700
+ def _fanout_per(self, projections: list[exp.Expr], ctx: ExpandContext) -> None:
564
701
  """
565
702
  Writes each aggregate of the scan that reads a one-to-many join, or a joined dataset's
566
703
  own calculation like AGG(store.total_employees) FROM store_sales, as a PER by its grain's
567
704
  key, SUM(x) becomes SUM(MAX(x) PER (key)), so expand_per counts each row of the grain once.
568
- A permission's `having` counts its own source's rows, which a user join can repeat, as a
569
- generated join does those it joins, so its aggregates are written so for either.
705
+ The query's own joins are read as generated ones are, and a permission's `having` counts
706
+ its own source's rows whenever a join repeats them.
570
707
  """
571
- fans_out = bool(ctx.fanout_parents) or any(
572
- alias in ctx.joins for alias in ctx.aggregate_grains.values()
573
- )
574
- if not (fans_out or user_joins or ctx.joins):
708
+ repeated = ctx.joins.keys() | ctx.to_one_joins.keys()
709
+ if not (repeated or ctx.fanout_joins):
575
710
  return
711
+ fans_out = (
712
+ bool(ctx.fanout_parents)
713
+ or bool(ctx.fanout_joins)
714
+ or bool(ctx.outer_joins)
715
+ or any(alias in repeated for alias in ctx.aggregate_grains.values())
716
+ )
717
+ # The only join that may repeat rows repeats just the root's if each of its rows matches one.
718
+ unrepeated: str | None = None
719
+ if len(ctx.fanout_joins) == 1 and not ctx.fanout_parents:
720
+ [(only, parent)] = ctx.fanout_joins.items()
721
+ unrepeated = only if parent is not None else None
576
722
  determined_by_grain: dict[str, dict[str, bool]] = {}
577
723
  grains: dict[str, tuple[exp.Expr, ...]] = {}
578
724
  for projection in projections:
579
- for aggregate in list(projection.find_all(exp.AggFunc)):
725
+ for aggregate in list(find_all_in_scope(projection, exp.AggFunc)):
580
726
  if isinstance(aggregate, exp.Grouping) or is_window_function(aggregate):
581
727
  continue
582
728
  having_grain = aggregate.meta.get(_HAVING_GRAIN)
583
- if not fans_out and (
584
- having_grain is None or not (user_joins or having_grain in ctx.joins)
585
- ):
729
+ if not fans_out and (having_grain is None or having_grain not in repeated):
586
730
  continue
731
+ scan = aggregate.find_ancestor(exp.Select)
587
732
  referenced_aliases = {
588
- column.table for column in aggregate.find_all(exp.Column) if column.table
589
- }
590
- fanout_aliases = {
591
- ctx.fanout_grain_by_alias[alias]
592
- for alias in referenced_aliases
593
- if alias in ctx.fanout_grain_by_alias
733
+ column.table
734
+ for column in aggregate.find_all(exp.Column)
735
+ if column.table and not is_shadowed(column, column.table, scan)
594
736
  }
595
737
  own_alias = having_grain or ctx.aggregate_grains.get(id(aggregate), ctx.root_alias)
738
+ fanout_aliases: set[str] = set()
739
+ for alias in referenced_aliases:
740
+ if alias in ctx.fanout_grain_by_alias:
741
+ fanout_aliases.add(ctx.fanout_grain_by_alias[alias])
742
+ # A to-one join's rows repeat with the query's own join it's reached from,
743
+ # unless the aggregate counts the to-one join's own rows.
744
+ reached_from = alias
745
+ while reached_from != own_alias and (
746
+ parent := ctx.join_parents.get(reached_from)
747
+ or ctx.to_one_joins.get(reached_from)
748
+ ):
749
+ reached_from = parent
750
+ if reached_from in ctx.fanout_joins:
751
+ fanout_aliases.add(reached_from)
596
752
  grain_alias = max(
597
753
  (*fanout_aliases, own_alias), key=lambda alias: ctx.join_depths.get(alias, 0)
598
754
  )
@@ -600,8 +756,23 @@ class ExpandDatasetsRule:
600
756
  self._reject_fanout_aggregate(
601
757
  ctx, aggregate, grain_alias, referenced_aliases, determined_by_grain
602
758
  )
759
+ if grain_alias == unrepeated:
760
+ continue
761
+ # MAX(x) PER (key) keeps each row's value, not the order an aggregate reads rows in.
762
+ ordered = isinstance(aggregate.this, (exp.Order, exp.Limit, exp.HavingMax))
763
+ within_group = isinstance(aggregate.parent, exp.WithinGroup)
764
+ if ordered or within_group:
765
+ self._fail(
766
+ ctx,
767
+ "Unsupported query - an ordered aggregate across joins",
768
+ aggregate.parent if within_group else aggregate,
769
+ )
603
770
  if grain_alias not in grains:
604
- grains[grain_alias] = self._grain(ctx, grain_alias)
771
+ grains[grain_alias] = (
772
+ self._countable_grain(ctx, grain_alias, aggregate)
773
+ if _repeated_by_user_join(ctx, grain_alias)
774
+ else self._grain(ctx, grain_alias)
775
+ )
605
776
  key = grains[grain_alias]
606
777
  distinct = False
607
778
  match aggregate:
@@ -615,7 +786,7 @@ class ExpandDatasetsRule:
615
786
  value = aggregate.this
616
787
  # A row the join didn't match has NULL keys, so a value that isn't the joined
617
788
  # dataset's own column must not count for it.
618
- if grain_alias != ctx.root_alias and not (
789
+ if (grain_alias != ctx.root_alias or ctx.outer_joins) and not (
619
790
  isinstance(value, exp.Column) and value.table == grain_alias
620
791
  ):
621
792
  value = exp.case().when(
@@ -628,6 +799,40 @@ class ExpandDatasetsRule:
628
799
  per = exp.Per(this=inner, expressions=[column.copy() for column in key])
629
800
  aggregate.set("this", exp.Distinct(expressions=[per]) if distinct else per)
630
801
 
802
+ def _check_to_one_unnest(
803
+ self,
804
+ outer: ExpandContext,
805
+ ctx: ExpandContext,
806
+ target: RelationshipTarget,
807
+ names: list[exp.Identifier],
808
+ path: exp.Column | exp.Dot,
809
+ ) -> None:
810
+ """
811
+ Fails unless `names`, read from a many-to-one relationship's `target`, reach a value, e.g.
812
+ an array column, through many-to-one relationships only.
813
+ """
814
+ for name in names:
815
+ # An entity's attributes are values, which the path's expansion checks.
816
+ if not isinstance(target, DatasetTarget):
817
+ return
818
+ field = target.dataset.get_column(name)
819
+ if not isinstance(field, Relationship):
820
+ return
821
+ target, cardinality = self._relationship_target(ctx, field)
822
+ if cardinality is Cardinality.ONE_TO_MANY:
823
+ self._fail(
824
+ outer,
825
+ "Unsupported query - UNNEST needs a path that starts with a one-to-many "
826
+ "relationship",
827
+ path,
828
+ )
829
+ self._fail(
830
+ outer,
831
+ "Unsupported query - UNNEST of a many-to-one relationship, which is one row: read "
832
+ "its fields directly",
833
+ path,
834
+ )
835
+
631
836
  def _unnest_query(
632
837
  self, subquery: exp.Select, path: exp.Column | exp.Dot, outer: ExpandContext
633
838
  ) -> exp.Select:
@@ -641,6 +846,17 @@ class ExpandDatasetsRule:
641
846
  if not isinstance(relationship, Relationship):
642
847
  # An array column, e.g. `UNNEST(revenue.managers)`, is the warehouse's to unnest.
643
848
  return subquery
849
+ target, cardinality = self._relationship_target(parent, relationship)
850
+ if cardinality is not Cardinality.ONE_TO_MANY:
851
+ self._check_to_one_unnest(outer, parent, target, names[1:], path)
852
+ return subquery
853
+ if len(names) > 1:
854
+ self._fail(
855
+ outer,
856
+ "Unsupported query - UNNEST's path ends at the one-to-many relationship: read "
857
+ "its rows' fields in the subquery",
858
+ path,
859
+ )
644
860
  alias = unnest.alias
645
861
  unsupported = [
646
862
  arg
@@ -663,14 +879,6 @@ class ExpandDatasetsRule:
663
879
  " with an optional WHERE",
664
880
  path,
665
881
  )
666
- target, cardinality = self._relationship_target(parent, relationship)
667
- if cardinality is not Cardinality.ONE_TO_MANY:
668
- self._fail(
669
- outer,
670
- "Unsupported query - UNNEST needs a path that starts with a one-to-many "
671
- "relationship; read a many-to-one one directly",
672
- path,
673
- )
674
882
 
675
883
  # The related rows get joins of their own, under a context of their own: none of them is
676
884
  # the outer query's, whose aliases they don't reuse.
@@ -755,7 +963,14 @@ class ExpandDatasetsRule:
755
963
  available.add(needed)
756
964
 
757
965
  for join in user_joins:
758
- for alias in sorted(other_table_names(join) & ctx.joins.keys()):
966
+ needed = other_table_names(join)
967
+ # An UNNEST reads its array from a source, e.g. `advertiser_current.periods`.
968
+ if isinstance(join.this, exp.Unnest):
969
+ needed |= exp.column_table_names(join.this)
970
+ later = {other.alias_or_name for other in user_joins} - available
971
+ if needed & later:
972
+ self._fail(ctx, f"JOIN ON needs {min(needed & later)} before it is joined", join)
973
+ for alias in sorted(needed & ctx.joins.keys()):
759
974
  add_generated(alias)
760
975
  ordered.append(join)
761
976
  available.add(join.alias_or_name)
@@ -765,10 +980,7 @@ class ExpandDatasetsRule:
765
980
  return ordered
766
981
 
767
982
  def _join_terms(self, expression: exp.Expr, dialect: DialectType) -> set[exp.Expr]:
768
- normalized = simplify(expression, dialect=dialect).unnest()
769
- if isinstance(normalized, exp.And):
770
- return set(normalized.flatten())
771
- return {normalized}
983
+ return set(_conjuncts(simplify(expression, dialect=dialect)))
772
984
 
773
985
  def _warn_unverified_join(
774
986
  self,
@@ -832,7 +1044,7 @@ class ExpandDatasetsRule:
832
1044
  )
833
1045
  logger.warning(
834
1046
  "Join %s -> %s could not be verified as a subset of %s; "
835
- "results may have missing or duplicate rows",
1047
+ "results may have missing rows, and repeated ones where not aggregated",
836
1048
  ", ".join(sorted(sources)),
837
1049
  alias,
838
1050
  description,
@@ -851,8 +1063,10 @@ class ExpandDatasetsRule:
851
1063
  if determined is None:
852
1064
  determined = {grain_alias: True}
853
1065
  alias = grain_alias
854
- while alias in ctx.fanout_parents:
855
- alias = ctx.fanout_parents[alias]
1066
+ while (
1067
+ parent := ctx.fanout_parents.get(alias) or ctx.fanout_joins.get(alias)
1068
+ ) is not None:
1069
+ alias = parent
856
1070
  determined[alias] = True
857
1071
  determined_by_grain[grain_alias] = determined
858
1072
  for referenced_alias in referenced_aliases:
@@ -863,7 +1077,7 @@ class ExpandDatasetsRule:
863
1077
  if alias in ctx.fanout_parents:
864
1078
  determined[alias] = False
865
1079
  break
866
- parent = ctx.join_parents.get(alias)
1080
+ parent = ctx.join_parents.get(alias) or ctx.to_one_joins.get(alias)
867
1081
  if parent is None:
868
1082
  determined[alias] = False
869
1083
  break
@@ -990,14 +1204,15 @@ class ExpandDatasetsRule:
990
1204
  and isinstance(ctx.dataset.get_column(path_names(node)[0]), Relationship)
991
1205
  ):
992
1206
  return self._expand_path(list(path_names(node)), node, ctx, fill=fill)
993
- # A field of a struct expression, e.g. `{'n': x}.n`, isn't a path, nor is a qualified
994
- # function, e.g. `udfs.f(x)`.
1207
+ # Only a source's path is: not a field of a struct expression, e.g. `{'n': x}.n`, or of
1208
+ # an UNNEST's element, e.g. `h.segment`, nor a qualified function, e.g. `udfs.f(x)`.
995
1209
  if (
996
1210
  isinstance(node, exp.Dot)
997
1211
  and isinstance(node.this, exp.Column | exp.Dot)
998
1212
  and not isinstance(node.expression, exp.Func)
1213
+ and ((head := node.parts[0].name) == ctx.alias or head in ctx.datasets_by_alias)
999
1214
  ):
1000
- path_ctx = self._context_for_alias(ctx, node.parts[0].name)
1215
+ path_ctx = self._context_for_alias(ctx, head)
1001
1216
  return self._expand_relationship_path(node, path_ctx, fill)
1002
1217
  if isinstance(node, exp.Column):
1003
1218
  if not node.table or node.args["table"] == source_qualifier:
@@ -1035,6 +1250,8 @@ class ExpandDatasetsRule:
1035
1250
  return simplify_parens(wrapped, ctx.dialect)
1036
1251
 
1037
1252
  root = expr.copy()
1253
+ if calculation:
1254
+ _qualify_subquery_fields(root, ctx)
1038
1255
  key = root.unalias()
1039
1256
  return root.transform(lambda n: expand(n, fill if n is key else None), copy=False)
1040
1257
 
@@ -1331,17 +1548,34 @@ class ExpandDatasetsRule:
1331
1548
  self._fail(ctx, f"No source for {entity_name} on {dataset_name}")
1332
1549
  return source
1333
1550
 
1551
+ def _key_columns(
1552
+ self, ctx: ExpandContext, dataset: DatasetProxy, alias: str
1553
+ ) -> tuple[exp.Expr, ...] | None:
1554
+ """The physical columns of `dataset`'s key, read as `alias`."""
1555
+ key = dataset.key
1556
+ # A condition's parameters aren't fields of the rows, so they can't identify them.
1557
+ if key is None or key.conditions():
1558
+ return None
1559
+ alias_ctx = replace(ctx, dataset=dataset, alias=alias, physical=True)
1560
+ return tuple(self._expand_col(name, alias_ctx, agg=False) for name in key.fields())
1561
+
1334
1562
  def _grain(self, ctx: ExpandContext, alias: str) -> tuple[exp.Expr, ...]:
1563
+ grain = self._grain_or_none(ctx, alias)
1564
+ if grain is None:
1565
+ dataset = self._dataset_at(ctx, alias)
1566
+ reason = "its key has a condition" if dataset.key is not None else "give it a key"
1567
+ self._fail(ctx, f"Cannot determine the grain of {dataset.name}: {reason}")
1568
+ return grain
1569
+
1570
+ def _grain_or_none(self, ctx: ExpandContext, alias: str) -> tuple[exp.Expr, ...] | None:
1335
1571
  """
1336
1572
  Expressions identifying the rows of the source `alias`: its dataset's key, else the key of
1337
1573
  the entity source it was joined through, else of its dataset's only entity source.
1338
1574
  """
1339
1575
  dataset = self._dataset_at(ctx, alias)
1340
- key = dataset.key
1341
- # A condition's parameters aren't fields of the rows, so they can't identify them.
1342
- if key is not None and not key.conditions():
1343
- alias_ctx = replace(ctx, dataset=dataset, alias=alias, physical=True)
1344
- return tuple(self._expand_col(name, alias_ctx, agg=False) for name in key.fields())
1576
+ key = self._key_columns(ctx, dataset, alias)
1577
+ if key is not None:
1578
+ return key
1345
1579
  source = ctx.grain_sources.get(alias)
1346
1580
  if source is not None:
1347
1581
  return self._entity_keys_from_on(ctx, source, alias)
@@ -1352,10 +1586,7 @@ class ExpandDatasetsRule:
1352
1586
  for entity_source in dataset.get_entity_sources().values()
1353
1587
  )
1354
1588
  }
1355
- if len(grains) != 1:
1356
- reason = "its key has a condition" if key is not None else "give it a key"
1357
- self._fail(ctx, f"Cannot determine the grain of {dataset.name}: {reason}")
1358
- return next(iter(grains.values()))
1589
+ return next(iter(grains.values())) if len(grains) == 1 else None
1359
1590
 
1360
1591
  def _dataset_at(self, ctx: ExpandContext, alias: str) -> DatasetProxy:
1361
1592
  """The dataset the source `alias` reads: the root, a generated join, or a user join."""
@@ -1765,6 +1996,18 @@ def _is_alias(node: exp.Expr, select: exp.Select) -> bool:
1765
1996
  )
1766
1997
 
1767
1998
 
1999
+ def _repeated_by_user_join(ctx: ExpandContext, alias: str) -> bool:
2000
+ """Whether a join of the query's own may repeat the rows of the source `alias`."""
2001
+ if alias == ctx.root_alias:
2002
+ return bool(ctx.fanout_joins)
2003
+ return alias in ctx.to_one_joins or alias in ctx.fanout_joins
2004
+
2005
+
2006
+ def _conjuncts(condition: exp.Expr) -> list[exp.Expr]:
2007
+ unnested = condition.unnest()
2008
+ return list(unnested.flatten()) if isinstance(unnested, exp.And) else [unnested]
2009
+
2010
+
1768
2011
  def _each_row(having: exp.Expr) -> exp.Expr:
1769
2012
  """
1770
2013
  A query that doesn't aggregate treats each row as its own group. An aggregate of the outer
@@ -0,0 +1,145 @@
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+
5
+ from sqlglot import exp
6
+ from sqlglot.helper import ensure_list, find_new_name
7
+
8
+ from metricflow_sql.utils.sql import (
9
+ group_all_keys,
10
+ internal_alias,
11
+ is_shadowed,
12
+ normalize_group,
13
+ )
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+ _AGGREGATE_ARGS = ("from_", "joins", "laterals", "sample", "prewhere", "where", "group", "having")
18
+ _WINDOW_ARGS = (
19
+ "expressions",
20
+ "distinct",
21
+ "qualify",
22
+ "windows",
23
+ "order",
24
+ "sort",
25
+ "cluster",
26
+ "distribute",
27
+ )
28
+ _AGGREGATE_WRAPPERS = (exp.Filter, exp.IgnoreNulls, exp.RespectNulls, exp.WithinGroup)
29
+
30
+
31
+ def nest_windows(expression: exp.Expr) -> exp.Expr:
32
+ """
33
+ Computes the windows of every select over the rows its aggregation returns, read from a
34
+ derived table:
35
+
36
+ SELECT DATE_TRUNC('month', d) AS m, LAG(SUM(x)) OVER (ORDER BY DATE_TRUNC('month', d)) AS p
37
+ FROM t GROUP BY DATE_TRUNC('month', d)
38
+ =>
39
+ SELECT aggregated.m AS m, LAG(aggregated._agg_1) OVER (ORDER BY aggregated.m) AS p
40
+ FROM (
41
+ SELECT DATE_TRUNC('month', d) AS m, SUM(x) AS _agg_1
42
+ FROM t GROUP BY DATE_TRUNC('month', d)
43
+ ) AS aggregated
44
+ """
45
+ selects = dict.fromkeys(window.parent_select for window in expression.find_all(exp.Window))
46
+ if not selects:
47
+ return expression
48
+ aliases = {source.name for source in expression.find_all(exp.Table, exp.TableAlias)}
49
+ for select in selects:
50
+ if select is not None:
51
+ _nest(select, aliases)
52
+ return expression
53
+
54
+
55
+ def _nest(select: exp.Select, aliases: set[str]) -> None:
56
+ dimensions = _dimensions(select)
57
+ if dimensions is None:
58
+ return
59
+ read = _grouped_reads(select, dimensions)
60
+ if not read:
61
+ return
62
+
63
+ used = {projection.alias_or_name for projection in select.expressions}
64
+ projected: dict[exp.Expr, exp.Identifier] = {}
65
+ for node in read:
66
+ if isinstance(node.parent, exp.Alias) and node.parent.parent is select:
67
+ projected.setdefault(node, node.parent.args["alias"])
68
+ names: dict[exp.Expr, exp.Identifier] = {}
69
+ for index, node in enumerate(dict.fromkeys(read)):
70
+ name = projected.get(node)
71
+ if name is None or any(name.name == other.name for other in names.values()):
72
+ prefix = "_dim" if node in dimensions else "_agg"
73
+ name = exp.to_identifier(internal_alias(used, f"{prefix}_{index}"))
74
+ names[node] = name
75
+
76
+ alias = find_new_name(aliases, "aggregated")
77
+ aliases.add(alias)
78
+ for node in read:
79
+ column = exp.column(names[node].copy(), table=alias, copy=False)
80
+ node.replace(column.as_(node.output_name, copy=False) if node.parent is select else column)
81
+ inner = exp.Select(
82
+ expressions=[exp.alias_(node, name.copy(), copy=False) for node, name in names.items()]
83
+ )
84
+ for arg in _AGGREGATE_ARGS:
85
+ moved = select.args.get(arg)
86
+ if moved:
87
+ select.set(arg, None)
88
+ inner.set(arg, moved)
89
+ select.set("from_", exp.From(this=inner.subquery(alias, copy=False)))
90
+
91
+
92
+ def _grouped_reads(select: exp.Select, dimensions: list[exp.Expr]) -> list[exp.Expr]:
93
+ """
94
+ The GROUP BY keys and aggregates the select's windows and what runs after them read, each as
95
+ it's written, or none when they read another column of the select's sources. A subquery's
96
+ own expression can equal one of them, e.g. an aggregate over the same table.
97
+ """
98
+ sources = {
99
+ source.alias_or_name
100
+ for source in (select.args.get("from_"), *(select.args.get("joins") or []))
101
+ if source
102
+ }
103
+ read: list[exp.Expr] = []
104
+
105
+ def own(column: exp.Column) -> bool:
106
+ return column.table in sources and not is_shadowed(column, column.table, select)
107
+
108
+ def collect(node: exp.Expr, nested: bool) -> bool:
109
+ if (not nested and _is_aggregate(node)) or (
110
+ node in dimensions and (not nested or all(map(own, node.find_all(exp.Column))))
111
+ ):
112
+ read.append(node)
113
+ return True
114
+ if isinstance(node, exp.Column) and own(node):
115
+ return False
116
+ return all(
117
+ collect(child, nested or isinstance(node, exp.Query))
118
+ for child in node.iter_expressions()
119
+ )
120
+
121
+ clauses = [clause for arg in _WINDOW_ARGS for clause in ensure_list(select.args.get(arg))]
122
+ return read if all(collect(clause, False) for clause in clauses) else []
123
+
124
+
125
+ def _dimensions(select: exp.Select) -> list[exp.Expr] | None:
126
+ group = select.args.get("group")
127
+ if group is None:
128
+ return []
129
+ if group.args.get("all") and not group.expressions:
130
+ keys = [select.expressions[index].unalias() for index in group_all_keys(select)]
131
+ else:
132
+ keys = [key for grouping_set in normalize_group(group) for key in grouping_set]
133
+ if any(key.is_int for key in keys):
134
+ return None
135
+ return [key for key in dict.fromkeys(keys) if key.find(exp.Column) is not None]
136
+
137
+
138
+ def _is_aggregate(node: exp.Expr) -> bool:
139
+ aggregate = node
140
+ while isinstance(aggregate, _AGGREGATE_WRAPPERS):
141
+ aggregate = aggregate.this
142
+ if not isinstance(aggregate, exp.AggFunc):
143
+ return False
144
+ parent = node.parent
145
+ return not (isinstance(parent, (*_AGGREGATE_WRAPPERS, exp.Window)) and parent.this is node)
File without changes
File without changes
File without changes