metricflow-sql 0.3.1__tar.gz → 0.3.2__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.1 → metricflow_sql-0.3.2}/PKG-INFO +3 -3
  2. metricflow_sql-0.3.2/PYPI.md +5 -0
  3. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/pyproject.toml +2 -2
  4. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/compiler.py +2 -0
  5. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/rules/expand_constellations.py +377 -39
  6. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/rules/expand_datasets.py +157 -325
  7. metricflow_sql-0.3.2/src/metricflow_sql/compiler/rules/expand_per.py +464 -0
  8. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/converters/lookml.py +122 -23
  9. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/objects/wiki.py +4 -1
  10. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/registry/type_resolver.py +5 -0
  11. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/schemas/bundle.py +188 -12
  12. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/schemas/fragment.schema.json +13 -7
  13. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/schemas/load.py +4 -2
  14. metricflow_sql-0.3.2/src/metricflow_sql/schemas/markdown.py +105 -0
  15. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/schemas/v1/fragment.py +28 -6
  16. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/utils/sql.py +51 -1
  17. metricflow_sql-0.3.1/PYPI.md +0 -5
  18. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/.gitignore +0 -0
  19. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/LICENSE +0 -0
  20. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/README.md +0 -0
  21. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/__init__.py +0 -0
  22. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/__init__.py +0 -0
  23. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/catalog/__init__.py +0 -0
  24. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/catalog/cluster.py +0 -0
  25. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/catalog/information_schema.py +0 -0
  26. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/catalog/metadata.py +0 -0
  27. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/catalog/passthrough.py +0 -0
  28. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/catalog/protocols.py +0 -0
  29. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/catalog/semantic.py +0 -0
  30. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/rules/__init__.py +0 -0
  31. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/rules/expand_metadata.py +0 -0
  32. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/rules/isolate_fragments.py +0 -0
  33. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/rules/passthrough_tables.py +0 -0
  34. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/compiler/table_arguments.py +0 -0
  35. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/converters/__init__.py +0 -0
  36. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/objects/__init__.py +0 -0
  37. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/objects/base.py +0 -0
  38. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/objects/constellation.py +0 -0
  39. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/objects/dataset.py +0 -0
  40. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/objects/entity.py +0 -0
  41. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/objects/reference.py +0 -0
  42. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/py.typed +0 -0
  43. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/registry/__init__.py +0 -0
  44. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/registry/memory.py +0 -0
  45. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/registry/operation.py +0 -0
  46. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/registry/reference_resolution.py +0 -0
  47. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/registry/registry.py +0 -0
  48. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/schemas/__init__.py +0 -0
  49. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/schemas/generate.py +0 -0
  50. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/schemas/v1/__init__.py +0 -0
  51. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/server/__init__.py +0 -0
  52. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/server/app.py +0 -0
  53. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/server/compile.py +0 -0
  54. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/server/errors.py +0 -0
  55. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/server/http.py +0 -0
  56. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/server/registry.py +0 -0
  57. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/server/serde.py +0 -0
  58. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/server/serve.py +0 -0
  59. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/utils/__init__.py +0 -0
  60. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/utils/composed_set.py +0 -0
  61. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/utils/normalize.py +0 -0
  62. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/utils/ordered_set.py +0 -0
  63. {metricflow_sql-0.3.1 → metricflow_sql-0.3.2}/src/metricflow_sql/utils/template.py +0 -0
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: metricflow-sql
3
- Version: 0.3.1
3
+ Version: 0.3.2
4
4
  Summary: MetricFlow's core semantic layer engine
5
- Project-URL: Documentation, https://congenial-bassoon-7zkjv8w.pages.github.io/
5
+ Project-URL: Documentation, https://docs-internal-git-mfsql-dbt-labs.vercel.app/metricflow
6
6
  License-Expression: LicenseRef-Fivetran
7
7
  License-File: LICENSE
8
8
  Classifier: Programming Language :: Python :: 3
@@ -27,4 +27,4 @@ Description-Content-Type: text/markdown
27
27
 
28
28
  Something is cooking...
29
29
 
