From f39d6d1c4fb9c346f1a141e0b2331359979016ae Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Tue, 15 Sep 2026 05:20:37 +0000 Subject: [PATCH 1/7] feat(clickhouse): migrate legacy clickhouse connections to clickhouse-connect Rewrites the sqlalchemy_uri of Database rows on the legacy `clickhouse` backend (clickhouse-sqlalchemy driver) to `clickhousedb+connect://` so they resolve to ClickHouseConnectEngineSpec and render the new dynamic connection form. - HTTP schemes (clickhouse://, clickhouse+http://) change scheme only; the HTTP port (8123) is preserved byte-for-byte along with credentials, database and query string. - Native schemes (clickhouse+native://, clickhouse+asynch://) also move the native default port 9000 to the HTTP port 8123 because clickhouse-connect is HTTP-only. Non-default native ports are left on the legacy driver. - Idempotent (rows already on clickhousedb are skipped). Downgrade is a documented no-op: migrated rows are indistinguishable from natively-created clickhousedb connections and remain functional after a rollback. - Merges the two open revision heads (88a01c781622, c7f53d184ea2). Story: https://app.shortcut.com/preset/story/120997 Co-Authored-By: Claude Opus 4.8 --- ...4e02_migrate_clickhouse_to_clickhousedb.py | 195 +++++++++++++++ ...test_migrate_clickhouse_to_clickhousedb.py | 229 ++++++++++++++++++ 2 files changed, 424 insertions(+) create mode 100644 superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py create mode 100644 tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py diff --git a/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py b/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py new file mode 100644 index 000000000000..b74e9c433dce --- /dev/null +++ b/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py @@ -0,0 +1,195 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""migrate legacy ClickHouse connections onto the clickhouse-connect driver + +Superset ships two ClickHouse engine specs. ``ClickHouseEngineSpec`` (backend +``clickhouse``, the ``clickhouse-sqlalchemy`` driver) is the legacy spec and has +no dynamic parameters schema, so its connections still render the free-form +SQLAlchemy URI editor. ``ClickHouseConnectEngineSpec`` (backend ``clickhousedb``, +default driver ``connect``, the ``clickhouse-connect`` driver) defines a +``parameters_schema`` and therefore renders the new dynamic connection form. + +This migration rewrites the ``sqlalchemy_uri`` of connections stored on the +legacy ``clickhouse`` backend so they resolve to ``ClickHouseConnectEngineSpec`` +and expose the new form. The backend name is what selects the engine spec +(``Database.db_engine_spec`` reads ``url.get_backend_name()``), so the scheme is +rewritten from ``clickhouse[+driver]://`` to ``clickhousedb+connect://``. + +Scheme and port mapping +----------------------- + +* ``clickhouse://`` and ``clickhouse+http://`` -- the ``clickhouse-sqlalchemy`` + HTTP dialect, default port 8123. ``clickhouse-connect`` also speaks HTTP on + 8123, so only the scheme changes; host, port, credentials, database and query + string are preserved byte-for-byte. +* ``clickhouse+native://`` and ``clickhouse+asynch://`` -- the native TCP + protocol, default port 9000. ``clickhouse-connect`` cannot speak the native + protocol; it is HTTP-only. A native connection therefore also needs its port + moved to the HTTP interface. When the port is the native default (9000, or + absent -- which implies 9000) it is rewritten to the HTTP default (8123). + A *non-default* native port cannot be mapped to an HTTP port without knowing + the server's configuration, so those rows are left on the legacy driver for a + human to migrate rather than pointed at a guessed port. Operators should + confirm the HTTP interface is enabled on the rewritten native connections. + +Password handling: the credential lives either inline in the URI or in +``encrypted_extra``; both are preserved because the URI is edited in place (only +the scheme, and for native rows the port, are touched) and ``encrypted_extra`` +is never read. + +Only rows whose backend is exactly ``clickhouse`` are rewritten; rows already on +``clickhousedb`` are skipped, which also makes ``upgrade`` idempotent. + +Downgrade +--------- + +``downgrade`` is intentionally a no-op. After ``upgrade`` a migrated row is +byte-for-byte indistinguishable from a connection an operator created directly on +the ``clickhousedb`` key (both are produced by ``build_sqlalchemy_uri`` as +``clickhousedb+connect://...``), so a blind reversal would also revert genuine +``clickhousedb`` connections onto the legacy driver and break them. The migrated +connections keep working after a code rollback regardless, because +``ClickHouseConnectEngineSpec`` predates this migration -- no data restoration is +required for them to remain functional -- so the safe choice is to leave the +rewritten URIs in place. + +The revision tree had two open heads when this was authored -- ``88a01c781622`` +(``index_ab_user_lower_username``) and ``c7f53d184ea2`` +(``coordinate_purge_audit_pruning``), which forked at ``7e2c9a4f1b83``. This +revision merges them so the tree keeps a single head; the data rewrite itself is +independent of both branches. + +Revision ID: f7b3a9c14e02 +Revises: 88a01c781622, c7f53d184ea2 +Create Date: 2026-09-15 00:00:00.000000 + +""" + +from alembic import op +from sqlalchemy import Column, Integer, String +from sqlalchemy.orm import declarative_base + +from superset import db +from superset.migrations.shared.utils import paginated_update + +# revision identifiers, used by Alembic. +revision = "f7b3a9c14e02" +down_revision = ("88a01c781622", "c7f53d184ea2") + +Base = declarative_base() + +LEGACY_BACKEND = "clickhouse" +TARGET_SCHEME = "clickhousedb+connect" + +# Drivers that use the native TCP protocol rather than HTTP. +NATIVE_DRIVERS = {"native", "asynch"} +NATIVE_DEFAULT_PORT = "9000" +HTTP_DEFAULT_PORT = "8123" + + +class Database(Base): # type: ignore + __tablename__ = "dbs" + + id = Column(Integer, primary_key=True) + sqlalchemy_uri = Column(String(1024), nullable=False) + + +def _swap_native_default_port(remainder: str) -> str | None: + """Move a native-default port onto the HTTP interface. + + ``remainder`` is everything after ``://`` -- ``userinfo@host[:port][/path] + [?query]``. Returns the remainder with the port rewritten to the HTTP + default when it is the native default (9000) or absent (which implies 9000), + and ``None`` when the port is a non-default native port or an IPv6 literal + host is present, so the caller can leave those rows on the legacy driver + rather than guess an HTTP port. + """ + # Credentials are not escaped for "@", so the host section starts after the + # last one. + host_start = remainder.rfind("@") + 1 + + # The authority ends at the path or query, whichever comes first. + end = len(remainder) + for index in range(host_start, len(remainder)): + if remainder[index] in "/?": + end = index + break + + authority = remainder[host_start:end] + if authority.startswith("["): + # IPv6 literal host -- the "host:port" split below is unsafe here. + return None + + host, colon, port = authority.rpartition(":") + if not colon: + # No explicit port: the native driver defaults to 9000, so pin the HTTP + # port explicitly for clickhouse-connect. + new_authority = f"{authority}:{HTTP_DEFAULT_PORT}" + elif port == NATIVE_DEFAULT_PORT: + new_authority = f"{host}:{HTTP_DEFAULT_PORT}" + else: + return None + + return remainder[:host_start] + new_authority + remainder[end:] + + +def _migrate_uri(uri: str) -> str | None: + """Rewrite a legacy ``clickhouse`` URI onto ``clickhousedb+connect``. + + Returns ``None`` when the URI should be left untouched (already on the + ``clickhousedb`` backend, malformed, or a native connection whose port + cannot be mapped to the HTTP interface). + """ + scheme, separator, remainder = uri.partition("://") + if not separator: + return None + + backend, _, driver = scheme.partition("+") + if backend != LEGACY_BACKEND: + # Already clickhousedb, or an unrelated engine. + return None + + if driver in NATIVE_DRIVERS: + remapped = _swap_native_default_port(remainder) + if remapped is None: + return None + remainder = remapped + + return f"{TARGET_SCHEME}://{remainder}" + + +def upgrade() -> None: + bind = op.get_bind() + session = db.Session(bind=bind) + + # The LIKE also matches "clickhousedb%"; _migrate_uri filters those out by + # backend name, so re-running is a no-op. + query = session.query(Database).filter(Database.sqlalchemy_uri.like("clickhouse%")) + for database in paginated_update(query): + updated = _migrate_uri(database.sqlalchemy_uri) + if updated: + database.sqlalchemy_uri = updated + + session.commit() + + +def downgrade() -> None: + # Intentionally a no-op; see the module docstring. A migrated row is + # indistinguishable from a natively-created clickhousedb connection, and the + # rewritten URIs remain functional after a code rollback, so nothing is + # reverted. + pass diff --git a/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py b/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py new file mode 100644 index 000000000000..fa760b4795bf --- /dev/null +++ b/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py @@ -0,0 +1,229 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +"""Tests for migration ``f7b3a9c14e02_migrate_clickhouse_to_clickhousedb``. + +Covers the URI rewrite helper (HTTP and native drivers, port mapping, rows that +must be skipped), the full upgrade() path over a mixture of connections, and the +no-op downgrade(). +""" + +from __future__ import annotations + +from importlib import import_module +from unittest.mock import patch + +import pytest +from sqlalchemy import create_engine +from sqlalchemy.orm import Session + +migration = import_module( + "superset.migrations.versions." + "2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb" +) + +Database = migration.Database +_migrate_uri = migration._migrate_uri + +# Superset stores the password as this mask rather than the real credential +MASK = "X" * 10 + + +@pytest.fixture +def engine(): + engine = create_engine("sqlite:///:memory:") + migration.Base.metadata.create_all(engine) + return engine + + +def _run(migrate, conn) -> None: + session = Session(bind=conn) + with ( + patch.object(migration, "op") as mock_op, + patch.object(migration, "db") as mock_db, + ): + mock_op.get_bind.return_value = conn + mock_db.Session.return_value = session + migrate() + + +@pytest.mark.parametrize( + "uri,expected", + [ + # HTTP driver: scheme only changes, port (8123) is preserved as-is + ( + f"clickhouse://user:{MASK}@host:8123/db", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # explicit +http driver maps to the same target + ( + f"clickhouse+http://user:{MASK}@host:8123/db", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # no port and no credentials: nothing but the scheme is rewritten + ("clickhouse://localhost/default", "clickhousedb+connect://localhost/default"), + # query string and secure flag are preserved + ( + f"clickhouse://user:{MASK}@host:8123/db?secure=true", + f"clickhousedb+connect://user:{MASK}@host:8123/db?secure=true", + ), + ], +) +def test_migrate_uri_http_preserves_everything_but_scheme( + uri: str, expected: str +) -> None: + assert _migrate_uri(uri) == expected + + +@pytest.mark.parametrize( + "uri,expected", + [ + # native default port 9000 moves to the HTTP interface (8123) + ( + f"clickhouse+native://user:{MASK}@host:9000/db", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # asynch is also a native-protocol driver + ( + f"clickhouse+asynch://user:{MASK}@host:9000/db", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # no explicit port implies the native default 9000 -> pin 8123 + ( + f"clickhouse+native://user:{MASK}@host/db", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # host with no credentials + ( + "clickhouse+native://host:9000/db", + "clickhousedb+connect://host:8123/db", + ), + ], +) +def test_migrate_uri_native_remaps_default_port(uri: str, expected: str) -> None: + assert _migrate_uri(uri) == expected + + +@pytest.mark.parametrize( + "uri", + [ + # already on the clickhousedb backend -> idempotent skip + f"clickhousedb+connect://user:{MASK}@host:8123/db", + f"clickhousedb://user:{MASK}@host:8443/db?secure=true", + # a non-default native port can't be mapped to an HTTP port safely + f"clickhouse+native://user:{MASK}@host:9440/db", + # IPv6 literal host is left for a human rather than mis-parsed + f"clickhouse+native://user:{MASK}@[::1]:9000/db", + # an unrelated engine + f"postgresql://user:{MASK}@host:5432/db", + # not a URI at all + "clickhouse-not-a-uri", + ], +) +def test_migrate_uri_leaves_non_target_rows_alone(uri: str) -> None: + assert _migrate_uri(uri) is None + + +def test_migrate_uri_ignores_at_sign_in_credentials() -> None: + """The host section is located after the last "@" in the credentials.""" + assert ( + _migrate_uri("clickhouse+native://user:p@ss@host:9000/db") + == "clickhousedb+connect://user:p@ss@host:8123/db" + ) + + +def test_upgrade_rewrites_only_legacy_clickhouse_connections(engine) -> None: + with Session(engine) as seed: + seed.add_all( + [ + Database(id=1, sqlalchemy_uri=f"clickhouse://user:{MASK}@host:8123/db"), + Database( + id=2, + sqlalchemy_uri=f"clickhouse+native://user:{MASK}@host:9000/db", + ), + # non-default native port: stays on the legacy driver + Database( + id=3, + sqlalchemy_uri=f"clickhouse+native://user:{MASK}@host:9440/db", + ), + # already on the new form: untouched + Database( + id=4, + sqlalchemy_uri=f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # different engine that merely shares the "click" prefix space + Database(id=5, sqlalchemy_uri=f"postgresql://user:{MASK}@host:5432/db"), + ] + ) + seed.commit() + + with engine.begin() as conn: + _run(migration.upgrade, conn) + + with Session(engine) as verify: + assert ( + verify.get(Database, 1).sqlalchemy_uri + == f"clickhousedb+connect://user:{MASK}@host:8123/db" + ) + assert ( + verify.get(Database, 2).sqlalchemy_uri + == f"clickhousedb+connect://user:{MASK}@host:8123/db" + ) + assert ( + verify.get(Database, 3).sqlalchemy_uri + == f"clickhouse+native://user:{MASK}@host:9440/db" + ) + assert ( + verify.get(Database, 4).sqlalchemy_uri + == f"clickhousedb+connect://user:{MASK}@host:8123/db" + ) + assert ( + verify.get(Database, 5).sqlalchemy_uri + == f"postgresql://user:{MASK}@host:5432/db" + ) + + +def test_upgrade_is_idempotent(engine) -> None: + with Session(engine) as seed: + seed.add( + Database(id=1, sqlalchemy_uri=f"clickhouse://user:{MASK}@host:8123/db") + ) + seed.commit() + + for _ in range(2): + with engine.begin() as conn: + _run(migration.upgrade, conn) + + with Session(engine) as verify: + assert ( + verify.get(Database, 1).sqlalchemy_uri + == f"clickhousedb+connect://user:{MASK}@host:8123/db" + ) + + +def test_downgrade_is_a_no_op(engine) -> None: + """A migrated row is indistinguishable from a native clickhousedb one, so + downgrade leaves the rewritten URIs in place.""" + migrated = f"clickhousedb+connect://user:{MASK}@host:8123/db" + with Session(engine) as seed: + seed.add(Database(id=1, sqlalchemy_uri=migrated)) + seed.commit() + + with engine.begin() as conn: + _run(migration.downgrade, conn) + + with Session(engine) as verify: + assert verify.get(Database, 1).sqlalchemy_uri == migrated From 602db41a84cc6a232f524fcbbb700c992ea7c5a1 Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Tue, 15 Sep 2026 18:48:58 +0000 Subject: [PATCH 2/7] fix(clickhouse): map legacy TLS flag, harden URI parsing and length Addresses PR review feedback: - Map legacy `protocol=https` to clickhouse-connect's `secure=true` (and drop the meaningless `protocol` param) so migrated TLS connections are not silently downgraded to plaintext HTTP (CWE-319). - Bound the credential-separator `@` search to the authority so an `@` in the path or query no longer corrupts host detection. - Skip (with a warning) rows whose rewritten URI would exceed the dbs.sqlalchemy_uri 1024-char column limit rather than truncating them. Co-Authored-By: Claude Opus 4.8 --- ...4e02_migrate_clickhouse_to_clickhousedb.py | 134 +++++++++++++----- ...test_migrate_clickhouse_to_clickhousedb.py | 53 +++++++ 2 files changed, 155 insertions(+), 32 deletions(-) diff --git a/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py b/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py index b74e9c433dce..f35c9c7e98c2 100644 --- a/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py +++ b/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py @@ -46,13 +46,22 @@ human to migrate rather than pointed at a guessed port. Operators should confirm the HTTP interface is enabled on the rewritten native connections. +TLS: ``clickhouse-sqlalchemy`` enables TLS with ``?protocol=https``, but +``clickhouse-connect`` ignores ``protocol`` and reads ``secure`` instead, so a +preserved ``protocol=https`` would silently downgrade an encrypted connection to +plaintext HTTP. ``protocol=https`` is therefore rewritten to ``secure=true`` and +the meaningless ``protocol`` parameter is dropped; ``secure`` values that a +connection already carries are left untouched. + Password handling: the credential lives either inline in the URI or in ``encrypted_extra``; both are preserved because the URI is edited in place (only -the scheme, and for native rows the port, are touched) and ``encrypted_extra`` -is never read. +the scheme, the TLS parameter, and for native rows the port, are touched) and +``encrypted_extra`` is never read. Only rows whose backend is exactly ``clickhouse`` are rewritten; rows already on -``clickhousedb`` are skipped, which also makes ``upgrade`` idempotent. +``clickhousedb`` are skipped, which also makes ``upgrade`` idempotent. A row +whose rewritten URI would exceed the ``dbs.sqlalchemy_uri`` column length is +skipped with a warning rather than truncated. Downgrade --------- @@ -79,6 +88,8 @@ """ +import logging + from alembic import op from sqlalchemy import Column, Integer, String from sqlalchemy.orm import declarative_base @@ -86,6 +97,8 @@ from superset import db from superset.migrations.shared.utils import paginated_update +logger = logging.getLogger("alembic") + # revision identifiers, used by Alembic. revision = "f7b3a9c14e02" down_revision = ("88a01c781622", "c7f53d184ea2") @@ -100,6 +113,10 @@ NATIVE_DEFAULT_PORT = "9000" HTTP_DEFAULT_PORT = "8123" +# Matches the String(1024) length of dbs.sqlalchemy_uri; the rewrite lengthens +# the scheme (and may add a port), so a row near the limit could overflow. +URI_MAX_LENGTH = 1024 + class Database(Base): # type: ignore __tablename__ = "dbs" @@ -108,51 +125,88 @@ class Database(Base): # type: ignore sqlalchemy_uri = Column(String(1024), nullable=False) -def _swap_native_default_port(remainder: str) -> str | None: - """Move a native-default port onto the HTTP interface. +def _split_uri(remainder: str) -> tuple[str, str, str, str]: + """Split the part after ``://`` into userinfo, host:port, path and query. - ``remainder`` is everything after ``://`` -- ``userinfo@host[:port][/path] - [?query]``. Returns the remainder with the port rewritten to the HTTP - default when it is the native default (9000) or absent (which implies 9000), - and ``None`` when the port is a non-default native port or an IPv6 literal - host is present, so the caller can leave those rows on the legacy driver - rather than guess an HTTP port. + ``remainder`` is ``[userinfo@]host[:port][/path][?query]``. The authority + (userinfo + host) is delimited by the first ``/`` or ``?``, and the + credential separator is the last ``@`` *within* that authority -- searching + the whole string would let an ``@`` in the path or query be mistaken for it. + ``userinfo`` retains its trailing ``@`` (empty when there are no + credentials) so the pieces concatenate back losslessly. """ - # Credentials are not escaped for "@", so the host section starts after the - # last one. - host_start = remainder.rfind("@") + 1 - - # The authority ends at the path or query, whichever comes first. end = len(remainder) - for index in range(host_start, len(remainder)): - if remainder[index] in "/?": + for index, char in enumerate(remainder): + if char in "/?": end = index break - authority = remainder[host_start:end] - if authority.startswith("["): + authority = remainder[:end] + rest = remainder[end:] + + at = authority.rfind("@") + userinfo = authority[: at + 1] + hostport = authority[at + 1 :] + + path, _, query = rest.partition("?") + return userinfo, hostport, path, query + + +def _remap_native_port(hostport: str) -> str | None: + """Move a native-default port onto the HTTP interface. + + Returns ``hostport`` with the port rewritten to the HTTP default when it is + the native default (9000) or absent (which implies 9000), and ``None`` when + the port is a non-default native port or an IPv6 literal host is present, so + the caller can leave those rows on the legacy driver rather than guess an + HTTP port. + """ + if hostport.startswith("["): # IPv6 literal host -- the "host:port" split below is unsafe here. return None - host, colon, port = authority.rpartition(":") + host, colon, port = hostport.rpartition(":") if not colon: # No explicit port: the native driver defaults to 9000, so pin the HTTP # port explicitly for clickhouse-connect. - new_authority = f"{authority}:{HTTP_DEFAULT_PORT}" - elif port == NATIVE_DEFAULT_PORT: - new_authority = f"{host}:{HTTP_DEFAULT_PORT}" - else: - return None + return f"{hostport}:{HTTP_DEFAULT_PORT}" + if port == NATIVE_DEFAULT_PORT: + return f"{host}:{HTTP_DEFAULT_PORT}" + return None - return remainder[:host_start] + new_authority + remainder[end:] + +def _migrate_query(query: str) -> str: + """Translate the legacy ``protocol`` TLS flag to clickhouse-connect's. + + ``clickhouse-sqlalchemy`` selects TLS with ``?protocol=https``; + ``clickhouse-connect`` ignores ``protocol`` and reads ``secure`` instead, so + a preserved ``protocol=https`` would silently downgrade an encrypted + connection to plaintext HTTP. ``protocol=https`` becomes ``secure=true`` and + the now-meaningless ``protocol`` parameter is dropped; every other parameter + keeps its position and value. + """ + if not query: + return query + + rewritten = [] + for pair in query.split("&"): + key, _, value = pair.partition("=") + if key == "protocol": + if value.lower() == "https": + rewritten.append("secure=true") + # protocol=http (the plaintext default) carries no meaning for + # clickhouse-connect and is dropped. + continue + rewritten.append(pair) + return "&".join(rewritten) def _migrate_uri(uri: str) -> str | None: """Rewrite a legacy ``clickhouse`` URI onto ``clickhousedb+connect``. Returns ``None`` when the URI should be left untouched (already on the - ``clickhousedb`` backend, malformed, or a native connection whose port - cannot be mapped to the HTTP interface). + ``clickhousedb`` backend, malformed, a native connection whose port cannot + be mapped to the HTTP interface, or one that would overflow the column). """ scheme, separator, remainder = uri.partition("://") if not separator: @@ -163,13 +217,29 @@ def _migrate_uri(uri: str) -> str | None: # Already clickhousedb, or an unrelated engine. return None + userinfo, hostport, path, query = _split_uri(remainder) + if driver in NATIVE_DRIVERS: - remapped = _swap_native_default_port(remainder) + remapped = _remap_native_port(hostport) if remapped is None: return None - remainder = remapped + hostport = remapped + + query = _migrate_query(query) + + migrated = f"{TARGET_SCHEME}://{userinfo}{hostport}{path}" + if query: + migrated = f"{migrated}?{query}" + + if len(migrated) > URI_MAX_LENGTH: + logger.warning( + "Skipping ClickHouse connection whose migrated URI exceeds the " + "%d-character dbs.sqlalchemy_uri limit; migrate it manually.", + URI_MAX_LENGTH, + ) + return None - return f"{TARGET_SCHEME}://{remainder}" + return migrated def upgrade() -> None: diff --git a/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py b/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py index fa760b4795bf..b9f7219b6b3e 100644 --- a/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py +++ b/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py @@ -145,6 +145,59 @@ def test_migrate_uri_ignores_at_sign_in_credentials() -> None: ) +def test_migrate_uri_ignores_at_sign_in_query() -> None: + """An "@" after the authority (in the path or query) must not be mistaken + for the credential separator.""" + assert ( + _migrate_uri("clickhouse+native://host:9000/db?comment=a@b") + == "clickhousedb+connect://host:8123/db?comment=a@b" + ) + + +@pytest.mark.parametrize( + "uri,expected", + [ + # legacy TLS flag (protocol=https) becomes clickhouse-connect's secure + ( + f"clickhouse://user:{MASK}@host:8443/db?protocol=https", + f"clickhousedb+connect://user:{MASK}@host:8443/db?secure=true", + ), + # protocol=http is the plaintext default and is simply dropped + ( + f"clickhouse://user:{MASK}@host:8123/db?protocol=http", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # other parameters keep their position around the rewritten flag + ( + f"clickhouse://user:{MASK}@host:8443/db?a=1&protocol=https&b=2", + f"clickhousedb+connect://user:{MASK}@host:8443/db?a=1&secure=true&b=2", + ), + # native connection carrying the legacy TLS flag: port and flag both move + ( + f"clickhouse+native://user:{MASK}@host:9000/db?protocol=https", + f"clickhousedb+connect://user:{MASK}@host:8123/db?secure=true", + ), + # a secure flag already present is preserved untouched + ( + f"clickhouse://user:{MASK}@host:8443/db?secure=true", + f"clickhousedb+connect://user:{MASK}@host:8443/db?secure=true", + ), + ], +) +def test_migrate_uri_maps_legacy_tls_flag(uri: str, expected: str) -> None: + assert _migrate_uri(uri) == expected + + +def test_migrate_uri_skips_rows_that_would_overflow_the_column() -> None: + """The rewrite lengthens the URI, so a row already near the column limit is + left on the legacy driver rather than truncated.""" + padding = "x" * (migration.URI_MAX_LENGTH - len("clickhouse://host/")) + uri = f"clickhouse://host/{padding}" + assert len(uri) <= migration.URI_MAX_LENGTH + assert len(f"clickhousedb+connect://host/{padding}") > migration.URI_MAX_LENGTH + assert _migrate_uri(uri) is None + + def test_upgrade_rewrites_only_legacy_clickhouse_connections(engine) -> None: with Session(engine) as seed: seed.add_all( From 8403e908d2a09246d4eb0f9e521be05b73f2fc7b Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Wed, 4 Nov 2026 01:03:08 +0000 Subject: [PATCH 3/7] fix(clickhouse): chain migration off master head and address review - Reparent onto master's single head b8f3a2c91d64. #44288 merged the two former parents into e2f3a1b9c640, and several merges have since stacked on top of it, so the old tuple re-forked the graph. - HTTP rows: the legacy driver ignores `secure` and defaults to 8123 even for `protocol=https`, so drop stray `secure` (no duplicates / no silent plaintext->TLS flip) and pin 8123 when `secure=true` is introduced without a port (clickhouse-connect would otherwise pick 8443). - Native rows carrying TLS (`secure=true`) are skipped instead of being pointed at the plaintext HTTP port. - Parameters the drivers don't share (endpoint, timeout, ca_certs, header__*, a CA-path `verify`, ...) are no longer carried verbatim; the row stays on the legacy driver and its id is logged for the operator. - Exact rollback: upgrade records the original URI and a fingerprint of the migrated state in a migration-owned table; downgrade restores only unchanged converted rows, then drops the table (Databricks precedent). - Add `clickhousedb` to DISALLOWED_SQL_FUNCTIONS so the ClickHouse denylist follows rewritten rows. - Document the change in UPDATING.md. Co-Authored-By: Claude Opus 5.5 --- UPDATING.md | 15 + superset/config.py | 4 + ...4e02_migrate_clickhouse_to_clickhousedb.py | 413 +++++++++++------- ...test_migrate_clickhouse_to_clickhousedb.py | 355 ++++++++------- 4 files changed, 455 insertions(+), 332 deletions(-) diff --git a/UPDATING.md b/UPDATING.md index 4a32db9c694f..39636fbeb867 100644 --- a/UPDATING.md +++ b/UPDATING.md @@ -65,6 +65,21 @@ assists people when migrating to a new version. destinations. Both policies ignore environment proxies and preserve budgets and TLS hostname verification. See the [provider transport guide](docs/developer_docs/extensions/semantic-provider-transport.md). +- Saved ClickHouse connections on the legacy `clickhouse://` (clickhouse-sqlalchemy) + driver are migrated to `clickhousedb+connect://` (clickhouse-connect) by + `superset db upgrade`, so they use the dynamic connection form. Install + `clickhouse-connect>=0.13.0` before upgrading. HTTP connections keep their port; + `?protocol=https` becomes `?secure=true` (port 8123 is pinned when none was set). + Native-protocol connections (`clickhouse+native://`, `clickhouse+asynch://`) move + from the native default port 9000 to the HTTP port 8123, because + clickhouse-connect speaks HTTP only — confirm the server's HTTP interface is + reachable. Connections whose settings cannot be carried over exactly (other + URI parameters, a non-default native port, native TLS) stay on the legacy driver + and are logged by database id during the upgrade for manual migration. A + downgrade restores the original URI of every converted connection that has not + been edited since. `DISALLOWED_SQL_FUNCTIONS` gains a `clickhousedb` entry + matching `clickhouse`; deployments that override `DISALLOWED_SQL_FUNCTIONS` + should add it as well. - Semantic-view filters with an empty IN or NOT IN selection no longer fail with a query validation error. They follow SQL semantics where the filter sits: an empty IN matches no rows (grouped charts return no rows; an ungrouped total diff --git a/superset/config.py b/superset/config.py index ac7ea35f7a06..28e768f61088 100644 --- a/superset/config.py +++ b/superset/config.py @@ -2694,6 +2694,10 @@ def engine_context_manager( # pylint: disable=unused-argument "httpuritype", }, } +# The lookup is keyed by engine spec ``engine``: ClickHouse connections use +# ``clickhouse`` (clickhouse-sqlalchemy) or ``clickhousedb`` (clickhouse-connect), +# and both drivers reach the same server functions. +DISALLOWED_SQL_FUNCTIONS["clickhousedb"] = set(DISALLOWED_SQL_FUNCTIONS["clickhouse"]) # Per-engine blocklist of system catalog tables/views that should not be queried. # Prevents information disclosure through system catalog access. diff --git a/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py b/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py index f35c9c7e98c2..119f261d3669 100644 --- a/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py +++ b/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py @@ -23,106 +23,126 @@ default driver ``connect``, the ``clickhouse-connect`` driver) defines a ``parameters_schema`` and therefore renders the new dynamic connection form. -This migration rewrites the ``sqlalchemy_uri`` of connections stored on the -legacy ``clickhouse`` backend so they resolve to ``ClickHouseConnectEngineSpec`` -and expose the new form. The backend name is what selects the engine spec -(``Database.db_engine_spec`` reads ``url.get_backend_name()``), so the scheme is -rewritten from ``clickhouse[+driver]://`` to ``clickhousedb+connect://``. - -Scheme and port mapping ------------------------ - -* ``clickhouse://`` and ``clickhouse+http://`` -- the ``clickhouse-sqlalchemy`` - HTTP dialect, default port 8123. ``clickhouse-connect`` also speaks HTTP on - 8123, so only the scheme changes; host, port, credentials, database and query - string are preserved byte-for-byte. -* ``clickhouse+native://`` and ``clickhouse+asynch://`` -- the native TCP - protocol, default port 9000. ``clickhouse-connect`` cannot speak the native - protocol; it is HTTP-only. A native connection therefore also needs its port - moved to the HTTP interface. When the port is the native default (9000, or - absent -- which implies 9000) it is rewritten to the HTTP default (8123). - A *non-default* native port cannot be mapped to an HTTP port without knowing - the server's configuration, so those rows are left on the legacy driver for a - human to migrate rather than pointed at a guessed port. Operators should - confirm the HTTP interface is enabled on the rewritten native connections. - -TLS: ``clickhouse-sqlalchemy`` enables TLS with ``?protocol=https``, but -``clickhouse-connect`` ignores ``protocol`` and reads ``secure`` instead, so a -preserved ``protocol=https`` would silently downgrade an encrypted connection to -plaintext HTTP. ``protocol=https`` is therefore rewritten to ``secure=true`` and -the meaningless ``protocol`` parameter is dropped; ``secure`` values that a -connection already carries are left untouched. - -Password handling: the credential lives either inline in the URI or in -``encrypted_extra``; both are preserved because the URI is edited in place (only -the scheme, the TLS parameter, and for native rows the port, are touched) and -``encrypted_extra`` is never read. - -Only rows whose backend is exactly ``clickhouse`` are rewritten; rows already on -``clickhousedb`` are skipped, which also makes ``upgrade`` idempotent. A row -whose rewritten URI would exceed the ``dbs.sqlalchemy_uri`` column length is -skipped with a warning rather than truncated. - -Downgrade ---------- - -``downgrade`` is intentionally a no-op. After ``upgrade`` a migrated row is -byte-for-byte indistinguishable from a connection an operator created directly on -the ``clickhousedb`` key (both are produced by ``build_sqlalchemy_uri`` as -``clickhousedb+connect://...``), so a blind reversal would also revert genuine -``clickhousedb`` connections onto the legacy driver and break them. The migrated -connections keep working after a code rollback regardless, because -``ClickHouseConnectEngineSpec`` predates this migration -- no data restoration is -required for them to remain functional -- so the safe choice is to leave the -rewritten URIs in place. - -The revision tree had two open heads when this was authored -- ``88a01c781622`` -(``index_ab_user_lower_username``) and ``c7f53d184ea2`` -(``coordinate_purge_audit_pruning``), which forked at ``7e2c9a4f1b83``. This -revision merges them so the tree keeps a single head; the data rewrite itself is -independent of both branches. +The backend name selects the engine spec (``Database.db_engine_spec`` reads +``url.get_backend_name()``), so saved legacy URIs are rewritten from +``clickhouse[+driver]://`` to ``clickhousedb+connect://``. Only rows whose +meaning can be carried across exactly are rewritten; everything else is left on +the legacy driver -- which keeps working -- and logged by id for an operator. + +HTTP driver (``clickhouse://``, ``clickhouse+http://``) +------------------------------------------------------- + +``clickhouse-sqlalchemy`` builds the server URL as +``f"{protocol}://{host}:{url.port or 8123}/{endpoint}"``: TLS comes only from +``?protocol=https``, the port defaults to 8123 whatever the protocol, and +``secure`` is not read at all. ``clickhouse-connect`` reads ``secure`` instead +and defaults a TLS connection to 8443. So: + +* ``protocol=https`` becomes ``secure=true``; ``protocol=http`` is dropped. +* a stray ``secure`` is dropped -- the legacy driver ignored it, so keeping it + would switch a plaintext connection to TLS (or, alongside ``protocol=https``, + produce a duplicate whose last value wins). +* when the rewrite introduces ``secure=true`` and the URI has no port, 8123 is + pinned so the connection keeps addressing the same interface. +* ``verify=true|false`` has the same meaning in both drivers and is kept. + +Native driver (``clickhouse+native://``, ``clickhouse+asynch://``) +------------------------------------------------------------------ + +``clickhouse-connect`` is HTTP-only, so a native connection also has to move to +the HTTP interface. The native default port (9000, or no port, which implies +9000) becomes the HTTP default 8123. A falsy ``secure`` is dropped. + +Rows left on the legacy driver +------------------------------ + +* any query parameter other than the ones above -- the drivers do not share a + vocabulary (e.g. the legacy ``endpoint`` is the HTTP request path, while + ``clickhouse-connect`` forwards unknown keys as server settings and rejects + unrecognised ones), so carrying them over verbatim would silently change or + break the connection; +* ``verify`` with a non-boolean value (a CA bundle path); +* a non-default native port, or native TLS (``secure=true``), neither of which + maps to a known HTTP port without the server's configuration; +* a rewritten URI that would overflow the ``dbs.sqlalchemy_uri`` column. + +Operators should confirm the HTTP interface is reachable for rewritten native +connections. + +Credentials live in the separately encrypted ``password`` column (the URI only +carries the masked placeholder), which this migration never reads or writes; +``encrypted_extra`` is untouched too. + +Rollback +-------- + +The rewrite is not textually reversible (parameters are translated and native +ports change), and afterwards a migrated row looks like any connection created +on the ``clickhousedb`` key. ``upgrade`` therefore records each rewritten row's +original URI and a fingerprint of its migrated state in a migration-owned +table. ``downgrade`` restores the original only for rows whose fingerprint still +matches -- connections edited since the upgrade, and connections created on the +``clickhousedb`` key, are left alone -- and then drops the table. Revision ID: f7b3a9c14e02 -Revises: 88a01c781622, c7f53d184ea2 +Revises: b8f3a2c91d64 Create Date: 2026-09-15 00:00:00.000000 """ +from __future__ import annotations + import logging +from datetime import datetime +from hashlib import sha256 +import sqlalchemy as sa from alembic import op -from sqlalchemy import Column, Integer, String -from sqlalchemy.orm import declarative_base -from superset import db -from superset.migrations.shared.utils import paginated_update +from superset.migrations.shared.utils import create_table, drop_table +from superset.utils import json -logger = logging.getLogger("alembic") +logger = logging.getLogger("alembic.env") # revision identifiers, used by Alembic. revision = "f7b3a9c14e02" -down_revision = ("88a01c781622", "c7f53d184ea2") - -Base = declarative_base() +down_revision = "b8f3a2c91d64" LEGACY_BACKEND = "clickhouse" TARGET_SCHEME = "clickhousedb+connect" # Drivers that use the native TCP protocol rather than HTTP. NATIVE_DRIVERS = {"native", "asynch"} +HTTP_DRIVERS = {"", "http"} NATIVE_DEFAULT_PORT = "9000" HTTP_DEFAULT_PORT = "8123" # Matches the String(1024) length of dbs.sqlalchemy_uri; the rewrite lengthens # the scheme (and may add a port), so a row near the limit could overflow. URI_MAX_LENGTH = 1024 +BATCH_SIZE = 1000 + +_TRUE = {"true", "1", "yes", "y", "on", "t"} +_FALSE = {"false", "0", "no", "n", "off", "f", ""} +# Deliberately independent of application models and encrypted column types. +databases = sa.table( + "dbs", + sa.column("id", sa.Integer), + sa.column("sqlalchemy_uri", sa.String(1024)), + sa.column("changed_on", sa.DateTime), +) -class Database(Base): # type: ignore - __tablename__ = "dbs" +records = sa.table( + "clickhouse_uri_migration", + sa.column("id", sa.Integer), + sa.column("original_uri", sa.String(1024)), + sa.column("fingerprint", sa.String(64)), +) - id = Column(Integer, primary_key=True) - sqlalchemy_uri = Column(String(1024), nullable=False) + +class UnconvertibleError(Exception): + """A legacy row that cannot be rewritten without changing its meaning.""" def _split_uri(remainder: str) -> tuple[str, str, str, str]: @@ -142,124 +162,183 @@ def _split_uri(remainder: str) -> tuple[str, str, str, str]: break authority = remainder[:end] - rest = remainder[end:] - at = authority.rfind("@") - userinfo = authority[: at + 1] - hostport = authority[at + 1 :] + path, _, query = remainder[end:].partition("?") + return authority[: at + 1], authority[at + 1 :], path, query - path, _, query = rest.partition("?") - return userinfo, hostport, path, query - -def _remap_native_port(hostport: str) -> str | None: - """Move a native-default port onto the HTTP interface. - - Returns ``hostport`` with the port rewritten to the HTTP default when it is - the native default (9000) or absent (which implies 9000), and ``None`` when - the port is a non-default native port or an IPv6 literal host is present, so - the caller can leave those rows on the legacy driver rather than guess an - HTTP port. - """ +def _split_hostport(hostport: str) -> tuple[str, str | None]: + """Split ``host[:port]``, treating a bracketed IPv6 literal as one host.""" if hostport.startswith("["): - # IPv6 literal host -- the "host:port" split below is unsafe here. - return None - + close = hostport.find("]") + rest = hostport[close + 1 :] + if close == -1 or (rest and not rest.startswith(":")): + raise UnconvertibleError("unparseable IPv6 host") + return hostport[: close + 1], rest[1:] if rest else None host, colon, port = hostport.rpartition(":") - if not colon: - # No explicit port: the native driver defaults to 9000, so pin the HTTP - # port explicitly for clickhouse-connect. - return f"{hostport}:{HTTP_DEFAULT_PORT}" - if port == NATIVE_DEFAULT_PORT: - return f"{host}:{HTTP_DEFAULT_PORT}" - return None - - -def _migrate_query(query: str) -> str: - """Translate the legacy ``protocol`` TLS flag to clickhouse-connect's. - - ``clickhouse-sqlalchemy`` selects TLS with ``?protocol=https``; - ``clickhouse-connect`` ignores ``protocol`` and reads ``secure`` instead, so - a preserved ``protocol=https`` would silently downgrade an encrypted - connection to plaintext HTTP. ``protocol=https`` becomes ``secure=true`` and - the now-meaningless ``protocol`` parameter is dropped; every other parameter - keeps its position and value. - """ - if not query: - return query - - rewritten = [] - for pair in query.split("&"): - key, _, value = pair.partition("=") - if key == "protocol": - if value.lower() == "https": - rewritten.append("secure=true") - # protocol=http (the plaintext default) carries no meaning for - # clickhouse-connect and is dropped. - continue - rewritten.append(pair) - return "&".join(rewritten) + return (host, port) if colon else (hostport, None) -def _migrate_uri(uri: str) -> str | None: - """Rewrite a legacy ``clickhouse`` URI onto ``clickhousedb+connect``. - - Returns ``None`` when the URI should be left untouched (already on the - ``clickhousedb`` backend, malformed, a native connection whose port cannot - be mapped to the HTTP interface, or one that would overflow the column). - """ +def _rewrite_query(query: str, native: bool) -> tuple[list[str], bool]: + """Translate the query string; return the new pairs and whether TLS is on.""" + pairs: list[str] = [] + secure = False + for pair in query.split("&") if query else []: + key, _, value = pair.partition("=") + lowered = value.lower() + if key == "protocol" and not native: + if lowered not in {"http", "https"}: + raise UnconvertibleError(f"unsupported protocol {value!r}") + if lowered == "https" and not secure: + # Takes the position of the protocol flag it replaces. + secure = True + pairs.append("secure=true") + elif key == "secure": + if native and lowered not in _FALSE: + raise UnconvertibleError("native TLS has no known HTTP port") + # The legacy HTTP driver ignores ``secure``; TLS comes from protocol. + elif key == "verify" and not native and lowered in _TRUE | _FALSE: + pairs.append(pair) + else: + raise UnconvertibleError( + f"parameter {key!r} has no clickhouse-connect equivalent" + ) + return pairs, secure + + +def _rewrite(uri: str) -> str | None: + """Return the migrated URI, ``None`` for a non-legacy row, or raise.""" scheme, separator, remainder = uri.partition("://") - if not separator: - return None - backend, _, driver = scheme.partition("+") - if backend != LEGACY_BACKEND: + if not separator or backend != LEGACY_BACKEND: # Already clickhousedb, or an unrelated engine. return None + if driver not in NATIVE_DRIVERS | HTTP_DRIVERS: + raise UnconvertibleError(f"unknown driver {driver!r}") + native = driver in NATIVE_DRIVERS userinfo, hostport, path, query = _split_uri(remainder) - - if driver in NATIVE_DRIVERS: - remapped = _remap_native_port(hostport) - if remapped is None: - return None - hostport = remapped - - query = _migrate_query(query) - - migrated = f"{TARGET_SCHEME}://{userinfo}{hostport}{path}" - if query: - migrated = f"{migrated}?{query}" + host, port = _split_hostport(hostport) + pairs, secure = _rewrite_query(query, native) + + if native: + if port not in (None, NATIVE_DEFAULT_PORT): + raise UnconvertibleError(f"non-default native port {port}") + port = HTTP_DEFAULT_PORT + elif port is None and secure: + # clickhouse-connect would default a TLS connection to 8443, but the + # legacy driver always defaulted to 8123. + port = HTTP_DEFAULT_PORT + + migrated = f"{TARGET_SCHEME}://{userinfo}{host}" + if port is not None: + migrated = f"{migrated}:{port}" + migrated = f"{migrated}{path}" + if pairs: + migrated = f"{migrated}?{'&'.join(pairs)}" if len(migrated) > URI_MAX_LENGTH: - logger.warning( - "Skipping ClickHouse connection whose migrated URI exceeds the " - "%d-character dbs.sqlalchemy_uri limit; migrate it manually.", - URI_MAX_LENGTH, + raise UnconvertibleError( + f"migrated URI would exceed {URI_MAX_LENGTH} characters" ) + return migrated + + +def _migrate_uri(uri: str) -> str | None: + """Return the migrated URI, or ``None`` when the row is left untouched.""" + try: + return _rewrite(uri) + except UnconvertibleError: return None - return migrated + +def _fingerprint(uri: str, changed_on: datetime | None) -> str: + """Recognize the migrated state, including later edits to the connection.""" + return sha256(json.dumps([uri, str(changed_on)]).encode("utf-8")).hexdigest() def upgrade() -> None: + """Rewrite legacy URIs and record each converted row for exact rollback.""" + create_table( + records.name, + sa.Column("id", sa.Integer, primary_key=True, autoincrement=False), + sa.Column("original_uri", sa.String(1024), nullable=False), + sa.Column("fingerprint", sa.String(64), nullable=False), + ) bind = op.get_bind() - session = db.Session(bind=bind) - - # The LIKE also matches "clickhousedb%"; _migrate_uri filters those out by - # backend name, so re-running is a no-op. - query = session.query(Database).filter(Database.sqlalchemy_uri.like("clickhouse%")) - for database in paginated_update(query): - updated = _migrate_uri(database.sqlalchemy_uri) - if updated: - database.sqlalchemy_uri = updated - - session.commit() + last_id = -1 + while True: + # Keyset batches, so rewriting rows out of the LIKE cannot skip others. + rows = bind.execute( + sa.select(databases) + .where( + databases.c.id > last_id, + databases.c.sqlalchemy_uri.like(f"{LEGACY_BACKEND}%"), + ) + .order_by(databases.c.id) + .limit(BATCH_SIZE) + ).fetchall() + if not rows: + break + for row in rows: + last_id = row.id + try: + migrated = _rewrite(row.sqlalchemy_uri) + except UnconvertibleError as ex: + logger.warning( + "Leaving ClickHouse database id=%s on the legacy clickhouse " + "driver (%s); migrate it to clickhousedb manually.", + row.id, + ex, + ) + continue + if migrated is None: + continue + updated = bind.execute( + databases.update() + .where( + databases.c.id == row.id, + databases.c.sqlalchemy_uri == row.sqlalchemy_uri, + ) + .values(sqlalchemy_uri=migrated) + ) + if updated.rowcount: + bind.execute(records.delete().where(records.c.id == row.id)) + bind.execute( + records.insert().values( + id=row.id, + original_uri=row.sqlalchemy_uri, + fingerprint=_fingerprint(migrated, row.changed_on), + ) + ) def downgrade() -> None: - # Intentionally a no-op; see the module docstring. A migrated row is - # indistinguishable from a natively-created clickhousedb connection, and the - # rewritten URIs remain functional after a code rollback, so nothing is - # reverted. - pass + """Restore unchanged converted URIs, then remove migration bookkeeping.""" + bind = op.get_bind() + rows = bind.execute( + sa.select( + databases.c.id, + databases.c.sqlalchemy_uri, + databases.c.changed_on, + records.c.original_uri, + records.c.fingerprint, + ).select_from(records.join(databases, databases.c.id == records.c.id)) + ).fetchall() + for row in rows: + if row.fingerprint != _fingerprint(row.sqlalchemy_uri, row.changed_on): + logger.warning( + "Not reverting ClickHouse database id=%s: it changed after the " + "upgrade.", + row.id, + ) + continue + bind.execute( + databases.update() + .where( + databases.c.id == row.id, + databases.c.sqlalchemy_uri == row.sqlalchemy_uri, + ) + .values(sqlalchemy_uri=row.original_uri) + ) + drop_table(records.name) diff --git a/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py b/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py index b9f7219b6b3e..5202685655de 100644 --- a/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py +++ b/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py @@ -14,77 +14,147 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. -"""Tests for migration ``f7b3a9c14e02_migrate_clickhouse_to_clickhousedb``. - -Covers the URI rewrite helper (HTTP and native drivers, port mapping, rows that -must be skipped), the full upgrade() path over a mixture of connections, and the -no-op downgrade(). -""" +"""Tests for migration ``f7b3a9c14e02_migrate_clickhouse_to_clickhousedb``.""" from __future__ import annotations +from collections.abc import Iterator +from datetime import datetime from importlib import import_module from unittest.mock import patch import pytest -from sqlalchemy import create_engine -from sqlalchemy.orm import Session +import sqlalchemy as sa +from alembic.migration import MigrationContext +from alembic.operations import Operations +from sqlalchemy.engine import Engine migration = import_module( "superset.migrations.versions." "2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb" ) - -Database = migration.Database _migrate_uri = migration._migrate_uri # Superset stores the password as this mask rather than the real credential MASK = "X" * 10 +CHANGED_ON = datetime(2026, 1, 1) @pytest.fixture -def engine(): - engine = create_engine("sqlite:///:memory:") - migration.Base.metadata.create_all(engine) - return engine +def engine() -> Iterator[Engine]: + engine = sa.create_engine("sqlite://") + metadata = sa.MetaData() + sa.Table( + "dbs", + metadata, + sa.Column("id", sa.Integer, primary_key=True), + sa.Column("sqlalchemy_uri", sa.String(1024)), + sa.Column("changed_on", sa.DateTime), + ) + metadata.create_all(engine) + yield engine + engine.dispose() + + +def _seed(engine: Engine, uris: dict[int, str]) -> None: + with engine.begin() as conn: + conn.execute( + migration.databases.insert(), + [ + {"id": id_, "sqlalchemy_uri": uri, "changed_on": CHANGED_ON} + for id_, uri in uris.items() + ], + ) + + +def _uris(engine: Engine) -> dict[int, str]: + with engine.connect() as conn: + return dict( + conn.execute( + sa.select( + migration.databases.c.id, migration.databases.c.sqlalchemy_uri + ) + ).fetchall() + ) -def _run(migrate, conn) -> None: - session = Session(bind=conn) - with ( - patch.object(migration, "op") as mock_op, - patch.object(migration, "db") as mock_db, - ): - mock_op.get_bind.return_value = conn - mock_db.Session.return_value = session - migrate() +def _run(engine: Engine, upgrading: bool) -> None: + """Execute with real Alembic operations and deliberately small batches.""" + with engine.begin() as conn, patch.object(migration, "BATCH_SIZE", 2): + with Operations.context(MigrationContext.configure(conn)): + (migration.upgrade if upgrading else migration.downgrade)() @pytest.mark.parametrize( "uri,expected", [ - # HTTP driver: scheme only changes, port (8123) is preserved as-is + # HTTP driver: only the scheme changes ( f"clickhouse://user:{MASK}@host:8123/db", f"clickhousedb+connect://user:{MASK}@host:8123/db", ), - # explicit +http driver maps to the same target ( f"clickhouse+http://user:{MASK}@host:8123/db", f"clickhousedb+connect://user:{MASK}@host:8123/db", ), - # no port and no credentials: nothing but the scheme is rewritten + # no port and no TLS: both drivers default to 8123, so none is added ("clickhouse://localhost/default", "clickhousedb+connect://localhost/default"), - # query string and secure flag are preserved + # verify has the same meaning in both drivers ( - f"clickhouse://user:{MASK}@host:8123/db?secure=true", + f"clickhouse://user:{MASK}@host:8443/db?protocol=https&verify=false", + f"clickhousedb+connect://user:{MASK}@host:8443/db?secure=true&verify=false", + ), + # an "@" in the credentials is not the separator + ( + "clickhouse+native://user:p@ss@host:9000/db", + "clickhousedb+connect://user:p@ss@host:8123/db", + ), + # IPv6 literal hosts keep their brackets + ("clickhouse://[::1]:8123/db", "clickhousedb+connect://[::1]:8123/db"), + ("clickhouse+native://[::1]/db", "clickhousedb+connect://[::1]:8123/db"), + ], +) +def test_migrate_uri_http(uri: str, expected: str) -> None: + assert _migrate_uri(uri) == expected + + +@pytest.mark.parametrize( + "uri,expected", + [ + # legacy TLS flag becomes clickhouse-connect's secure + ( + f"clickhouse://user:{MASK}@host:8443/db?protocol=https", + f"clickhousedb+connect://user:{MASK}@host:8443/db?secure=true", + ), + # without a port the legacy driver used 8123 even for https, while + # clickhouse-connect would pick 8443 for secure=true, so 8123 is pinned + ( + f"clickhouse://user:{MASK}@host/db?protocol=https", f"clickhousedb+connect://user:{MASK}@host:8123/db?secure=true", ), + # protocol=http is the plaintext default and is dropped + ( + f"clickhouse://user:{MASK}@host:8123/db?protocol=http", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # the legacy HTTP driver ignored secure, so it must not turn TLS on... + ( + f"clickhouse://user:{MASK}@host:8123/db?secure=true", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # ...nor leave a conflicting duplicate next to the translated flag + ( + f"clickhouse://user:{MASK}@host:8443/db?secure=false&protocol=https", + f"clickhousedb+connect://user:{MASK}@host:8443/db?secure=true", + ), + # the translated flag keeps the position of the one it replaces + ( + "clickhouse://host:8443/db?verify=true&protocol=https&verify=true", + "clickhousedb+connect://host:8443/db?verify=true&secure=true&verify=true", + ), ], ) -def test_migrate_uri_http_preserves_everything_but_scheme( - uri: str, expected: str -) -> None: +def test_migrate_uri_translates_tls(uri: str, expected: str) -> None: assert _migrate_uri(uri) == expected @@ -96,187 +166,142 @@ def test_migrate_uri_http_preserves_everything_but_scheme( f"clickhouse+native://user:{MASK}@host:9000/db", f"clickhousedb+connect://user:{MASK}@host:8123/db", ), - # asynch is also a native-protocol driver ( f"clickhouse+asynch://user:{MASK}@host:9000/db", f"clickhousedb+connect://user:{MASK}@host:8123/db", ), - # no explicit port implies the native default 9000 -> pin 8123 + # no explicit port implies the native default 9000 ( f"clickhouse+native://user:{MASK}@host/db", f"clickhousedb+connect://user:{MASK}@host:8123/db", ), - # host with no credentials + # a falsy secure is plaintext in both drivers and is dropped ( - "clickhouse+native://host:9000/db", + "clickhouse+native://host:9000/db?secure=false", "clickhousedb+connect://host:8123/db", ), ], ) -def test_migrate_uri_native_remaps_default_port(uri: str, expected: str) -> None: +def test_migrate_uri_native(uri: str, expected: str) -> None: assert _migrate_uri(uri) == expected @pytest.mark.parametrize( "uri", [ - # already on the clickhousedb backend -> idempotent skip + # already on the clickhousedb backend, or another engine f"clickhousedb+connect://user:{MASK}@host:8123/db", f"clickhousedb://user:{MASK}@host:8443/db?secure=true", - # a non-default native port can't be mapped to an HTTP port safely - f"clickhouse+native://user:{MASK}@host:9440/db", - # IPv6 literal host is left for a human rather than mis-parsed - f"clickhouse+native://user:{MASK}@[::1]:9000/db", - # an unrelated engine f"postgresql://user:{MASK}@host:5432/db", - # not a URI at all "clickhouse-not-a-uri", + # a non-default native port has no known HTTP equivalent + f"clickhouse+native://user:{MASK}@host:9440/db", + # native TLS has no known HTTP port either + "clickhouse+native://host:9000/db?secure=true", + # parameters the drivers don't share are not carried over silently + "clickhouse://host:8123/db?endpoint=clickhouse", + "clickhouse://host:8123/db?timeout=30", + "clickhouse://host:8443/db?protocol=https&ca_certs=/etc/ca.pem", + "clickhouse://host:8443/db?protocol=https&verify=/etc/ca.pem", + "clickhouse+native://host:9000/db?compression=lz4", + "clickhouse://host:8123/db?protocol=ftp", + # an unknown driver + "clickhouse+mystery://host:8123/db", ], ) -def test_migrate_uri_leaves_non_target_rows_alone(uri: str) -> None: +def test_migrate_uri_leaves_row_alone(uri: str) -> None: assert _migrate_uri(uri) is None -def test_migrate_uri_ignores_at_sign_in_credentials() -> None: - """The host section is located after the last "@" in the credentials.""" - assert ( - _migrate_uri("clickhouse+native://user:p@ss@host:9000/db") - == "clickhousedb+connect://user:p@ss@host:8123/db" - ) - - def test_migrate_uri_ignores_at_sign_in_query() -> None: - """An "@" after the authority (in the path or query) must not be mistaken - for the credential separator.""" + """An "@" after the authority must not be mistaken for the separator.""" assert ( - _migrate_uri("clickhouse+native://host:9000/db?comment=a@b") - == "clickhousedb+connect://host:8123/db?comment=a@b" + _migrate_uri("clickhouse+native://host:9000/db@x") + == "clickhousedb+connect://host:8123/db@x" ) -@pytest.mark.parametrize( - "uri,expected", - [ - # legacy TLS flag (protocol=https) becomes clickhouse-connect's secure - ( - f"clickhouse://user:{MASK}@host:8443/db?protocol=https", - f"clickhousedb+connect://user:{MASK}@host:8443/db?secure=true", - ), - # protocol=http is the plaintext default and is simply dropped - ( - f"clickhouse://user:{MASK}@host:8123/db?protocol=http", - f"clickhousedb+connect://user:{MASK}@host:8123/db", - ), - # other parameters keep their position around the rewritten flag - ( - f"clickhouse://user:{MASK}@host:8443/db?a=1&protocol=https&b=2", - f"clickhousedb+connect://user:{MASK}@host:8443/db?a=1&secure=true&b=2", - ), - # native connection carrying the legacy TLS flag: port and flag both move - ( - f"clickhouse+native://user:{MASK}@host:9000/db?protocol=https", - f"clickhousedb+connect://user:{MASK}@host:8123/db?secure=true", - ), - # a secure flag already present is preserved untouched - ( - f"clickhouse://user:{MASK}@host:8443/db?secure=true", - f"clickhousedb+connect://user:{MASK}@host:8443/db?secure=true", - ), - ], -) -def test_migrate_uri_maps_legacy_tls_flag(uri: str, expected: str) -> None: - assert _migrate_uri(uri) == expected - - def test_migrate_uri_skips_rows_that_would_overflow_the_column() -> None: - """The rewrite lengthens the URI, so a row already near the column limit is - left on the legacy driver rather than truncated.""" padding = "x" * (migration.URI_MAX_LENGTH - len("clickhouse://host/")) uri = f"clickhouse://host/{padding}" - assert len(uri) <= migration.URI_MAX_LENGTH - assert len(f"clickhousedb+connect://host/{padding}") > migration.URI_MAX_LENGTH + assert len(uri) == migration.URI_MAX_LENGTH assert _migrate_uri(uri) is None -def test_upgrade_rewrites_only_legacy_clickhouse_connections(engine) -> None: - with Session(engine) as seed: - seed.add_all( - [ - Database(id=1, sqlalchemy_uri=f"clickhouse://user:{MASK}@host:8123/db"), - Database( - id=2, - sqlalchemy_uri=f"clickhouse+native://user:{MASK}@host:9000/db", - ), - # non-default native port: stays on the legacy driver - Database( - id=3, - sqlalchemy_uri=f"clickhouse+native://user:{MASK}@host:9440/db", - ), - # already on the new form: untouched - Database( - id=4, - sqlalchemy_uri=f"clickhousedb+connect://user:{MASK}@host:8123/db", - ), - # different engine that merely shares the "click" prefix space - Database(id=5, sqlalchemy_uri=f"postgresql://user:{MASK}@host:5432/db"), - ] - ) - seed.commit() +def test_upgrade_rewrites_only_convertible_rows(engine: Engine, caplog) -> None: + _seed( + engine, + { + 1: f"clickhouse://user:{MASK}@host:8123/db", + 2: f"clickhouse+native://user:{MASK}@host:9000/db", + 3: f"clickhouse+native://user:{MASK}@host:9440/db", + 4: f"clickhousedb+connect://user:{MASK}@host:8123/db", + 5: f"postgresql://user:{MASK}@host:5432/db", + 6: "clickhouse://host:8123/db?endpoint=proxy", + }, + ) - with engine.begin() as conn: - _run(migration.upgrade, conn) + _run(engine, upgrading=True) - with Session(engine) as verify: - assert ( - verify.get(Database, 1).sqlalchemy_uri - == f"clickhousedb+connect://user:{MASK}@host:8123/db" - ) - assert ( - verify.get(Database, 2).sqlalchemy_uri - == f"clickhousedb+connect://user:{MASK}@host:8123/db" - ) - assert ( - verify.get(Database, 3).sqlalchemy_uri - == f"clickhouse+native://user:{MASK}@host:9440/db" - ) - assert ( - verify.get(Database, 4).sqlalchemy_uri - == f"clickhousedb+connect://user:{MASK}@host:8123/db" - ) - assert ( - verify.get(Database, 5).sqlalchemy_uri - == f"postgresql://user:{MASK}@host:5432/db" - ) + assert _uris(engine) == { + 1: f"clickhousedb+connect://user:{MASK}@host:8123/db", + 2: f"clickhousedb+connect://user:{MASK}@host:8123/db", + 3: f"clickhouse+native://user:{MASK}@host:9440/db", + 4: f"clickhousedb+connect://user:{MASK}@host:8123/db", + 5: f"postgresql://user:{MASK}@host:5432/db", + 6: "clickhouse://host:8123/db?endpoint=proxy", + } + # skipped rows reach the operator by id + assert "id=3" in caplog.text + assert "id=6" in caplog.text -def test_upgrade_is_idempotent(engine) -> None: - with Session(engine) as seed: - seed.add( - Database(id=1, sqlalchemy_uri=f"clickhouse://user:{MASK}@host:8123/db") - ) - seed.commit() +def test_upgrade_is_idempotent(engine: Engine) -> None: + _seed(engine, {1: f"clickhouse://user:{MASK}@host:8123/db"}) - for _ in range(2): - with engine.begin() as conn: - _run(migration.upgrade, conn) + _run(engine, upgrading=True) + _run(engine, upgrading=True) + + assert _uris(engine) == {1: f"clickhousedb+connect://user:{MASK}@host:8123/db"} - with Session(engine) as verify: - assert ( - verify.get(Database, 1).sqlalchemy_uri - == f"clickhousedb+connect://user:{MASK}@host:8123/db" - ) +def test_round_trip_restores_original_uris(engine: Engine) -> None: + original = { + 1: f"clickhouse://user:{MASK}@host/db?protocol=https&verify=false", + 2: f"clickhouse+native://user:{MASK}@host/db?secure=false", + 3: f"clickhouse+native://user:{MASK}@host:9440/db", + } + _seed(engine, original) -def test_downgrade_is_a_no_op(engine) -> None: - """A migrated row is indistinguishable from a native clickhousedb one, so - downgrade leaves the rewritten URIs in place.""" - migrated = f"clickhousedb+connect://user:{MASK}@host:8123/db" - with Session(engine) as seed: - seed.add(Database(id=1, sqlalchemy_uri=migrated)) - seed.commit() + _run(engine, upgrading=True) + _run(engine, upgrading=False) + assert _uris(engine) == original + assert not sa.inspect(engine).has_table(migration.records.name) + + +def test_downgrade_leaves_native_and_edited_connections(engine: Engine) -> None: + """Rows created on clickhousedb, or edited after the upgrade, stay put.""" + _seed( + engine, + { + 1: f"clickhouse://user:{MASK}@host:8123/db", + 2: f"clickhouse://user:{MASK}@host:8123/db", + 3: f"clickhousedb+connect://user:{MASK}@host:8123/db", + }, + ) + _run(engine, upgrading=True) with engine.begin() as conn: - _run(migration.downgrade, conn) + conn.execute( + migration.databases.update() + .where(migration.databases.c.id == 2) + .values(changed_on=datetime(2026, 2, 1)) + ) + + _run(engine, upgrading=False) - with Session(engine) as verify: - assert verify.get(Database, 1).sqlalchemy_uri == migrated + assert _uris(engine) == { + 1: f"clickhouse://user:{MASK}@host:8123/db", + 2: f"clickhousedb+connect://user:{MASK}@host:8123/db", + 3: f"clickhousedb+connect://user:{MASK}@host:8123/db", + } From eba10e7bfb281ec0485814fbb4db10caaacdc230 Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Fri, 6 Nov 2026 00:56:05 +0000 Subject: [PATCH 4/7] fix(clickhouse): address migration review (connect_args, form, grains, denylist) - Skip (and log by id) rows whose extra.engine_params.connect_args is non-empty, or whose extra cannot be inspected. clickhouse-connect sends unknown keys such as `timeout` to the server as settings (every query fails) and coerces a CA-bundle path in `verify` to False, silently disabling certificate verification. - Set configuration_method to `dynamic_form` on converted rows so the edit modal opens the new form; record the original value and restore it on downgrade alongside the URI (it is part of the rollback fingerprint). - Add `time_grain_addon_aliases` to engine specs; ClickHouseConnectEngineSpec declares ("clickhouse",), so TIME_GRAIN_ADDON_EXPRESSIONS configured under `clickhouse` keep resolving for converted connections (both in get_time_grain_expressions and the partition-mirroring width check), with `clickhousedb` entries taking precedence. - Test that the default config's ClickHouse function denylist is enforced on a clickhousedb connection: `SELECT version()` is rejected and `SELECT 1` runs, without patching config. Co-Authored-By: Claude Opus 5.5 --- UPDATING.md | 21 ++-- superset/connectors/sqla/partition_mapping.py | 23 +++- superset/db_engine_specs/base.py | 24 ++++- superset/db_engine_specs/clickhouse.py | 3 + ...4e02_migrate_clickhouse_to_clickhousedb.py | 78 +++++++++++--- .../db_engine_specs/test_clickhouse.py | 55 ++++++++-- ...test_migrate_clickhouse_to_clickhousedb.py | 101 +++++++++++++++++- .../unit_tests/sql/execution/test_executor.py | 36 +++++++ 8 files changed, 310 insertions(+), 31 deletions(-) diff --git a/UPDATING.md b/UPDATING.md index 39636fbeb867..2abd81e7eaa7 100644 --- a/UPDATING.md +++ b/UPDATING.md @@ -73,13 +73,20 @@ assists people when migrating to a new version. Native-protocol connections (`clickhouse+native://`, `clickhouse+asynch://`) move from the native default port 9000 to the HTTP port 8123, because clickhouse-connect speaks HTTP only — confirm the server's HTTP interface is - reachable. Connections whose settings cannot be carried over exactly (other - URI parameters, a non-default native port, native TLS) stay on the legacy driver - and are logged by database id during the upgrade for manual migration. A - downgrade restores the original URI of every converted connection that has not - been edited since. `DISALLOWED_SQL_FUNCTIONS` gains a `clickhousedb` entry - matching `clickhouse`; deployments that override `DISALLOWED_SQL_FUNCTIONS` - should add it as well. + reachable. Converted connections open in the dynamic form + (`configuration_method` becomes `dynamic_form`). Connections whose settings + cannot be carried over exactly stay on the legacy driver and are logged by + database id during the upgrade for manual migration: other URI parameters, a + non-default native port, native TLS, or any `extra.engine_params.connect_args` + (clickhouse-connect would send unknown keys such as `timeout` to the server as + settings, and turns a CA-bundle path in `verify` into `False`). A downgrade + restores the original URI and `configuration_method` of every converted + connection that has not been edited since. Custom grains configured in + `TIME_GRAIN_ADDON_EXPRESSIONS` under `clickhouse` keep applying to converted + connections; entries under `clickhousedb` take precedence. + `DISALLOWED_SQL_FUNCTIONS` gains a `clickhousedb` entry matching `clickhouse`; + deployments that override `DISALLOWED_SQL_FUNCTIONS` must add a `clickhousedb` + entry too, or converted connections run without a function denylist. - Semantic-view filters with an empty IN or NOT IN selection no longer fail with a query validation error. They follow SQL semantics where the filter sits: an empty IN matches no rows (grouped charts return no rows; an ungrouped total diff --git a/superset/connectors/sqla/partition_mapping.py b/superset/connectors/sqla/partition_mapping.py index 2c56e75a54b8..0051010f83bd 100644 --- a/superset/connectors/sqla/partition_mapping.py +++ b/superset/connectors/sqla/partition_mapping.py @@ -725,6 +725,23 @@ def equality_mirrors_safely( } +@lru_cache(maxsize=None) +def _grain_addon_engines(engine: str) -> tuple[str, ...]: + """ + The ``TIME_GRAIN_ADDON_EXPRESSIONS`` keys that apply to ``engine``. + + An engine spec can inherit custom grains configured for a predecessor's + engine name through ``time_grain_addon_aliases``. Specs are fixed for the + life of the process, so the lookup is resolved once per engine name. + """ + # pylint: disable=import-outside-toplevel + from superset.db_engine_specs import get_engine_spec + + spec = get_engine_spec(engine) + aliases = spec.time_grain_addon_aliases if spec.engine == engine else () + return (*aliases, engine) + + def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None: """ How far a grain's truncation can move a timestamp, or ``None`` if unknown. @@ -748,7 +765,11 @@ def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None: # claim to know, so both fall back to not mirroring. if grain in app.config["TIME_GRAIN_ADDONS"]: return None - if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}): + addon_expressions = app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] + if any( + grain in addon_expressions.get(name, {}) + for name in _grain_addon_engines(engine) + ): return None return GRAIN_BUCKET_WIDTHS.get(grain) diff --git a/superset/db_engine_specs/base.py b/superset/db_engine_specs/base.py index 3ba1bbbc2ccf..55478d378798 100644 --- a/superset/db_engine_specs/base.py +++ b/superset/db_engine_specs/base.py @@ -443,6 +443,11 @@ class BaseEngineSpec: # pylint: disable=too-many-public-methods engine_aliases: set[str] = set() drivers: dict[str, str] = {} default_driver: str | None = None + + # Older ``engine`` names whose ``TIME_GRAIN_ADDON_EXPRESSIONS`` entries also + # apply to this spec, so custom grains survive connections being moved onto + # it from a predecessor spec. Entries under ``engine`` take precedence. + time_grain_addon_aliases: tuple[str, ...] = () # Historical default names that must continue to match DBS_AVAILABLE_DENYLIST. default_driver_aliases: tuple[str, ...] = () @@ -1623,6 +1628,22 @@ def sort_interval() -> float: return plist.get(index, 0) + @classmethod + def get_time_grain_addon_expressions(cls) -> dict[str | None, str]: + """ + Return the operator-configured time grain expressions for this engine. + + Entries keyed by any of ``time_grain_addon_aliases`` are included, with + entries keyed by ``engine`` taking precedence. + + :return: The ``TIME_GRAIN_ADDON_EXPRESSIONS`` that apply to the engine + """ + grain_addon_expressions = app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] + expressions: dict[str | None, str] = {} + for engine in (*cls.time_grain_addon_aliases, cls.engine): + expressions.update(grain_addon_expressions.get(engine, {})) + return expressions + @classmethod def get_time_grain_expressions(cls) -> dict[str | None, str]: """ @@ -1633,8 +1654,7 @@ def get_time_grain_expressions(cls) -> dict[str | None, str]: """ # TODO: use @memoize decorator or similar to avoid recomputation on every call time_grain_expressions = cls._time_grain_expressions.copy() - grain_addon_expressions = app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] - time_grain_expressions.update(grain_addon_expressions.get(cls.engine, {})) + time_grain_expressions.update(cls.get_time_grain_addon_expressions()) denylist: list[str] = app.config["TIME_GRAIN_DENYLIST"] for key in denylist: time_grain_expressions.pop(key, None) diff --git a/superset/db_engine_specs/clickhouse.py b/superset/db_engine_specs/clickhouse.py index 7a29cbcbf8b7..af933e6b7bd1 100644 --- a/superset/db_engine_specs/clickhouse.py +++ b/superset/db_engine_specs/clickhouse.py @@ -463,6 +463,9 @@ class ClickHouseConnectEngineSpec(BasicParametersMixin, ClickHouseEngineSpec): engine_name = "ClickHouse" default_driver = "connect" + # Connections migrated from the legacy ``clickhouse`` spec keep the custom + # grains operators configured under that engine name. + time_grain_addon_aliases = ("clickhouse",) _function_names: list[str] = [] sqlalchemy_uri_placeholder = ( diff --git a/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py b/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py index 119f261d3669..79c0f4eba0a9 100644 --- a/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py +++ b/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py @@ -64,14 +64,23 @@ * ``verify`` with a non-boolean value (a CA bundle path); * a non-default native port, or native TLS (``secure=true``), neither of which maps to a known HTTP port without the server's configuration; -* a rewritten URI that would overflow the ``dbs.sqlalchemy_uri`` column. +* a rewritten URI that would overflow the ``dbs.sqlalchemy_uri`` column; +* non-empty ``extra.engine_params.connect_args``, or an ``extra`` that cannot be + parsed. Both drivers receive ``connect_args`` as keyword arguments, but under + different names: ``clickhouse-connect`` forwards unknown keys to the server as + settings (so a legacy ``timeout`` fails every query) and coerces a CA-bundle + path in ``verify`` to ``False``, silently disabling certificate verification. Operators should confirm the HTTP interface is reachable for rewritten native connections. +Converted rows also get ``configuration_method = 'dynamic_form'``: the edit +modal picks its form from that field, so leaving the legacy ``sqlalchemy_form`` +would keep opening the URI editor instead of the new form. + Credentials live in the separately encrypted ``password`` column (the URI only carries the masked placeholder), which this migration never reads or writes; -``encrypted_extra`` is untouched too. +``extra`` is only read, and ``encrypted_extra`` is untouched. Rollback -------- @@ -79,10 +88,11 @@ The rewrite is not textually reversible (parameters are translated and native ports change), and afterwards a migrated row looks like any connection created on the ``clickhousedb`` key. ``upgrade`` therefore records each rewritten row's -original URI and a fingerprint of its migrated state in a migration-owned -table. ``downgrade`` restores the original only for rows whose fingerprint still -matches -- connections edited since the upgrade, and connections created on the -``clickhousedb`` key, are left alone -- and then drops the table. +original URI and ``configuration_method`` and a fingerprint of its migrated +state in a migration-owned table. ``downgrade`` restores both only for rows +whose fingerprint still matches -- connections edited since the upgrade, and +connections created on the ``clickhousedb`` key, are left alone -- and then +drops the table. Revision ID: f7b3a9c14e02 Revises: b8f3a2c91d64 @@ -121,6 +131,7 @@ # the scheme (and may add a port), so a row near the limit could overflow. URI_MAX_LENGTH = 1024 BATCH_SIZE = 1000 +DYNAMIC_FORM = "dynamic_form" _TRUE = {"true", "1", "yes", "y", "on", "t"} _FALSE = {"false", "0", "no", "n", "off", "f", ""} @@ -130,6 +141,8 @@ "dbs", sa.column("id", sa.Integer), sa.column("sqlalchemy_uri", sa.String(1024)), + sa.column("extra", sa.Text), + sa.column("configuration_method", sa.String(255)), sa.column("changed_on", sa.DateTime), ) @@ -137,6 +150,7 @@ "clickhouse_uri_migration", sa.column("id", sa.Integer), sa.column("original_uri", sa.String(1024)), + sa.column("original_configuration_method", sa.String(255)), sa.column("fingerprint", sa.String(64)), ) @@ -252,9 +266,33 @@ def _migrate_uri(uri: str) -> str | None: return None -def _fingerprint(uri: str, changed_on: datetime | None) -> str: +def _check_extra(extra: str | None) -> None: + """Raise when ``extra`` passes driver arguments that may not carry over.""" + if not extra: + return + try: + parsed = json.loads(extra) + except (ValueError, RecursionError) as ex: + raise UnconvertibleError("extra is not valid JSON") from ex + if not isinstance(parsed, dict): + raise UnconvertibleError("extra is not a JSON object") + engine_params = parsed.get("engine_params") or {} + if not isinstance(engine_params, dict): + raise UnconvertibleError("extra.engine_params is not a JSON object") + if connect_args := engine_params.get("connect_args"): + keys = sorted(connect_args) if isinstance(connect_args, dict) else [] + raise UnconvertibleError( + "extra.engine_params.connect_args would be passed to " + f"clickhouse-connect unchanged ({', '.join(keys) or connect_args!r})" + ) + + +def _fingerprint( + uri: str, configuration_method: str | None, changed_on: datetime | None +) -> str: """Recognize the migrated state, including later edits to the connection.""" - return sha256(json.dumps([uri, str(changed_on)]).encode("utf-8")).hexdigest() + state = json.dumps([uri, configuration_method, str(changed_on)]) + return sha256(state.encode("utf-8")).hexdigest() def upgrade() -> None: @@ -263,6 +301,7 @@ def upgrade() -> None: records.name, sa.Column("id", sa.Integer, primary_key=True, autoincrement=False), sa.Column("original_uri", sa.String(1024), nullable=False), + sa.Column("original_configuration_method", sa.String(255), nullable=True), sa.Column("fingerprint", sa.String(64), nullable=False), ) bind = op.get_bind() @@ -284,6 +323,8 @@ def upgrade() -> None: last_id = row.id try: migrated = _rewrite(row.sqlalchemy_uri) + if migrated is not None: + _check_extra(row.extra) except UnconvertibleError as ex: logger.warning( "Leaving ClickHouse database id=%s on the legacy clickhouse " @@ -300,7 +341,7 @@ def upgrade() -> None: databases.c.id == row.id, databases.c.sqlalchemy_uri == row.sqlalchemy_uri, ) - .values(sqlalchemy_uri=migrated) + .values(sqlalchemy_uri=migrated, configuration_method=DYNAMIC_FORM) ) if updated.rowcount: bind.execute(records.delete().where(records.c.id == row.id)) @@ -308,25 +349,33 @@ def upgrade() -> None: records.insert().values( id=row.id, original_uri=row.sqlalchemy_uri, - fingerprint=_fingerprint(migrated, row.changed_on), + original_configuration_method=row.configuration_method, + fingerprint=_fingerprint( + migrated, DYNAMIC_FORM, row.changed_on + ), ) ) def downgrade() -> None: - """Restore unchanged converted URIs, then remove migration bookkeeping.""" + """Restore unchanged converted rows, then remove migration bookkeeping.""" bind = op.get_bind() rows = bind.execute( sa.select( databases.c.id, databases.c.sqlalchemy_uri, + databases.c.configuration_method, databases.c.changed_on, records.c.original_uri, + records.c.original_configuration_method, records.c.fingerprint, ).select_from(records.join(databases, databases.c.id == records.c.id)) ).fetchall() for row in rows: - if row.fingerprint != _fingerprint(row.sqlalchemy_uri, row.changed_on): + current = _fingerprint( + row.sqlalchemy_uri, row.configuration_method, row.changed_on + ) + if row.fingerprint != current: logger.warning( "Not reverting ClickHouse database id=%s: it changed after the " "upgrade.", @@ -339,6 +388,9 @@ def downgrade() -> None: databases.c.id == row.id, databases.c.sqlalchemy_uri == row.sqlalchemy_uri, ) - .values(sqlalchemy_uri=row.original_uri) + .values( + sqlalchemy_uri=row.original_uri, + configuration_method=row.original_configuration_method, + ) ) drop_table(records.name) diff --git a/tests/unit_tests/db_engine_specs/test_clickhouse.py b/tests/unit_tests/db_engine_specs/test_clickhouse.py index ffef94a53c40..a8acbd4bc0e0 100644 --- a/tests/unit_tests/db_engine_specs/test_clickhouse.py +++ b/tests/unit_tests/db_engine_specs/test_clickhouse.py @@ -956,9 +956,9 @@ def test_cancel_query_returns_false_when_kill_status_not_confirmed() -> None: cursor_mock.fetchall.return_value = [ [kill_status, cancel_query_id, "default", "SELECT 1"] ] - assert spec.cancel_query(cursor_mock, Query(), cancel_query_id) is False, ( - f"kill_status={kill_status!r} must not report success" - ) + assert ( + spec.cancel_query(cursor_mock, Query(), cancel_query_id) is False + ), f"kill_status={kill_status!r} must not report success" def test_cancel_query_returns_true_when_nothing_matched() -> None: @@ -1028,9 +1028,9 @@ def test_cancel_query_returns_false_when_query_finished_during_kill_round_trip() cursor_mock.fetchall.return_value = [] with patch("superset.db_engine_specs.clickhouse.db.session.refresh"): - assert spec.cancel_query(cursor_mock, query, cancel_query_id) is False, ( - f"status={terminal_status!r} must not be overwritten" - ) + assert ( + spec.cancel_query(cursor_mock, query, cancel_query_id) is False + ), f"status={terminal_status!r} must not be overwritten" def test_cancel_query_returns_true_when_refresh_shows_still_running() -> None: @@ -1277,3 +1277,46 @@ def test_connect_get_table_names_excludes_views() -> None: assert ClickHouseConnectEngineSpec.get_view_names( database, inspector, "default" ) == {"v1"} + + +def test_connect_spec_resolves_grain_addons_configured_for_clickhouse( + mocker: Any, app_context: None +) -> None: + """ + Connections migrated from the legacy spec keep the custom grains operators + configured under the ``clickhouse`` engine name, while ``clickhousedb`` + entries take precedence. + """ + from flask import current_app + + from superset.connectors.sqla.partition_mapping import grain_bucket_width + from superset.db_engine_specs.clickhouse import ( + ClickHouseConnectEngineSpec, + ClickHouseEngineSpec, + ) + + mocker.patch.dict( + current_app.config, + { + "TIME_GRAIN_ADDON_EXPRESSIONS": { + "clickhouse": { + "PT2S": "legacy-2s({col})", + "P1D": "legacy-day({col})", + }, + "clickhousedb": {"P1D": "connect-day({col})"}, + }, + "TIME_GRAIN_DENYLIST": [], + }, + ) + + grains = ClickHouseConnectEngineSpec.get_time_grain_expressions() + assert grains["PT2S"] == "legacy-2s({col})" + assert grains["P1D"] == "connect-day({col})" + # the legacy spec does not pick up the newer engine's entries + assert ClickHouseEngineSpec.get_time_grain_expressions()["P1D"] == ( + "legacy-day({col})" + ) + # an operator-redefined grain has no known width on either spec + assert grain_bucket_width("P1D", "clickhousedb") is None + assert grain_bucket_width("PT2S", "clickhousedb") is None + assert grain_bucket_width("P1W", "clickhousedb") is not None diff --git a/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py b/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py index 5202685655de..b4f0b46a0577 100644 --- a/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py +++ b/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py @@ -49,6 +49,8 @@ def engine() -> Iterator[Engine]: metadata, sa.Column("id", sa.Integer, primary_key=True), sa.Column("sqlalchemy_uri", sa.String(1024)), + sa.Column("extra", sa.Text), + sa.Column("configuration_method", sa.String(255)), sa.Column("changed_on", sa.DateTime), ) metadata.create_all(engine) @@ -56,17 +58,39 @@ def engine() -> Iterator[Engine]: engine.dispose() -def _seed(engine: Engine, uris: dict[int, str]) -> None: +def _seed( + engine: Engine, + uris: dict[int, str], + extras: dict[int, str | None] | None = None, +) -> None: with engine.begin() as conn: conn.execute( migration.databases.insert(), [ - {"id": id_, "sqlalchemy_uri": uri, "changed_on": CHANGED_ON} + { + "id": id_, + "sqlalchemy_uri": uri, + "extra": (extras or {}).get(id_), + "configuration_method": "sqlalchemy_form", + "changed_on": CHANGED_ON, + } for id_, uri in uris.items() ], ) +def _methods(engine: Engine) -> dict[int, str]: + with engine.connect() as conn: + return dict( + conn.execute( + sa.select( + migration.databases.c.id, + migration.databases.c.configuration_method, + ) + ).fetchall() + ) + + def _uris(engine: Engine) -> dict[int, str]: with engine.connect() as conn: return dict( @@ -305,3 +329,76 @@ def test_downgrade_leaves_native_and_edited_connections(engine: Engine) -> None: 2: f"clickhousedb+connect://user:{MASK}@host:8123/db", 3: f"clickhousedb+connect://user:{MASK}@host:8123/db", } + + +def test_upgrade_switches_converted_rows_to_the_dynamic_form(engine: Engine) -> None: + """The edit modal picks its form from configuration_method.""" + _seed( + engine, + { + 1: f"clickhouse://user:{MASK}@host:8123/db", + 2: f"clickhouse+native://user:{MASK}@host:9440/db", + }, + ) + + _run(engine, upgrading=True) + + # the skipped row keeps the URI editor it can still be edited in + assert _methods(engine) == {1: "dynamic_form", 2: "sqlalchemy_form"} + + +def test_round_trip_restores_configuration_method(engine: Engine) -> None: + _seed(engine, {1: f"clickhouse://user:{MASK}@host:8123/db"}) + + _run(engine, upgrading=True) + _run(engine, upgrading=False) + + assert _methods(engine) == {1: "sqlalchemy_form"} + assert _uris(engine) == {1: f"clickhouse://user:{MASK}@host:8123/db"} + + +@pytest.mark.parametrize( + "extra", + [ + # clickhouse-connect would send this as an unknown server setting + '{"engine_params": {"connect_args": {"timeout": 30}}}', + # ...and would coerce the CA path to False, disabling verification + '{"engine_params": {"connect_args": {"verify": "/etc/ssl/ca.pem"}}}', + # an extra that cannot be inspected is not assumed to be safe + "{not json", + '["not", "an", "object"]', + '{"engine_params": ["not", "an", "object"]}', + ], +) +def test_upgrade_skips_rows_with_driver_connect_args( + engine: Engine, caplog, extra: str +) -> None: + uri = f"clickhouse://user:{MASK}@host:8123/db" + _seed(engine, {1: uri}, extras={1: extra}) + + _run(engine, upgrading=True) + + assert _uris(engine) == {1: uri} + assert _methods(engine) == {1: "sqlalchemy_form"} + assert "id=1" in caplog.text + + +@pytest.mark.parametrize( + "extra", + [ + None, + "", + "{}", + '{"engine_params": {}}', + '{"engine_params": {"connect_args": {}}}', + '{"engine_params": {"pool_size": 5}, "allows_virtual_table_explore": true}', + ], +) +def test_upgrade_converts_rows_without_connect_args( + engine: Engine, extra: str | None +) -> None: + _seed(engine, {1: f"clickhouse://user:{MASK}@host:8123/db"}, extras={1: extra}) + + _run(engine, upgrading=True) + + assert _uris(engine) == {1: f"clickhousedb+connect://user:{MASK}@host:8123/db"} diff --git a/tests/unit_tests/sql/execution/test_executor.py b/tests/unit_tests/sql/execution/test_executor.py index c48adbc6cbea..c1f140ec57d0 100644 --- a/tests/unit_tests/sql/execution/test_executor.py +++ b/tests/unit_tests/sql/execution/test_executor.py @@ -411,6 +411,42 @@ def test_execute_allowed_functions( assert result.status == QueryStatus.SUCCESS +def test_execute_default_denylist_applies_to_clickhouse_connect( + mocker: MockerFixture, app_context: None +) -> None: + """ + The default ClickHouse function denylist applies to the clickhousedb spec. + + Connections migrated from the legacy ``clickhouse`` spec resolve to + ``ClickHouseConnectEngineSpec``, and the denylist is looked up by its + ``clickhousedb`` engine name. Config is deliberately not patched here, so + dropping that default entry fails this test. + """ + from superset.db_engine_specs.clickhouse import ClickHouseConnectEngineSpec + + database = Database( + id=3, + database_name="clickhouse_db", + sqlalchemy_uri="clickhousedb+connect://default@localhost:8123/default", + ) + assert database.db_engine_spec is ClickHouseConnectEngineSpec + mocker.patch.dict( + current_app.config, {"SQL_QUERY_MUTATOR": None, "QUERY_LOGGER": None} + ) + + denied = database.execute("SELECT version()") + + assert denied.status == QueryStatus.FAILED + assert denied.error_message is not None + assert "Disallowed SQL functions" in denied.error_message + + mock_query_execution(mocker, database, return_data=[(1,)], column_names=["1"]) + + allowed = database.execute("SELECT 1") + + assert allowed.status == QueryStatus.SUCCESS + + def test_execute_disallowed_function_names_in_identifiers_are_allowed( mocker: MockerFixture, database: Database, app_context: None ) -> None: From 0127f202f51ee849bb1d6449002fba57f3e586c8 Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Fri, 6 Nov 2026 01:07:36 +0000 Subject: [PATCH 5/7] style(clickhouse): restore ruff 0.9.7 formatting in test_clickhouse A stale local ruff reformatted two existing asserts; restore master's formatting so the file only carries the new test. Co-Authored-By: Claude Opus 5.5 --- .../db_engine_specs/test_clickhouse.py | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/tests/unit_tests/db_engine_specs/test_clickhouse.py b/tests/unit_tests/db_engine_specs/test_clickhouse.py index a8acbd4bc0e0..535843a16257 100644 --- a/tests/unit_tests/db_engine_specs/test_clickhouse.py +++ b/tests/unit_tests/db_engine_specs/test_clickhouse.py @@ -956,9 +956,9 @@ def test_cancel_query_returns_false_when_kill_status_not_confirmed() -> None: cursor_mock.fetchall.return_value = [ [kill_status, cancel_query_id, "default", "SELECT 1"] ] - assert ( - spec.cancel_query(cursor_mock, Query(), cancel_query_id) is False - ), f"kill_status={kill_status!r} must not report success" + assert spec.cancel_query(cursor_mock, Query(), cancel_query_id) is False, ( + f"kill_status={kill_status!r} must not report success" + ) def test_cancel_query_returns_true_when_nothing_matched() -> None: @@ -1028,9 +1028,9 @@ def test_cancel_query_returns_false_when_query_finished_during_kill_round_trip() cursor_mock.fetchall.return_value = [] with patch("superset.db_engine_specs.clickhouse.db.session.refresh"): - assert ( - spec.cancel_query(cursor_mock, query, cancel_query_id) is False - ), f"status={terminal_status!r} must not be overwritten" + assert spec.cancel_query(cursor_mock, query, cancel_query_id) is False, ( + f"status={terminal_status!r} must not be overwritten" + ) def test_cancel_query_returns_true_when_refresh_shows_still_running() -> None: @@ -1313,9 +1313,8 @@ def test_connect_spec_resolves_grain_addons_configured_for_clickhouse( assert grains["PT2S"] == "legacy-2s({col})" assert grains["P1D"] == "connect-day({col})" # the legacy spec does not pick up the newer engine's entries - assert ClickHouseEngineSpec.get_time_grain_expressions()["P1D"] == ( - "legacy-day({col})" - ) + legacy_grains = ClickHouseEngineSpec.get_time_grain_expressions() + assert legacy_grains["P1D"] == "legacy-day({col})" # an operator-redefined grain has no known width on either spec assert grain_bucket_width("P1D", "clickhousedb") is None assert grain_bucket_width("PT2S", "clickhousedb") is None From 8247f9ea78937b7b1d901124a80fdb4800d249a6 Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Mon, 23 Nov 2026 17:20:11 +0000 Subject: [PATCH 6/7] fix(migrations): re-point clickhousedb migration to the current single head Co-Authored-By: Claude Sonnet 5.5 --- ...0-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py} | 6 +++--- .../migrations/test_migrate_clickhouse_to_clickhousedb.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) rename superset/migrations/versions/{2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py => 2026-11-23_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py} (99%) diff --git a/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py b/superset/migrations/versions/2026-11-23_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py similarity index 99% rename from superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py rename to superset/migrations/versions/2026-11-23_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py index 79c0f4eba0a9..92e08ad0a22a 100644 --- a/superset/migrations/versions/2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py +++ b/superset/migrations/versions/2026-11-23_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py @@ -95,8 +95,8 @@ drops the table. Revision ID: f7b3a9c14e02 -Revises: b8f3a2c91d64 -Create Date: 2026-09-15 00:00:00.000000 +Revises: dfa683969f48 +Create Date: 2026-11-23 00:00:00.000000 """ @@ -116,7 +116,7 @@ # revision identifiers, used by Alembic. revision = "f7b3a9c14e02" -down_revision = "b8f3a2c91d64" +down_revision = "dfa683969f48" LEGACY_BACKEND = "clickhouse" TARGET_SCHEME = "clickhousedb+connect" diff --git a/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py b/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py index b4f0b46a0577..a6624510ca52 100644 --- a/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py +++ b/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py @@ -31,7 +31,7 @@ migration = import_module( "superset.migrations.versions." - "2026-09-15_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb" + "2026-11-23_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb" ) _migrate_uri = migration._migrate_uri From e906ddf1d5d26e3821f20db95a4ee91849dd4949 Mon Sep 17 00:00:00 2001 From: Elizabeth Thompson Date: Wed, 25 Nov 2026 16:02:06 +0000 Subject: [PATCH 7/7] fix(migrations): re-point clickhousedb migration to the current single head (a7d29bc4e681) Co-Authored-By: Claude Sonnet 5.5 --- ...3_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/superset/migrations/versions/2026-11-23_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py b/superset/migrations/versions/2026-11-23_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py index 92e08ad0a22a..ee3480ff3e9f 100644 --- a/superset/migrations/versions/2026-11-23_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py +++ b/superset/migrations/versions/2026-11-23_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py @@ -95,7 +95,7 @@ drops the table. Revision ID: f7b3a9c14e02 -Revises: dfa683969f48 +Revises: a7d29bc4e681 Create Date: 2026-11-23 00:00:00.000000 """ @@ -116,7 +116,7 @@ # revision identifiers, used by Alembic. revision = "f7b3a9c14e02" -down_revision = "dfa683969f48" +down_revision = "a7d29bc4e681" LEGACY_BACKEND = "clickhouse" TARGET_SCHEME = "clickhousedb+connect"