metricflow-sql 0.5.2__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.2 → metricflow_sql-0.5.4}/PKG-INFO +2 -2
  2. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/pyproject.toml +2 -2
  3. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/compiler.py +2 -0
  4. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/expand_constellations.py +2 -0
  5. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/expand_datasets.py +299 -57
  6. metricflow_sql-0.5.4/src/metricflow_sql/compiler/rules/nest_windows.py +145 -0
  7. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/converters/legacy.py +66 -13
  8. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/converters/lookml.py +79 -14
  9. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/.gitignore +0 -0
  10. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/LICENSE +0 -0
  11. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/PYPI.md +0 -0
  12. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/README.md +0 -0
  13. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/__init__.py +0 -0
  14. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/__init__.py +0 -0
  15. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/__init__.py +0 -0
  16. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/cluster.py +0 -0
  17. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/information_schema.py +0 -0
  18. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/metadata.py +0 -0
  19. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/passthrough.py +0 -0
  20. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/protocols.py +0 -0
  21. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/catalog/semantic.py +0 -0
  22. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/guard.py +0 -0
  23. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/__init__.py +0 -0
  24. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/constellation_permissions.py +0 -0
  25. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/expand_fill.py +0 -0
  26. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/expand_metadata.py +0 -0
  27. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/expand_per.py +0 -0
  28. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/isolate_fragments.py +0 -0
  29. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/rules/passthrough_tables.py +0 -0
  30. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/compiler/table_arguments.py +0 -0
  31. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/converters/__init__.py +0 -0
  32. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/__init__.py +0 -0
  33. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/base.py +0 -0
  34. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/constellation.py +0 -0
  35. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/dataset.py +0 -0
  36. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/entity.py +0 -0
  37. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/reference.py +0 -0
  38. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/objects/wiki.py +0 -0
  39. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/py.typed +0 -0
  40. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/__init__.py +0 -0
  41. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/dao.py +0 -0
  42. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/dependency_resolution.py +0 -0
  43. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/memory.py +0 -0
  44. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/operation.py +0 -0
  45. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/reference_resolution.py +0 -0
  46. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/registry.py +0 -0
  47. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/resolved.py +0 -0
  48. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/registry/type_resolver.py +0 -0
  49. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/__init__.py +0 -0
  50. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/bundle.py +0 -0
  51. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/fragment.schema.json +0 -0
  52. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/generate.py +0 -0
  53. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/load.py +0 -0
  54. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/markdown.py +0 -0
  55. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/v1/__init__.py +0 -0
  56. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/schemas/v1/fragment.py +0 -0
  57. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/server/__init__.py +0 -0
  58. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/server/app.py +0 -0
  59. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/server/compile.py +0 -0
  60. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/server/errors.py +0 -0
  61. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/server/http.py +0 -0
  62. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/server/registry.py +0 -0
  63. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/server/serde.py +0 -0
  64. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/server/serve.py +0 -0
  65. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/utils/__init__.py +0 -0
  66. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/utils/composed_set.py +0 -0
  67. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/utils/normalize.py +0 -0
  68. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/utils/ordered_set.py +0 -0
  69. {metricflow_sql-0.5.2 → metricflow_sql-0.5.4}/src/metricflow_sql/utils/sql.py +0 -0
  70. {metricflow_sql-0.5.2 → 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.2
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.31.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.2"
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.31.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
 
@@ -1064,6 +1064,8 @@ class ExpandConstellationsRule:
1064
1064
  return grouped(sets)
1065
1065
 
1066
1066
  projections = [exp.alias_(expr, name) for name, expr in translated.items()] + leaves()
1067
+ if not projections:
1068
+ projections = [exp.Literal.number(1)]
1067
1069
  groupings = [translated[name] for name in groupable]
1068
1070
  group = exp.Group(expressions=groupings) if groupings and not ctx.stack else None
1069
1071
  order = None
@@ -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,54 +640,139 @@ 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
- grain_alias = (
596
- max(fanout_aliases, key=lambda alias: ctx.join_depths[alias])
597
- if fanout_aliases
598
- else having_grain or ctx.aggregate_grains.get(id(aggregate), ctx.root_alias)
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)
752
+ grain_alias = max(
753
+ (*fanout_aliases, own_alias), key=lambda alias: ctx.join_depths.get(alias, 0)
599
754
  )
600
755
  if referenced_aliases:
601
756
  self._reject_fanout_aggregate(
602
757
  ctx, aggregate, grain_alias, referenced_aliases, determined_by_grain
603
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
+ )
604
770
  if grain_alias not in grains:
605
- 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
+ )
606
776
  key = grains[grain_alias]