30
- [Documentation](https://congenial-bassoon-7zkjv8w.pages.github.io/), for design partners with access.
30
+ [Documentation](https://docs-internal-git-mfsql-dbt-labs.vercel.app/metricflow), for design partners, with the password we share with them.
@@ -0,0 +1,5 @@
1
+ # metricflow-sql
2
+
3
+ Something is cooking...
4
+
5
+ [Documentation](https://docs-internal-git-mfsql-dbt-labs.vercel.app/metricflow), for design partners, with the password we share with them.
@@ -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.1"
4
+ version = "0.3.2"
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"
@@ -37,7 +37,7 @@ server = [
37
37
  ]
38
38
 
39
39
  [project.urls]
40
- Documentation = "https://congenial-bassoon-7zkjv8w.pages.github.io/"
40
+ Documentation = "https://docs-internal-git-mfsql-dbt-labs.vercel.app/metricflow"
41
41
 
42
42
  [build-system]
43
43
  requires = ["hatchling"]
@@ -25,6 +25,7 @@ from metricflow_sql.compiler.catalog.semantic import SemanticCatalog
25
25
  from metricflow_sql.compiler.rules.expand_constellations import ExpandConstellationsRule
26
26
  from metricflow_sql.compiler.rules.expand_datasets import ExpandDatasetsRule
27
27
  from metricflow_sql.compiler.rules.expand_metadata import ENGINE, ExpandMetadataRule
28
+ from metricflow_sql.compiler.rules.expand_per import expand_per
28
29
  from metricflow_sql.compiler.rules.isolate_fragments import isolate_fragments
29
30
  from metricflow_sql.compiler.rules.passthrough_tables import name_passthrough_tables
30
31
  from metricflow_sql.compiler.table_arguments import bind_table_arguments
@@ -87,6 +88,7 @@ PLANNER_RULES: Sequence[OptimizerFn] = (
87
88
  ExpandMetadataRule(),
88
89
  ExpandConstellationsRule(),
89
90
  ExpandDatasetsRule(),
91
+ expand_per,
90
92
  )
91
93
 
92
94
 
@@ -14,12 +14,24 @@ from sqlglot.optimizer.simplify import simplify_parens
14
14
 
15
15
  from metricflow_sql.compiler.catalog.cluster import Cluster
16
16
  from metricflow_sql.compiler.catalog.semantic import SemanticCatalog
17
+ from metricflow_sql.compiler.rules.expand_per import expand_over
17
18
  from metricflow_sql.compiler.table_arguments import TABLE_ARGUMENTS
18
19
  from metricflow_sql.objects.base import resolve_dataset_path
19
20
  from metricflow_sql.objects.constellation import Metric, Role
21
+ from metricflow_sql.objects.dataset import Relationship
20
22
  from metricflow_sql.registry.reference_resolution import resolve_metric
21
23
  from metricflow_sql.registry.registry import ConstellationProxy, Registry
22
- from metricflow_sql.utils.sql import group_all_keys, normalize_group, path_names, table_scopes
24
+ from metricflow_sql.utils.sql import (
25
+ group_all_keys,
26
+ group_of_sets,
27
+ in_per,
28
+ internal_alias,
29
+ is_window_function,
30
+ normalize_group,
31
+ path_names,
32
+ per_argument,
33
+ table_scopes,
34
+ )
23
35
 
24
36
  logger = logging.getLogger(__name__)
25
37
 
@@ -41,16 +53,24 @@ def _prefixed(column: exp.Column, name: exp.Identifier) -> exp.Expr:
41
53
  return _column(name.copy(), *path_names(column))
42
54
 
43
55
 
56
+ def _joined_column(node: exp.Expr, alias: str) -> str | None:
57
+ """The name a column of the joined rows reads, e.g. universe.sales_amount gives sales_amount."""
58
+ if isinstance(node, exp.Column) and node.table == alias:
59
+ return node.name
60
+ return None
61
+
62
+
44
63
  def _replace(node: exp.Expr, replacement: exp.Expr) -> exp.Expr:
45
64
  """
46
65
  Returns `replacement` to stand in for `node` in a transform, parenthesized when `node` sits
47
66
  inside a larger expression, e.g. a metric `a + b` in `100 * AGG(metric)` gives `100 * (a + b)`.
48
67
 
49
68
  sqlglot doesn't parenthesize a replaced node, so it's always wrapped here, and the rule drops
50
- the parentheses that aren't needed once the query is expanded.
69
+ the parentheses that aren't needed once the query is expanded. A column needs none, and a
70
+ transform doesn't look inside a replacement, so wrapping it would leave them in.
51
71
  """
52
- if node.parent is not None:
53
- return exp.Paren(this=replacement)
72
+ if node.parent is not None and not isinstance(replacement, exp.Column):
73
+ return exp.paren(replacement, copy=False)
54
74
  return replacement
55
75
 
56
76
 
@@ -227,6 +247,7 @@ class ExpandConstellationsRule:
227
247
  )
228
248
  for projection in select.expressions
229
249
  ]
250
+ collapse = self._pushdown_per(projections, ctx)
230
251
  if ctx.leaves:
231
252
  datasets = list(dict.fromkeys(leaf.dataset for leaf in ctx.leaves.values()))
232
253
  elif ctx.keys:
@@ -234,6 +255,8 @@ class ExpandConstellationsRule:
234
255
  else:
235
256
  self._fail(ctx, "Constellation queries must aggregate a metric or group by roles")
236
257
 
258
+ if collapse:
259
+ return self._collapse_over_branches(projections, datasets, condition, ctx)
237
260
  if ctx.stack:
238
261
  branches = [self._branch(dataset, condition, ctx) for dataset in datasets]
239
262
  rows = exp.union(*branches, distinct=False, copy=False) if branches[1:] else branches[0]
@@ -299,14 +322,23 @@ class ExpandConstellationsRule:
299
322
  100 * AGG(store_return_rate) -> 100 * (return_amount / sales_amount)
300
323
  """
301
324
  # Any other aggregate or window would run over the joined rows, not the datasets' rows.
325
+ # A PER collapse is expanded in a branch or over the join, with whatever the PER holds.
302
326
  for node in find_all_in_scope(expr, exp.AggFunc, exp.Window):
303
- if not isinstance(node, exp.Agg):
327
+ if not (
328
+ isinstance(node, exp.Agg)
329
+ or (isinstance(node, exp.AggFunc) and per_argument(node) is not None)
330
+ or node.find_ancestor(exp.Per) is not None
331
+ ):
304
332
  self._fail(ctx, "Only AGG(metric) can aggregate over a constellation", node)
305
333
 
306
334
  def rewrite(node: exp.Expr) -> exp.Expr:
307
335
  if (key := ctx.keys.get(node)) is not None:
308
336
  return exp.column(key, ctx.alias)
309
337
  if self._role_parts(node, ctx) is not None:
338
+ # A role in a PER, or read by its collapse, is a dimension of the PER's grain,
339
+ # translated for the branches.
340
+ if in_per(node):
341
+ return node
310
342
  self._fail(ctx, "Roles used on a constellation must appear in GROUP BY", node)
311
343
  match node:
312
344
  case exp.Filter(
@@ -387,8 +419,9 @@ class ExpandConstellationsRule:
387
419
  metric.namespace,
388
420
  lambda name: ctx.registry.get_dataset(name) is not None,
389
421
  )
390
- if window := expr.find(exp.Window):
391
- self._fail(ctx, "Windows in metrics are not supported yet", window)
422
+ for window in expr.find_all(exp.Window):
423
+ if window.find_ancestor(exp.Per) is None:
424
+ self._fail(ctx, "Windows in metrics are not supported yet", window)
392
425
 
393
426
  def rewrite(node: exp.Expr) -> exp.Expr:
394
427
  match node:
@@ -406,6 +439,9 @@ class ExpandConstellationsRule:
406
439
  self._fail(
407
440
  ctx, "AGG in a metric must reference a metric or a dataset field", node
408
441
  )
442
+ # A PER collapse keeps its shape, windows included, for _pushdown_per or the join.
443
+ case exp.AggFunc() if per_argument(node) is not None or is_window_function(node):
444
+ return node
409
445
  # A FILTER belongs to its aggregate, so the branch computes both.
410
446
  case exp.AggFunc() | exp.Filter():
411
447
  read = {
@@ -425,7 +461,7 @@ class ExpandConstellationsRule:
425
461
  return self._leaf(dataset, local, name.name, condition, ctx)
426
462
  # Columns inside aggregates were replaced above, so this one is outside them, e.g.
427
463
  # a role in `AGG(m) * item.category` or a metric missing its AGG.
428
- case exp.Column():
464
+ case exp.Column() if node.find_ancestor(exp.Per) is None:
429
465
  self._fail(
430
466
  ctx, "Columns outside aggregates in metrics are not supported yet", node
431
467
  )
@@ -449,6 +485,202 @@ class ExpandConstellationsRule:
449
485
  ctx.expanding.discard(key)
450
486
  return expanded
451
487
 
488
+ def _pushdown_per(self, projections: list[exp.Expr], ctx: ConstellationContext) -> bool:
489
+ """
490
+ Makes each f(... PER (roles)) a leaf of the one dataset its metrics read, e.g.
491
+ AVG(AGG(store_sales_amount) PER (customer)) becomes AVG(AGG(sales_amount) PER (customer))
492
+ on store_sales, which its branch computes like any dataset query with a PER.
493
+
494
+ When any collapse reads several datasets, none is pushed down: the branches are then
495
+ grouped by the PER grain for the join, and a PER of their own would overlap it. Returns
496
+ whether a PER is left to collapse over the join.
497
+ """
498
+ by_name = {leaf.name: leaf for leaf in ctx.leaves.values()}
499
+ keys = {name: key for key, name in ctx.keys.items()}
500
+
501
+ leaves: dict[int, list[Leaf]] = {}
502
+ for projection in projections:
503
+ for node in find_all_in_scope(projection, exp.AggFunc):
504
+ if per_argument(node) is None:
505
+ continue
506
+ read = [
507
+ by_name[name]
508
+ for column in find_all_in_scope(node, exp.Column)
509
+ if (name := _joined_column(column, ctx.alias)) in by_name
510
+ ]
511
+ if not read:
512
+ self._fail(ctx, "PER on a constellation must aggregate a metric", node)
513
+ if len({leaf.dataset for leaf in read}) > 1:
514
+ return True
515
+ leaves[id(node)] = read
516
+ if not leaves:
517
+ return False
518
+
519
+ def as_roles(node: exp.Expr) -> exp.Expr:
520
+ if (name := _joined_column(node, ctx.alias)) in keys:
521
+ return keys[name].copy()
522
+ return node
523
+
524
+ def as_aggregates(node: exp.Expr) -> exp.Expr:
525
+ if (name := _joined_column(node, ctx.alias)) in by_name:
526
+ return self._filtered(by_name[name], ctx).copy()
527
+ return node
528
+
529
+ def rewrite(node: exp.Expr) -> exp.Expr:
530
+ if id(node) not in leaves:
531
+ return node
532
+ dataset = leaves[id(node)][0].dataset
533
+ pushed = self._translate(node.transform(as_roles), dataset, ctx).transform(
534
+ as_aggregates, copy=False
535
+ )
536
+ name = f"{node.key}_{leaves[id(node)][0].name}"
537
+ return _replace(node, self._leaf(dataset, pushed, name, None, ctx))
538
+
539
+ for projection in projections:
540
+ projection.transform(rewrite, copy=False)
541
+ # A leaf only a pushed-down PER reads is computed inside that leaf.
542
+ referenced = {
543
+ _joined_column(column, ctx.alias)
544
+ for projection in projections
545
+ for column in find_all_in_scope(projection, exp.Column)
546
+ }
547
+ ctx.leaves = {key: leaf for key, leaf in ctx.leaves.items() if leaf.name in referenced}
548
+ return False
549
+
550
+ def _collapse_over_branches(
551
+ self,
552
+ projections: list[exp.Expr],
553
+ datasets: list[exp.Table],
554
+ condition: exp.Expr | None,
555
+ ctx: ConstellationContext,
556
+ ) -> exp.Select:
557
+ """
558
+ Collapses the PERs over several datasets' metrics, e.g. AVG(AGG(margin) PER (customer))
559
+ with margin = AGG(orders.order) - AGG(costs.cost): expand_per derives the grouping sets,
560
+ the keys and the PER columns, and reads the branches grouped by them as its scan.
561
+ """
562
+ leaf_names = {leaf.name for leaf in ctx.leaves.values()}
563
+
564
+ def read(node: exp.Expr) -> exp.Expr:
565
+ # A metric outside a PER has one value per key row, read like a plain aggregate.
566
+ if (
567
+ _joined_column(node, ctx.alias) in leaf_names
568
+ and node.find_ancestor(exp.AggFunc) is None
569
+ ):
570
+ return exp.Max(this=node)
571
+ return node
572
+
573
+ projections = [projection.transform(read, copy=False) for projection in projections]
574
+ groups: list[tuple[exp.Expr, ...]] = [
575
+ tuple(exp.column(name, ctx.alias) for name in ctx.keys.values())
576
+ ]
577
+
578
+ def scan(
579
+ projections: list[exp.Expr],
580
+ requested_groups: list[tuple[exp.Expr, ...]],
581
+ needs: dict[str, list[tuple[exp.Expr, ...]]],
582
+ ) -> exp.Select:
583
+ return self._scan_branches(
584
+ datasets, condition, ctx, projections, requested_groups, needs
585
+ )
586
+
587
+ expanded = expand_over(projections, groups, scan, ctx.dialect)
588
+ assert expanded is not None, "the projections hold a PER"
589
+ return expanded[0]
590
+
591
+ def _scan_branches(
592
+ self,
593
+ datasets: list[exp.Table],
594
+ condition: exp.Expr | None,
595
+ ctx: ConstellationContext,
596
+ projections: list[exp.Expr],
597
+ requested_groups: list[tuple[exp.Expr, ...]],
598
+ needs: dict[str, list[tuple[exp.Expr, ...]]],
599
+ ) -> exp.Select:
600
+ """
601
+ The scan of a collapse over the branches: each branch grouped by the sets its leaves are
602
+ read at, its keys and PER columns translated, full outer joined on them, and the
603
+ projections over the joined rows, each leaf merged by MAX as in _join_branches and each
604
+ GROUPING read from the branches, where the grouping happened.
605
+ """
606
+ keys = {name: key for key, name in ctx.keys.items()}
607
+ by_name = {leaf.name: leaf for leaf in ctx.leaves.values()}
608
+ taken = set(by_name)
609
+ # A dimension as the projections write it, a key column or a role path, to its name.
610
+ dims: dict[exp.Expr, str] = {}
611
+ for group in requested_groups:
612
+ for dim in group:
613
+ if dim in dims:
614
+ continue
615
+ if (name := _joined_column(dim, ctx.alias)) in keys:
616
+ dims[dim] = internal_alias(taken, name)
617
+ elif (parts := self._role_parts(dim, ctx)) is not None:
618
+ dims[dim] = internal_alias(taken, "_".join(part.name for part in parts))
619
+ elif any(self._role_parts(path, ctx) is not None for path in self._paths(dim)):
620
+ dims[dim] = internal_alias(taken, "_per_dimension")
621
+ else:
622
+ self._fail(ctx, "PER on a constellation can only use roles", dim)
623
+ exprs = {name: keys[name] if name in keys else dim for dim, name in dims.items()}
624
+ grouping: dict[str, str] = {}
625
+ # A branch groups by the sets the projections reading its leaves need.
626
+ read_at: dict[exp.Table, dict[tuple[exp.Expr, ...], None]] = {}
627
+ for projection in projections:
628
+ groups = needs.get(projection.alias, requested_groups)
629
+ for node in find_all_in_scope(projection, exp.Grouping, exp.Column):
630
+ if isinstance(node, exp.Grouping):
631
+ name = dims[node.expressions[0]]
632
+ if name not in grouping:
633
+ grouping[name] = internal_alias(taken, f"_grouping_{name}")
634
+ elif (name := _joined_column(node, ctx.alias)) in by_name:
635
+ read_at.setdefault(by_name[name].dataset, {}).update(dict.fromkeys(groups))
636
+
637
+ aliases: dict[exp.Table, str] = {}
638
+ for dataset in datasets:
639
+ aliases[dataset] = find_new_name(set(aliases.values()), dataset.name)
640
+ per_columns = frozenset(name for name in dims.values() if name not in keys)
641
+ branches = [
642
+ self._branch(
643
+ dataset,
644
+ condition,
645
+ ctx,
646
+ exprs,
647
+ [
648
+ tuple(dims[dim] for dim in group)
649
+ for group in read_at.get(dataset, dict.fromkeys(requested_groups))
650
+ ],
651
+ grouping,
652
+ per_columns,
653
+ ).subquery(aliases[dataset], copy=False)
654
+ for dataset in datasets
655
+ ]
656
+ names = list(aliases.values())
657
+ columns = {
658
+ name: self._coalesce(name, names) for name in (*dims.values(), *grouping.values())
659
+ }
660
+ leaf_alias = {name: aliases[leaf.dataset] for name, leaf in by_name.items()}
661
+
662
+ def rewrite(node: exp.Expr) -> exp.Expr:
663
+ if node in dims:
664
+ return columns[dims[node]].copy()
665
+ if isinstance(node, exp.Grouping):
666
+ return columns[grouping[dims[node.expressions[0]]]].copy()
667
+ if (name := _joined_column(node, ctx.alias)) in leaf_alias:
668
+ column = exp.column(name, leaf_alias[name])
669
+ aggregate = node.find_ancestor(exp.AggFunc)
670
+ if aggregate is not None and not is_window_function(aggregate):
671
+ return column
672
+ return exp.Max(this=column)
673
+ return node
674
+
675
+ scan = exp.select(
676
+ *(projection.transform(rewrite, copy=False) for projection in projections), copy=False
677
+ ).from_(branches[0], copy=False)
678
+ scan = self._full_join(scan, branches, names, list(columns))
679
+ return scan.group_by(
680
+ *(column.copy() for column in columns.values() if column.find(exp.Column)),
681
+ copy=False,
682
+ )
683
+
452
684
  def _leaf(
453
685
  self,
454
686
  dataset: exp.Table,
@@ -509,6 +741,15 @@ class ExpandConstellationsRule:
509
741
  outputs.append(exp.alias_(exp.Max(this=column), leaf.name) if merge else column)
510
742
  joined = exp.select(*outputs, copy=False).from_(branches[0], copy=False)
511
743
 
744
+ joined = self._full_join(joined, branches, names, list(keys))
745
+ if merge:
746
+ joined = joined.group_by(*keys.values(), copy=False)
747
+ return joined
748
+
749
+ def _full_join(
750
+ self, joined: exp.Select, branches: list[exp.Subquery], names: list[str], keys: list[str]
751
+ ) -> exp.Select:
752
+ """Full outer joins branches after the first on keys."""
512
753
  for n, branch in enumerate(branches[1:], start=1):
513
754
  # A key can be missing from any earlier branch, so compare with all of them. Without
514
755
  # keys, every branch is a single row, so they all match.
@@ -517,9 +758,6 @@ class ExpandConstellationsRule:
517
758
  ]
518
759
  on = exp.and_(*conditions) if conditions else exp.true()
519
760
  joined = joined.join(branch, join_type="FULL OUTER", on=on, copy=False)
520
-
521
- if merge:
522
- joined = joined.group_by(*keys.values(), copy=False)
523
761
  return joined
524
762
 
525
763
  def _key_datasets(
@@ -554,42 +792,107 @@ class ExpandConstellationsRule:
554
792
  return datasets
555
793
 
556
794
  def _branch(
557
- self, dataset: exp.Table, condition: exp.Expr | None, ctx: ConstellationContext
558
- ) -> exp.Select:
795
+ self,
796
+ dataset: exp.Table,
797
+ condition: exp.Expr | None,
798
+ ctx: ConstellationContext,
799
+ dims: dict[str, exp.Expr] | None = None,
800
+ sets: list[tuple[str, ...]] | None = None,
801
+ grouping: dict[str, str] | None = None,
802
+ per_columns: frozenset[str] = frozenset(),
803
+ ) -> exp.Query:
559
804
  """
560
805
  Builds the query for one dataset: its keys and leaves over the rows that pass `condition`,
561
806
  with one row per key, or per row when stacking.
562
807
 
563
808
  For example, `store_sales` by `item.category` gives the sales amount per item category,
564
809
  with the category read through `store_sales`' own assignment for the `item` role.
565
- """
566
- translated = {name: self._translate(expr, dataset, ctx) for expr, name in ctx.keys.items()}
567
- projections = [exp.alias_(expr, name) for name, expr in translated.items()]
568
- projections += [
569
- exp.alias_(self._filtered(leaf, ctx), leaf.name)
570
- for leaf in ctx.leaves.values()
571
- if leaf.dataset == dataset and not ctx.stack
572
- ]
573
810
 
574
- table = exp.table_(dataset.this, db=dataset.args["db"], catalog=ctx.catalog)
575
- table.meta[TABLE_ARGUMENTS] = ctx.arguments
576
- branch = exp.select(*projections, copy=False).from_(table, copy=False)
577
- if condition is not None:
578
- branch.where(self._translate(condition, dataset, ctx), copy=False)
811
+ A collapse over the branches asks for its own dims by name, the keys and the
812
+ per_columns, grouped by the grouping sets of their names, and for GROUPING of some of
813
+ them, named by grouping. A dim in none of the sets is NULL, with GROUPING 1. A dim the
814
+ dataset assigns as a constant can't be grouped by, so its GROUPING is the literal of its
815
+ membership, and when that differs between the sets, each set is its own select.
816
+ """
817
+ if dims is None:
818
+ dims = {name: expr for expr, name in ctx.keys.items()}
819
+ translated = {
820
+ name: (
821
+ self._per_column(expr, dataset, ctx)
822
+ if name in per_columns
823
+ else self._translate(expr, dataset, ctx)
824
+ )
825
+ for name, expr in dims.items()
826
+ }
579
827
  # Constant keys like `'store'` don't need grouping, and some engines reject or
580
828
  # misread `GROUP BY <literal>`.
581
- groupings = [expr for expr in translated.values() if expr.find(exp.Column)]
582
- if groupings and not ctx.stack:
583
- branch.set("group", exp.Group(expressions=groupings))
584
- # ExpandDatasetsRule expects qualified SQL. Keys are named after the query's output names,
585
- # which can match a column of the dataset, so they mustn't be read as alias references.
586
- # Its aliases are normalized names, which normalizing again could change, so they're quoted.
587
- qualified = qualify(
588
- quote_identifiers(branch, dialect=ctx.dialect),
589
- schema=ctx.cluster,
590
- dialect=ctx.dialect,
591
- quote_identifiers=False,
592
- expand_alias_refs=False,
829
+ groupable = [name for name, expr in translated.items() if expr.find(exp.Column)]
830
+
831
+ def leaves() -> list[exp.Expr]:
832
+ return [
833
+ exp.alias_(self._filtered(leaf, ctx), leaf.name)
834
+ for leaf in ctx.leaves.values()
835
+ if leaf.dataset == dataset and not ctx.stack
836
+ ]
837
+
838
+ def query(projections: list[exp.Expr], group: exp.Group | None) -> exp.Select:
839
+ table = exp.table_(dataset.this, db=dataset.args["db"], catalog=ctx.catalog)
840
+ table.meta[TABLE_ARGUMENTS] = ctx.arguments
841
+ branch = exp.select(*projections, copy=False).from_(table, copy=False)
842
+ if condition is not None:
843
+ branch.where(self._translate(condition, dataset, ctx), copy=False)
844
+ branch.set("group", group)
845
+ # ExpandDatasetsRule expects qualified SQL. Keys are named after the query's output
846
+ # names, which can match a column of the dataset, so they mustn't be read as alias
847
+ # references. Its aliases are normalized names, which normalizing again could
848
+ # change, so they're quoted.
849
+ return qualify(
850
+ quote_identifiers(branch, dialect=ctx.dialect),
851
+ schema=ctx.cluster,
852
+ dialect=ctx.dialect,
853
+ quote_identifiers=False,
854
+ expand_alias_refs=False,
855
+ )
856
+
857
+ def grouped(grouping_sets: list[tuple[str, ...]]) -> exp.Select:
858
+ present = {name for grouping_set in grouping_sets for name in grouping_set}
859
+ projections = [
860
+ exp.alias_(expr if name in present else exp.Null(), name)
861
+ for name, expr in translated.items()
862
+ ]
863
+ projections += leaves()
864
+ projections += [
865
+ exp.alias_(
866
+ exp.Grouping(expressions=[translated[dim].copy()])
867
+ if dim in groupable and dim in present
868
+ else exp.Literal.number(0 if dim in present else 1),
869
+ name,
870
+ )
871
+ for dim, name in (grouping or {}).items()
872
+ ]
873
+ group = group_of_sets(
874
+ [
875
+ tuple(translated[name].copy() for name in grouping_set if name in groupable)
876
+ for grouping_set in grouping_sets
877
+ ]
878
+ )
879
+ return query(projections, group)
880
+
881
+ if sets is not None:
882
+ present = {name for grouping_set in sets for name in grouping_set}
883
+ if any(
884
+ name not in groupable and any(name not in grouping_set for grouping_set in sets)
885
+ for name in present
886
+ ):
887
+ return exp.union(
888
+ *(grouped([grouping_set]) for grouping_set in sets), distinct=False, copy=False
889
+ )
890
+ return grouped(sets)
891
+
892
+ projections = [exp.alias_(expr, name) for name, expr in translated.items()] + leaves()
893
+ groupings = [translated[name] for name in groupable]
894
+ qualified = query(
895
+ projections, exp.Group(expressions=groupings) if groupings and not ctx.stack else None
593
896
  )
594
897
  # Without leaves or a GROUP BY, e.g. just `'store' AS sales_channel`, the branch has a row
595
898
  # per row of the dataset, which the join would multiply by every other branch's rows. The
@@ -602,6 +905,38 @@ class ExpandConstellationsRule:
602
905
  )
603
906
  return qualified
604
907
 
908
+ def _per_column(
909
+ self, expr: exp.Expr, dataset: exp.Table, ctx: ConstellationContext
910
+ ) -> exp.Expr:
911
+ """
912
+ A PER column for dataset: the role path translated, or for a bare entity role the key of
913
+ the relationship its assignment names, as a PER by that relationship takes.
914
+ """
915
+ parts = self._role_parts(expr, ctx)
916
+ if parts is None or len(parts) > 1:
917
+ return self._translate(expr, dataset, ctx)
918
+ role = ctx.constellation.get_column(parts[0])
919
+ if role is None or not role.datatype or not role.datatype.is_type(exp.DType.REF):
920
+ return self._translate(expr, dataset, ctx)
921
+ assignment = ctx.constellation.get_assignment(dataset, parts[0])
922
+ proxy = ctx.registry.get_dataset(dataset)
923
+ relationship = (
924
+ proxy.get_column(assignment.expr.this)
925
+ if assignment is not None
926
+ and proxy is not None
927
+ and isinstance(assignment.expr, exp.Column)
928
+ else None
929
+ )
930
+ if not isinstance(relationship, Relationship):
931
+ name = f"{self._sql(ctx, ctx.constellation.name)}.{self._sql(ctx, parts[0])}"
932
+ self._fail(
933
+ ctx,
934
+ f"Dataset {self._sql(ctx, dataset)} does not provide role {name} as a relationship",
935
+ )
936
+ if len(relationship.key) != 1:
937
+ self._fail(ctx, "PER by a role with a composite key is not supported yet", expr)
938
+ return next(iter(relationship.key.values())).copy()
939
+
605
940
  def _translate(self, expr: exp.Expr, dataset: exp.Table, ctx: ConstellationContext) -> exp.Expr:
606
941
  """
607
942
  Rewrites an expression over roles, i.e. a key, the WHERE or a FILTER condition, for
@@ -637,7 +972,10 @@ class ExpandConstellationsRule:
637
972
  else assignment.expr.copy()
638
973
  )
639
974
  if not path:
640
- # A reference role is a key to follow, not a value to group or filter by.
975
+ # A reference role is a key to follow, not a value to group or filter by, except
976
+ # in a PER or its collapse, which take the key of the relationship it stands for.
977
+ if in_per(node):
978
+ return _replace(node, assigned)
641
979
  # TODO: let a bare reference role stand for its key, e.g. `customer IN (SELECT ...)`
642
980
  # filtering on `customer.c_customer_sk`, or on `ss_customer_sk` without a join.
643
981
  field = ctx.constellation.get_column(role)