Skip to content

Commit 1fd8977

Browse files
committed
Quote MySQL table, view and column names in export sql
1 parent 1dd48a1 commit 1fd8977

3 files changed

Lines changed: 56 additions & 9 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1313
### Fixed
1414
- Inlining a linked definition merges `logicalTypeOptions` key by key, and allowed values the contract declares in an older form (`logicalTypeOptions.enum`, the `enum` custom property, the `invalidValues` quality rule) win over the definition's `enum`
1515
- `datacontract catalog`: home links lead to the catalog's index when it is not hosted at the domain root (#1810)
16+
- `datacontract export sql` quotes MySQL table, view and column names, so reserved words like `order` no longer break the DDL
1617

1718
- - `datacontract dbt sync` inlines the definitions a contract's properties link to, like `lint`, `test` and `export` (#1765)
1819

‎datacontract/export/sql_exporter.py‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -120,14 +120,15 @@ def _to_sql_table(
120120
if (model.physicalType or "").lower() == "view":
121121
return _to_sql_view(model_name, model, server_type)
122122

123+
quote = "`" if server_type == "mysql" else ""
123124
if server_type == "databricks":
124125
# Databricks recommends to use the CREATE OR REPLACE statement for unity managed tables
125126
# https://docs.databricks.com/en/sql/language-manual/sql-ref-syntax-ddl-create-table-using.html
126127
result = f"CREATE OR REPLACE TABLE {model_name} (\n"
127128
elif server_type == "clickhouse":
128129
result = f"CREATE TABLE IF NOT EXISTS `{model_name}` (\n"
129130
else:
130-
result = f"CREATE TABLE {model_name} (\n"
131+
result = f"CREATE TABLE {quote}{model_name}{quote} (\n"
131132

132133
properties = model.properties or []
133134
pk_props = [p for p in properties if p.primaryKey]
@@ -151,7 +152,7 @@ def _to_sql_table(
151152
if prop.description is not None:
152153
col += f" COMMENT '{_escape_single_quoted(prop.description)}'"
153154
else:
154-
col = f" {column_name} {type_str}"
155+
col = f" {quote}{column_name}{quote} {type_str}"
155156
if prop.required:
156157
col += " not null"
157158
if prop.primaryKey and not composite_pk:
@@ -171,7 +172,7 @@ def _to_sql_table(
171172
if composite_pk and server_type != "clickhouse":
172173
# Sort by primaryKeyPosition (treat None as infinity so un-positioned cols go last)
173174
sorted_pk = sorted(pk_props, key=lambda p: (p.primaryKeyPosition is None, p.primaryKeyPosition))
174-
pk_columns = ", ".join(p.physicalName or p.name for p in sorted_pk)
175+
pk_columns = ", ".join(f"{quote}{p.physicalName or p.name}{quote}" for p in sorted_pk)
175176
# Use the bare table name (strip schema prefix) for the constraint name
176177
constraint_name = model_name.split(".")[-1]
177178
result += f" CONSTRAINT pk_{constraint_name} PRIMARY KEY ({pk_columns})\n"
@@ -224,9 +225,10 @@ def _to_sql_view(model_name: str, model: SchemaObject, server_type: str) -> str:
224225
while alias in aliases.values():
225226
alias, n = f"{base}_{n}", n + 1
226227
aliases[source] = alias
228+
quote = "`" if server_type == "mysql" else ""
227229
select = [
228-
(f"{aliases[source]}.{column}" if source in aliases else column)
229-
+ ("" if column == column_name else f" AS {column_name}")
230+
(f"{aliases[source]}.{quote}{column}{quote}" if source in aliases else f"{quote}{column}{quote}")
231+
+ ("" if column == column_name else f" AS {quote}{column_name}{quote}")
230232
for source, column, column_name in select
231233
]
232234
if len(sources) != 1:
@@ -245,7 +247,7 @@ def _to_sql_view(model_name: str, model: SchemaObject, server_type: str) -> str:
245247

246248
if server_type == "sqlserver":
247249
result = f"CREATE OR ALTER VIEW {model_name}"
248-
elif server_type == "clickhouse":
250+
elif server_type in ("clickhouse", "mysql"):
249251
result = f"CREATE OR REPLACE VIEW `{model_name}`"
250252
else:
251253
result = f"CREATE OR REPLACE VIEW {model_name}"

‎tests/test_export_sql.py‎

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,13 +98,57 @@ def test_to_sql_ddl_mysql_comments():
9898
expected = """
9999
-- Data Contract: mysql-comments
100100
-- SQL Dialect: mysql
101-
CREATE TABLE orders (
102-
order_id int COMMENT 'Unique identifier of the order.'
101+
CREATE TABLE `orders` (
102+
`order_id` int COMMENT 'Unique identifier of the order.'
103103
) COMMENT='The shop''s orders.';
104104
""".strip()
105105
assert actual == expected
106106

107107

108+
def test_to_sql_ddl_mysql_quotes_reserved_words():
109+
actual = DataContract(
110+
data_contract_str="""
111+
apiVersion: v3.1.0
112+
kind: DataContract
113+
id: mysql-reserved
114+
name: MySQL Reserved Words
115+
version: 1.0.0
116+
status: active
117+
schema:
118+
- name: order
119+
properties:
120+
- name: key
121+
logicalType: integer
122+
primaryKey: true
123+
primaryKeyPosition: 1
124+
- name: group
125+
logicalType: integer
126+
primaryKey: true
127+
primaryKeyPosition: 2
128+
- name: window
129+
physicalType: view
130+
properties:
131+
- name: rank
132+
logicalType: integer
133+
transformSourceObjects: [orders.rank]
134+
"""
135+
).export("sql", sql_server_type="mysql")
136+
expected = """
137+
-- Data Contract: mysql-reserved
138+
-- SQL Dialect: mysql
139+
CREATE TABLE `order` (
140+
`key` int,
141+
`group` int,
142+
CONSTRAINT pk_order PRIMARY KEY (`key`, `group`)
143+
);
144+
CREATE OR REPLACE VIEW `window` AS
145+
SELECT
146+
`rank`
147+
FROM orders;
148+
""".strip()
149+
assert actual == expected
150+
151+
108152
def test_to_sql_ddl_mysql_truncates_long_comments():
109153
actual = DataContract(
110154
data_contract_str=f"""
@@ -125,7 +169,7 @@ def test_to_sql_ddl_mysql_truncates_long_comments():
125169
).export("sql", sql_server_type="mysql")
126170
column_comment = "c" * 1000 + "... (1000 chars omitted)"
127171
table_comment = "t" * 2024 + "... (976 chars omitted)"
128-
assert f"order_id int COMMENT '{column_comment}'" in actual
172+
assert f"`order_id` int COMMENT '{column_comment}'" in actual
129173
assert f") COMMENT='{table_comment}';" in actual
130174
assert len(column_comment) <= 1024
131175
assert len(table_comment) <= 2048

0 commit comments

Comments
 (0)