Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
### Unreleased

#### Bugs
* Fix `on_schema_change` and `mv_on_schema_change` reporting a spurious type change on the HTTP driver for named `Tuple` columns, such as `Array(Tuple(id UInt64, name String))`, and for `JSON` columns with parameters ([#836](https://github.com/ClickHouse/dbt-clickhouse/pull/836)).
* A `primary_key` config that is only whitespace, as a string or as list entries, is now trimmed and treated as unset instead of rendering an invalid `PRIMARY KEY` clause ([#832](https://github.com/ClickHouse/dbt-clickhouse/pull/832)).

### Release [1.10.4], 2026-11-24
Expand Down
28 changes: 28 additions & 0 deletions dbt/adapters/clickhouse/column.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,38 @@
from typing import Any, List, Literal, TypeVar

from dbt.adapters.base.column import Column
from dbt.adapters.clickhouse.query import escape_str
from dbt_common.exceptions import DbtRuntimeError

Self = TypeVar('Self', bound='ClickHouseColumn')

# A single-quoted string literal or a backquoted identifier, each with its escapes
_QUOTED_TOKEN_REGEX = re.compile(r"'(?:[^'\\]|\\.|'')*'|`(?:[^`\\]|\\.|``)*`")
_IDENTIFIER_ESCAPE_REGEX = re.compile(r'\\(.)|``')
_BARE_IDENTIFIER_REGEX = re.compile(r'[A-Za-z_][0-9A-Za-z_]*')
_SPACE_AROUND_PUNCTUATION_REGEX = re.compile(r'\s*([(),=])\s*')


def _comparable_identifier(quoted: str) -> str:
name = _IDENTIFIER_ESCAPE_REGEX.sub(lambda m: m.group(1) or '`', quoted[1:-1])
if _BARE_IDENTIFIER_REGEX.fullmatch(name):
return name
return f'`{escape_str(name)}`'


def comparable_type_name(type_name: str) -> str:
"""Type name with the quotes and spacing that differ between the server's and
clickhouse-connect's spelling normalised away. Only for comparisons, not for DDL."""
parts = []
pos = 0
for match in _QUOTED_TOKEN_REGEX.finditer(type_name):
parts.append(_SPACE_AROUND_PUNCTUATION_REGEX.sub(r'\1', type_name[pos : match.start()]))
token = match.group(0)
parts.append(_comparable_identifier(token) if token[0] == '`' else token)
pos = match.end()
parts.append(_SPACE_AROUND_PUNCTUATION_REGEX.sub(r'\1', type_name[pos:]))
return ''.join(parts)


@dataclass
class ClickHouseColumn(Column):
Expand Down
17 changes: 15 additions & 2 deletions dbt/adapters/clickhouse/impl.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@
from dbt.adapters.base.relation import BaseRelation, InformationSchema
from dbt.adapters.capability import Capability, CapabilityDict, CapabilitySupport, Support
from dbt.adapters.clickhouse.cache import ClickHouseRelationsCache
from dbt.adapters.clickhouse.column import ClickHouseColumn, ClickHouseColumnChanges
from dbt.adapters.clickhouse.column import (
ClickHouseColumn,
ClickHouseColumnChanges,
comparable_type_name,
)
from dbt.adapters.clickhouse.connections import ClickHouseConnectionManager
from dbt.adapters.clickhouse.dbclient import ND_MUTATION_SETTING
from dbt.adapters.clickhouse.errors import (
Expand Down Expand Up @@ -194,6 +198,13 @@ def should_on_cluster(
)
return ClickHouseRelation.get_on_cluster()

@available
def data_types_match(self, left: Optional[str], right: Optional[str]) -> bool:
"""True if both type names are the same type, however each driver spells it."""
if left is None or right is None:
return left == right
return comparable_type_name(left) == comparable_type_name(right)

@available
def render_event_time_filter(
self, field_name: str, start: Optional[datetime], end: Optional[datetime]
Expand Down Expand Up @@ -267,7 +278,9 @@ def check_incremental_schema_changes(
changed_data_types = []
for column in target_in_source:
source_column = source_map.get(column.name)
if source_column is not None and column.dtype != source_column.dtype:
if source_column is not None and not self.data_types_match(
column.dtype, source_column.dtype
):
changed_data_types.append(column)

clickhouse_column_changes = ClickHouseColumnChanges(
Expand Down
2 changes: 1 addition & 1 deletion dbt/include/clickhouse/macros/column_spec_ddl.sql
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
{#-- Column with name not found in yaml #}
{%- do exceptions.raise_contract_error(yaml_columns, sql_columns) -%}
{%- endif -%}
{%- if sql_col['data_type'] != yaml_col[0]['data_type'] -%}
{%- if not adapter.data_types_match(sql_col['data_type'], yaml_col[0]['data_type']) -%}
{#-- Column data types don't match #}
{%- do exceptions.raise_contract_error(yaml_columns, sql_columns) -%}
{%- endif -%}
Expand Down
20 changes: 20 additions & 0 deletions tests/integration/adapter/constraints/test_constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,26 @@ def test__contract_fixedstring_string_mismatch(self, project):
]
assert all([(exp in log_output or exp.upper() in log_output) for exp in expected])

def test__contract_named_tuple_data_type(self, project):
# The HTTP driver reports the element names backquoted; either spelling must pass
write_file(
my_model_data_type_sql.format(
sql_value="CAST((1, 'a'), 'Tuple(id UInt64, name String)')"
),
"models",
"my_model_data_type.sql",
)
for schema_data_type in (
'Tuple(id UInt64, name String)',
'Tuple(`id` UInt64, `name` String)',
):
write_file(
model_data_type_schema_yml.format(data_type=schema_data_type),
"models",
"contract_schema.yml",
)
run_dbt(["run", "-s", "my_model_data_type"])

def test__contract_correct_column_data_types(self, project, data_types):
for sql_column_value, schema_data_type, _ in data_types:
# Write parametrized data_type to sql file
Expand Down
44 changes: 44 additions & 0 deletions tests/integration/adapter/incremental/test_schema_change.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,3 +373,47 @@ def test_sync(self, project, model):
# The MODIFY COLUMN that widens col_2 must use the exact type, not String
assert self.column_type(project, model, 'col_2') == 'FixedString(32)'
run_dbt(["run", "--select", model])


# No unique_key, so the default strategy is append, which checks for schema changes
named_tuple_sql = """
{{
config(
materialized='%s',
on_schema_change='fail'
)
}}

select
number as id,
CAST([], 'Array(Tuple(id UInt64, name String, request_count UInt64))') as tags,
CAST((1, 'a'), 'Tuple(`from` UInt8, `table` String)') as keyword_names
from numbers(3)
"""


class TestNamedTupleSchemaChange:
@pytest.fixture(scope="class")
def models(self):
return {
"named_tuple.sql": named_tuple_sql % "incremental",
"named_tuple_distributed.sql": named_tuple_sql % "distributed_incremental",
}

@pytest.mark.parametrize("model", ("named_tuple", "named_tuple_distributed"))
def test_unchanged_schema(self, project, model):
if "distributed" in model and os.environ.get('DBT_CH_TEST_CLUSTER', '').strip() == '':
pytest.skip("Not on a cluster")
run_dbt(["run", "--select", model])
result = project.run_sql(
f"select type from system.columns "
f"where database = currentDatabase() and table = '{model}' and name = 'tags'",
fetch="one",
)
assert result[0] == 'Array(Tuple(id UInt64, name String, request_count UInt64))'
# The HTTP driver reported the element names backquoted, which failed this
# run with a spurious type change. Which of the keyword_names elements the
# server quotes depends on its version.
run_dbt(["run", "--select", model])
result = project.run_sql(f"select count() from {model}", fetch="one")
assert result[0] == 6
91 changes: 91 additions & 0 deletions tests/unit/test_type_comparison.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import pytest
from clickhouse_connect.datatypes.registry import get_from_name
from dbt.adapters.clickhouse.column import ClickHouseColumn, comparable_type_name
from dbt.adapters.clickhouse.impl import ClickHouseAdapter


@pytest.mark.parametrize(
'server_spelling',
[
'Array(Tuple(id UInt64, name String, request_count UInt64))',
'Tuple(a Int32, b Tuple(c String, d Array(UInt8)))',
'Map(String, Tuple(k UInt64, v String))',
# Names ClickHouse 24.3-25.8 writes bare but newer servers quote
'Tuple(from UInt8, select String, values UInt8)',
'Tuple(`from` UInt8, `select` String, `values` UInt8)',
'Tuple(`b c` String, `1x` UInt8)',
"Tuple(`it's` String)",
'JSON(max_dynamic_paths=10)',
'JSON(`a.b` UInt32, SKIP c)',
"Enum8('a' = 1, 'b' = 2)",
"DateTime64(3, 'UTC')",
'Decimal(18, 4)',
],
)
def test_http_spelling_compares_equal_to_server_spelling(server_spelling):
http_spelling = get_from_name(server_spelling).name
assert comparable_type_name(http_spelling) == comparable_type_name(server_spelling)


@pytest.mark.parametrize(
'left,right',
[
('Tuple(id UInt64)', 'Tuple(id String)'),
('Tuple(id UInt64)', 'Tuple(uid UInt64)'),
('Tuple(`a b` UInt8)', 'Tuple(a_b UInt8)'),
('Tuple(`a,b` UInt8)', 'Tuple(a UInt8, b UInt8)'),
("Enum8('a' = 1)", "Enum8('a ' = 1)"),
("Enum8('`a`' = 1)", "Enum8('a' = 1)"),
('Tuple(UInt64, String)', 'Tuple(a UInt64, b String)'),
],
)
def test_different_types_still_compare_different(left, right):
assert comparable_type_name(left) != comparable_type_name(right)


def _adapter_with_columns(source, target) -> ClickHouseAdapter:
adapter = ClickHouseAdapter.__new__(ClickHouseAdapter)
adapter.get_columns_in_relation = lambda relation: [
ClickHouseColumn(name, dtype) for name, dtype in source
]
adapter.get_column_schema_from_query = lambda sql, **kwargs: [
ClickHouseColumn(name, dtype) for name, dtype in target
]
return adapter


def test_schema_change_check_ignores_http_spelling():
server_spelling = 'Array(Tuple(id UInt64, from String))'
adapter = _adapter_with_columns(
source=[('tags', server_spelling)],
target=[('tags', get_from_name(server_spelling).name)],
)

changes = adapter.check_incremental_schema_changes('fail', None, 'select 1')

assert not changes


def test_schema_change_check_detects_tuple_element_type_change():
adapter = _adapter_with_columns(
source=[('tags', 'Array(Tuple(id UInt64, name String))')],
target=[('tags', 'Array(Tuple(`id` UInt64, `name` LowCardinality(String)))')],
)

changes = adapter.check_incremental_schema_changes('sync_all_columns', None, 'select 1')

assert [column.name for column in changes.columns_to_modify] == ['tags']


@pytest.mark.parametrize(
'left,right,expected',
[
('Tuple(id UInt64)', 'Tuple(`id` UInt64)', True),
('Tuple(id UInt64)', 'Tuple(id String)', False),
('String', None, False),
(None, None, True),
],
)
def test_data_types_match(left, right, expected):
adapter = ClickHouseAdapter.__new__(ClickHouseAdapter)
assert adapter.data_types_match(left, right) is expected