metricflow-sql 0.3.2__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/PKG-INFO +1 -1
  2. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/pyproject.toml +1 -1
  3. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/rules/expand_datasets.py +113 -12
  4. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/rules/expand_per.py +91 -23
  5. metricflow_sql-0.4.0/src/metricflow_sql/converters/legacy.py +1323 -0
  6. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/converters/lookml.py +55 -7
  7. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/schemas/fragment.schema.json +1 -1
  8. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/schemas/v1/fragment.py +9 -1
  9. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/server/serve.py +9 -0
  10. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/.gitignore +0 -0
  11. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/LICENSE +0 -0
  12. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/PYPI.md +0 -0
  13. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/README.md +0 -0
  14. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/__init__.py +0 -0
  15. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/__init__.py +0 -0
  16. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/catalog/__init__.py +0 -0
  17. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/catalog/cluster.py +0 -0
  18. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/catalog/information_schema.py +0 -0
  19. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/catalog/metadata.py +0 -0
  20. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/catalog/passthrough.py +0 -0
  21. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/catalog/protocols.py +0 -0
  22. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/catalog/semantic.py +0 -0
  23. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/compiler.py +0 -0
  24. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/rules/__init__.py +0 -0
  25. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/rules/expand_constellations.py +0 -0
  26. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/rules/expand_metadata.py +0 -0
  27. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/rules/isolate_fragments.py +0 -0
  28. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/rules/passthrough_tables.py +0 -0
  29. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/compiler/table_arguments.py +0 -0
  30. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/converters/__init__.py +0 -0
  31. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/objects/__init__.py +0 -0
  32. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/objects/base.py +0 -0
  33. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/objects/constellation.py +0 -0
  34. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/objects/dataset.py +0 -0
  35. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/objects/entity.py +0 -0
  36. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/objects/reference.py +0 -0
  37. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/objects/wiki.py +0 -0
  38. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/py.typed +0 -0
  39. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/registry/__init__.py +0 -0
  40. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/registry/memory.py +0 -0
  41. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/registry/operation.py +0 -0
  42. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/registry/reference_resolution.py +0 -0
  43. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/registry/registry.py +0 -0
  44. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/registry/type_resolver.py +0 -0
  45. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/schemas/__init__.py +0 -0
  46. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/schemas/bundle.py +0 -0
  47. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/schemas/generate.py +0 -0
  48. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/schemas/load.py +0 -0
  49. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/schemas/markdown.py +0 -0
  50. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/schemas/v1/__init__.py +0 -0
  51. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/server/__init__.py +0 -0
  52. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/server/app.py +0 -0
  53. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/server/compile.py +0 -0
  54. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/server/errors.py +0 -0
  55. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/server/http.py +0 -0
  56. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/server/registry.py +0 -0
  57. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/server/serde.py +0 -0
  58. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/utils/__init__.py +0 -0
  59. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/utils/composed_set.py +0 -0
  60. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/utils/normalize.py +0 -0
  61. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/utils/ordered_set.py +0 -0
  62. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/src/metricflow_sql/utils/sql.py +0 -0
  63. {metricflow_sql-0.3.2 → metricflow_sql-0.4.0}/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.3.2
3
+ Version: 0.4.0
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
@@ -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.3.2"
4
+ version = "0.4.0"
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"
@@ -83,6 +83,9 @@ class ExpandContext:
83
83
  dialect: DialectType = None
84
84
  # The root table's table function arguments, passed to every dataset its relationships reach.
85
85
  arguments: dict[str, exp.Expr] = field(default_factory=dict)
86
+ # The key values each generated join was reached with, by its alias. This is needed to propagate
87
+ # keys across relationship paths.
88
+ reached_with: dict[str, dict[exp.Identifier, exp.Expr]] = field(default_factory=dict)
86
89
 
87
90
 
88
91
  class ExpandDatasetsRule:
@@ -452,7 +455,14 @@ class ExpandDatasetsRule:
452
455
  *,
453
456
  calculation: bool = False,
