Skip to content

Commit b736130

Browse files
committed
Export a schema with physicalType: view as a view in SQL DDL
Closes #1031
1 parent 1cb0363 commit b736130

4 files changed

Lines changed: 129 additions & 0 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +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)
1718

1819
### Fixed
1920
- `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: 38 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,15 @@ def _to_sql_table(
113115
server_type: str = "snowflake",
114116
**kwargs,
115117
) -> str:
118+
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+
)
126+
116127
if server_type == "databricks":
117128
# Databricks recommends to use the CREATE OR REPLACE statement for unity managed tables
118129
# https://docs.databricks.com/en/sql/language-manual/sql-ref-syntax-ddl-create-table-using.html
@@ -184,6 +195,33 @@ def _to_sql_table(
184195
return result
185196

186197

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]
200+
if server_type == "sqlserver":
201+
result = f"CREATE OR ALTER VIEW {model_name}"
202+
elif server_type == "clickhouse":
203+
result = f"CREATE OR REPLACE VIEW `{model_name}`"
204+
else:
205+
result = f"CREATE OR REPLACE VIEW {model_name}"
206+
207+
# Snowflake and Databricks take column comments in the view's column list
208+
if server_type in ("snowflake", "databricks"):
209+
quote = '"' if server_type == "databricks" else "'"
210+
columns = []
211+
for prop, column_name in zip(model.properties, column_names):
212+
if prop.description is not None:
213+
column_name += f" COMMENT {quote}{_escape(prop.description)}{quote}"
214+
columns.append(f" {column_name}")
215+
result += " (\n" + ",\n".join(columns) + "\n)"
216+
if model.description is not None:
217+
separator = "=" if server_type == "snowflake" else " "
218+
result += f" COMMENT{separator}{quote}{_escape(model.description)}{quote}"
219+
220+
result += " AS\nSELECT\n" + ",\n".join(f" {c}" for c in column_names)
221+
result += "\nFROM " + ", ".join(sources) + ";\n"
222+
return result
223+
224+
187225
def _get_clickhouse_order_by(pk_props: list) -> str | None:
188226
"""Build the ORDER BY clause for ClickHouse from primary key columns."""
189227
if not pk_props:

‎docs/docs/exports/sql.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,31 @@ 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 its properties from the tables listed in their `transformSourceObjects`. Snowflake and Databricks views keep the column and view descriptions as comments.
58+
59+
```yaml
60+
schema:
61+
- name: orders_enriched
62+
physicalType: view
63+
properties:
64+
- name: order_id
65+
transformSourceObjects: [bronze.orders]
66+
- name: customer_name
67+
transformSourceObjects: [bronze.customers]
68+
```
69+
70+
```sql
71+
CREATE OR REPLACE VIEW orders_enriched AS
72+
SELECT
73+
order_id,
74+
customer_name
75+
FROM bronze.orders, bronze.customers;
76+
```
77+
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.
79+
5580
## ClickHouse
5681

5782
```bash

‎tests/test_export_sql.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,3 +144,68 @@ def test_to_sql_ddl_databricks_unity_catalog_staging():
144144
) COMMENT "A single article that is part of an order.";
145145
""".strip()
146146
assert actual == expected
147+
148+
149+
VIEW_CONTRACT = """
150+
apiVersion: v3.1.0
151+
kind: DataContract
152+
id: orders-view
153+
name: orders-view
154+
version: 1.0.0
155+
status: active
156+
schema:
157+
- name: orders_enriched
158+
physicalType: view
159+
description: One row per order with its customer.
160+
properties:
161+
- name: order_id
162+
logicalType: string
163+
required: true
164+
primaryKey: true
165+
description: Unique identifier of the order.
166+
transformSourceObjects:
167+
- bronze.orders
168+
- name: customer_name
169+
logicalType: string
170+
transformSourceObjects:
171+
- bronze.customers
172+
"""
173+
174+
175+
def test_to_sql_ddl_view_postgres():
176+
actual = DataContract(data_contract_str=VIEW_CONTRACT).export("sql", sql_server_type="postgres")
177+
expected = """
178+
-- Data Contract: orders-view
179+
-- SQL Dialect: postgres
180+
CREATE OR REPLACE VIEW orders_enriched AS
181+
SELECT
182+
order_id,
183+
customer_name
184+
FROM bronze.orders, bronze.customers;
185+
""".strip()
186+
assert actual == expected
187+
188+
189+
def test_to_sql_ddl_view_snowflake():
190+
actual = DataContract(data_contract_str=VIEW_CONTRACT).export("sql", sql_server_type="snowflake")
191+
expected = """
192+
-- Data Contract: orders-view
193+
-- SQL Dialect: snowflake
194+
CREATE OR REPLACE VIEW orders_enriched (
195+
order_id COMMENT 'Unique identifier of the order.',
196+
customer_name
197+
) COMMENT='One row per order with its customer.' AS
198+
SELECT
199+
order_id,
200+
customer_name
201+
FROM bronze.orders, bronze.customers;
202+
""".strip()
203+
assert actual == expected
204+
205+
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", ""
209+
)
210+
actual = DataContract(data_contract_str=contract).export("sql", sql_server_type="postgres")
211+
assert "CREATE TABLE orders_enriched (" in actual

0 commit comments

Comments
 (0)