Skip to content

Commit 52b3689

Browse files
committed
Export a schema with physicalType: view as a view in SQL DDL
1 parent ec58c79 commit 52b3689

4 files changed

Lines changed: 175 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
5959
- `datacontract edit`: enable the editor's AI assistant via `DATACONTRACT_EDITOR_AI_*` environment variables (endpoint, API key, model, provider, auth header)
6060
- `datacontract test`: check constraints and quality rules on nested properties on Athena and Trino servers
6161
- `DATACONTRACT_CONNECT_TIMEOUT` (default 30 seconds): `datacontract test` on Postgres, Redshift, MySQL and SQL Server fails with a connection error instead of waiting forever for a server that does not answer, e.g. on a wrong port
62+
- `datacontract export sql`: export a schema with `physicalType: view` as a view that selects from its `transformSourceObjects`, or as a draft with TODOs when there are several or none (#1031)
6263

6364
### Fixed
6465
- `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: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import logging
2+
13
from open_data_contract_standard.model import OpenDataContractStandard, SchemaObject
24

35
from datacontract.export.exporter import Exporter, _check_schema_name_for_export, _determine_sql_server_type
@@ -113,6 +115,9 @@ def _to_sql_table(
113115
server_type: str = "snowflake",
114116
**kwargs,
115117
) -> str:
118+
if (model.physicalType or "").lower() == "view":
119+
return _to_sql_view(model_name, model, server_type)
120+
116121
if server_type == "databricks":
117122
# Databricks recommends to use the CREATE OR REPLACE statement for unity managed tables
118123
# https://docs.databricks.com/en/sql/language-manual/sql-ref-syntax-ddl-create-table-using.html
@@ -184,6 +189,68 @@ def _to_sql_table(
184189
return result
185190

186191

192+
def _to_sql_view(model_name: str, model: SchemaObject, server_type: str) -> str:
193+
"""Select the properties from their transformSourceObjects.
194+
195+
ODCS does not say how several source objects are joined, so the view is then a draft with a
196+
`<TODO: join condition>` that the user has to fill in before it can be created. Without any source object,
197+
it is a draft selecting `FROM <TODO: source object>`.
198+
"""
199+
properties = model.properties or []
200+
column_names = [prop.physicalName or prop.name for prop in properties]
201+
202+
# An entry of transformSourceObjects whose last part is the property's name is a column of the object
203+
# before it; any other entry is an object.
204+
select = []
205+
all_sources = []
206+
for prop, column_name in zip(properties, column_names):
207+
names = {n.lower() for n in (prop.name, prop.physicalName) if n}
208+
column = column_name
209+
for entry in prop.transformSourceObjects or []:
210+
obj, _, col = entry.rpartition(".")
211+
if obj and col.lower() in names:
212+
all_sources.append(obj)
213+
column = col
214+
else:
215+
all_sources.append(entry)
216+
select.append(column if column == column_name else f"{column} AS {column_name}")
217+
sources = list(dict.fromkeys(all_sources))
218+
if len(sources) != 1:
219+
logging.getLogger(__name__).warning(
220+
"Schema '%s' is a view with %s source objects; the exported view is a draft with TODOs to fill in.",
221+
model.name,
222+
len(sources),
223+
)
224+
225+
from_clause = sources[0] if sources else "<TODO: source object>"
226+
for source in sources[1:]:
227+
from_clause += f"\nJOIN {source} ON <TODO: join condition>"
228+
229+
if server_type == "sqlserver":
230+
result = f"CREATE OR ALTER VIEW {model_name}"
231+
elif server_type == "clickhouse":
232+
result = f"CREATE OR REPLACE VIEW `{model_name}`"
233+
else:
234+
result = f"CREATE OR REPLACE VIEW {model_name}"
235+
236+
# Snowflake and Databricks take column comments in the view's column list
237+
if server_type in ("snowflake", "databricks"):
238+
quote = '"' if server_type == "databricks" else "'"
239+
columns = []
240+
for prop, column_name in zip(properties, column_names):
241+
if prop.description is not None:
242+
column_name += f" COMMENT {quote}{_escape(prop.description)}{quote}"
243+
columns.append(f" {column_name}")
244+
result += " (\n" + ",\n".join(columns) + "\n)"
245+
if model.description is not None:
246+
separator = "=" if server_type == "snowflake" else " "
247+
result += f" COMMENT{separator}{quote}{_escape(model.description)}{quote}"
248+
249+
result += " AS\nSELECT\n" + ",\n".join(f" {c}" for c in select)
250+
result += f"\nFROM {from_clause};\n"
251+
return result
252+
253+
187254
def _get_clickhouse_order_by(pk_props: list) -> str | None:
188255
"""Build the ORDER BY clause for ClickHouse from primary key columns."""
189256
if not pk_props:

‎docs/docs/exports/sql.md‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,35 @@ spark.conf.set("spark.databricks.delta.schema.typeCheck.enabled", "false")
5252
```
5353
:::
5454

55+
## Views
56+
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+
ODCS does not say how several source objects are joined. When the properties come from several source objects, or from none, the view is exported as a draft that cannot be created until you fill in each `<TODO: join condition>` or `<TODO: source object>`, and a warning is logged.
60+
61+
```yaml
62+
schema:
63+
- name: orders_enriched
64+
physicalType: view
65+
properties:
66+
- name: order_id
67+
transformSourceObjects: [bronze.orders]
68+
- name: customer_id
69+
transformSourceObjects: [bronze.orders]
70+
- name: customer_name
71+
transformSourceObjects: [bronze.customers]
72+
```
73+
74+
```sql
75+
CREATE OR REPLACE VIEW orders_enriched AS
76+
SELECT
77+
order_id,
78+
customer_id,
79+
customer_name
80+
FROM bronze.orders
81+
JOIN bronze.customers ON <TODO: join condition>;
82+
```
83+
5584
## ClickHouse
5685
5786
```bash

‎tests/test_export_sql.py‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import re
2+
13
from typer.testing import CliRunner
24

35
from datacontract.cli import app
@@ -173,3 +175,79 @@ def test_to_sql_ddl_databricks_unity_catalog_staging():
173175
) COMMENT "A single article that is part of an order.";
174176
""".strip()
175177
assert actual == expected
178+
179+
180+
VIEW_CONTRACT = """
181+
apiVersion: v3.1.0
182+
kind: DataContract
183+
id: orders-view
184+
name: orders-view
185+
version: 1.0.0
186+
status: active
187+
schema:
188+
- name: orders_enriched
189+
physicalType: view
190+
description: One row per order with its customer.
191+
properties:
192+
- name: order_id
193+
logicalType: string
194+
required: true
195+
primaryKey: true
196+
description: Unique identifier of the order.
197+
transformSourceObjects:
198+
- bronze.orders.order_id
199+
- name: customer_id
200+
logicalType: string
201+
transformSourceObjects:
202+
- bronze.orders
203+
- name: customer_name
204+
logicalType: string
205+
transformSourceObjects:
206+
- bronze.orders
207+
"""
208+
209+
210+
def test_to_sql_ddl_view_postgres():
211+
actual = DataContract(data_contract_str=VIEW_CONTRACT).export("sql", sql_server_type="postgres")
212+
expected = """
213+
-- Data Contract: orders-view
214+
-- SQL Dialect: postgres
215+
CREATE OR REPLACE VIEW orders_enriched AS
216+
SELECT
217+
order_id,
218+
customer_id,
219+
customer_name
220+
FROM bronze.orders;
221+
""".strip()
222+
assert actual == expected
223+
224+
225+
def test_to_sql_ddl_view_snowflake():
226+
actual = DataContract(data_contract_str=VIEW_CONTRACT).export("sql", sql_server_type="snowflake")
227+
expected = """
228+
-- Data Contract: orders-view
229+
-- SQL Dialect: snowflake
230+
CREATE OR REPLACE VIEW orders_enriched (
231+
order_id COMMENT 'Unique identifier of the order.',
232+
customer_id,
233+
customer_name
234+
) COMMENT='One row per order with its customer.' AS
235+
SELECT
236+
order_id,
237+
customer_id,
238+
customer_name
239+
FROM bronze.orders;
240+
""".strip()
241+
assert actual == expected
242+
243+
244+
def test_to_sql_ddl_view_several_sources_is_a_draft():
245+
contract = VIEW_CONTRACT.removesuffix("bronze.orders\n") + "bronze.customers\n"
246+
actual = DataContract(data_contract_str=contract).export("sql", sql_server_type="postgres")
247+
assert actual.endswith("FROM bronze.orders\nJOIN bronze.customers ON <TODO: join condition>;")
248+
249+
250+
def test_to_sql_ddl_view_without_sources_is_a_draft():
251+
contract = re.sub(r" +transformSourceObjects:\n( {10}- .*\n)+", "", VIEW_CONTRACT)
252+
actual = DataContract(data_contract_str=contract).export("sql", sql_server_type="postgres")
253+
assert actual.endswith("FROM <TODO: source object>;")

0 commit comments

Comments
 (0)