454
457
  agg: bool = False,
458
+ passed_keys: dict[str, exp.Expr] | None = None,
455
459
  ) -> exp.Expr:
460
+ """
461
+ Expands `expr`'s fields and paths.
462
+
463
+ `passed_keys` are the values of the `:name` placeholders from relationships
464
+ """
465
+
456
466
  def recurse(node: exp.Expr) -> exp.Expr:
457
467
  # `AGG(calc) FILTER (WHERE c)` filters every aggregate the calculation has, e.g.
458
468
  # `SUM(a) - SUM(b)` becomes `SUM(a) FILTER (WHERE c) - SUM(b) FILTER (WHERE c)`, and
@@ -497,6 +507,8 @@ class ExpandDatasetsRule:
497
507
  return aggfunc
498
508
  if isinstance(node, exp.AggFunc) and not is_window_function(node):
499
509
  ctx.aggregate_grains[id(node)] = ctx.alias
510
+ if passed_keys and isinstance(node, exp.Placeholder) and node.name in passed_keys:
511
+ return passed_keys[node.name].copy()
500
512
  if calculation and isinstance(node, exp.Placeholder):
501
513
  parameters = {name.name: name for name in ctx.dataset.parameters}
502
514
  resolved = resolve_name(node.name, parameters)
@@ -620,14 +632,16 @@ class ExpandDatasetsRule:
620
632
  if not key:
621
633
  return exp.null()
622
634
  # A PER's relationship stands for its key, as a tuple of its values.
623
- _, cardinality = self._relationship_target(ctx, field)
635
+ per_target, cardinality = self._relationship_target(ctx, field)
624
636
  if cardinality is Cardinality.ONE_TO_MANY:
625
637
  self._fail(
626
638
  ctx,
627
639
  "Unsupported query - PER by a one-to-many relationship",
628
640
  expr,
629
641
  )
630
- values = self._key_values(ctx, field.key, dataset, dataset_alias)
642
+ values = self._key_values(
643
+ ctx, field, per_target, dataset, dataset_alias
644
+ )
631
645
  return exp.Tuple(expressions=list(values.values()))
632
646
  match self._relationship_target(ctx, field):
633
647
  case EntityTarget(entity=target_entity), target_cardinality:
@@ -641,8 +655,15 @@ class ExpandDatasetsRule:
641
655
  and remaining[0] in field.key
642
656
  and target.get_column(remaining[0]) is not None
643
657
  ):
644
- value = field.key[remaining[0]]
645
- return self._key_value(ctx, value, dataset, dataset_alias)
658
+ value = self._relationship_key_value(
659
+ ctx,
660
+ field,
661
+ DatasetTarget(target),
662
+ remaining[0],
663
+ dataset,
664
+ dataset_alias,
665
+ )
666
+ return exp.null() if value is None else value
646
667
  dataset_alias = self._register_dataset_join(
647
668
  ctx, field, target, cardinality, dataset, dataset_alias
648
669
  )
@@ -665,7 +686,11 @@ class ExpandDatasetsRule:
665
686
  if name in relationship.key and cardinality is Cardinality.MANY_TO_ONE:
666
687
  if remaining:
667
688
  self._fail(ctx, "Unsupported relationship path", expr)
668
- return self._key_value(ctx, relationship.key[name], dataset, dataset_alias)
689
+ # An optional key the relationship leaves unbound reads as NULL.
690
+ value = self._relationship_key_value(
691
+ ctx, relationship, EntityTarget(entity), name, dataset, dataset_alias
692
+ )
693
+ return exp.null() if value is None else value
669
694
  attribute = entity.get_column(name)
670
695
  if attribute is None:
671
696
  entity_name = self._sql(ctx, entity.name)
@@ -859,7 +884,10 @@ class ExpandDatasetsRule:
859
884
  ctx.join_datasets[alias] = dataset
860
885
  # The entity's key, from the source's `on`, is the grain of the rows it joins.
861
886
  ctx.grain_sources[alias] = source