607
777
  distinct = False
608
778
  match aggregate:
@@ -616,7 +786,7 @@ class ExpandDatasetsRule:
616
786
  value = aggregate.this
617
787
  # A row the join didn't match has NULL keys, so a value that isn't the joined
618
788
  # dataset's own column must not count for it.
619
- if grain_alias != ctx.root_alias and not (
789
+ if (grain_alias != ctx.root_alias or ctx.outer_joins) and not (
620
790
  isinstance(value, exp.Column) and value.table == grain_alias
621
791
  ):
622
792
  value = exp.case().when(
@@ -629,6 +799,40 @@ class ExpandDatasetsRule:
629
799
  per = exp.Per(this=inner, expressions=[column.copy() for column in key])
630
800
  aggregate.set("this", exp.Distinct(expressions=[per]) if distinct else per)
631
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
+
632
836
  def _unnest_query(
633
837
  self, subquery: exp.Select, path: exp.Column | exp.Dot, outer: ExpandContext
634
838
  ) -> exp.Select:
@@ -642,6 +846,17 @@ class ExpandDatasetsRule:
642
846
  if not isinstance(relationship, Relationship):
643
847
  # An array column, e.g. `UNNEST(revenue.managers)`, is the warehouse's to unnest.
644
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
+ )
645
860
  alias = unnest.alias
646
861
  unsupported = [
647
862
  arg
@@ -664,14 +879,6 @@ class ExpandDatasetsRule:
664
879
  " with an optional WHERE",
665
880
  path,
666
881
  )
667
- target, cardinality = self._relationship_target(parent, relationship)
668
- if cardinality is not Cardinality.ONE_TO_MANY:
669
- self._fail(
670
- outer,
671
- "Unsupported query - UNNEST needs a path that starts with a one-to-many "
672
- "relationship; read a many-to-one one directly",
673
- path,
674
- )
675
882
 
676
883
  # The related rows get joins of their own, under a context of their own: none of them is
677
884
  # the outer query's, whose aliases they don't reuse.
@@ -756,7 +963,14 @@ class ExpandDatasetsRule:
756
963
  available.add(needed)
757
964
 
758
965
  for join in user_joins:
759
- 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()):
760
974
  add_generated(alias)
761
975
  ordered.append(join)
762
976
  available.add(join.alias_or_name)
@@ -766,10 +980,7 @@ class ExpandDatasetsRule:
766
980
  return ordered
767
981
 
768
982
  def _join_terms(self, expression: exp.Expr, dialect: DialectType) -> set[exp.Expr]:
769
- normalized = simplify(expression, dialect=dialect).unnest()
770
- if isinstance(normalized, exp.And):
771
- return set(normalized.flatten())
772
- return {normalized}
983
+ return set(_conjuncts(simplify(expression, dialect=dialect)))
773
984
 
774
985
  def _warn_unverified_join(
775
986
  self,
@@ -833,7 +1044,7 @@ class ExpandDatasetsRule:
833
1044
  )
834
1045
  logger.warning(
835
1046
  "Join %s -> %s could not be verified as a subset of %s; "
836
- "results may have missing or duplicate rows",
1047
+ "results may have missing rows, and repeated ones where not aggregated",
837
1048
  ", ".join(sorted(sources)),
838
1049
  alias,
839
1050
  description,
@@ -852,8 +1063,10 @@ class ExpandDatasetsRule:
852
1063
  if determined is None:
853
1064
  determined = {grain_alias: True}
854
1065
  alias = grain_alias
855
- while alias in ctx.fanout_parents:
856
- 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
857
1070
  determined[alias] = True
858
1071
  determined_by_grain[grain_alias] = determined
859
1072
  for referenced_alias in referenced_aliases:
@@ -864,7 +1077,7 @@ class ExpandDatasetsRule:
864
1077
  if alias in ctx.fanout_parents:
865
1078
  determined[alias] = False
866
1079
  break
867
- parent = ctx.join_parents.get(alias)
1080
+ parent = ctx.join_parents.get(alias) or ctx.to_one_joins.get(alias)
868
1081
  if parent is None:
869
1082
  determined[alias] = False
870
1083
  break
@@ -991,14 +1204,15 @@ class ExpandDatasetsRule:
991
1204
  and isinstance(ctx.dataset.get_column(path_names(node)[0]), Relationship)
992
1205
  ):
993
1206
  return self._expand_path(list(path_names(node)), node, ctx, fill=fill)
994
- # A field of a struct expression, e.g. `{'n': x}.n`, isn't a path, nor is a qualified
995
- # 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)`.
996
1209
  if (
997
1210
  isinstance(node, exp.Dot)
998
1211
  and isinstance(node.this, exp.Column | exp.Dot)
999
1212
  and not isinstance(node.expression, exp.Func)
1213
+ and ((head := node.parts[0].name) == ctx.alias or head in ctx.datasets_by_alias)
1000
1214
  ):
1001
- path_ctx = self._context_for_alias(ctx, node.parts[0].name)
1215
+ path_ctx = self._context_for_alias(ctx, head)
1002
1216
  return self._expand_relationship_path(node, path_ctx, fill)
1003
1217
  if isinstance(node, exp.Column):
1004
1218
  if not node.table or node.args["table"] == source_qualifier:
@@ -1036,6 +1250,8 @@ class ExpandDatasetsRule:
1036
1250
  return simplify_parens(wrapped, ctx.dialect)
1037
1251
 
1038
1252
  root = expr.copy()
1253
+ if calculation:
1254
+ _qualify_subquery_fields(root, ctx)
1039
1255
  key = root.unalias()
1040
1256
  return root.transform(lambda n: expand(n, fill if n is key else None), copy=False)
1041
1257
 
@@ -1332,17 +1548,34 @@ class ExpandDatasetsRule:
1332
1548
  self._fail(ctx, f"No source for {entity_name} on {dataset_name}")
1333
1549
  return source
1334
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
+
1335
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:
1336
1571
  """
1337
1572
  Expressions identifying the rows of the source `alias`: its dataset's key, else the key of
1338
1573
  the entity source it was joined through, else of its dataset's only entity source.
1339
1574
  """
1340
1575
  dataset = self._dataset_at(ctx, alias)
1341
- key = dataset.key
1342
- # A condition's parameters aren't fields of the rows, so they can't identify them.
1343
- if key is not None and not key.conditions():
1344
- alias_ctx = replace(ctx, dataset=dataset, alias=alias, physical=True)
1345
- 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
1346
1579
  source = ctx.grain_sources.get(alias)
1347
1580
  if source is not None:
1348
1581
  return self._entity_keys_from_on(ctx, source, alias)
@@ -1353,10 +1586,7 @@ class ExpandDatasetsRule:
1353
1586
  for entity_source in dataset.get_entity_sources().values()
1354
1587
  )
1355
1588
  }
1356
- if len(grains) != 1:
1357
- reason = "its key has a condition" if key is not None else "give it a key"
1358
- self._fail(ctx, f"Cannot determine the grain of {dataset.name}: {reason}")
1359
- return next(iter(grains.values()))
1589
+ return next(iter(grains.values())) if len(grains) == 1 else None
1360
1590
 
1361
1591
  def _dataset_at(self, ctx: ExpandContext, alias: str) -> DatasetProxy:
1362
1592
  """The dataset the source `alias` reads: the root, a generated join, or a user join."""
@@ -1766,6 +1996,18 @@ def _is_alias(node: exp.Expr, select: exp.Select) -> bool:
1766
1996
  )
1767
1997
 
1768
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
+
1769
2011
  def _each_row(having: exp.Expr) -> exp.Expr:
1770
2012
  """
1771
2013
  A query that doesn't aggregate treats each row as its own group. An aggregate of the outer