diff --git a/UPDATING.md b/UPDATING.md index e79a7dfd8000..f7101dbe55f5 100644 --- a/UPDATING.md +++ b/UPDATING.md @@ -274,6 +274,28 @@ 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. 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/config.py b/superset/config.py index 58c5d08be252..3de36ef18c1a 100644 --- a/superset/config.py +++ b/superset/config.py @@ -2744,6 +2744,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/connectors/sqla/partition_mapping.py b/superset/connectors/sqla/partition_mapping.py index 322456153cc6..65021cd34a59 100644 --- a/superset/connectors/sqla/partition_mapping.py +++ b/superset/connectors/sqla/partition_mapping.py @@ -730,6 +730,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. @@ -753,7 +770,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 6bdd973d392c..589d83281d38 100644 --- a/superset/db_engine_specs/base.py +++ b/superset/db_engine_specs/base.py @@ -458,6 +458,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, ...] = () @@ -1748,6 +1753,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]: """ @@ -1758,8 +1779,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 bc90e999c316..b0cab0e17878 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-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 new file mode 100644 index 000000000000..ee3480ff3e9f --- /dev/null +++ b/superset/migrations/versions/2026-11-23_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb.py @@ -0,0 +1,396 @@ +# 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. + +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; +* 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; +``extra`` is only read, and ``encrypted_extra`` is untouched. + +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 ``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: a7d29bc4e681 +Create Date: 2026-11-23 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 superset.migrations.shared.utils import create_table, drop_table +from superset.utils import json + +logger = logging.getLogger("alembic.env") + +# revision identifiers, used by Alembic. +revision = "f7b3a9c14e02" +down_revision = "a7d29bc4e681" + +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 +DYNAMIC_FORM = "dynamic_form" + +_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("extra", sa.Text), + sa.column("configuration_method", sa.String(255)), + sa.column("changed_on", sa.DateTime), +) + +records = sa.table( + "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)), +) + + +class UnconvertibleError(Exception): + """A legacy row that cannot be rewritten without changing its meaning.""" + + +def _split_uri(remainder: str) -> tuple[str, str, str, str]: + """Split the part after ``://`` into userinfo, host:port, path and query. + + ``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. + """ + end = len(remainder) + for index, char in enumerate(remainder): + if char in "/?": + end = index + break + + authority = remainder[:end] + at = authority.rfind("@") + path, _, query = remainder[end:].partition("?") + return authority[: at + 1], authority[at + 1 :], path, query + + +def _split_hostport(hostport: str) -> tuple[str, str | None]: + """Split ``host[:port]``, treating a bracketed IPv6 literal as one host.""" + if hostport.startswith("["): + 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(":") + return (host, port) if colon else (hostport, None) + + +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("://") + backend, _, driver = scheme.partition("+") + 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) + 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: + 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 + + +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.""" + state = json.dumps([uri, configuration_method, str(changed_on)]) + return sha256(state.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("original_configuration_method", sa.String(255), nullable=True), + sa.Column("fingerprint", sa.String(64), nullable=False), + ) + bind = op.get_bind() + 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) + if migrated is not None: + _check_extra(row.extra) + 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, configuration_method=DYNAMIC_FORM) + ) + 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, + original_configuration_method=row.configuration_method, + fingerprint=_fingerprint( + migrated, DYNAMIC_FORM, row.changed_on + ), + ) + ) + + +def downgrade() -> None: + """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: + 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.", + 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, + 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 0aaa430f6479..bc26d6c376d1 100644 --- a/tests/unit_tests/db_engine_specs/test_clickhouse.py +++ b/tests/unit_tests/db_engine_specs/test_clickhouse.py @@ -1356,3 +1356,45 @@ 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 + 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 + 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 new file mode 100644 index 000000000000..a6624510ca52 --- /dev/null +++ b/tests/unit_tests/migrations/test_migrate_clickhouse_to_clickhousedb.py @@ -0,0 +1,404 @@ +# 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``.""" + +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 +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-11-23_00-00_f7b3a9c14e02_migrate_clickhouse_to_clickhousedb" +) +_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() -> 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("extra", sa.Text), + sa.Column("configuration_method", sa.String(255)), + sa.Column("changed_on", sa.DateTime), + ) + metadata.create_all(engine) + yield engine + engine.dispose() + + +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, + "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( + conn.execute( + sa.select( + migration.databases.c.id, migration.databases.c.sqlalchemy_uri + ) + ).fetchall() + ) + + +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: only the scheme changes + ( + f"clickhouse://user:{MASK}@host:8123/db", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + ( + f"clickhouse+http://user:{MASK}@host:8123/db", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # no port and no TLS: both drivers default to 8123, so none is added + ("clickhouse://localhost/default", "clickhousedb+connect://localhost/default"), + # verify has the same meaning in both drivers + ( + 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_translates_tls(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", + ), + ( + f"clickhouse+asynch://user:{MASK}@host:9000/db", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # no explicit port implies the native default 9000 + ( + f"clickhouse+native://user:{MASK}@host/db", + f"clickhousedb+connect://user:{MASK}@host:8123/db", + ), + # a falsy secure is plaintext in both drivers and is dropped + ( + "clickhouse+native://host:9000/db?secure=false", + "clickhousedb+connect://host:8123/db", + ), + ], +) +def test_migrate_uri_native(uri: str, expected: str) -> None: + assert _migrate_uri(uri) == expected + + +@pytest.mark.parametrize( + "uri", + [ + # 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", + f"postgresql://user:{MASK}@host:5432/db", + "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_row_alone(uri: str) -> None: + assert _migrate_uri(uri) is None + + +def test_migrate_uri_ignores_at_sign_in_query() -> None: + """An "@" after the authority must not be mistaken for the separator.""" + assert ( + _migrate_uri("clickhouse+native://host:9000/db@x") + == "clickhousedb+connect://host:8123/db@x" + ) + + +def test_migrate_uri_skips_rows_that_would_overflow_the_column() -> None: + padding = "x" * (migration.URI_MAX_LENGTH - len("clickhouse://host/")) + uri = f"clickhouse://host/{padding}" + assert len(uri) == migration.URI_MAX_LENGTH + assert _migrate_uri(uri) is None + + +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", + }, + ) + + _run(engine, upgrading=True) + + 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: Engine) -> None: + _seed(engine, {1: f"clickhouse://user:{MASK}@host:8123/db"}) + + _run(engine, upgrading=True) + _run(engine, upgrading=True) + + assert _uris(engine) == {1: 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) + + _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: + conn.execute( + migration.databases.update() + .where(migration.databases.c.id == 2) + .values(changed_on=datetime(2026, 2, 1)) + ) + + _run(engine, upgrading=False) + + 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", + } + + +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 a958186a5f10..304641535f84 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: