From 2a1523b0c5a3e70fb9ff9cc3423433c776d9ee75 Mon Sep 17 00:00:00 2001 From: Anas Khan <83116240+anxkhn@users.noreply.github.com> Date: Sun, 5 Jul 2026 05:06:18 +0530 Subject: [PATCH] fix(clickhouse): unwrap parenthesized PRIMARY_KEY independent of ORDER_BY The PRIMARY_KEY branch in _build_table_properties_exp tested the ORDER_BY value (ordered_by_raw) for exp.Paren instead of the primary_key value, a copy-paste leftover from the ORDER_BY block above it. As a result a single parenthesized PRIMARY_KEY such as PRIMARY_KEY = (a) was only unwrapped when ORDER_BY also happened to be a Paren; with a bare column, a tuple, or no ORDER_BY the parentheses were kept and the adapter emitted the malformed PRIMARY KEY ((a)). The generated primary key wrongly depended on the unrelated ORDER_BY shape. Check primary_key for exp.Paren so it is unwrapped regardless of ORDER_BY, and add regression cases pairing PRIMARY_KEY = (a) with a bare and a tuple ORDER_BY. Signed-off-by: Anas Khan <83116240+anxkhn@users.noreply.github.com> --- sqlmesh/core/engine_adapter/clickhouse.py | 2 +- tests/core/engine_adapter/test_clickhouse.py | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/sqlmesh/core/engine_adapter/clickhouse.py b/sqlmesh/core/engine_adapter/clickhouse.py index f5ef705b08..7bbb7d9870 100644 --- a/sqlmesh/core/engine_adapter/clickhouse.py +++ b/sqlmesh/core/engine_adapter/clickhouse.py @@ -850,7 +850,7 @@ def _build_table_properties_exp( primary_key_vals = [] if isinstance(primary_key, (exp.Tuple, exp.Array)): primary_key_vals = primary_key.expressions - if isinstance(ordered_by_raw, exp.Paren): + if isinstance(primary_key, exp.Paren): primary_key_vals = [primary_key.this] if not primary_key_vals: diff --git a/tests/core/engine_adapter/test_clickhouse.py b/tests/core/engine_adapter/test_clickhouse.py index 110f937ccb..6b0a7d57f3 100644 --- a/tests/core/engine_adapter/test_clickhouse.py +++ b/tests/core/engine_adapter/test_clickhouse.py @@ -305,6 +305,20 @@ def build_properties_sql(storage_format="", order_by="", primary_key="", propert == "ENGINE=MergeTree ORDER BY (a) PRIMARY KEY (a)" ) + # A parenthesized single-column PRIMARY_KEY must be unwrapped regardless of the + # ORDER_BY shape. Previously the PRIMARY_KEY branch checked ORDER_BY's expression, + # so pairing PRIMARY_KEY = (a) with a non-parenthesized ORDER_BY emitted the + # malformed "PRIMARY KEY ((a))". + assert ( + build_properties_sql(order_by="ORDER_BY = a,", primary_key="PRIMARY_KEY = (a)") + == "ENGINE=MergeTree ORDER BY (a) PRIMARY KEY (a)" + ) + + assert ( + build_properties_sql(order_by="ORDER_BY = (a, b),", primary_key="PRIMARY_KEY = (a)") + == "ENGINE=MergeTree ORDER BY (a, b) PRIMARY KEY (a)" + ) + assert build_properties_sql(order_by="ORDER_BY = a + 1,") == "ENGINE=MergeTree ORDER BY (a + 1)" assert (