Skip to content

Commit 30d9aec

Browse files
committed
Join the source objects of a view on its relationships instead of a cross join
1 parent b736130 commit 30d9aec

4 files changed

Lines changed: 144 additions & 27 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1414
- `datacontract import postgres` imports primary and foreign keys from the Postgres catalog, also for SELECT-only roles (#1709 @vtulus)
1515
- `datacontract edit`: enable the editor's AI assistant via `DATACONTRACT_EDITOR_AI_*` environment variables (endpoint, API key, model, provider, auth header)
1616
- `datacontract test`: check constraints and quality rules on nested properties on Athena and Trino servers
17-
- `datacontract export sql`: export a schema with `physicalType: view` as a view that selects from its `transformSourceObjects` (#1031)
17+
- `datacontract export sql`: export a schema with `physicalType: view` as a view that selects from its `transformSourceObjects`, joined on its relationships (#1031)
1818

1919
### Fixed
2020
- `datacontract lint` and `datacontract test`: warn about unknown fields, such as a misspelled `quality`, instead of silently ignoring them (will be an error in the next major version in January 2027)

‎datacontract/export/sql_exporter.py‎

Lines changed: 90 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -116,13 +116,9 @@ def _to_sql_table(
116116
**kwargs,
117117
) -> str:
118118
if (model.physicalType or "").lower() == "view":
119-
sources = list(dict.fromkeys(s for p in model.properties or [] for s in p.transformSourceObjects or []))
120-
if sources:
121-
return _to_sql_view(model_name, model, sources, server_type)
122-
logging.getLogger(__name__).warning(
123-
"Schema '%s' is a view without transformSourceObjects on its properties; exporting it as a table.",
124-
model.name,
125-
)
119+
view = _to_sql_view(model_name, model, server_type)
120+
if view is not None:
121+
return view
126122

127123
if server_type == "databricks":
128124
# Databricks recommends to use the CREATE OR REPLACE statement for unity managed tables
@@ -195,8 +191,90 @@ def _to_sql_table(
195191
return result
196192

197193

198-
def _to_sql_view(model_name: str, model: SchemaObject, sources: list[str], server_type: str) -> str:
199-
column_names = [prop.physicalName or prop.name for prop in model.properties]
194+
def _to_sql_view(model_name: str, model: SchemaObject, server_type: str) -> str | None:
195+
"""Select the properties from their transformSourceObjects, joined on the view's foreignKey relationships.
196+
197+
Returns None, after a warning, when the view cannot be written: no source objects, or a source object
198+
that no relationship joins to the others.
199+
"""
200+
properties = model.properties or []
201+
column_names = [prop.physicalName or prop.name for prop in properties]
202+
203+
# Per property, its (source object, source column). An entry of transformSourceObjects whose last part is
204+
# the property's name is a column of the object before it; any other entry is an object.
205+
property_sources = []
206+
all_sources = []
207+
for prop, column_name in zip(properties, column_names):
208+
names = {n.lower() for n in (prop.name, prop.physicalName) if n}
209+
refs = []
210+
for entry in prop.transformSourceObjects or []:
211+
obj, _, col = entry.rpartition(".")
212+
refs.append((obj, col) if obj and col.lower() in names else (entry, None))
213+
objects = list(dict.fromkeys(obj for obj, _ in refs))
214+
all_sources += objects
215+
column = next((col for _, col in refs if col), column_name)
216+
property_sources.append((objects[0] if len(objects) == 1 else None, column))
217+
sources = list(dict.fromkeys(all_sources))
218+
if not sources:
219+
logging.getLogger(__name__).warning(
220+
"Schema '%s' is a view without transformSourceObjects on its properties; exporting it as a table.",
221+
model.name,
222+
)
223+
return None
224+
225+
def resolve(ref):
226+
# A `table.column` reference points to the source object that is, or ends with, that table
227+
table, _, column = str(ref).rpartition(".")
228+
matches = [s for s in sources if table and (s == table or s.endswith(f".{table}"))]
229+
return (matches[0], column) if len(matches) == 1 else None
230+
231+
def as_list(refs):
232+
return refs if isinstance(refs, list) else [refs]
233+
234+
edges = []
235+
for rel in model.relationships or []:
236+
if (rel.type or "foreignKey") == "foreignKey" and len(as_list(rel.from_)) == len(as_list(rel.to)):
237+
edges += [(resolve(f), resolve(t)) for f, t in zip(as_list(rel.from_), as_list(rel.to))]
238+
for prop, (source, column) in zip(properties, property_sources):
239+
for rel in prop.relationships or []:
240+
if (rel.type or "foreignKey") == "foreignKey" and source is not None and len(as_list(rel.to)) == 1:
241+
edges.append(((source, column), resolve(as_list(rel.to)[0])))
242+
edges = [(a, b) for a, b in edges if a and b and a[0] != b[0]]
243+
244+
# Join each further source object to the ones already joined, on every relationship between them
245+
joined, joins = [sources[0]], []
246+
while len(joined) < len(sources):
247+
for source in (s for s in sources if s not in joined):
248+
conditions = [
249+
(b, a) if a[0] == source else (a, b) for a, b in edges if {a[0], b[0]} - {*joined} == {source}
250+
]
251+
if conditions:
252+
joined.append(source)
253+
joins.append((source, conditions))
254+
break
255+
else:
256+
logging.getLogger(__name__).warning(
257+
"Schema '%s' is a view whose source objects %s are not all joined by foreignKey relationships; "
258+
"exporting it as a table.",
259+
model.name,
260+
", ".join(sources),
261+
)
262+
return None
263+
264+
# With several source objects, columns are qualified by an alias: the object's last part, made unique
265+
aliases = {}
266+
for source in sources:
267+
alias = source.rpartition(".")[2]
268+
aliases[source] = alias if alias not in aliases.values() else f"{alias}_{len(aliases) + 1}"
269+
select = []
270+
for column_name, (source, column) in zip(column_names, property_sources):
271+
expression = f"{aliases[source]}.{column}" if source is not None and len(sources) > 1 else column
272+
select.append(expression if column == column_name else f"{expression} AS {column_name}")
273+
from_clause = sources[0] if len(sources) == 1 else f"{sources[0]} {aliases[sources[0]]}"
274+
for source, conditions in joins:
275+
on = " AND ".join(f"{aliases[a[0]]}.{a[1]} = {aliases[b[0]]}.{b[1]}" for a, b in conditions)
276+
from_clause += f"\nLEFT JOIN {source} {aliases[source]} ON {on}"
277+
200278
if server_type == "sqlserver":
201279
result = f"CREATE OR ALTER VIEW {model_name}"
202280
elif server_type == "clickhouse":
@@ -208,7 +286,7 @@ def _to_sql_view(model_name: str, model: SchemaObject, sources: list[str], serve
208286
if server_type in ("snowflake", "databricks"):
209287
quote = '"' if server_type == "databricks" else "'"
210288
columns = []
211-
for prop, column_name in zip(model.properties, column_names):
289+
for prop, column_name in zip(properties, column_names):
212290
if prop.description is not None:
213291
column_name += f" COMMENT {quote}{_escape(prop.description)}{quote}"
214292
columns.append(f" {column_name}")
@@ -217,8 +295,8 @@ def _to_sql_view(model_name: str, model: SchemaObject, sources: list[str], serve
217295
separator = "=" if server_type == "snowflake" else " "
218296
result += f" COMMENT{separator}{quote}{_escape(model.description)}{quote}"
219297

220-
result += " AS\nSELECT\n" + ",\n".join(f" {c}" for c in column_names)
221-
result += "\nFROM " + ", ".join(sources) + ";\n"
298+
result += " AS\nSELECT\n" + ",\n".join(f" {c}" for c in select)
299+
result += f"\nFROM {from_clause};\n"
222300
return result
223301

224302

‎docs/docs/exports/sql.md‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,9 @@ spark.conf.set("spark.databricks.delta.schema.typeCheck.enabled", "false")
5454

5555
## Views
5656

57-
A schema with `physicalType: view` is exported as a `CREATE OR REPLACE VIEW` (`CREATE OR ALTER VIEW` on SQL Server) that selects its properties from the tables listed in their `transformSourceObjects`. Snowflake and Databricks views keep the column and view descriptions as comments.
57+
A schema with `physicalType: view` is exported as a `CREATE OR REPLACE VIEW` (`CREATE OR ALTER VIEW` on SQL Server) that selects each property from the object in its `transformSourceObjects`. An entry whose last part is the property's name, such as `bronze.orders.order_id`, is read as that column of the object. Snowflake and Databricks views keep the column and view descriptions as comments.
58+
59+
When the properties come from several source objects, they are joined with `LEFT JOIN`, starting from the first object, on the `foreignKey` relationships of the view. A `customers.id` reference points to the source object `customers` or `<schema>.customers`.
5860

5961
```yaml
6062
schema:
@@ -63,19 +65,25 @@ schema:
6365
properties:
6466
- name: order_id
6567
transformSourceObjects: [bronze.orders]
68+
- name: customer_id
69+
transformSourceObjects: [bronze.orders]
70+
relationships:
71+
- to: customers.id
6672
- name: customer_name
6773
transformSourceObjects: [bronze.customers]
6874
```
6975
7076
```sql
7177
CREATE OR REPLACE VIEW orders_enriched AS
7278
SELECT
73-
order_id,
74-
customer_name
75-
FROM bronze.orders, bronze.customers;
79+
orders.order_id,
80+
orders.customer_id,
81+
customers.customer_name
82+
FROM bronze.orders orders
83+
LEFT JOIN bronze.customers customers ON orders.customer_id = customers.id;
7684
```
7785

78-
Several source objects are listed in one `FROM` clause; add the join condition by hand. A view without any `transformSourceObjects` is exported as a table.
86+
A view is exported as a table, with a warning, when its properties have no `transformSourceObjects` or when a source object is not joined to the others by a relationship.
7987

8088
## ClickHouse
8189

‎tests/test_export_sql.py‎

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import re
2+
3+
import pytest
14
from typer.testing import CliRunner
25

36
from datacontract.cli import app
@@ -163,8 +166,14 @@ def test_to_sql_ddl_databricks_unity_catalog_staging():
163166
required: true
164167
primaryKey: true
165168
description: Unique identifier of the order.
169+
transformSourceObjects:
170+
- bronze.orders.order_id
171+
- name: customer_id
172+
logicalType: string
166173
transformSourceObjects:
167174
- bronze.orders
175+
relationships:
176+
- to: customers.id
168177
- name: customer_name
169178
logicalType: string
170179
transformSourceObjects:
@@ -179,9 +188,11 @@ def test_to_sql_ddl_view_postgres():
179188
-- SQL Dialect: postgres
180189
CREATE OR REPLACE VIEW orders_enriched AS
181190
SELECT
182-
order_id,
183-
customer_name
184-
FROM bronze.orders, bronze.customers;
191+
orders.order_id,
192+
orders.customer_id,
193+
customers.customer_name
194+
FROM bronze.orders orders
195+
LEFT JOIN bronze.customers customers ON orders.customer_id = customers.id;
185196
""".strip()
186197
assert actual == expected
187198

@@ -193,19 +204,39 @@ def test_to_sql_ddl_view_snowflake():
193204
-- SQL Dialect: snowflake
194205
CREATE OR REPLACE VIEW orders_enriched (
195206
order_id COMMENT 'Unique identifier of the order.',
207+
customer_id,
196208
customer_name
197209
) COMMENT='One row per order with its customer.' AS
198210
SELECT
199-
order_id,
200-
customer_name
201-
FROM bronze.orders, bronze.customers;
211+
orders.order_id,
212+
orders.customer_id,
213+
customers.customer_name
214+
FROM bronze.orders orders
215+
LEFT JOIN bronze.customers customers ON orders.customer_id = customers.id;
202216
""".strip()
203217
assert actual == expected
204218

205219

206-
def test_to_sql_ddl_view_without_source_objects_is_a_table():
207-
contract = VIEW_CONTRACT.replace(" transformSourceObjects:\n - bronze.orders\n", "").replace(
208-
" transformSourceObjects:\n - bronze.customers\n", ""
220+
def test_to_sql_ddl_view_schema_level_relationship():
221+
contract = VIEW_CONTRACT.replace(" relationships:\n - to: customers.id\n", "") + (
222+
" relationships:\n - from: orders.customer_id\n to: customers.id\n"
209223
)
210224
actual = DataContract(data_contract_str=contract).export("sql", sql_server_type="postgres")
225+
assert "LEFT JOIN bronze.customers customers ON orders.customer_id = customers.id;" in actual
226+
227+
228+
def test_to_sql_ddl_view_single_source():
229+
contract = VIEW_CONTRACT.replace(" - bronze.customers\n", " - bronze.orders\n")
230+
actual = DataContract(data_contract_str=contract).export("sql", sql_server_type="postgres")
231+
assert actual.endswith("SELECT\n order_id,\n customer_id,\n customer_name\nFROM bronze.orders;")
232+
233+
234+
@pytest.mark.parametrize(
235+
"removed",
236+
[r" +relationships:\n +- to: .*\n", r" +transformSourceObjects:\n( +- .*\n)+"],
237+
ids=["sources not joined", "no sources"],
238+
)
239+
def test_to_sql_ddl_view_that_cannot_be_written_is_a_table(removed):
240+
contract = re.sub(removed, "", VIEW_CONTRACT)
241+
actual = DataContract(data_contract_str=contract).export("sql", sql_server_type="postgres")
211242
assert "CREATE TABLE orders_enriched (" in actual

0 commit comments

Comments
 (0)