862
- values = self._key_values(ctx, relationship.key, parent, parent_alias)
887
+ values = self._key_values(ctx, relationship, EntityTarget(entity), parent, parent_alias)
888
+ ctx.reached_with[alias] = {
889
+ name: value for name, value in values.items() if name in entity.key
890
+ }
863
891
  on = (
864
892
  self._bind_join_keys(ctx, source.on, values, alias)
865
893
  if cardinality is Cardinality.MANY_TO_ONE
@@ -929,7 +957,9 @@ class ExpandDatasetsRule:
929
957
  if alias in ctx.joins:
930
958
  return alias
931
959
  ctx.join_datasets[alias] = target
932
- values = self._key_values(ctx, relationship.key, parent, parent_alias)
960
+ values = self._key_values(ctx, relationship, DatasetTarget(target), parent, parent_alias)
961
+ names = target.key.names() if target.key is not None else ()
962
+ ctx.reached_with[alias] = {name: value for name, value in values.items() if name in names}
933
963
  ctx.joins[alias] = exp.Join(
934
964
  this=exp.alias_(target.from_(ctx.arguments), alias, copy=False),
935
965
  on=self._dataset_join_on(ctx, relationship, target, alias, values),
@@ -987,24 +1017,95 @@ class ExpandDatasetsRule:
987
1017
  def _key_values(
988
1018
  self,
989
1019
  ctx: ExpandContext,
990
- key: dict[exp.Identifier, exp.Expr],
1020
+ relationship: Relationship,
1021
+ target: RelationshipTarget,
991
1022
  dataset: DatasetProxy,
992
1023
  alias: str,
993
1024
  ) -> dict[exp.Identifier, exp.Expr]:
994
- """A relationship's key, read from `dataset` joined as `alias`."""
995
- return {name: self._key_value(ctx, expr, dataset, alias) for name, expr in key.items()}
1025
+ """
1026
+ `relationship`'s key, read from `dataset` joined as `alias`, without the optional keys
1027
+ that pass on a key `alias` wasn't reached with, see _key_value.
1028
+ """
1029
+ values: dict[exp.Identifier, exp.Expr] = {}
1030
+ for name in relationship.key:
1031
+ value = self._relationship_key_value(ctx, relationship, target, name, dataset, alias)
1032
+ if value is not None:
1033
+ values[name] = value
1034
+ return values
1035
+
1036
+ def _relationship_key_value(
1037
+ self,
1038
+ ctx: ExpandContext,
1039
+ relationship: Relationship,
1040
+ target: RelationshipTarget,
1041
+ name: exp.Identifier,
1042
+ dataset: DatasetProxy,
1043
+ alias: str,
1044
+ ) -> exp.Expr | None:
1045
+ value = self._key_value(ctx, relationship.key[name], dataset, alias)
1046
+ if value is not None:
1047
+ return value
1048
+ match target:
1049
+ case EntityTarget(entity=entity) if name in entity.key and entity.key[name].optional:
1050
+ return None
1051
+ where = f"{self._sql(ctx, relationship.dataset)}.{self._sql(ctx, relationship.name)}"
1052
+ self._fail(
1053
+ ctx,
1054
+ f"Relationship {where} can't bind {self._sql(ctx, name)}: "
1055
+ f"{self._sql(ctx, dataset.name)} wasn't reached with the key it passes on, and only "
1056
+ "an entity's optional key can be left unbound",
1057
+ )
996
1058
 
997
1059
  def _key_value(
998
1060
  self, ctx: ExpandContext, expr: exp.Expr, dataset: DatasetProxy, alias: str
999
- ) -> exp.Expr:
1061
+ ) -> exp.Expr | None:
1000
1062
  """
1001
1063
  A value of a relationship's key, read from `dataset` joined as `alias` like a calculation
1002
1064
  is, so it can read other fields and paths, e.g. `_item.i_item_id`.
1065
+
1066
+ A `:name` placeholder passes on a key value `alias` was reached with.
1003
1067
  """
1068
+ placeholders = list(expr.find_all(exp.Placeholder))
1069
+ passed: dict[str, exp.Expr] = {}
1070
+ if placeholders:
1071
+ parameters = [name.name for name in dataset.parameters]
1072
+ keys = {name.name: name for name in self._passable_keys(ctx, dataset)}
1073
+ reached_with = ctx.reached_with.get(alias, {})
1074
+ for placeholder in placeholders:
1075
+ key = resolve_name(placeholder.name, keys)
1076
+ is_parameter = resolve_name(placeholder.name, parameters) is not None
1077
+ dataset_name = self._sql(ctx, dataset.name)
1078
+ if key is None:
1079
+ if not is_parameter:
1080
+ self._fail(
1081
+ ctx,
1082
+ f"Dataset {dataset_name} has no parameter or key {placeholder.name}",
1083
+ )
1084
+ continue
1085
+ if is_parameter:
1086
+ self._fail(
1087
+ ctx,
1088
+ f":{placeholder.name} of dataset {dataset_name} is ambiguous: it names "
1089
+ "both a parameter and a key the dataset can be reached with",
1090
+ )
1091
+ value = reached_with.get(keys[key])
1092
+ if value is None:
1093
+ return None
1094
+ passed[placeholder.name] = value
1004
1095
  return self._expand_expr(
1005
- expr, replace(ctx, dataset=dataset, alias=alias), calculation=True, agg=False
1096
+ expr,
1097
+ replace(ctx, dataset=dataset, alias=alias),
1098
+ calculation=True,
1099
+ agg=False,
1100
+ passed_keys=passed,
1006
1101
  )
1007
1102
 
1103
+ def _passable_keys(self, ctx: ExpandContext, dataset: DatasetProxy) -> set[exp.Identifier]:
1104
+ names = set(dataset.key.names()) if dataset.key is not None else set()
1105
+ for source in dataset.get_entity_sources().values():
1106
+ names.update(self._entity(ctx, source.entity).key)
1107
+ return names
1108
+
1008
1109
  def _bind_join_keys(
1009
1110
  self,
1010
1111
  ctx: ExpandContext,
@@ -207,11 +207,9 @@ def _restrict(
207
207
  Restricts the aggregate to the rows of groups: aggregate FILTER (WHERE grouped._group_id IN
208
208
  (ids)). A filter, unlike a CASE argument, also keeps the other rows out of ARRAY_AGG.
209
209
  """
210
- if group_id_alias is None:
210
+ test = _group_test(group_id_alias, [set_ids[group] for group in groups])
211
+ if test is None:
211
212
  return
212
- ids = sorted(set_ids[group] for group in groups)
213
- group_id = exp.column(group_id_alias, table="grouped")
214
- test = group_id.eq(ids[0]) if len(ids) == 1 else group_id.isin(*ids, copy=False)
215
213
  if isinstance(aggregate.parent, exp.Filter):
216
214
  where = aggregate.parent.args["expression"]
217
215
  where.set("this", exp.and_(where.this, test, copy=False))
@@ -221,6 +219,46 @@ def _restrict(
221
219
  filtered.set("this", aggregate)
222
220
 
223
221
 
222
+ def _group_test(group_id_alias: str | None, ids: list[int]) -> exp.Expr | None:
223
+ """grouped._group_id IN (ids), or None when every row is of one grouping set."""
224
+ if group_id_alias is None:
225
+ return None
226
+ unique_ids = sorted(set(ids))
227
+ group_id = exp.column(group_id_alias, table="grouped")
228
+ if len(unique_ids) == 1:
229
+ return group_id.eq(unique_ids[0])
230
+ return group_id.isin(*unique_ids, copy=False)
231
+
232
+
233
+ def _set_target(
234
+ targets: dict[frozenset[exp.Expr], frozenset[exp.Expr]],
235
+ grouping_set: tuple[exp.Expr, ...],
236
+ target: tuple[exp.Expr, ...],
237
+ unit: exp.Expr,
238
+ dialect: DialectType,
239
+ ) -> None:
240
+ """Records the group grouping_set's rows collapse into. A row can only be in one."""
241
+ if targets.setdefault(frozenset(grouping_set), frozenset(target)) != frozenset(target):
242
+ _fail(
243
+ dialect,
244
+ "Unsupported query - a PER cannot add a column another grouping set already groups by",
245
+ unit,
246
+ )
247
+
248
+
249
+ def _masked(node: exp.Expr, masks: dict[str, tuple[exp.Expr, exp.Expr | None]]) -> exp.Expr:
250
+ """
251
+ Reads a grouped dimension or GROUPING as its target group does: the replacement on the
252
+ rows of the sets that add it, e.g. CASE WHEN grouped._group_id = 1 THEN NULL ELSE grouped.c END.
253
+ """
254
+ if not isinstance(node, exp.Column) or node.table != "grouped" or node.name not in masks:
255
+ return node
256
+ replacement, test = masks[node.name]
257
+ if test is None:
258
+ return replacement.copy()
259
+ return exp.case().when(test.copy(), replacement.copy()).else_(node.copy())
260
+
261
+
224
262
  def _from_grouped(node: exp.Expr, aliases: dict[exp.Expr, str]) -> exp.Expr:
225
263
  if node in aliases:
226
264
  return exp.column(aliases[node], table="grouped")
@@ -243,10 +281,18 @@ def _expand_level(
243
281
  rows = scan(projections, requested_groups, needs)
244
282
  return rows, rows
245
283
  grouped_dims = list(dict.fromkeys(dim for group in requested_groups for dim in group))
246
-
247
- # A PER column in every requested group adds no grain. One in some of them is another
248
- # PER's, whose rows this PER would collapse.
249
- common = frozenset.intersection(*(frozenset(group) for group in requested_groups))
284
+ # A projection reading the scan's values without an aggregate, e.g. a constellation metric
285
+ # moved out of a PER beside another PER, is computed by the scan too.
286
+ for index, (projection, units) in enumerate(zip(projections, units_by_projection, strict=True)):
287
+ if not units and any(
288
+ isinstance(node, exp.Column) and node not in grouped_dims
289
+ for node in walk_in_scope(projection.this, prune=lambda node: node in grouped_dims)
290
+ ):
291
+ units_by_projection[index] = [projection.this]
292
+
293
+ # The group each grouping set's rows collapse into: its own, or for a PER's set the group
294
+ # the PER is read at. The outer select drops the dimensions a set adds to its group.
295
+ targets: dict[frozenset[exp.Expr], frozenset[exp.Expr]] = {}
250
296
  sets_by_per: dict[int, list[tuple[exp.Expr, ...]]] = {}
251
297
  references_by_per: dict[int, list[exp.Column]] = {}
252
298
  collapses: dict[int, tuple[exp.AggFunc, list[tuple[exp.Expr, ...]]]] = {}
@@ -268,12 +314,17 @@ def _expand_level(
268
314
  "Unsupported query - PER must be the argument of an aggregate without OVER",
269
315
  unit,
270
316
  )
317
+ groups = needs.get(projection.alias, requested_groups)
318
+ # A PER column in every group the projection is read at adds no grain.
319
+ common = frozenset.intersection(*(frozenset(group) for group in groups))
271
320
  # The collapse, or its FILTER, may read the PER columns, e.g. ARG_MAX(c, AGG(x) PER (c)).
321
+ # The scan projects the ones the PER adds, which the outer select drops as dimensions.
272
322
  scope = collapse.parent if isinstance(collapse.parent, exp.Filter) else collapse
273
323
  references = [
274
324
  node
275
325
  for node in walk_in_scope(scope, prune=lambda node: isinstance(node, exp.Per))
276
- if isinstance(node, exp.Column) and node not in grouped_dims
326
+ if isinstance(node, exp.Column)
327
+ and (node not in grouped_dims or (node in unit.expressions and node not in common))
277
328
  ]
278
329
  for column in references:
279
330
  if column not in unit.expressions:
@@ -286,18 +337,18 @@ def _expand_level(
286
337
  # An aggregate calculation reads as NULL here, a literal is a constant: no grain.
287
338
  if not all(column.find(exp.Column) for column in unit.expressions):
288
339
  _fail(dialect, "Unsupported query - PER needs a column", unit)
289
- columns = [column for column in unit.expressions if column not in common]
290
- if any(column in grouped_dims for column in columns):
291
- _fail(
292
- dialect,
293
- "Unsupported query - GROUPING SETS cannot overlap the PER columns",
294
- unit,
295
- )
296
- sets_by_per[id(unit)] = [
297
- tuple(dim.copy() for dim in (*group, *columns))
298
- for group in needs.get(projection.alias, requested_groups)
299
- ]
300
- collapses[id(collapse)] = (collapse, sets_by_per[id(unit)])
340
+ sets = []
341
+ for group in groups:
342
+ columns = [column for column in unit.expressions if column not in group]
343
+ grouping_set = tuple(dim.copy() for dim in dict.fromkeys((*group, *columns)))
344
+ _set_target(targets, grouping_set, group, unit, dialect)
345
+ sets.append(grouping_set)
346
+ sets_by_per[id(unit)] = sets
347
+ collapses[id(collapse)] = (collapse, sets)
348
+ for unit in units:
349
+ if not isinstance(unit, (exp.Per, exp.Grouping)):
350
+ for group in needs.get(projection.alias, requested_groups):
351
+ _set_target(targets, group, group, unit, dialect)
301
352
 
302
353
  # A plain aggregate needs the groups its projection is read at, a PER its sets.
303
354
  inner_groups = list(
@@ -323,6 +374,15 @@ def _expand_level(
323
374
  group: sum(weight for dim, weight in weights.items() if dim not in group)
324
375
  for group in inner_groups
325
376
  }
377
+ # A set's rows collapse into its target group, so the outer select reads the dimensions the
378
+ # set adds as NULL and their GROUPING as 1. E.g. beside SUM(x) at (c), AVG(SUM(x) PER (c))
379
+ # read at (g) collapses the rows at (g, c) into the group (g).
380
+ added_ids: dict[exp.Expr, list[int]] = {}
381
+ for group in inner_groups:
382
+ target = targets[frozenset(group)]
383
+ for dim in group:
384
+ if dim in grouped_dims and dim not in target:
385
+ added_ids.setdefault(dim, []).append(set_ids[group])
326
386
 
327
387
  used_aliases = {projection.alias for projection in projections}
328
388
  group_id_alias = internal_alias(used_aliases, "_group_id") if id_dims else None
@@ -399,9 +459,17 @@ def _expand_level(
399
459
 
400
460
  inner, rows = _expand_level(inner_projections, inner_groups, inner_needs, scan, dialect)
401
461
 
462
+ masks: dict[str, tuple[exp.Expr, exp.Expr | None]] = {}
463
+ for dim, ids in added_ids.items():
464
+ test = _group_test(group_id_alias, ids)
465
+ masks[dimension_aliases[dim]] = (exp.null(), test)
466
+ masks[slots[exp.Grouping(expressions=[dim.copy()])]] = (exp.Literal.number(1), test)
467
+
402
468
  outer_projections = [
403
469
  exp.alias_(
404
- projection.this.transform(_from_grouped, dimension_aliases, copy=False),
470
+ projection.this.transform(_from_grouped, dimension_aliases, copy=False).transform(
471
+ _masked, masks, copy=False
472
+ ),
405
473
  projection.alias,
406
474
  copy=False,
407
475
  )
@@ -419,7 +487,7 @@ def _expand_level(
419
487
  ),
420
488
  ]
421
489
  if outer_group:
422
- outer.group_by(*outer_group, copy=False)
490
+ outer.group_by(*(_masked(key, masks) for key in outer_group), copy=False)
423
491
  return outer, rows
424
492
 
425
493