metricflow-sql 0.4.0__tar.gz → 0.5.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.4.0 → metricflow_sql-0.5.0}/PKG-INFO +1 -1
  2. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/pyproject.toml +1 -1
  3. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/rules/expand_constellations.py +112 -103
  4. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/converters/legacy.py +8 -5
  5. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/converters/lookml.py +61 -8
  6. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/objects/base.py +5 -1
  7. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/objects/constellation.py +57 -15
  8. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/registry/memory.py +91 -23
  9. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/registry/reference_resolution.py +16 -0
  10. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/registry/registry.py +12 -5
  11. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/registry/type_resolver.py +14 -10
  12. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/schemas/fragment.schema.json +49 -37
  13. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/schemas/load.py +13 -3
  14. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/schemas/v1/__init__.py +2 -2
  15. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/schemas/v1/fragment.py +26 -16
  16. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/server/serde.py +8 -1
  17. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/.gitignore +0 -0
  18. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/LICENSE +0 -0
  19. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/PYPI.md +0 -0
  20. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/README.md +0 -0
  21. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/__init__.py +0 -0
  22. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/__init__.py +0 -0
  23. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/catalog/__init__.py +0 -0
  24. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/catalog/cluster.py +0 -0
  25. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/catalog/information_schema.py +0 -0
  26. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/catalog/metadata.py +0 -0
  27. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/catalog/passthrough.py +0 -0
  28. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/catalog/protocols.py +0 -0
  29. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/catalog/semantic.py +0 -0
  30. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/compiler.py +0 -0
  31. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/rules/__init__.py +0 -0
  32. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/rules/expand_datasets.py +0 -0
  33. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/rules/expand_metadata.py +0 -0
  34. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/rules/expand_per.py +0 -0
  35. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/rules/isolate_fragments.py +0 -0
  36. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/rules/passthrough_tables.py +0 -0
  37. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/compiler/table_arguments.py +0 -0
  38. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/converters/__init__.py +0 -0
  39. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/objects/__init__.py +0 -0
  40. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/objects/dataset.py +0 -0
  41. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/objects/entity.py +0 -0
  42. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/objects/reference.py +0 -0
  43. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/objects/wiki.py +0 -0
  44. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/py.typed +0 -0
  45. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/registry/__init__.py +0 -0
  46. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/registry/operation.py +0 -0
  47. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/schemas/__init__.py +0 -0
  48. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/schemas/bundle.py +0 -0
  49. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/schemas/generate.py +0 -0
  50. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/schemas/markdown.py +0 -0
  51. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/server/__init__.py +0 -0
  52. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/server/app.py +0 -0
  53. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/server/compile.py +0 -0
  54. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/server/errors.py +0 -0
  55. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/server/http.py +0 -0
  56. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/server/registry.py +0 -0
  57. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/server/serve.py +0 -0
  58. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/utils/__init__.py +0 -0
  59. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/utils/composed_set.py +0 -0
  60. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/utils/normalize.py +0 -0
  61. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/utils/ordered_set.py +0 -0
  62. {metricflow_sql-0.4.0 → metricflow_sql-0.5.0}/src/metricflow_sql/utils/sql.py +0 -0
  63. {metricflow_sql-0.4.0 → metricflow_sql-0.5.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.4.0
3
+ Version: 0.5.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.4.0"
4
+ version = "0.5.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"
@@ -16,10 +16,12 @@ from metricflow_sql.compiler.catalog.cluster import Cluster
16
16
  from metricflow_sql.compiler.catalog.semantic import SemanticCatalog
17
17
  from metricflow_sql.compiler.rules.expand_per import expand_over
18
18
  from metricflow_sql.compiler.table_arguments import TABLE_ARGUMENTS
19
- from metricflow_sql.objects.base import resolve_dataset_path
20
19
  from metricflow_sql.objects.constellation import Metric, Role
21
20
  from metricflow_sql.objects.dataset import Relationship
22
- from metricflow_sql.registry.reference_resolution import resolve_metric
21
+ from metricflow_sql.registry.reference_resolution import (
22
+ resolve_metric,
23
+ resolve_metric_path,
24
+ )
23
25
  from metricflow_sql.registry.registry import ConstellationProxy, Registry
24
26
  from metricflow_sql.utils.sql import (
25
27
  group_all_keys,
@@ -90,9 +92,11 @@ class Leaf:
90
92
 
91
93
  A leaf is named after what it computes: the calculation (`return_amount`), or the metric
92
94
  for an aggregate written inline in it (`catalog_sales_amount = SUM(...)`).
95
+
96
+ Each fact gets its own branch, so a dataset that's two facts is read twice.
93
97
  """
94
98
 
95
- dataset: exp.Table
99
+ fact: exp.Table
96
100
  expr: exp.Expr
97
101
  name: str
98
102
  # A filter over roles that only this aggregate applies, from a query's
@@ -116,7 +120,7 @@ class ConstellationContext:
116
120
  # output them as, e.g. `item.category` -> `item_category`. Matched structurally, since
117
121
  # qualify writes every use of a GROUP BY expression the same way.
118
122
  keys: dict[exp.Expr, str] = field(default_factory=dict)
119
- # Keyed by (dataset, aggregate, filter), so an aggregate shared by several metrics is
123
+ # Keyed by (fact, aggregate, filter), so an aggregate shared by several metrics is
120
124
  # computed once.
121
125
  leaves: dict[tuple[exp.Table, exp.Expr, exp.Expr | None], Leaf] = field(default_factory=dict)
122
126
  # Metrics being unfolded right now, to catch a metric that references itself. Keyed by
@@ -137,7 +141,7 @@ class ExpandConstellationsRule:
137
141
  through a shared role such as the item category would pair every sale with every return
138
142
  in the same category, and inflate both sums (the chasm trap). So the rule compiles:
139
143
 
140
- 1. One branch per dataset the metrics read from: a query that aggregates that dataset by
144
+ 1. One branch per fact the metrics read from: a query that aggregates its dataset by
141
145
  the query's GROUP BY expressions, so it has exactly one row per key, e.g. sales per
142
146
  category. A GROUP BY expression can be any expression over roles, e.g. a birth decade,
143
147
  and each branch computes it from its own assignments, like it does the WHERE.
@@ -249,19 +253,19 @@ class ExpandConstellationsRule:
249
253
  ]
250
254
  collapse = self._pushdown_per(projections, ctx)
251
255
  if ctx.leaves:
252
- datasets = list(dict.fromkeys(leaf.dataset for leaf in ctx.leaves.values()))
256
+ facts = list(dict.fromkeys(leaf.fact for leaf in ctx.leaves.values()))
253
257
  elif ctx.keys:
254
- datasets = self._key_datasets(condition, ctx)
258
+ facts = self._key_facts(condition, ctx)
255
259
  else:
256
260
  self._fail(ctx, "Constellation queries must aggregate a metric or group by roles")
257
261
 
258
262
  if collapse:
259
- return self._collapse_over_branches(projections, datasets, condition, ctx)
263
+ return self._collapse_over_branches(projections, facts, condition, ctx)
260
264
  if ctx.stack:
261
- branches = [self._branch(dataset, condition, ctx) for dataset in datasets]
265
+ branches = [self._branch(fact, condition, ctx) for fact in facts]
262
266
  rows = exp.union(*branches, distinct=False, copy=False) if branches[1:] else branches[0]
263
267
  else:
264
- rows = self._join_branches(datasets, condition, ctx)
268
+ rows = self._join_branches(facts, condition, ctx)
265
269
  joined = rows.subquery(ctx.alias, copy=False)
266
270
  return exp.select(*projections, copy=False).from_(joined, copy=False)
267
271
 
@@ -409,16 +413,12 @@ class ExpandConstellationsRule:
409
413
  )
410
414
  ctx.expanding.add(key)
411
415
  expr = metric.expr.copy()
412
- # `revenue.accounts.account_count` reads `accounts.account_count` on `revenue`. As in SQL,
413
- # a dataset `retail` in the metric's own namespace wins over `retail.store_sales`.
416
+ # E.g. `revenue.accounts.account_count` reads `accounts.account_count` on the fact
417
+ # `revenue`.
414
418
  reads: dict[int, tuple[exp.Table, tuple[exp.Identifier, ...]]] = {}
415
419
  for path in self._paths(expr):
416
420
  if isinstance(path, exp.Column | exp.Dot) and len(names := path_names(path)) > 1:
417
- reads[id(path)] = resolve_dataset_path(
418
- names,
419
- metric.namespace,
420
- lambda name: ctx.registry.get_dataset(name) is not None,
421
- )
421
+ reads[id(path)] = resolve_metric_path(ctx.constellation, names, metric.namespace)
422
422
  for window in expr.find_all(exp.Window):
423
423
  if window.find_ancestor(exp.Per) is None:
424
424
  self._fail(ctx, "Windows in metrics are not supported yet", window)
@@ -448,17 +448,17 @@ class ExpandConstellationsRule:
448
448
  reads[id(path)][0] if id(path) in reads else None
449
449
  for path in self._paths(node)
450
450
  }
451
- dataset = read.pop() if len(read) == 1 else None
452
- if dataset is None:
451
+ fact = read.pop() if len(read) == 1 else None
452
+ if fact is None:
453
453
  self._fail(
454
- ctx, "An aggregate in a metric must read from exactly one dataset", node
454
+ ctx, "An aggregate in a metric must read from exactly one fact", node
455
455
  )
456
456
  # Inside the copied metric, so its paths are reused.
457
457
  local = node.transform(
458
458
  lambda n: _column(*reads[id(n)][1]) if id(n) in reads else n,
459
459
  copy=False,
460
460
  )
461
- return self._leaf(dataset, local, name.name, condition, ctx)
461
+ return self._leaf(fact, local, name.name, condition, ctx)
462
462
  # Columns inside aggregates were replaced above, so this one is outside them, e.g.
463
463
  # a role in `AGG(m) * item.category` or a metric missing its AGG.
464
464
  case exp.Column() if node.find_ancestor(exp.Per) is None:
@@ -487,11 +487,11 @@ class ExpandConstellationsRule:
487
487
 
488
488
  def _pushdown_per(self, projections: list[exp.Expr], ctx: ConstellationContext) -> bool:
489
489
  """
490
- Makes each f(... PER (roles)) a leaf of the one dataset its metrics read, e.g.
490
+ Makes each f(... PER (roles)) a leaf of the one fact its metrics read, e.g.
491
491
  AVG(AGG(store_sales_amount) PER (customer)) becomes AVG(AGG(sales_amount) PER (customer))
492
492
  on store_sales, which its branch computes like any dataset query with a PER.
493
493
 
494
- When any collapse reads several datasets, none is pushed down: the branches are then
494
+ When any collapse reads several facts, none is pushed down: the branches are then
495
495
  grouped by the PER grain for the join, and a PER of their own would overlap it. Returns
496
496
  whether a PER is left to collapse over the join.
497
497
  """
@@ -510,7 +510,7 @@ class ExpandConstellationsRule:
510
510
  ]
511
511
  if not read:
512
512
  self._fail(ctx, "PER on a constellation must aggregate a metric", node)
513
- if len({leaf.dataset for leaf in read}) > 1:
513
+ if len({leaf.fact for leaf in read}) > 1:
514
514
  return True
515
515
  leaves[id(node)] = read
516
516
  if not leaves:
@@ -529,12 +529,12 @@ class ExpandConstellationsRule:
529
529
  def rewrite(node: exp.Expr) -> exp.Expr:
530
530
  if id(node) not in leaves:
531
531
  return node
532
- dataset = leaves[id(node)][0].dataset
533
- pushed = self._translate(node.transform(as_roles), dataset, ctx).transform(
532
+ fact = leaves[id(node)][0].fact
533
+ pushed = self._translate(node.transform(as_roles), fact, ctx).transform(
534
534
  as_aggregates, copy=False
535
535
  )
536
536
  name = f"{node.key}_{leaves[id(node)][0].name}"
537
- return _replace(node, self._leaf(dataset, pushed, name, None, ctx))
537
+ return _replace(node, self._leaf(fact, pushed, name, None, ctx))
538
538
 
539
539
  for projection in projections:
540
540
  projection.transform(rewrite, copy=False)
@@ -550,7 +550,7 @@ class ExpandConstellationsRule:
550
550
  def _collapse_over_branches(
551
551
  self,
552
552
  projections: list[exp.Expr],
553
- datasets: list[exp.Table],
553
+ facts: list[exp.Table],
554
554
  condition: exp.Expr | None,
555
555
  ctx: ConstellationContext,
556
556
  ) -> exp.Select:
@@ -580,9 +580,7 @@ class ExpandConstellationsRule:
580
580
  requested_groups: list[tuple[exp.Expr, ...]],
581
581
  needs: dict[str, list[tuple[exp.Expr, ...]]],
582
582
  ) -> exp.Select:
583
- return self._scan_branches(
584
- datasets, condition, ctx, projections, requested_groups, needs
585
- )
583
+ return self._scan_branches(facts, condition, ctx, projections, requested_groups, needs)
586
584
 
587
585
  expanded = expand_over(projections, groups, scan, ctx.dialect)
588
586
  assert expanded is not None, "the projections hold a PER"
@@ -590,7 +588,7 @@ class ExpandConstellationsRule:
590
588
 
591
589
  def _scan_branches(
592
590
  self,
593
- datasets: list[exp.Table],
591
+ facts: list[exp.Table],
594
592
  condition: exp.Expr | None,
595
593
  ctx: ConstellationContext,
596
594
  projections: list[exp.Expr],
@@ -632,32 +630,30 @@ class ExpandConstellationsRule:
632
630
  if name not in grouping:
633
631
  grouping[name] = internal_alias(taken, f"_grouping_{name}")
634
632
  elif (name := _joined_column(node, ctx.alias)) in by_name:
635
- read_at.setdefault(by_name[name].dataset, {}).update(dict.fromkeys(groups))
633
+ read_at.setdefault(by_name[name].fact, {}).update(dict.fromkeys(groups))
636
634
 
637
- aliases: dict[exp.Table, str] = {}
638
- for dataset in datasets:
639
- aliases[dataset] = find_new_name(set(aliases.values()), dataset.name)
635
+ branch_names = self._branch_names(facts)
640
636
  per_columns = frozenset(name for name in dims.values() if name not in keys)
641
637
  branches = [
642
638
  self._branch(
643
- dataset,
639
+ fact,
644
640
  condition,
645
641
  ctx,
646
642
  exprs,
647
643
  [
648
644
  tuple(dims[dim] for dim in group)
649
- for group in read_at.get(dataset, dict.fromkeys(requested_groups))
645
+ for group in read_at.get(fact, dict.fromkeys(requested_groups))
650
646
  ],
651
647
  grouping,
652
648
  per_columns,
653
- ).subquery(aliases[dataset], copy=False)
654
- for dataset in datasets
649
+ ).subquery(branch_names[fact], copy=False)
650
+ for fact in facts
655
651
  ]
656
- names = list(aliases.values())
652
+ names = list(branch_names.values())
657
653
  columns = {
658
654
  name: self._coalesce(name, names) for name in (*dims.values(), *grouping.values())
659
655
  }
660
- leaf_alias = {name: aliases[leaf.dataset] for name, leaf in by_name.items()}
656
+ leaf_alias = {name: branch_names[leaf.fact] for name, leaf in by_name.items()}
661
657
 
662
658
  def rewrite(node: exp.Expr) -> exp.Expr:
663
659
  if node in dims:
@@ -683,49 +679,43 @@ class ExpandConstellationsRule:
683
679
 
684
680
  def _leaf(
685
681
  self,
686
- dataset: exp.Table,
682
+ fact: exp.Table,
687
683
  expr: exp.Expr,
688
684
  name: str,
689
685
  condition: exp.Expr | None,
690
686
  ctx: ConstellationContext,
691
687
  ) -> exp.Expr:
692
688
  """
693
- Registers an aggregate over `dataset` as a leaf and returns its joined column.
689
+ Registers an aggregate over `fact` as a leaf and returns its joined column.
694
690
 
695
691
  The same aggregate always gets the same leaf, so `AGG(sales_amount)` on `store_sales` is
696
692
  computed once when both `store_sales_amount` and `store_return_rate` are selected. The
697
693
  leaf is called `name` when that's free, e.g. `sales_amount`, and gets a numbered suffix
698
694
  otherwise, e.g. `sales_amount_2` for a second dataset with a `sales_amount`.
699
695
  """
700
- if ctx.registry.get_dataset(dataset) is None:
701
- self._fail(ctx, f"Unknown dataset in metric: {self._sql(ctx, dataset)}")
702
- leaf_key = (dataset, expr, condition)
696
+ self._dataset(fact, ctx)
697
+ leaf_key = (fact, expr, condition)
703
698
  if (leaf := ctx.leaves.get(leaf_key)) is None:
704
699
  taken = {*ctx.keys.values(), *(other.name for other in ctx.leaves.values())}
705
- leaf = Leaf(
706
- dataset=dataset, expr=expr, name=find_new_name(taken, name), condition=condition
707
- )
700
+ leaf = Leaf(fact=fact, expr=expr, name=find_new_name(taken, name), condition=condition)
708
701
  ctx.leaves[leaf_key] = leaf
709
702
  return exp.column(leaf.name, ctx.alias)
710
703
 
711
704
  def _join_branches(
712
- self, datasets: list[exp.Table], condition: exp.Expr | None, ctx: ConstellationContext
705
+ self, facts: list[exp.Table], condition: exp.Expr | None, ctx: ConstellationContext
713
706
  ) -> exp.Select:
714
707
  """
715
- Builds one branch per dataset and joins them on the keys (step 2 in the class docstring).
708
+ Builds one branch per fact and joins them on the keys (step 2 in the class docstring).
716
709
 
717
710
  The result outputs each key once, taken from whichever branch has it, and each leaf from
718
- the branch that computes it. Branches are aliased by their dataset's name without its
719
- namespace, numbered when datasets of two namespaces share it, e.g. `sales` and `sales_2`.
711
+ the branch that computes it.
720
712
  """
721
- aliases: dict[exp.Table, str] = {}
722
- for dataset in datasets:
723
- aliases[dataset] = find_new_name(set(aliases.values()), dataset.name)
713
+ branch_names = self._branch_names(facts)
724
714
  branches = [
725
- self._branch(dataset, condition, ctx).subquery(aliases[dataset], copy=False)
726
- for dataset in datasets
715
+ self._branch(fact, condition, ctx).subquery(branch_names[fact], copy=False)
716
+ for fact in facts
727
717
  ]
728
- names = list(aliases.values())
718
+ names = list(branch_names.values())
729
719
  keys = {name: self._coalesce(name, names) for name in ctx.keys.values()}
730
720
  # A NULL key is a proper group, e.g. sales with no customer, but `=` never matches NULL,
731
721
  # so with several branches it comes out as one row per branch. Grouping by the keys merges
@@ -733,11 +723,9 @@ class ExpandConstellationsRule:
733
723
  # This assumes leaves are values MAX accepts: Postgres, for one, has no MAX(boolean), so
734
724
  # a metric like BOOL_OR(...) only merges on engines that do.
735
725
  merge = bool(keys) and len(branches) > 1
736
- outputs = [
737
- exp.alias_(key, name) if len(datasets) > 1 else key for name, key in keys.items()
738
- ]
726
+ outputs = [exp.alias_(key, name) if len(facts) > 1 else key for name, key in keys.items()]
739
727
  for leaf in ctx.leaves.values():
740
- column = exp.column(leaf.name, aliases[leaf.dataset])
728
+ column = exp.column(leaf.name, branch_names[leaf.fact])
741
729
  outputs.append(exp.alias_(exp.Max(this=column), leaf.name) if merge else column)
742
730
  joined = exp.select(*outputs, copy=False).from_(branches[0], copy=False)
743
731
 
@@ -746,6 +734,16 @@ class ExpandConstellationsRule:
746
734
  joined = joined.group_by(*keys.values(), copy=False)
747
735
  return joined
748
736
 
737
+ def _branch_names(self, facts: list[exp.Table]) -> dict[exp.Table, str]:
738
+ """
739
+ Names each fact's branch by its name without its namespace, numbered when facts of two
740
+ namespaces share it, e.g. `sales` and `sales_2`.
741
+ """
742
+ names: dict[exp.Table, str] = {}
743
+ for fact in facts:
744
+ names[fact] = find_new_name(set(names.values()), fact.name)
745
+ return names
746
+
749
747
  def _full_join(
750
748
  self, joined: exp.Select, branches: list[exp.Subquery], names: list[str], keys: list[str]
751
749
  ) -> exp.Select:
@@ -760,12 +758,10 @@ class ExpandConstellationsRule:
760
758
  joined = joined.join(branch, join_type="FULL OUTER", on=on, copy=False)
761
759
  return joined
762
760
 
763
- def _key_datasets(
764
- self, condition: exp.Expr | None, ctx: ConstellationContext
765
- ) -> list[exp.Table]:
761
+ def _key_facts(self, condition: exp.Expr | None, ctx: ConstellationContext) -> list[exp.Table]:
766
762
  """
767
- Returns the datasets a query without metrics reads its keys from: every dataset that
768
- provides all the roles the query uses.
763
+ Returns the facts a query without metrics reads its keys from: every fact whose
764
+ dataset provides all the roles the query uses.
769
765
 
770
766
  The constellation stands for all its datasets stacked, so e.g.
771
767
  `SELECT customer.birth_year FROM universe GROUP BY 1` gives the birth years of the
@@ -779,21 +775,21 @@ class ExpandConstellationsRule:
779
775
  for path in self._paths(expr)
780
776
  if (parts := self._role_parts(path, ctx)) is not None
781
777
  }
782
- datasets = [
783
- dataset
784
- for dataset in sorted(
785
- ctx.constellation.assigned_datasets(), key=lambda name: (name.db, name.name)
778
+ facts = [
779
+ fact
780
+ for fact in sorted(
781
+ ctx.constellation.fact_names(), key=lambda name: (name.db, name.name)
786
782
  )
787
- if all(ctx.constellation.get_assignment(dataset, role) is not None for role in roles)
783
+ if all(ctx.constellation.get_assignment(fact, role) is not None for role in roles)
788
784
  ]
789
- if not datasets:
785
+ if not facts:
790
786
  names = ", ".join(sorted(self._sql(ctx, role) for role in roles))
791
- self._fail(ctx, f"No dataset provides every role the query uses: {names}")
792
- return datasets
787
+ self._fail(ctx, f"No fact provides every role the query uses: {names}")
788
+ return facts
793
789
 
794
790
  def _branch(
795
791
  self,
796
- dataset: exp.Table,
792
+ fact: exp.Table,
797
793
  condition: exp.Expr | None,
798
794
  ctx: ConstellationContext,
799
795
  dims: dict[str, exp.Expr] | None = None,
@@ -802,8 +798,8 @@ class ExpandConstellationsRule:
802
798
  per_columns: frozenset[str] = frozenset(),
803
799
  ) -> exp.Query:
804
800
  """
805
- Builds the query for one dataset: its keys and leaves over the rows that pass `condition`,
806
- with one row per key, or per row when stacking.
801
+ Builds the query for one fact: its keys and leaves over its dataset's rows that pass
802
+ `condition`, with one row per key, or per row when stacking.
807
803
 
808
804
  For example, `store_sales` by `item.category` gives the sales amount per item category,
809
805
  with the category read through `store_sales`' own assignment for the `item` role.
@@ -816,11 +812,12 @@ class ExpandConstellationsRule:
816
812
  """
817
813
  if dims is None:
818
814
  dims = {name: expr for expr, name in ctx.keys.items()}
815
+ dataset = self._dataset(fact, ctx)
819
816
  translated = {
820
817
  name: (
821
- self._per_column(expr, dataset, ctx)
818
+ self._per_column(expr, fact, ctx)
822
819
  if name in per_columns
823
- else self._translate(expr, dataset, ctx)
820
+ else self._translate(expr, fact, ctx)
824
821
  )
825
822
  for name, expr in dims.items()
826
823
  }
@@ -832,7 +829,7 @@ class ExpandConstellationsRule:
832
829
  return [
833
830
  exp.alias_(self._filtered(leaf, ctx), leaf.name)
834
831
  for leaf in ctx.leaves.values()
835
- if leaf.dataset == dataset and not ctx.stack
832
+ if leaf.fact == fact and not ctx.stack
836
833
  ]
837
834
 
838
835
  def query(projections: list[exp.Expr], group: exp.Group | None) -> exp.Select:
@@ -840,7 +837,7 @@ class ExpandConstellationsRule:
840
837
  table.meta[TABLE_ARGUMENTS] = ctx.arguments
841
838
  branch = exp.select(*projections, copy=False).from_(table, copy=False)
842
839
  if condition is not None:
843
- branch.where(self._translate(condition, dataset, ctx), copy=False)
840
+ branch.where(self._translate(condition, fact, ctx), copy=False)
844
841
  branch.set("group", group)
845
842
  # ExpandDatasetsRule expects qualified SQL. Keys are named after the query's output
846
843
  # names, which can match a column of the dataset, so they mustn't be read as alias
@@ -900,26 +897,24 @@ class ExpandConstellationsRule:
900
897
  if not ctx.leaves and not groupings and not ctx.stack:
901
898
  return (
902
899
  exp.select("*")
903
- .from_(qualified.subquery(dataset.name, copy=False), copy=False)
900
+ .from_(qualified.subquery(fact.name, copy=False), copy=False)
904
901
  .distinct()
905
902
  )
906
903
  return qualified
907
904
 
908
- def _per_column(
909
- self, expr: exp.Expr, dataset: exp.Table, ctx: ConstellationContext
910
- ) -> exp.Expr:
905
+ def _per_column(self, expr: exp.Expr, fact: exp.Table, ctx: ConstellationContext) -> exp.Expr:
911
906
  """
912
- A PER column for dataset: the role path translated, or for a bare entity role the key of
907
+ A PER column for a fact: the role path translated, or for a bare entity role the key of
913
908
  the relationship its assignment names, as a PER by that relationship takes.
914
909
  """
915
910
  parts = self._role_parts(expr, ctx)
916
911
  if parts is None or len(parts) > 1:
917
- return self._translate(expr, dataset, ctx)
912
+ return self._translate(expr, fact, ctx)
918
913
  role = ctx.constellation.get_column(parts[0])
919
914
  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)
915
+ return self._translate(expr, fact, ctx)
916
+ assignment = ctx.constellation.get_assignment(fact, parts[0])
917
+ proxy = ctx.registry.get_dataset(self._dataset(fact, ctx))
923
918
  relationship = (
924
919
  proxy.get_column(assignment.expr.this)
925
920
  if assignment is not None
@@ -931,16 +926,16 @@ class ExpandConstellationsRule:
931
926
  name = f"{self._sql(ctx, ctx.constellation.name)}.{self._sql(ctx, parts[0])}"
932
927
  self._fail(
933
928
  ctx,
934
- f"Dataset {self._sql(ctx, dataset)} does not provide role {name} as a relationship",
929
+ f"Fact {self._sql(ctx, fact)} does not provide role {name} as a relationship",
935
930
  )
936
931
  if len(relationship.key) != 1:
937
932
  self._fail(ctx, "PER by a role with a composite key is not supported yet", expr)
938
933
  return next(iter(relationship.key.values())).copy()
939
934
 
940
- def _translate(self, expr: exp.Expr, dataset: exp.Table, ctx: ConstellationContext) -> exp.Expr:
935
+ def _translate(self, expr: exp.Expr, fact: exp.Table, ctx: ConstellationContext) -> exp.Expr:
941
936
  """
942
937
  Rewrites an expression over roles, i.e. a key, the WHERE or a FILTER condition, for
943
- `dataset`, replacing each role with the dataset's assignment for it, e.g.
938
+ `fact`, replacing each role with the fact's assignment for it, e.g.
944
939
 
945
940
  customer.birth_year on store_sales -> customer.birth_year
946
941
  customer.birth_year on catalog_sales -> bill_customer.birth_year
@@ -960,13 +955,14 @@ class ExpandConstellationsRule:
960
955
  ) is None:
961
956
  return node
962
957
  role, *path = parts
963
- if (assignment := ctx.constellation.get_assignment(dataset, role)) is None:
958
+ if (assignment := ctx.constellation.get_assignment(fact, role)) is None:
964
959
  name = f"{self._sql(ctx, ctx.constellation.name)}.{self._sql(ctx, role)}"
965
- self._fail(ctx, f"Dataset {self._sql(ctx, dataset)} does not provide role {name}")
960
+ self._fail(ctx, f"Fact {self._sql(ctx, fact)} does not provide role {name}")
961
+ # The branch reads the dataset by its own name, not the fact's.
962
+ dataset = self._dataset(fact, ctx).this
966
963
  assigned = (
967
- # The branch reads the dataset by its name.
968
964
  assignment.expr.transform(
969
- lambda n: _prefixed(n, dataset.this) if isinstance(n, exp.Column) else n
965
+ lambda n: _prefixed(n, dataset) if isinstance(n, exp.Column) else n
970
966
  )
971
967
  if correlated
972
968
  else assignment.expr.copy()
@@ -988,14 +984,27 @@ class ExpandConstellationsRule:
988
984
  if not isinstance(assigned, exp.Column | exp.Dot):
989
985
  self._fail(
990
986
  ctx,
991
- f"Role {self._sql(ctx, role)} is not a relationship on dataset "
992
- f"{self._sql(ctx, dataset)}",
987
+ f"Role {self._sql(ctx, role)} is not a relationship on fact "
988
+ f"{self._sql(ctx, fact)}",
993
989
  assigned,
994
990
  )
995
991
  return exp.Dot.build([assigned, *path])
996
992
 
997
993
  return expr.transform(rewrite)
998
994
 
995
+ def _dataset(self, fact: exp.Table, ctx: ConstellationContext) -> exp.Table:
996
+ """The dataset of the fact named `fact`, e.g. `events` for `visits`."""
997
+ if (found := ctx.constellation.get_fact(fact)) is None:
998
+ self._fail(
999
+ ctx,
1000
+ f"Metrics read datasets through facts, and {self._sql(ctx, fact)} is "
1001
+ f"not a fact of constellation {self._sql(ctx, ctx.constellation.name)}",
1002
+ )
1003
+ dataset = found.dataset
1004
+ if ctx.registry.get_dataset(dataset) is None:
1005
+ self._fail(ctx, f"Unknown dataset in metric: {self._sql(ctx, dataset)}")
1006
+ return dataset
1007
+
999
1008
  def _role_parts(
1000
1009
  self, expr: exp.Expr, ctx: ConstellationContext
1001
1010
  ) -> tuple[exp.Identifier, ...] | None:
@@ -1024,7 +1033,7 @@ class ExpandConstellationsRule:
1024
1033
  """
1025
1034
  if leaf.condition is None:
1026
1035
  return leaf.expr
1027
- condition = self._translate(leaf.condition, leaf.dataset, ctx)
1036
+ condition = self._translate(leaf.condition, leaf.fact, ctx)
1028
1037
  if isinstance(leaf.expr, exp.Filter):
1029
1038
  own = leaf.expr.expression.this
1030
1039
  return exp.Filter(
@@ -341,21 +341,24 @@ class _Converter:
341
341
  return fragment
342
342
 
343
343
  def _constellation(self) -> dict[str, Any]:
344
- assignments: list[dict[str, Any]] = []
344
+ facts: list[dict[str, Any]] = []
345
345
  for dataset in self.datasets.values():
346
346
  if not dataset.used:
347
347
  continue
348
+ # Metrics only read facts, so every used dataset needs one, even without roles.
348
349
  roles = self._assignments(dataset)
350
+ fact: dict[str, Any] = {"dataset": dataset.name}
349
351
  if roles:
350
- assignments.append({"dataset": dataset.name, "roles": roles})
351
- used = {role["name"] for assignment in assignments for role in assignment["roles"]}
352
+ fact["roles"] = roles
353
+ facts.append(fact)
354
+ used = {role["name"] for fact in facts for role in fact.get("roles", ())}
352
355
  constellation: dict[str, Any] = {
353
356
  "name": _namespaced(CONSTELLATION),
354
357
  "roles": [role for name, role in self.roles.items() if name in used],
355
358
  "metrics": list(self.constellation_metrics.values()),
356
359
  }
357
- if assignments:
358
- constellation["assignments"] = assignments
360
+ if facts:
361
+ constellation["facts"] = facts
359
362
  return {key: value for key, value in constellation.items() if value}
360
363
 
361
364
  def _assignments(self, dataset: _Dataset) -> list[dict[str, str]]: