metricflow-sql 0.5.5__tar.gz → 0.5.6__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.5 → metricflow_sql-0.5.6}/PKG-INFO +1 -1
  2. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/pyproject.toml +1 -1
  3. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/converters/lookml.py +268 -35
  4. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/.gitignore +0 -0
  5. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/LICENSE +0 -0
  6. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/PYPI.md +0 -0
  7. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/__init__.py +0 -0
  8. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/__init__.py +0 -0
  9. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/catalog/__init__.py +0 -0
  10. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/catalog/cluster.py +0 -0
  11. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/catalog/information_schema.py +0 -0
  12. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/catalog/metadata.py +0 -0
  13. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/catalog/passthrough.py +0 -0
  14. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/catalog/protocols.py +0 -0
  15. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/catalog/semantic.py +0 -0
  16. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/compiler.py +0 -0
  17. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/guard.py +0 -0
  18. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/rules/__init__.py +0 -0
  19. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/rules/constellation_permissions.py +0 -0
  20. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/rules/expand_constellations.py +0 -0
  21. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/rules/expand_datasets.py +0 -0
  22. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/rules/expand_fill.py +0 -0
  23. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/rules/expand_metadata.py +0 -0
  24. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/rules/expand_per.py +0 -0
  25. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/rules/isolate_fragments.py +0 -0
  26. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/rules/nest_grouped_subqueries.py +0 -0
  27. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/rules/nest_windows.py +0 -0
  28. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/rules/passthrough_tables.py +0 -0
  29. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/compiler/table_arguments.py +0 -0
  30. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/converters/__init__.py +0 -0
  31. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/converters/legacy.py +0 -0
  32. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/objects/__init__.py +0 -0
  33. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/objects/base.py +0 -0
  34. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/objects/constellation.py +0 -0
  35. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/objects/dataset.py +0 -0
  36. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/objects/entity.py +0 -0
  37. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/objects/reference.py +0 -0
  38. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/objects/wiki.py +0 -0
  39. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/py.typed +0 -0
  40. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/registry/__init__.py +0 -0
  41. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/registry/dao.py +0 -0
  42. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/registry/dependency_resolution.py +0 -0
  43. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/registry/memory.py +0 -0
  44. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/registry/operation.py +0 -0
  45. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/registry/reference_resolution.py +0 -0
  46. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/registry/registry.py +0 -0
  47. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/registry/resolved.py +0 -0
  48. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/registry/type_resolver.py +0 -0
  49. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/schemas/__init__.py +0 -0
  50. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/schemas/bundle.py +0 -0
  51. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/schemas/fragment.schema.json +0 -0
  52. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/schemas/generate.py +0 -0
  53. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/schemas/load.py +0 -0
  54. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/schemas/markdown.py +0 -0
  55. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/schemas/v1/__init__.py +0 -0
  56. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/schemas/v1/fragment.py +0 -0
  57. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/server/__init__.py +0 -0
  58. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/server/app.py +0 -0
  59. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/server/compile.py +0 -0
  60. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/server/errors.py +0 -0
  61. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/server/http.py +0 -0
  62. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/server/registry.py +0 -0
  63. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/server/serde.py +0 -0
  64. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/server/serve.py +0 -0
  65. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/utils/__init__.py +0 -0
  66. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/utils/composed_set.py +0 -0
  67. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/utils/normalize.py +0 -0
  68. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/utils/ordered_set.py +0 -0
  69. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/src/metricflow_sql/utils/sql.py +0 -0
  70. {metricflow_sql-0.5.5 → metricflow_sql-0.5.6}/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.5
3
+ Version: 0.5.6
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.5.5"
4
+ version = "0.5.6"
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"
@@ -5,9 +5,9 @@
5
5
  --user-attribute dbt_ft_prod_schema=transforms_bi --out out/revenue
6
6
 
7
7
  Each view becomes a dataset and a LookML view of the same name, shared by explores, and each
8
- joined view an entity, e.g. `accounts_entity`. Each explore becomes a constellation, for other
9
- semantic-layer clients, and its LookML reads the explore's base dataset, its joins writing no
10
- SQL, e.g.
8
+ join an entity named for it, e.g. `accounts_by_account_id`. Each explore becomes a constellation,
9
+ for other semantic-layer clients, and its LookML reads the explore's base dataset, its joins
10
+ writing no SQL, e.g.
11
11
 
12
12
  SELECT accounts.account_facts.tier, SUM(revenue.revenue_value), AGG(accounts.account_count)
13
13
  FROM metrics.public.revenue(since => ...) AS revenue
@@ -151,6 +151,14 @@ class _Skip(Exception):
151
151
  pass
152
152
 
153
153
 
154
+ class _CopiesDiffer(Exception):
155
+ """Copies of a view, see `convert`, whose fields convert differently from the view's."""
156
+
157
+ def __init__(self, copies: set[str]) -> None:
158
+ super().__init__(copies)
159
+ self.copies = copies
160
+
161
+
154
162
  type _Resolve = Callable[[str, str, str], exp.Expr]
155
163
  # A field's calculation, its converted LookML's SQL for a `filter` or a parameter, which Looker
156
164
  # renders, or why it was skipped.
@@ -176,6 +184,8 @@ class _Converter:
176
184
  reads, and only the references in other fields' SQL convert here."""
177
185
  back: dict[str, str] = field(default_factory=dict)
178
186
  """By joined view, its relationship back to the base, see `back_explores`."""
187
+ copied: dict[str, str] = field(default_factory=dict)
188
+ """By join with `from`, the view it copies, e.g. `{referral_account: accounts}`."""
179
189
  base: str = field(init=False)
180
190
  parents: dict[str, str] = field(init=False)
181
191
  """The view each joined view hangs off."""
@@ -610,6 +620,10 @@ class _Converter:
610
620
  def entity_name(self, view: str) -> str:
611
621
  return self.entities.get(view, _entity_name(view))
612
622
 
623
+ def dataset_name(self, view: str) -> str:
624
+ """A copy reads the dataset of the view it copies, which has the same fields."""
625
+ return self.copied.get(view, view)
626
+
613
627
  def path(self, view: str, name: str) -> exp.Expr:
614
628
  """A reference as the converted LookML writes it, e.g. `accounts.account_facts.region`."""
615
629
  _, calculation, template = self.name(view, name)
@@ -679,15 +693,14 @@ class _Converter:
679
693
  return calculations
680
694
 
681
695
  def field_docs(self, view: str) -> dict[str, dict[str, Any]]:
682
- """Each converted field's LookML `label` and `description`, and in `meta.lookml` the field
683
- it came from, e.g. `{view: accounts, field: region, kind: dimension}`, by the name of the
684
- dataset field it converts to: the crosswalk from Looker's fields to MetricFlow's."""
696
+ """Each converted field's LookML `label` and `description`, and `meta.hidden` when Looker
697
+ hides it, by the name of the dataset field it converts to."""
685
698
  docs: dict[str, dict[str, Any]] = {}
686
699
  for kind, definition in self.fields(view):
687
700
  if isinstance(self.result(view, definition["name"]), _Skip):
688
701
  continue
689
702
  name = self.calculation(view, kind, definition["name"])
690
- docs[name] = _docs(definition, view=view, kind=kind.removesuffix("s"))
703
+ docs[name] = _docs(definition)
691
704
  # A dimension that reads its column documents it in every explore, so the views
692
705
  # explores share agree even where one renames the field, e.g. `items__products`.
693
706
  if kind == "dimensions" and _is_column(
@@ -720,7 +733,7 @@ class _Converter:
720
733
  {"name": column, **docs.get(column, {})} for column in self.columns[view]
721
734
  ]
722
735
  return {
723
- **_docs(definition, view=view, kind="view"),
736
+ **_docs(definition, view=self.dataset_name(view)),
724
737
  "source": source,
725
738
  "key": self.key(view),
726
739
  "parameters": _named(parameters),
@@ -834,7 +847,7 @@ class _Converter:
834
847
  on = exp.and_(on, exp.var(f":{key_name}").eq(self.inline(view, view, primary_key)))
835
848
  entity = {
836
849
  "key": [{"name": name} for name in entity_key],
837
- "sources": [{"dataset": view, "on": on.sql(_DIALECT)}],
850
+ "sources": [{"dataset": self.dataset_name(view), "on": on.sql(_DIALECT)}],
838
851
  }
839
852
  return entity, [{"name": name, "expr": expr.sql(_DIALECT)} for name, expr in key.items()]
840
853
 
@@ -865,10 +878,15 @@ class _Converter:
865
878
  *self.relationship_path(children),
866
879
  ]
867
880
  docs = self.field_docs(view)
881
+ dataset = self.dataset_name(view)
868
882
  return {
869
883
  **entity,
870
884
  "attributes": [
871
- {"name": name, "expr": exp.column(name, view).sql(_DIALECT), **docs.get(name, {})}
885
+ {
886
+ "name": name,
887
+ "expr": exp.column(name, dataset).sql(_DIALECT),
888
+ **docs.get(name, {}),
889
+ }
872
890
  for name in attributes
873
891
  ],
874
892
  }
@@ -877,7 +895,7 @@ class _Converter:
877
895
  """
878
896
  The explore, e.g. for `revenue` joining `accounts` and, through it, `account_facts`:
879
897
 
880
- roles: [accounts: REF(accounts_entity), account_facts: ..., pricing_type, ...]
898
+ roles: [accounts: REF(accounts_by_account_id), account_facts: ..., pricing_type, ...]
881
899
  metrics: [
882
900
  revenue__annual_revenue: AGG(revenue.annual_revenue),
883
901
  accounts__account_count: AGG(revenue.accounts.account_count),
@@ -901,7 +919,7 @@ class _Converter:
901
919
  reference = _path([self.base, *self.relationship_path(path), calculation])
902
920
  metrics[_metric_name(view, calculation)] = {
903
921
  "expr": exp.func("AGG", reference).sql(_DIALECT),
904
- **_docs(definition, view=view, kind="measure"),
922
+ **_docs(definition),
905
923
  }
906
924
  for kind, definition in self.fields(self.base):
907
925
  if kind in ("parameters", "filters", "measures") or isinstance(
@@ -917,14 +935,14 @@ class _Converter:
917
935
  definition["name"],
918
936
  name,
919
937
  )
920
- roles[name] = _docs(definition, view=self.base, kind=kind.removesuffix("s"))
938
+ roles[name] = _docs(definition)
921
939
  assignments[name] = exp.column(name)
922
940
  # A filter's SQL can read the view's columns, e.g. `${TABLE}.managers`.
923
941
  for column in self.columns[self.base]:
924
942
  roles.setdefault(column, {})
925
943
  assignments.setdefault(column, exp.column(column))
926
944
  return {
927
- **_docs(self.explore, explore=self.explore["name"], kind="explore"),
945
+ **_docs(self.explore, explore=self.explore["name"]),
928
946
  "roles": _named(roles),
929
947
  "metrics": _named(metrics),
930
948
  "facts": [
@@ -1140,6 +1158,149 @@ def _distinct_names[K](
1140
1158
  return names
1141
1159
 
1142
1160
 
1161
+ def _shared_entities(
1162
+ entities: dict[str, dict[str, Any]], datasets: dict[str, dict[str, Any]]
1163
+ ) -> tuple[dict[str, dict[str, Any]], dict[str, str]]:
1164
+ """
1165
+ One entity for each join, named for it rather than for the explores making it, which the
1166
+ relationships with that join share. The entity of `_Converter.join`'s example,
1167
+
1168
+ key: [{name: revenue__account_id}]
1169
+ sources: [{dataset: accounts, on: ":revenue__account_id = account_id"}]
1170
+
1171
+ is `accounts_by_account_id`, its key `accounts__account_id` after the column it matches, and
1172
+ so the entity of every join on `accounts.account_id`. A base's is e.g. `accounts_entity`.
1173
+ Entities that differ only in their attributes, which depend on what else the explore joins,
1174
+ stay apart: the one with the fewest keeps the name, and one adding a join or two to it is
1175
+ named for them, e.g. `accounts_by_account_id_with_account_facts`, others numbered, e.g.
1176
+ `accounts_by_account_id_2`. Returns the entities and each one's name by its old name, and
1177
+ retargets `datasets`' relationships.
1178
+ """
1179
+ relationships = [
1180
+ relationship
1181
+ for dataset in datasets.values()
1182
+ for relationship in dataset.get("relationships", [])
1183
+ ]
1184
+ bound = {
1185
+ relationship["target"]: [key["name"] for key in relationship["key"]]
1186
+ for relationship in relationships
1187
+ }
1188
+ renamed_keys: dict[str, dict[str, str]] = {}
1189
+ variants: dict[str, dict[str, dict[str, Any]]] = {}
1190
+ definitions: dict[str, str] = {}
1191
+ for name, entity in entities.items():
1192
+ (source,) = entity["sources"]
1193
+ dataset = source["dataset"]
1194
+ default = _entity_name(dataset)
1195
+ if name in bound:
1196
+ on = sqlglot.parse_one(source["on"], read=_DIALECT)
1197
+ columns = {key["name"]: _matched_column(on, key["name"]) for key in entity["key"]}
1198
+ keys = {
1199
+ key: f"{dataset}__{column}" if column else key for key, column in columns.items()
1200
+ }
1201
+ if len(set(keys.values())) < len(keys):
1202
+ keys = {key: key for key in columns}
1203
+ renamed_keys[name] = keys
1204
+ placeholders = {placeholder.name for placeholder in on.find_all(exp.Placeholder)}
1205
+ on = exp.replace_placeholders(
1206
+ on, **{key: exp.var(f":{keys.get(key, key)}") for key in placeholders}
1207
+ )
1208
+ entity = {
1209
+ **entity,
1210
+ "key": [{**key, "name": keys[key["name"]]} for key in entity["key"]],
1211
+ "sources": [{**source, "on": on.sql(_DIALECT)}],
1212
+ }
1213
+ # A key compared with an expression, e.g. `orders__ts`, names it by its field, `ts`.
1214
+ default = f"{dataset}_by_" + "_and_".join(
1215
+ columns[key] or key.split("__", 1)[-1] for key in bound[name]
1216
+ )
1217
+ definitions[name] = json.dumps(entity)
1218
+ variants.setdefault(default, {})[definitions[name]] = entity
1219
+ shared: dict[str, dict[str, Any]] = {}
1220
+ shared_names: dict[str, str] = {}
1221
+ for default, by_definition in variants.items():
1222
+ plain = min(by_definition.values(), key=lambda entity: len(entity.get("attributes", [])))
1223
+ for definition, entity in sorted(
1224
+ by_definition.items(), key=lambda item: item[1] is not plain
1225
+ ):
1226
+ joins = _added_joins(plain, entity, datasets)
1227
+ named = f"{default}_with_" + "_and_".join(joins) if 0 < len(joins) <= 2 else default
1228
+ shared_name, suffix = named, 1
1229
+ # Entities and datasets share names, e.g. a view `users_by_id`'s.
1230
+ while shared_name in shared or shared_name in datasets:
1231
+ suffix += 1
1232
+ shared_name = f"{named}_{suffix}"
1233
+ shared[shared_name] = entity
1234
+ shared_names[definition] = shared_name
1235
+ names = {name: shared_names[definition] for name, definition in definitions.items()}
1236
+ for relationship in relationships:
1237
+ keys = renamed_keys[relationship["target"]]
1238
+ relationship["key"] = [{**key, "name": keys[key["name"]]} for key in relationship["key"]]
1239
+ relationship["target"] = names[relationship["target"]]
1240
+ return shared, names
1241
+
1242
+
1243
+ def _added_joins(
1244
+ plain: dict[str, Any], entity: dict[str, Any], datasets: dict[str, dict[str, Any]]
1245
+ ) -> list[str]:
1246
+ """The relationships `entity` reads as attributes beyond `plain`'s, e.g. `[account_facts]`,
1247
+ when it's `plain`'s join with more attributes."""
1248
+ if _join(entity) != _join(plain):
1249
+ return []
1250
+ attributes = {attribute["name"]: attribute for attribute in entity.get("attributes", [])}
1251
+ known = {attribute["name"]: attribute for attribute in plain.get("attributes", [])}
1252
+ if any(attributes.get(name) != attribute for name, attribute in known.items()):
1253
+ return []
1254
+ (source,) = entity["sources"]
1255
+ relationships = {
1256
+ relationship["name"]
1257
+ for relationship in datasets[source["dataset"]].get("relationships", [])
1258
+ }
1259
+ return [name for name in attributes if name not in known and name in relationships]
1260
+
1261
+
1262
+ def _join(entity: dict[str, Any]) -> dict[str, Any]:
1263
+ """`entity` without its attributes, each equality in its `on` read with the key on its left,
1264
+ as `id = :users__id` and `:users__id = id` are the same join."""
1265
+
1266
+ def key_first(node: exp.Expr) -> exp.Expr:
1267
+ if (
1268
+ isinstance(node, exp.EQ)
1269
+ and node.right.find(exp.Placeholder)
1270
+ and not node.left.find(exp.Placeholder)
1271
+ ):
1272
+ return exp.EQ(this=node.right, expression=node.left)
1273
+ return node
1274
+
1275
+ return {
1276
+ **{key: value for key, value in entity.items() if key != "attributes"},
1277
+ "sources": [
1278
+ {
1279
+ **source,
1280
+ "on": sqlglot.parse_one(source["on"], read=_DIALECT)
1281
+ .transform(key_first)
1282
+ .sql(_DIALECT),
1283
+ }
1284
+ for source in entity["sources"]
1285
+ ],
1286
+ }
1287
+
1288
+
1289
+ def _matched_column(on: exp.Expr, key: str) -> str | None:
1290
+ """The joined dataset's column `on` compares the key with, e.g. `salesforce_account_id` in
1291
+ `:tickets__salesforce_account_id = salesforce_account_id`, when it's one column."""
1292
+ columns: set[str | None] = set()
1293
+ for comparison in on.find_all(exp.EQ, exp.NEQ, exp.LT, exp.LTE, exp.GT, exp.GTE):
1294
+ for side, other in (
1295
+ (comparison.left, comparison.right),
1296
+ (comparison.right, comparison.left),
1297
+ ):
1298
+ placeholders = {placeholder.name for placeholder in side.find_all(exp.Placeholder)}
1299
+ if key in placeholders and not side.find(exp.Column):
1300
+ columns |= {column.name for column in other.find_all(exp.Column)} or {None}
1301
+ return columns.pop() if len(columns) == 1 else None
1302
+
1303
+
1143
1304
  def _back_name(explore: str, view: str) -> str:
1144
1305
  """The name of the explore on `view` joining `explore`'s base back, see
1145
1306
  `_Converter.back_explores`."""
@@ -1218,19 +1379,13 @@ def _value_flag(match: re.Match[str]) -> str:
1218
1379
  return f"{match[2]}_is_{match[3]}"
1219
1380
 
1220
1381
 
1221
- def _docs(definition: dict[str, Any], **source: str) -> dict[str, Any]:
1222
- """A LookML object's `label` and `description`, and its origin in `meta.lookml`: `source`
1223
- (e.g. its view and field), the field's name, and its `group_label`, `view_label`, `tags` and
1224
- `hidden`, when set."""
1225
- origin: dict[str, Any] = dict(source)
1226
- if "name" in definition and source.get("kind") not in ("view", "explore"):
1227
- origin["field"] = definition["name"]
1228
- for key in ("group_label", "view_label", "tags"):
1229
- if definition.get(key):
1230
- origin[key] = definition[key]
1382
+ def _docs(definition: dict[str, Any], **origin: str) -> dict[str, Any]:
1383
+ """A LookML object's `label` and `description`, `meta.hidden` when Looker hides it, and its
1384
+ `origin` in `meta.lookml`, e.g. a dataset's view, `{view: accounts}`."""
1385
+ meta: dict[str, Any] = {"lookml": origin} if origin else {}
1231
1386
  if definition.get("hidden") == "yes":
1232
- origin["hidden"] = True
1233
- docs: dict[str, Any] = {"meta": {"lookml": origin}}
1387
+ meta["hidden"] = True
1388
+ docs: dict[str, Any] = {"meta": meta} if meta else {}
1234
1389
  for key in ("label", "description"):
1235
1390
  if isinstance(definition.get(key), str) and definition[key].strip():
1236
1391
  docs[key] = definition[key].strip()
@@ -1415,7 +1570,49 @@ def convert(
1415
1570
  ) -> Conversion:
1416
1571
  """Converts `explores` of `model`, or all of them, reading the views it includes: from the
1417
1572
  model's directory, and another project's, e.g. `//fivetran/*.view.lkml`, from `include`'s.
1418
- `group_label` replaces the explores', e.g. to list them apart from the model's."""
1573
+ `group_label` replaces the explores', e.g. to list them apart from the model's.
1574
+
1575
+ A join with `from`, e.g. `join: referral_account { from: accounts }`, reads its view's
1576
+ dataset, unless the view's fields convert differently for it, e.g. as one reads a join under
1577
+ it by another relationship: then the model converts again, the join with a dataset of its
1578
+ own, as Looker reads it."""
1579
+ apart: set[str] = set()
1580
+ while True:
1581
+ try:
1582
+ return _convert(
1583
+ model,
1584
+ explores,
1585
+ user_attributes=user_attributes,
1586
+ connection=connection,
1587
+ include=include,
1588
+ model_name=model_name,
1589
+ group_label=group_label,
1590
+ dashboards=dashboards,
1591
+ catalog=catalog,
1592
+ timezone=timezone,
1593
+ looker_converts=looker_converts,
1594
+ apart=apart,
1595
+ )
1596
+ except _CopiesDiffer as differ:
1597
+ apart |= differ.copies
1598
+
1599
+
1600
+ def _convert(
1601
+ model: Path,
1602
+ explores: list[str],
1603
+ *,
1604
+ user_attributes: dict[str, str],
1605
+ connection: str,
1606
+ include: tuple[Path, ...],
1607
+ model_name: str | None,
1608
+ group_label: str | None,
1609
+ dashboards: tuple[Path, ...],
1610
+ catalog: str,
1611
+ timezone: str | None,
1612
+ looker_converts: bool,
1613
+ apart: set[str],
1614
+ ) -> Conversion:
1615
+ """`convert`, the joins with `from` in `apart` with datasets of their own."""
1419
1616
  parsed = lkml.load(model.read_text())
1420
1617
  views = {
1421
1618
  view["name"]: view
@@ -1454,15 +1651,24 @@ def convert(
1454
1651
  and definition.get("extension") != "required"
1455
1652
  ]
1456
1653
  # Looker reads a join with `from`, e.g. `join: referral_account { from: accounts }`, as a copy
1457
- # of that view under the join's name, so the copy is a view of its own.
1654
+ # of that view under the join's name, so the copy is a view of its own, reading the view's
1655
+ # dataset unless it's `apart`.
1656
+ copied: dict[str, str] = {}
1458
1657
  for definition in selected:
1459
1658
  for join in definition.get("joins", []):
1460
1659
  if join.get("from", join["name"]) != join["name"] and join["name"] not in views:
1461
1660
  views[join["name"]] = {**copy.deepcopy(views[join["from"]]), "name": join["name"]}
1661
+ if join["name"] not in apart:
1662
+ copied[join["name"]] = join["from"]
1462
1663
  # What each explore's joins are, to name what explores join differently.
1463
1664
  drafts = {
1464
1665
  definition["name"]: _Converter(
1465
- views, definition, user_attributes, timezone=timezone, looker_converts=looker_converts
1666
+ views,
1667
+ definition,
1668
+ user_attributes,
1669
+ timezone=timezone,
1670
+ looker_converts=looker_converts,
1671
+ copied=copied,
1466
1672
  )
1467
1673
  for definition in selected
1468
1674
  }
@@ -1472,7 +1678,12 @@ def convert(
1472
1678
  backs = {explore: draft.back_explores() for explore, draft in drafts.items()}
1473
1679
  drafts |= {
1474
1680
  _back_name(explore, view): _Converter(
1475
- views, back, user_attributes, timezone=timezone, looker_converts=looker_converts
1681
+ views,
1682
+ back,
1683
+ user_attributes,
1684
+ timezone=timezone,
1685
+ looker_converts=looker_converts,
1686
+ copied=copied,
1476
1687
  )
1477
1688
  for explore, by_view in backs.items()
1478
1689
  for view, back in by_view.items()
@@ -1506,7 +1717,11 @@ def convert(
1506
1717
  _entity_name,
1507
1718
  )
1508
1719
  # A relationship is a field of its dataset, so it's renamed apart from a column of its name.
1509
- columns = {view: draft.columns[view] for draft in drafts.values() for view in draft.paths}
1720
+ columns = {
1721
+ draft.dataset_name(view): draft.columns[view]
1722
+ for draft in drafts.values()
1723
+ for view in draft.paths
1724
+ }
1510
1725
 
1511
1726
  def relationship_name(key: tuple[str, str]) -> str:
1512
1727
  parent, view = key
@@ -1518,7 +1733,7 @@ def convert(
1518
1733
  relationship_names = _distinct_names(
1519
1734
  {
1520
1735
  explore: {
1521
- (drafts[explore].parents[view], view): {
1736
+ (drafts[explore].dataset_name(drafts[explore].parents[view]), view): {
1522
1737
  "target": entity_names[explore][view],
1523
1738
  "key": key,
1524
1739
  }
@@ -1539,6 +1754,7 @@ def convert(
1539
1754
  datasets: dict[str, Any] = {}
1540
1755
  entities: dict[str, Any] = {}
1541
1756
  constellations: dict[str, Any] = {}
1757
+ converters: dict[str, _Converter] = {}
1542
1758
  skipped: dict[str, list[str]] = {}
1543
1759
  lookml_explores = []
1544
1760
  explore_views: dict[str, dict[str, Any]] = {}
@@ -1547,7 +1763,9 @@ def convert(
1547
1763
  explore = definition["name"]
1548
1764
  base = drafts[explore].base
1549
1765
  back = {
1550
- view: relationship_names[_back_name(explore, view)][(view, base)]
1766
+ view: relationship_names[_back_name(explore, view)][
1767
+ (drafts[explore].dataset_name(view), base)
1768
+ ]
1551
1769
  for view in backs[explore]
1552
1770
  }
1553
1771
  converter = _Converter(
@@ -1560,6 +1778,7 @@ def convert(
1560
1778
  timezone=timezone,
1561
1779
  looker_converts=looker_converts,
1562
1780
  back=back,
1781
+ copied=copied,
1563
1782
  )
1564
1783
  # Converting every field first, so field lists can drop the skipped ones.
1565
1784
  # Explores share views, so a view's skips would otherwise repeat.
@@ -1583,8 +1802,17 @@ def convert(
1583
1802
  {"name": name, "target": target, "key": key}
1584
1803
  )
1585
1804
  for view, dataset in explore_datasets.items():
1586
- _merge_member(datasets, view, dataset)
1587
- constellations[_constellation_name(explore)] = converter.constellation()
1805
+ name = converter.dataset_name(view)
1806
+ try:
1807
+ _merge_member(datasets, name, dataset)
1808
+ except ValueError:
1809
+ # The copy differs, or one of the view's copies merged before it.
1810
+ if differing := {view} & copied.keys() or {
1811
+ c for c, of in copied.items() if of == name
1812
+ }:
1813
+ raise _CopiesDiffer(differing) from None
1814
+ raise
1815
+ converters[explore] = converter
1588
1816
 
1589
1817
  lookml_explore = converter.lookml_explore(catalog)
1590
1818
  if group_label is not None:
@@ -1593,6 +1821,11 @@ def convert(
1593
1821
  for view in converter.paths:
1594
1822
  explore_views.setdefault(view, {})[explore] = converter.lookml_view(view)
1595
1823
  view_paths.setdefault(view, {})[explore] = tuple(converter.lookml_path(view))
1824
+ entities, shared = _shared_entities(entities, datasets)
1825
+ # A constellation's roles reference entities by name, so it waits for them to be shared.
1826
+ for explore, converter in converters.items():
1827
+ converter.entities = {view: shared[name] for view, name in converter.entities.items()}
1828
+ constellations[_constellation_name(explore)] = converter.constellation()
1596
1829
  # Explores share a view, read through its relationships from their base dataset. An explore
1597
1830
  # reaching it through others, e.g. `contacts.accounts` rather than `accounts`, joins a copy
1598
1831
  # read through those, named by them, as the view's fields can't read the path by explore:
File without changes
File without changes