|
| 1 | +import logging |
| 2 | + |
1 | 3 | from open_data_contract_standard.model import OpenDataContractStandard, SchemaObject |
2 | 4 |
|
3 | 5 | from datacontract.export.exporter import Exporter, _check_schema_name_for_export, _determine_sql_server_type |
@@ -113,6 +115,15 @@ def _to_sql_table( |
113 | 115 | server_type: str = "snowflake", |
114 | 116 | **kwargs, |
115 | 117 | ) -> 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 | + |
116 | 127 | if server_type == "databricks": |
117 | 128 | # Databricks recommends to use the CREATE OR REPLACE statement for unity managed tables |
118 | 129 | # https://docs.databricks.com/en/sql/language-manual/sql-ref-syntax-ddl-create-table-using.html |
@@ -184,6 +195,33 @@ def _to_sql_table( |
184 | 195 | return result |
185 | 196 |
|
186 | 197 |
|
| 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 | + |
187 | 225 | def _get_clickhouse_order_by(pk_props: list) -> str | None: |
188 | 226 | """Build the ORDER BY clause for ClickHouse from primary key columns.""" |
189 | 227 | if not pk_props: |
|
0 commit comments