From 8bd2483531a6c0311e8fe93a22f0eaa44a1ab976 Mon Sep 17 00:00:00 2001 From: Rodrigo-Palma Date: Thu, 17 Sep 2026 12:00:21 -0300 Subject: [PATCH 01/62] fix(macros): keep SAFE_ADD, SAFE_SUB and SAFE_DIV grouped inside surrounding operators The optimizer collapses the CASE built by SAFE_ADD/SAFE_SUB into its ELSE branch without parentheses, so an enclosing operator swallows an operand. Emit the ELSE arithmetic as an explicit Paren. SAFE_DIV now returns its quotient wrapped in a Paren so x / @SAFE_DIV(a, b) keeps its grouping. Closes #5649 Signed-off-by: Rodrigo-Palma --- docs/concepts/macros/sqlmesh_macros.md | 6 ++-- sqlmesh/core/macros.py | 33 +++++++++++------ tests/core/test_macros.py | 49 ++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 13 deletions(-) diff --git a/docs/concepts/macros/sqlmesh_macros.md b/docs/concepts/macros/sqlmesh_macros.md index 5459d79ca8..871ff43e80 100644 --- a/docs/concepts/macros/sqlmesh_macros.md +++ b/docs/concepts/macros/sqlmesh_macros.md @@ -887,7 +887,7 @@ would be rendered as: ```sql linenums="1" SELECT - CASE WHEN a IS NULL AND b IS NULL AND c IS NULL THEN NULL ELSE COALESCE(a, 0) + COALESCE(b, 0) + COALESCE(c, 0) END + CASE WHEN a IS NULL AND b IS NULL AND c IS NULL THEN NULL ELSE (COALESCE(a, 0) + COALESCE(b, 0) + COALESCE(c, 0)) END FROM foo ``` @@ -906,7 +906,7 @@ would be rendered as: ```sql linenums="1" SELECT - CASE WHEN a IS NULL AND b IS NULL AND c IS NULL THEN NULL ELSE COALESCE(a, 0) - COALESCE(b, 0) - COALESCE(c, 0) END + CASE WHEN a IS NULL AND b IS NULL AND c IS NULL THEN NULL ELSE (COALESCE(a, 0) - COALESCE(b, 0) - COALESCE(c, 0)) END FROM foo ``` @@ -925,7 +925,7 @@ would be rendered as: ```sql linenums="1" SELECT - a / NULLIF(b, 0) + (a / NULLIF(b, 0)) FROM foo ``` diff --git a/sqlmesh/core/macros.py b/sqlmesh/core/macros.py index 2e995003bf..4751bd85db 100644 --- a/sqlmesh/core/macros.py +++ b/sqlmesh/core/macros.py @@ -1052,12 +1052,11 @@ def safe_add(_: MacroEvaluator, *fields: exp.Expr) -> exp.Case: >>> from sqlmesh.core.macros import MacroEvaluator >>> sql = "SELECT @SAFE_ADD(a, b) FROM foo" >>> MacroEvaluator().transform(parse_one(sql)).sql() - 'SELECT CASE WHEN a IS NULL AND b IS NULL THEN NULL ELSE COALESCE(a, 0) + COALESCE(b, 0) END FROM foo' + 'SELECT CASE WHEN a IS NULL AND b IS NULL THEN NULL ELSE (COALESCE(a, 0) + COALESCE(b, 0)) END FROM foo' """ - return ( - exp.Case() - .when(exp.and_(*(field.is_(exp.null()) for field in fields)), exp.null()) - .else_(reduce(lambda a, b: a + b, [exp.func("COALESCE", field, 0) for field in fields])) # type: ignore + return _null_if_all_null( + fields, + reduce(lambda a, b: a + b, [exp.func("COALESCE", field, 0) for field in fields]), # type: ignore ) @@ -1070,17 +1069,30 @@ def safe_sub(_: MacroEvaluator, *fields: exp.Expr) -> exp.Case: >>> from sqlmesh.core.macros import MacroEvaluator >>> sql = "SELECT @SAFE_SUB(a, b) FROM foo" >>> MacroEvaluator().transform(parse_one(sql)).sql() - 'SELECT CASE WHEN a IS NULL AND b IS NULL THEN NULL ELSE COALESCE(a, 0) - COALESCE(b, 0) END FROM foo' + 'SELECT CASE WHEN a IS NULL AND b IS NULL THEN NULL ELSE (COALESCE(a, 0) - COALESCE(b, 0)) END FROM foo' + """ + return _null_if_all_null( + fields, + reduce(lambda a, b: a - b, [exp.func("COALESCE", field, 0) for field in fields]), # type: ignore + ) + + +def _null_if_all_null(fields: t.Sequence[exp.Expr], arithmetic: exp.Expr) -> exp.Case: + """Returns NULL when every field is NULL, otherwise the result of the arithmetic. + + The arithmetic is parenthesized because the optimizer replaces the CASE with this branch + when the condition is statically false (e.g. `1 IS NULL`), and without the parentheses + the operation would bind to the operators around the macro call. """ return ( exp.Case() .when(exp.and_(*(field.is_(exp.null()) for field in fields)), exp.null()) - .else_(reduce(lambda a, b: a - b, [exp.func("COALESCE", field, 0) for field in fields])) # type: ignore + .else_(exp.paren(arithmetic, copy=False)) ) @macro() -def safe_div(_: MacroEvaluator, numerator: exp.Expr, denominator: exp.Expr) -> exp.Div: +def safe_div(_: MacroEvaluator, numerator: exp.Expr, denominator: exp.Expr) -> exp.Paren: """Divides numbers, returns null if the denominator is 0. Example: @@ -1088,9 +1100,10 @@ def safe_div(_: MacroEvaluator, numerator: exp.Expr, denominator: exp.Expr) -> e >>> from sqlmesh.core.macros import MacroEvaluator >>> sql = "SELECT @SAFE_DIV(a, b) FROM foo" >>> MacroEvaluator().transform(parse_one(sql)).sql() - 'SELECT a / NULLIF(b, 0) FROM foo' + 'SELECT (a / NULLIF(b, 0)) FROM foo' """ - return numerator / exp.func("NULLIF", denominator, 0) + # The quotient must stay a single operand of whatever operator surrounds the macro call + return exp.paren(numerator / exp.func("NULLIF", denominator, 0), copy=False) @macro() diff --git a/tests/core/test_macros.py b/tests/core/test_macros.py index 0b3bcf70ee..fd5a6daf7e 100644 --- a/tests/core/test_macros.py +++ b/tests/core/test_macros.py @@ -11,6 +11,7 @@ from sqlmesh.utils.errors import SQLMeshError from sqlmesh.utils.metaprogramming import Executable from sqlmesh.core.macros import RuntimeStage +from sqlmesh.core.model import load_sql_based_model @pytest.fixture @@ -1313,3 +1314,51 @@ def render(dialect: str, hash_function: str) -> str: render("snowflake", "SHA256") == "SELECT SHA256(CONCAT(COALESCE(CAST(a AS VARCHAR), '_sqlmesh_surrogate_key_null_'))) FROM foo" ) + + +@pytest.mark.parametrize( + "projection, expected", + [ + # GitHub issue #5649: once the optimizer resolves `1 IS NULL`, the CASE collapses into its + # ELSE branch, and the arithmetic must stay grouped inside the surrounding multiplication. + ( + "(@SAFE_SUB(price, amount_off)) * (@SAFE_SUB(1, percent_off / 100))", + 'CASE WHEN "s"."amount_off" IS NULL AND "s"."price" IS NULL THEN NULL ELSE (COALESCE("s"."price", 0) - COALESCE("s"."amount_off", 0)) END * (COALESCE(1, 0) - COALESCE("s"."percent_off" / 100, 0))', + ), + ("x * @SAFE_SUB(1, y)", '"s"."x" * (COALESCE(1, 0) - COALESCE("s"."y", 0))'), + ("-@SAFE_SUB(1, y)", '-(COALESCE(1, 0) - COALESCE("s"."y", 0))'), + ("x - @SAFE_ADD(1, y)", '"s"."x" - (COALESCE(1, 0) + COALESCE("s"."y", 0))'), + ("x * @SAFE_ADD(1, y)", '"s"."x" * (COALESCE(1, 0) + COALESCE("s"."y", 0))'), + ( + "@SAFE_DIV(@SAFE_SUB(1, y), x)", + '(COALESCE(1, 0) - COALESCE("s"."y", 0)) / NULLIF("s"."x", 0)', + ), + # The quotient is a single operand of the enclosing operator. + ("x / @SAFE_DIV(price, y)", '"s"."x" / ("s"."price" / NULLIF("s"."y", 0))'), + ("x * @SAFE_DIV(price, y)", '"s"."x" * ("s"."price" / NULLIF("s"."y", 0))'), + # Standalone usages: the optimizer drops the redundant parentheses around the quotient, + # while the ELSE branch keeps its grouping. + ("@SAFE_DIV(price, y)", '"s"."price" / NULLIF("s"."y", 0)'), + ( + "@SAFE_SUB(price, amount_off) + 1", + 'CASE WHEN "s"."amount_off" IS NULL AND "s"."price" IS NULL THEN NULL ELSE (COALESCE("s"."price", 0) - COALESCE("s"."amount_off", 0)) END + 1', + ), + ], +) +def test_safe_arithmetic_macros_keep_precedence_after_optimization( + projection: str, expected: str +) -> None: + model = load_sql_based_model( + d.parse( + f""" + MODEL (name db.safe_arithmetic); + + SELECT {projection} AS result + FROM (SELECT 1 AS x, 2 AS y, 100 AS price, 25 AS amount_off, 20 AS percent_off) AS s + """ + ) + ) + + rendered_projection = model.render_query_or_raise().selects[0] + + assert rendered_projection.sql() == f'{expected} AS "result"' From 76225c61905c618b4f1bc7e616553df6039e0f88 Mon Sep 17 00:00:00 2001 From: Adegbite Ayoade Abel Date: Sun, 20 Sep 2026 21:08:26 +0100 Subject: [PATCH 02/62] feat(test): treat model file paths as test selectors (#6061) Signed-off-by: Adegbite Ayoade --- docs/concepts/tests.md | 14 ++++ docs/reference/cli.md | 4 ++ sqlmesh/cli/main.py | 8 ++- sqlmesh/core/context.py | 122 ++++++++++++++++++++++++++++---- tests/cli/test_cli.py | 95 +++++++++++++++++++++++++ tests/core/test_test.py | 151 ++++++++++++++++++++++++++++++++++++++++ 6 files changed, 378 insertions(+), 16 deletions(-) diff --git a/docs/concepts/tests.md b/docs/concepts/tests.md index a9bd45a25a..8bf0fe0cbf 100644 --- a/docs/concepts/tests.md +++ b/docs/concepts/tests.md @@ -463,6 +463,20 @@ You can also run tests that match a pattern or substring using a glob pathname e $ sqlmesh test tests/test_* ``` +Passing the path of a model file runs the tests for that model, which is useful for commit hooks and other tools that work with changed files rather than test names: + +``` +$ sqlmesh test models/full_model.sql +``` + +Model files and test files can be mixed, and the results are unioned. A test selected by more than one argument still runs only once, so the following runs each of `full_model`'s tests a single time even though both arguments cover them: + +``` +$ sqlmesh test models/full_model.sql tests/test_full_model.yaml +``` + +An argument that is neither a known model file nor a known test file is an error, so a mistyped or stale path fails instead of quietly running no tests. A model that simply has no tests is not an error. + You can pass `--local` to run tests without loading state from the configured state connection: ``` bash diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 1ed03535b9..f7943e2f71 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -623,6 +623,10 @@ Usage: sqlmesh test [OPTIONS] [TESTS]... Run model unit tests. + TESTS are test files, `file.yaml::test_name` selectors, or model files, in + which case the tests for those models are run. They are unioned, and a test + selected more than once still only runs once. + Options: -k TEXT Only run tests that match the pattern of substring. -v, --verbose Verbose output. diff --git a/sqlmesh/cli/main.py b/sqlmesh/cli/main.py index c2c81ada9c..fc6cad8011 100644 --- a/sqlmesh/cli/main.py +++ b/sqlmesh/cli/main.py @@ -835,7 +835,12 @@ def test( select_model: t.List[str], tests: t.List[str], ) -> None: - """Run model unit tests.""" + """Run model unit tests. + + TESTS are test files, `file.yaml::test_name` selectors, or model files, in which case the + tests for those models are run. They are unioned, and a test selected more than once still + only runs once. + """ model_names = ( obj._new_selector().expand_model_selections(select_model) if select_model else None ) @@ -845,6 +850,7 @@ def test( verbosity=Verbosity(verbose), preserve_fixtures=preserve_fixtures, model_names=model_names, + raise_on_unknown_paths=True, ) if not result.wasSuccessful(): exit(1) diff --git a/sqlmesh/core/context.py b/sqlmesh/core/context.py index b70ccae141..64dd6d67da 100644 --- a/sqlmesh/core/context.py +++ b/sqlmesh/core/context.py @@ -36,6 +36,7 @@ import abc import collections import logging +import os.path import sys import time import traceback @@ -119,7 +120,7 @@ filter_tests_by_patterns, ) from sqlmesh.core.user import User -from sqlmesh.utils import CorrelationId, UniqueKeyDict, Verbosity +from sqlmesh.utils import CorrelationId, UniqueKeyDict, Verbosity, unique from sqlmesh.utils.concurrency import concurrent_apply_to_values from sqlmesh.utils.dag import DAG from sqlmesh.utils.date import ( @@ -2407,6 +2408,7 @@ def test( preserve_fixtures: bool = False, stream: t.Optional[t.TextIO] = None, model_names: t.Optional[t.Collection[str]] = None, + raise_on_unknown_paths: bool = False, ) -> ModelTextTestResult: """Discover and run model tests""" if verbosity >= Verbosity.VERBOSE: @@ -2414,10 +2416,18 @@ def test( pd.set_option("display.max_columns", None) - baseline_meta = self.select_tests(tests=tests, patterns=match_patterns, model_names=None) + baseline_meta = self.select_tests( + tests=tests, + patterns=match_patterns, + model_names=None, + raise_on_unknown_paths=raise_on_unknown_paths, + ) if model_names is not None: test_meta = self.select_tests( - tests=tests, patterns=match_patterns, model_names=model_names + tests=tests, + patterns=match_patterns, + model_names=model_names, + raise_on_unknown_paths=raise_on_unknown_paths, ) tests_skipped = len(baseline_meta) - len(test_meta) else: @@ -3611,30 +3621,112 @@ def lint_models( return all_violations + def _tests_by_absolute_model_path(self) -> t.Dict[str, t.List[ModelTestMetadata]]: + """Map each model file to the tests that target the model(s) defined in it.""" + tests_by_model_name: t.Dict[str, t.List[ModelTestMetadata]] = collections.defaultdict(list) + for metadata in self._model_test_metadata: + if metadata.model_name: + tests_by_model_name[ + normalize_model_name( + metadata.model_name, + default_catalog=self.default_catalog, + dialect=self.default_dialect, + ) + ].append(metadata) + + # A path is made absolute rather than resolved, so this costs no syscalls per model. + tests_by_path: t.Dict[str, t.List[ModelTestMetadata]] = {} + for fqn, model in self._models.items(): + if model._path is not None: + tests_by_path.setdefault(os.path.abspath(model._path), []).extend( + tests_by_model_name.get(fqn, []) + ) + + return tests_by_path + + def _select_tests_by_test_path(self, selector: str) -> t.Optional[t.List[ModelTestMetadata]]: + """Resolve a selector against the test files, or return None if it matches none of them. + + The selector is a test file path or a `path::test_name`. Paths are matched as given + first, so an unchanged selector never pays for normalization. + """ + if "::" in selector: + metadata = self._model_test_metadata_fully_qualified_name_index.get(selector) + if metadata is None: + path, _, test_name = selector.rpartition("::") + metadata = self._model_test_metadata_fully_qualified_name_index.get( + f"{os.path.abspath(path)}::{test_name}" + ) + return [metadata] if metadata is not None else None + + for candidate in (Path(selector), Path(os.path.abspath(selector))): + matched = self._model_test_metadata_path_index.get(candidate) + if matched is not None: + return list(matched) + + return None + + def _unknown_test_selector_error(self, selector: str) -> str: + """Explains why a selector matched nothing. + + A `path::test_name` whose file is a known test file failed on the test name, not the + path, so the message says so rather than claiming the file is unknown. + """ + if "::" in selector: + path, _, _ = selector.rpartition("::") + if any( + candidate in self._model_test_metadata_path_index + for candidate in (Path(path), Path(os.path.abspath(path))) + ): + return f"'{selector}' is not a known test in '{path}'." + + return f"'{selector}' is not a known model or test file." + def select_tests( self, tests: t.Optional[t.List[str]] = None, patterns: t.Optional[t.List[str]] = None, model_names: t.Optional[t.Collection[str]] = None, + raise_on_unknown_paths: bool = False, ) -> t.List[ModelTestMetadata]: - """Filter pre-loaded test metadata based on tests and patterns.""" + """Filter pre-loaded test metadata based on tests and patterns. + + Args: + tests: Test selectors. Each one is a test file path, a `path::test_name`, or the path + of a model file, in which case that model's tests are selected. Selectors are + unioned and the result is deduplicated, so a model file and a test file that + resolve to the same test run it once rather than twice. + patterns: Patterns matched against fully qualified test names. + model_names: If given, narrows the selection to tests targeting these models. + raise_on_unknown_paths: Whether to raise when a selector matches neither a known test + nor a known model file. Off by default so that callers which probe arbitrary + documents, such as the LSP, keep getting an empty result instead of an error. + """ test_meta = self._model_test_metadata if tests: - filtered_tests = [] + filtered_tests: t.List[ModelTestMetadata] = [] + # Built at most once, and only if a selector turns out not to be a test file. + tests_by_model_path: t.Optional[t.Dict[str, t.List[ModelTestMetadata]]] = None + for test in tests: - if "::" in test: - if test in self._model_test_metadata_fully_qualified_name_index: - filtered_tests.append( - self._model_test_metadata_fully_qualified_name_index[test] - ) - else: - test_path = Path(test) - if test_path in self._model_test_metadata_path_index: - filtered_tests.extend(self._model_test_metadata_path_index[test_path]) + matched = self._select_tests_by_test_path(test) + if matched is None and "::" not in test: + if tests_by_model_path is None: + tests_by_model_path = self._tests_by_absolute_model_path() + # A known model with no tests matches an empty list, which is not the same + # as a selector that resolves to nothing at all. + matched = tests_by_model_path.get(os.path.abspath(test)) + if matched is None: + if raise_on_unknown_paths: + raise SQLMeshError(self._unknown_test_selector_error(test)) + continue + filtered_tests.extend(matched) - test_meta = filtered_tests + # Selectors can overlap, e.g. a model file and the test file holding its tests, so + # the union is deduplicated to avoid running the same test more than once. + test_meta = unique(filtered_tests) if patterns: test_meta = filter_tests_by_patterns(test_meta, patterns) diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index b52df5394a..251ea54fa3 100644 --- a/tests/cli/test_cli.py +++ b/tests/cli/test_cli.py @@ -2666,6 +2666,27 @@ def test_format_does_not_open_state_connection( mock.assert_not_called() +def test_test_accepts_model_paths(runner: CliRunner, tmp_path: Path) -> None: + create_example_project(tmp_path) + + result = runner.invoke( + cli, ["--paths", str(tmp_path), "test", str(tmp_path / "models" / "full_model.sql")] + ) + assert result.exit_code == 0, f"Test failed: {result.output}\nException: {result.exception}" + assert "Ran 1 test" in result.output + + +def test_test_unknown_path_fails(runner: CliRunner, tmp_path: Path) -> None: + """A staged file that resolves to nothing must fail rather than silently run no tests.""" + create_example_project(tmp_path) + + result = runner.invoke( + cli, ["--paths", str(tmp_path), "test", str(tmp_path / "models" / "nope.sql")] + ) + assert result.exit_code != 0 + assert "is not a known model or test file" in result.output + + def test_test_local_runs_project_unit_tests(runner: CliRunner, tmp_path: Path, mocker) -> None: """A real unit test from the project's YAML runs under `--local` without touching state.""" create_example_project(tmp_path) @@ -2776,3 +2797,77 @@ def test_test_local_multi_repo_partial(runner: CliRunner, copy_to_temp_path, moc ) assert "Successfully Ran 1 tests" in output, "the repo_2 test should still run" mock.assert_not_called() + + +def test_test_local_with_model_paths(runner: CliRunner, tmp_path: Path, mocker) -> None: + """`--local` and model path selectors compose, which is the pre-commit hook case in #6020.""" + create_example_project(tmp_path) + mock = _patch_state_access(mocker) + + result = runner.invoke( + cli, + ["--paths", str(tmp_path), "test", "--local", str(tmp_path / "models" / "full_model.sql")], + ) + + assert result.exit_code == 0, f"Test failed: {result.output}\nException: {result.exception}" + assert "Successfully Ran 1 tests" in " ".join(result.output.split()) + mock.assert_not_called() + + # An unresolvable path still fails loudly, without reaching state. + result = runner.invoke( + cli, ["--paths", str(tmp_path), "test", "--local", str(tmp_path / "models" / "nope.sql")] + ) + assert result.exit_code != 0 + assert "is not a known model or test file" in result.output + mock.assert_not_called() + + +def test_test_local_with_python_model_paths(runner: CliRunner, tmp_path: Path, mocker) -> None: + """The `--local` + path-selector combination works for Python models too.""" + create_example_project(tmp_path) + + (tmp_path / "models" / "py_model.py").write_text( + """ +import pandas as pd # noqa: TID253 +from sqlmesh import model, ExecutionContext +import typing as t + +@model( + name="sqlmesh_example.py_model", + columns={"id": "int"}, +) +def execute(context: ExecutionContext, **kwargs: t.Any) -> pd.DataFrame: + return pd.DataFrame([{"id": 1}]) +""", + encoding="utf-8", + ) + (tmp_path / "tests" / "test_py_model.yaml").write_text( + """ +test_py_model: + model: sqlmesh_example.py_model + outputs: + query: + rows: + - id: 1 +""", + encoding="utf-8", + ) + + mock = _patch_state_access(mocker) + + result = runner.invoke( + cli, + ["--paths", str(tmp_path), "test", "--local", str(tmp_path / "models" / "py_model.py")], + ) + + assert result.exit_code == 0, f"Test failed: {result.output}\nException: {result.exception}" + assert "Successfully Ran 1 tests" in " ".join(result.output.split()) + mock.assert_not_called() + + # A Python file that is not a model is still an error rather than a silent no-op. + result = runner.invoke( + cli, ["--paths", str(tmp_path), "test", "--local", str(tmp_path / "models" / "nope.py")] + ) + assert result.exit_code != 0 + assert "is not a known model or test file" in result.output + mock.assert_not_called() diff --git a/tests/core/test_test.py b/tests/core/test_test.py index 7c67192a14..0fbe8e926c 100644 --- a/tests/core/test_test.py +++ b/tests/core/test_test.py @@ -1,6 +1,7 @@ from __future__ import annotations import datetime +import re import typing as t import io from pathlib import Path @@ -2687,6 +2688,156 @@ def test_number_of_tests_found(tmp_path: Path) -> None: assert len(results.successes) == 1 +def test_model_path_selects_its_tests(tmp_path: Path) -> None: + """A model file path selects that model's tests, even though the YAML path wasn't given.""" + init_example_project(tmp_path, engine_type="duckdb") + context = Context(paths=tmp_path) + + results = context.test(tests=[str(tmp_path / "models" / "full_model.sql")]) + assert len(results.successes) == 1 + assert results.testsRun == 1 + + +def test_python_model_path_selects_its_tests(tmp_path: Path) -> None: + """Selection is by file path, so a Python model works the same way a SQL one does.""" + init_example_project(tmp_path, engine_type="duckdb") + + py_model = tmp_path / "models" / "py_model.py" + py_model.write_text( + """ +import pandas as pd # noqa: TID253 +from sqlmesh import model, ExecutionContext +import typing as t + +@model( + name="sqlmesh_example.py_model", + columns={"id": "int"}, +) +def execute(context: ExecutionContext, **kwargs: t.Any) -> pd.DataFrame: + return pd.DataFrame([{"id": 1}]) +""" + ) + (tmp_path / "tests" / "test_py_model.yaml").write_text( + """ +test_py_model: + model: sqlmesh_example.py_model + outputs: + query: + rows: + - id: 1 +""" + ) + + context = Context(paths=tmp_path) + + results = context.test(tests=[str(py_model)]) + assert results.testsRun == 1 + assert len(results.successes) == 1 + + # The SQL model's own test is not pulled in by selecting the Python model. + assert context.test(tests=[str(tmp_path / "models" / "full_model.sql")]).testsRun == 1 + + +def test_model_path_without_tests_selects_nothing(tmp_path: Path) -> None: + """A known model that simply has no tests is not an error.""" + init_example_project(tmp_path, engine_type="duckdb") + context = Context(paths=tmp_path) + + results = context.test(tests=[str(tmp_path / "models" / "incremental_model.sql")]) + assert results.testsRun == 0 + assert results.wasSuccessful() + + +def test_model_and_test_paths_are_unioned_without_duplicates(tmp_path: Path) -> None: + """Overlapping selectors must not run the same test twice.""" + init_example_project(tmp_path, engine_type="duckdb") + context = Context(paths=tmp_path) + + model_path = str(tmp_path / "models" / "full_model.sql") + test_path = str(tmp_path / "tests" / "test_full_model.yaml") + + # The YAML holds full_model's only test, so both selectors resolve to the same test. + assert context.test(tests=[model_path]).testsRun == 1 + assert context.test(tests=[test_path]).testsRun == 1 + assert context.test(tests=[model_path, test_path]).testsRun == 1 + + +def test_overlapping_yaml_and_named_test_are_deduplicated(tmp_path: Path) -> None: + """`file.yaml::name` is a subset of `file.yaml`, so together they're still one run.""" + init_example_project(tmp_path, engine_type="duckdb") + context = Context(paths=tmp_path) + + test_path = str(tmp_path / "tests" / "test_full_model.yaml") + results = context.test(tests=[f"{test_path}::test_example_full_model", test_path]) + assert results.testsRun == 1 + + +def test_relative_paths_select_tests(tmp_path: Path, monkeypatch) -> None: + """Pre-commit passes paths relative to the repo root, not absolute ones.""" + init_example_project(tmp_path, engine_type="duckdb") + context = Context(paths=tmp_path) + + monkeypatch.chdir(tmp_path) + assert context.test(tests=["models/full_model.sql"]).testsRun == 1 + assert context.test(tests=["tests/test_full_model.yaml"]).testsRun == 1 + + +def test_unknown_path_is_ignored_by_default(tmp_path: Path) -> None: + """Default behavior is unchanged, so the LSP can keep probing arbitrary documents.""" + init_example_project(tmp_path, engine_type="duckdb") + context = Context(paths=tmp_path) + + assert context.select_tests(tests=[str(tmp_path / "models" / "nope.sql")]) == [] + + +def test_unknown_path_errors_when_requested(tmp_path: Path) -> None: + """A path that is neither a known model nor a known test file must not pass silently.""" + init_example_project(tmp_path, engine_type="duckdb") + context = Context(paths=tmp_path) + + missing = tmp_path / "models" / "nope.sql" + with pytest.raises(SQLMeshError, match="is not a known model or test file"): + context.select_tests(tests=[str(missing)], raise_on_unknown_paths=True) + + with pytest.raises(SQLMeshError, match="is not a known model or test file"): + context.test(tests=[str(missing)], raise_on_unknown_paths=True) + + +def test_unknown_test_name_errors_when_requested(tmp_path: Path) -> None: + """A known YAML file with an unknown `::test_name` reports the test, not the file.""" + init_example_project(tmp_path, engine_type="duckdb") + context = Context(paths=tmp_path) + + test_path = tmp_path / "tests" / "test_full_model.yaml" + with pytest.raises(SQLMeshError, match=f"is not a known test in '{re.escape(str(test_path))}'"): + context.select_tests(tests=[f"{test_path}::nope"], raise_on_unknown_paths=True) + + +def test_unknown_test_name_in_unknown_file_reports_the_file(tmp_path: Path) -> None: + """A `::test_name` on a file that isn't a test file is a path problem, not a name one.""" + init_example_project(tmp_path, engine_type="duckdb") + context = Context(paths=tmp_path) + + missing = tmp_path / "tests" / "test_nope.yaml" + with pytest.raises(SQLMeshError, match="is not a known model or test file"): + context.select_tests(tests=[f"{missing}::nope"], raise_on_unknown_paths=True) + + +def test_select_model_still_filters_path_selection(tmp_path: Path) -> None: + """`--select-model` keeps narrowing the selection rather than adding to it.""" + init_example_project(tmp_path, engine_type="duckdb") + context = Context(paths=tmp_path) + + model_path = str(tmp_path / "models" / "full_model.sql") + assert ( + context.test(tests=[model_path], model_names=["sqlmesh_example.full_model"]).testsRun == 1 + ) + assert ( + context.test(tests=[model_path], model_names=["sqlmesh_example.incremental_model"]).testsRun + == 0 + ) + + def test_freeze_time_concurrent(tmp_path: Path) -> None: tests_dir = tmp_path / "tests" tests_dir.mkdir() From a6ba67dc87715ab74555db81cc992f8ea5037c78 Mon Sep 17 00:00:00 2001 From: Adegbite Ayoade Abel Date: Tue, 22 Sep 2026 02:35:06 +0100 Subject: [PATCH 03/62] fix(vscode): scope render tab assertions to the editor tab (#6076) Signed-off-by: Adegbite Ayoade Co-authored-by: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> --- vscode/extension/tests/render.spec.ts | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/vscode/extension/tests/render.spec.ts b/vscode/extension/tests/render.spec.ts index db660daae1..0fba008834 100644 --- a/vscode/extension/tests/render.spec.ts +++ b/vscode/extension/tests/render.spec.ts @@ -38,7 +38,9 @@ test('Render works correctly', async ({ page, sharedCodeServer, tempDir }) => { // Check if the model is rendered by check if "`oi`.`order_id` AS `order_id`," is in the window await expect(page.locator('text="marketing"."customer_id" AS')).toBeVisible() - await expect(page.locator('text=sushi.customers (rendered)')).toBeVisible() + await expect( + page.getByRole('tab', { name: 'sushi.customers (rendered)' }), + ).toBeVisible() }) test('Render works correctly with model without a description', async ({ @@ -74,7 +76,9 @@ test('Render works correctly with model without a description', async ({ // Check if the model is rendered correctly await expect(page.locator('text="orders"."id" AS "id",')).toBeVisible() - await expect(page.locator('text=sushi.latest_order (rendered)')).toBeVisible() + await expect( + page.getByRole('tab', { name: 'sushi.latest_order (rendered)' }), + ).toBeVisible() }) test('Render works correctly with every rendered model opening a new tab', async ({ @@ -104,7 +108,9 @@ test('Render works correctly with every rendered model opening a new tab', async await runCommand(page, 'Render Model') // Check if the model is rendered correctly - await expect(page.locator('text=sushi.latest_order (rendered)')).toBeVisible() + await expect( + page.getByRole('tab', { name: 'sushi.latest_order (rendered)' }), + ).toBeVisible() // Open the customers model await page @@ -117,8 +123,12 @@ test('Render works correctly with every rendered model opening a new tab', async await runCommand(page, 'Render Model') // Assert both tabs exist - await expect(page.locator('text=sushi.latest_order (rendered)')).toBeVisible() - await expect(page.locator('text=sushi.customers (rendered)')).toBeVisible() + await expect( + page.getByRole('tab', { name: 'sushi.latest_order (rendered)' }), + ).toBeVisible() + await expect( + page.getByRole('tab', { name: 'sushi.customers (rendered)' }), + ).toBeVisible() }) test('Render shows model picker when no active editor is open', async ({ @@ -146,7 +156,9 @@ test('Render shows model picker when no active editor is open', async ({ await page.locator('text=sushi.customers').click() // Verify the rendered model is shown - await expect(page.locator('text=sushi.customers (rendered)')).toBeVisible({ + await expect( + page.getByRole('tab', { name: 'sushi.customers (rendered)' }), + ).toBeVisible({ timeout: 2_000, }) }) From df6e3a58d6707f9d5b3dfc05c1b6bf4b5f9d8f27 Mon Sep 17 00:00:00 2001 From: Adegbite Ayoade Abel Date: Thu, 24 Sep 2026 02:41:15 +0100 Subject: [PATCH 04/62] fix(vscode): stop the LSP restarting on unrelated configuration changes (#6057) Signed-off-by: Adegbite Ayoade --- vscode/extension/src/extension.ts | 57 ++++++- .../src/utilities/coalesceAsync.test.ts | 159 ++++++++++++++++++ .../extension/src/utilities/coalesceAsync.ts | 51 ++++++ .../common/configurationChange.test.ts | 60 +++++++ .../utilities/common/configurationChange.ts | 35 ++++ 5 files changed, 353 insertions(+), 9 deletions(-) create mode 100644 vscode/extension/src/utilities/coalesceAsync.test.ts create mode 100644 vscode/extension/src/utilities/coalesceAsync.ts create mode 100644 vscode/extension/src/utilities/common/configurationChange.test.ts create mode 100644 vscode/extension/src/utilities/common/configurationChange.ts diff --git a/vscode/extension/src/extension.ts b/vscode/extension/src/extension.ts index cfea8c2228..db72414389 100644 --- a/vscode/extension/src/extension.ts +++ b/vscode/extension/src/extension.ts @@ -24,8 +24,10 @@ import { traceError, } from './utilities/common/log' import { onDidChangePythonInterpreter } from './utilities/common/python' +import { requiresLspRestart } from './utilities/common/configurationChange' +import { coalesceAsync } from './utilities/coalesceAsync' import { sleep } from './utilities/sleep' -import { handleError } from './utilities/errors' +import { ErrorType, handleError } from './utilities/errors' import { selector, completionProvider } from './completion/completion' import { LineagePanel } from './webviews/lineagePanel' @@ -65,7 +67,24 @@ export async function activate(context: vscode.ExtensionContext) { ), ) - const restartLsp = async (invokedByUser = false): Promise => { + /** + * Set when a restart was asked for explicitly, so that a user-invoked restart + * coalesced together with an automatic one is still treated as user-invoked. + */ + let restartInvokedByUser = false + + /** + * Set by a failed run and handled by the caller once the run has finished. + * Handling it inside the run would deadlock: the not_signed_in handler waits + * on a sign-in that restarts the client again, and that restart would wait on + * the run that is still waiting on the handler. + */ + let restartError: ErrorType | undefined + + const runRestart = async (): Promise => { + const invokedByUser = restartInvokedByUser + restartInvokedByUser = false + if (!lspClient) { lspClient = new LSPClient() } @@ -73,12 +92,7 @@ export async function activate(context: vscode.ExtensionContext) { traceVerbose('Restarting SQLMesh LSP client') const result = await lspClient.restart(invokedByUser) if (isErr(result)) { - await handleError( - authProvider, - restartLsp, - result.error, - 'LSP restart failed', - ) + restartError = result.error return } @@ -95,6 +109,25 @@ export async function activate(context: vscode.ExtensionContext) { context.subscriptions.push(testControllerDisposable) } + /** + * Restarts are serialized: a client disposing while the next one starts up + * leaves colliding command registrations and requests aimed at a disposed + * client, which is what surfaced as constant crashes. + */ + const restartLspSerialized = coalesceAsync(runRestart) + + const restartLsp = async (invokedByUser = false): Promise => { + restartInvokedByUser = restartInvokedByUser || invokedByUser + await restartLspSerialized() + + // Claimed so that callers coalesced into the same run don't each report it. + const error = restartError + restartError = undefined + if (error) { + await handleError(authProvider, restartLsp, error, 'LSP restart failed') + } + } + // commands needing the restart helper context.subscriptions.push( vscode.commands.registerCommand( @@ -191,7 +224,13 @@ export async function activate(context: vscode.ExtensionContext) { context.subscriptions.push( onDidChangePythonInterpreter(() => restartLsp()), - onDidChangeConfiguration(() => restartLsp()), + // Only restart for settings the server actually reads. This event fires for + // every setting in the editor, including ones written by other extensions. + onDidChangeConfiguration(event => { + if (requiresLspRestart(event)) { + void restartLsp() + } + }), ) if (!lspClient.hasCompletionCapability()) { diff --git a/vscode/extension/src/utilities/coalesceAsync.test.ts b/vscode/extension/src/utilities/coalesceAsync.test.ts new file mode 100644 index 0000000000..f40aba0aaa --- /dev/null +++ b/vscode/extension/src/utilities/coalesceAsync.test.ts @@ -0,0 +1,159 @@ +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from 'vitest' +import { coalesceAsync } from './coalesceAsync' + +/** + * Let pending microtasks run. A rerun is scheduled off the promise of the run + * that precedes it, so it starts a few hops after that run settles. + */ +const flush = () => new Promise(resolve => setTimeout(resolve, 0)) + +/** A task that only settles when the test releases it. */ +function deferredTask() { + let release: (() => void) | undefined + let rejectWith: ((error: Error) => void) | undefined + let calls = 0 + + const run = () => { + calls += 1 + return new Promise((resolve, reject) => { + release = resolve + rejectWith = reject + }) + } + + return { + run, + get calls() { + return calls + }, + release: () => release?.(), + reject: (error: Error) => rejectWith?.(error), + } +} + +describe('coalesceAsync', () => { + it('runs the task immediately when idle', async () => { + const task = deferredTask() + const run = coalesceAsync(task.run) + + const first = run() + expect(task.calls).toBe(1) + + task.release() + await first + }) + + // A burst of triggers used to start a restart per event, which left clients + // disposing and starting concurrently. See #5642. + it('collapses every call made while running into a single rerun', async () => { + const task = deferredTask() + const run = coalesceAsync(task.run) + + const first = run() + expect(task.calls).toBe(1) + + const queued = [run(), run(), run(), run()] + expect(task.calls).toBe(1) + + task.release() + await first + await flush() + + // Exactly one rerun is scheduled, no matter how many calls arrived. + expect(task.calls).toBe(2) + + task.release() + await Promise.all(queued) + await flush() + expect(task.calls).toBe(2) + }) + + it('runs again for calls made after the previous run finished', async () => { + const task = deferredTask() + const run = coalesceAsync(task.run) + + const first = run() + task.release() + await first + expect(task.calls).toBe(1) + + const second = run() + expect(task.calls).toBe(2) + task.release() + await second + }) + + it('resolves the callers that were coalesced together', async () => { + const task = deferredTask() + const run = coalesceAsync(task.run) + + const first = run() + const queued = [run(), run()] + + task.release() + await first + // The rerun has to be in flight before it can be released. + await flush() + task.release() + + await expect(Promise.all(queued)).resolves.toEqual([undefined, undefined]) + }) + + it('surfaces a failure without wedging later calls', async () => { + const task = deferredTask() + const run = coalesceAsync(task.run) + + const first = run() + task.reject(new Error('restart failed')) + await expect(first).rejects.toThrow('restart failed') + + const second = run() + expect(task.calls).toBe(2) + task.release() + await second + }) + + // A failed restart is reported to the caller, which handles it after the run + // has finished. The not_signed_in handler signs the user in and restarts the + // client again, so that handler must not run inside the task: the restart it + // triggers would wait on the run that is still waiting on the handler, and + // neither would ever settle. See #5920. + it('lets a failure handler trigger another run without deadlocking', async () => { + let failNextRun = true + let reportedError: string | undefined + let runs = 0 + + const runRestart = async (): Promise => { + runs += 1 + // The real run awaits the client restart before it knows the outcome. + // Without that await the re-entrant call below lands in the synchronous + // prefix of the run, before it has been recorded as in flight, and the + // deadlock this covers cannot happen. + const failed = await Promise.resolve(failNextRun) + if (failed) { + failNextRun = false + reportedError = 'not_signed_in' + } + } + + const runRestartSerialized = coalesceAsync(runRestart) + + const restart = async (): Promise => { + await runRestartSerialized() + + const error = reportedError + reportedError = undefined + if (error === 'not_signed_in') { + // Stands in for the sign-in flow, which restarts once signed in. + await restart() + } + } + + await restart() + + expect(runs).toBe(2) + expect(reportedError).toBeUndefined() + }, 2_000) +}) diff --git a/vscode/extension/src/utilities/coalesceAsync.ts b/vscode/extension/src/utilities/coalesceAsync.ts new file mode 100644 index 0000000000..46259f9d79 --- /dev/null +++ b/vscode/extension/src/utilities/coalesceAsync.ts @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: Apache-2.0 + +/** + * Serialize an async task so it never overlaps with itself, collapsing any + * calls that arrive while it is running into a single rerun. + * + * Restarting the language server means stopping a client and starting another. + * Letting two of those interleave leaves commands registered by the outgoing + * client colliding with the incoming one, and leaves requests addressed to a + * client that has already been disposed. Queueing one run per trigger would + * only spread the same problem out over time, so queued triggers collapse into + * one rerun: all the caller wants is for the task to have run after its + * request, not for it to run once per request. + * + * @param task The task to serialize. + * @returns A function that resolves once the task has run for that call. + */ +export function coalesceAsync(task: () => Promise): () => Promise { + let running: Promise | undefined + let queued: Promise | undefined + + const start = async (): Promise => { + try { + await task() + } finally { + running = undefined + } + } + + return (): Promise => { + if (!running) { + running = start() + return running + } + + // A rerun is already scheduled, so this call is satisfied by that one. + if (!queued) { + queued = running + // A failed run must not stop the rerun that was asked for; the caller + // waiting on the failed run is the one that sees the error. + .catch(() => undefined) + .then(() => { + queued = undefined + running = start() + return running + }) + } + + return queued + } +} diff --git a/vscode/extension/src/utilities/common/configurationChange.test.ts b/vscode/extension/src/utilities/common/configurationChange.test.ts new file mode 100644 index 0000000000..1a9c633ead --- /dev/null +++ b/vscode/extension/src/utilities/common/configurationChange.test.ts @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from 'vitest' +import { requiresLspRestart } from './configurationChange' + +/** + * Build a stand-in for `vscode.ConfigurationChangeEvent` from the settings that + * changed. VS Code reports a section as affected when the changed key is the + * section itself or sits underneath it. + */ +const changed = (...keys: string[]) => ({ + affectsConfiguration: (section: string) => + keys.some(key => key === section || key.startsWith(`${section}.`)), +}) + +describe('requiresLspRestart', () => { + it('restarts when a sqlmesh setting changes', () => { + expect(requiresLspRestart(changed('sqlmesh.projectPaths'))).toBe(true) + expect(requiresLspRestart(changed('sqlmesh.lspEntrypoint'))).toBe(true) + }) + + it('restarts when the python interpreter changes', () => { + expect(requiresLspRestart(changed('python.defaultInterpreterPath'))).toBe( + true, + ) + }) + + // The LSP used to restart on every configuration change in the editor, so + // anything that wrote a setting took the extension down with it. See #5920. + it('ignores settings the language server does not read', () => { + expect(requiresLspRestart(changed('editor.fontSize'))).toBe(false) + expect(requiresLspRestart(changed('workbench.colorTheme'))).toBe(false) + expect(requiresLspRestart(changed('files.autoSave'))).toBe(false) + }) + + // Running any python command in a VS Code terminal makes the Python + // extension touch its own terminal settings, which is what made the + // extension crash whenever sqlmesh was run in the terminal. See #5642. + it('ignores python settings unrelated to the interpreter', () => { + expect( + requiresLspRestart(changed('python.terminal.activateEnvironment')), + ).toBe(false) + expect( + requiresLspRestart(changed('python.analysis.typeCheckingMode')), + ).toBe(false) + expect(requiresLspRestart(changed('terminal.integrated.env.linux'))).toBe( + false, + ) + }) + + it('does not restart when nothing relevant changed', () => { + expect(requiresLspRestart(changed())).toBe(false) + }) + + it('restarts when a relevant setting changes alongside irrelevant ones', () => { + expect( + requiresLspRestart(changed('editor.fontSize', 'sqlmesh.projectPaths')), + ).toBe(true) + }) +}) diff --git a/vscode/extension/src/utilities/common/configurationChange.ts b/vscode/extension/src/utilities/common/configurationChange.ts new file mode 100644 index 0000000000..7e3ab1f3e0 --- /dev/null +++ b/vscode/extension/src/utilities/common/configurationChange.ts @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: Apache-2.0 + +/** + * Configuration sections the language server reads, so a change to any of them + * needs the server restarted to take effect. + * + * `sqlmesh` covers `sqlmesh.projectPaths` and `sqlmesh.lspEntrypoint`, both of + * which decide how the server is launched. The interpreter path matters because + * the server runs inside that interpreter. + */ +export const RESTART_CONFIGURATION_SECTIONS = [ + 'sqlmesh', + 'python.defaultInterpreterPath', +] + +/** + * The part of `vscode.ConfigurationChangeEvent` this module needs. Declared + * structurally so the check stays unit testable without the VS Code runtime. + */ +export interface ConfigurationChange { + affectsConfiguration(section: string): boolean +} + +/** + * Whether a configuration change affects a setting the language server reads. + * + * `workspace.onDidChangeConfiguration` fires for every setting in the editor, + * including ones written by other extensions, so the event has to be filtered + * before it triggers a restart. + */ +export function requiresLspRestart(event: ConfigurationChange): boolean { + return RESTART_CONFIGURATION_SECTIONS.some(section => + event.affectsConfiguration(section), + ) +} From 9bd35b774e2eb4775841ef5e37278f2b10900829 Mon Sep 17 00:00:00 2001 From: Adegbite Ayoade Abel Date: Thu, 24 Sep 2026 03:46:02 +0100 Subject: [PATCH 05/62] feat(cli): report state backend versions on rollback and info (#6088) Signed-off-by: Adegbite Ayoade --- sqlmesh/core/context.py | 36 +++++++- sqlmesh/core/state_sync/db/migrator.py | 9 ++ tests/cli/test_cli.py | 105 ++++++++++++++++++++++ tests/core/state_sync/test_state_sync.py | 32 +++++++ tests/integrations/jupyter/test_magics.py | 51 ++++++++--- 5 files changed, 217 insertions(+), 16 deletions(-) diff --git a/sqlmesh/core/context.py b/sqlmesh/core/context.py index 64dd6d67da..a6420f3ec1 100644 --- a/sqlmesh/core/context.py +++ b/sqlmesh/core/context.py @@ -108,6 +108,7 @@ CachingStateSync, StateReader, StateSync, + Versions, ) from sqlmesh.core.janitor import cleanup_expired_views, delete_expired_snapshots from sqlmesh.core.table_diff import TableDiff @@ -2610,8 +2611,10 @@ def migrate(self) -> None: """ self.notification_target_manager.notify(NotificationEvent.MIGRATION_START) self._load_materializations() + state_sync = self._new_state_sync() + previous_versions = self._state_versions(state_sync) try: - self._new_state_sync().migrate( + state_sync.migrate( promoted_snapshots_only=self.config.migration.promoted_snapshots_only, ) except Exception as e: @@ -2619,6 +2622,7 @@ def migrate(self) -> None: NotificationEvent.MIGRATION_FAILURE, traceback.format_exc() ) raise e + self._print_state_versions(self._state_versions(state_sync), previous_versions) self.notification_target_manager.notify(NotificationEvent.MIGRATION_END) @python_api_analytics @@ -2627,7 +2631,10 @@ def rollback(self) -> None: Please contact your SQLMesh administrator before doing this. This action cannot be undone. """ - self._new_state_sync().rollback() + state_sync = self._new_state_sync() + previous_versions = self._state_versions(state_sync) + state_sync.rollback() + self._print_state_versions(self._state_versions(state_sync), previous_versions) @python_api_analytics def create_external_models(self, strict: bool = False) -> None: @@ -2701,6 +2708,12 @@ def print_info( if state_connection: self._try_connection("state backend", state_connection.connection_validator()) + if verbosity >= Verbosity.VERBOSE: + try: + self._print_state_versions(self._state_versions()) + except Exception as ex: + self.console.log_error(f"Failed to fetch the state backend versions. {ex}") + @python_api_analytics def print_environment_names(self) -> None: """Prints all environment names along with expiry datetime.""" @@ -3290,6 +3303,25 @@ def _try_connection(self, connection_name: str, validator: t.Callable[[], None]) except Exception as ex: self.console.log_error(f"{connection_name} connection failed. {ex}") + def _state_versions(self, state_sync: t.Optional[StateSync] = None) -> Versions: + """Returns the versions recorded in the state backend without validating them.""" + return (state_sync or self._new_state_sync()).get_versions(validate=False) + + def _print_state_versions( + self, versions: Versions, previous_versions: t.Optional[Versions] = None + ) -> None: + """Prints the state backend versions, optionally alongside the ones they replaced.""" + self.console.log_status_update("\nState backend versions:") + for label, attribute in ( + ("Schema version", "schema_version"), + ("SQLGlot version", "sqlglot_version"), + ("SQLMesh version", "sqlmesh_version"), + ): + version = getattr(versions, attribute) + if previous_versions is not None: + version = f"{getattr(previous_versions, attribute)} -> {version}" + self.console.log_status_update(f"{label}: {version}") + def _new_state_sync(self) -> StateSync: return self._provided_state_sync or self._scheduler.create_state_sync(self) diff --git a/sqlmesh/core/state_sync/db/migrator.py b/sqlmesh/core/state_sync/db/migrator.py index 8d73e1d395..aaabeac5d9 100644 --- a/sqlmesh/core/state_sync/db/migrator.py +++ b/sqlmesh/core/state_sync/db/migrator.py @@ -96,6 +96,15 @@ def migrate( migrate_rows = self._apply_migrations(schema, skip_backup) if not migrate_rows and major_minor(SQLMESH_VERSION) == versions.minor_sqlmesh_version: + # Nothing to migrate, but a patch-level bump still leaves the recorded versions + # behind what is actually running, so they are brought up to date here. The + # schema version is carried over rather than defaulted, since no migration ran + # and moving it could hide one that is genuinely needed later. + if ( + versions.sqlmesh_version != SQLMESH_VERSION + or versions.sqlglot_version != SQLGLOT_VERSION + ): + self.version_state.update_versions(schema_version=versions.schema_version) return if migrate_rows: diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index 251ea54fa3..f1540727b1 100644 --- a/tests/cli/test_cli.py +++ b/tests/cli/test_cli.py @@ -10,11 +10,15 @@ from click import ClickException from click.testing import CliRunner +from sqlglot import __version__ as SQLGLOT_VERSION from sqlmesh import RuntimeEnv +from sqlmesh._version import __version__ as SQLMESH_VERSION from sqlmesh.cli.project_init import ProjectTemplate, init_example_project from sqlmesh.cli.main import cli from sqlmesh.core.context import Context +from sqlmesh.core.state_sync.base import SCHEMA_VERSION from sqlmesh.integrations.dlt import generate_dlt_models +from sqlmesh.utils import major_minor from sqlmesh.utils.date import now_ds, time_like_to_str, timedelta, to_datetime, yesterday_ds from sqlmesh.core.config.connection import DIALECT_TO_TYPE @@ -1024,6 +1028,107 @@ def test_info_on_new_project_does_not_create_state_sync(runner, tmp_path): assert not context.engine_adapter.table_exists("sqlmesh._versions") +def test_info_state_versions(runner, tmp_path): + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "info"]) + assert result.exit_code == 0 + assert "State backend versions" not in result.output + + result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "info", "-v"]) + assert result.exit_code == 0 + assert "State backend versions" in result.output + assert f"Schema version: {SCHEMA_VERSION}" in result.output + assert f"SQLGlot version: {SQLGLOT_VERSION}" in result.output + assert f"SQLMesh version: {SQLMESH_VERSION}" in result.output + + +def test_rollback_state_versions(runner, tmp_path): + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + context = Context(paths=tmp_path) + state_sync = context._new_state_sync() + # Back up the current state, then pretend the state was migrated by a newer SQLMesh. + state_sync.migrator._backup_state() + state_sync.version_state.update_versions( + schema_version=SCHEMA_VERSION + 1, + sqlglot_version="9999.0.0", + sqlmesh_version="9999.0.0", + ) + context.close() + + result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "rollback"]) + assert result.exit_code == 0 + assert "State backend versions" in result.output + assert f"Schema version: {SCHEMA_VERSION + 1} -> {SCHEMA_VERSION}" in result.output + assert f"SQLGlot version: 9999.0.0 -> {SQLGLOT_VERSION}" in result.output + assert f"SQLMesh version: 9999.0.0 -> {SQLMESH_VERSION}" in result.output + + +def test_migrate_state_versions(runner, tmp_path): + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + context = Context(paths=tmp_path) + # Pretend the state was written by an older patch release of the same minor version, which + # is the case `migrate` used to leave untouched. + major, minor = major_minor(SQLMESH_VERSION) + older_sqlmesh = f"{major}.{minor}.dev0" + context._new_state_sync().version_state.update_versions( + sqlglot_version="0.0.1", + sqlmesh_version=older_sqlmesh, + ) + context.close() + + result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "migrate"]) + assert result.exit_code == 0 + assert "State backend versions" in result.output + assert f"SQLGlot version: 0.0.1 -> {SQLGLOT_VERSION}" in result.output + assert f"SQLMesh version: {older_sqlmesh} -> {SQLMESH_VERSION}" in result.output + + +def test_migrate_updates_versions_after_a_patch_bump(runner, tmp_path): + """A patch bump leaves the minor version equal, but the recorded versions must still move. + + Both minor versions have to match the installed ones, otherwise `_apply_migrations` reports + rows to migrate and the early return this covers is never reached. + """ + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + sqlmesh_major, sqlmesh_minor = major_minor(SQLMESH_VERSION) + sqlglot_major, sqlglot_minor = major_minor(SQLGLOT_VERSION) + context = Context(paths=tmp_path) + context._new_state_sync().version_state.update_versions( + sqlglot_version=f"{sqlglot_major}.{sqlglot_minor}.dev0", + sqlmesh_version=f"{sqlmesh_major}.{sqlmesh_minor}.dev0", + ) + context.close() + + assert ( + runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "migrate"]).exit_code + == 0 + ) + + context = Context(paths=tmp_path) + versions = context._new_state_sync().get_versions(validate=False) + context.close() + assert versions.sqlmesh_version == SQLMESH_VERSION + assert versions.sqlglot_version == SQLGLOT_VERSION + + +def test_rollback_without_backup_does_not_print_state_versions(runner, tmp_path): + create_example_project(tmp_path) + init_prod_and_backfill(runner, tmp_path) + + result = runner.invoke(cli, ["--log-file-dir", tmp_path, "--paths", tmp_path, "rollback"]) + assert result.exit_code == 1 + assert "There are no prior migrations to roll back to." in result.output + assert "State backend versions" not in result.output + + def test_dlt_pipeline_errors(runner, tmp_path): # Error if no pipeline is provided result = runner.invoke(cli, ["--paths", tmp_path, "init", "-t", "dlt", "duckdb"]) diff --git a/tests/core/state_sync/test_state_sync.py b/tests/core/state_sync/test_state_sync.py index 562afc6ac7..32a359f667 100644 --- a/tests/core/state_sync/test_state_sync.py +++ b/tests/core/state_sync/test_state_sync.py @@ -4254,3 +4254,35 @@ def test_state_version_is_too_old( match="The current state belongs to an old version of SQLMesh that is no longer supported. Please upgrade to 0.134.0 first before upgrading to.*", ): state_sync.migrate(skip_backup=True) + + +def test_migrate_patch_bump_preserves_schema_version( + state_sync: EngineAdapterStateSync, mocker: MockerFixture +) -> None: + """A run with nothing to migrate must not move the recorded schema version. + + `_apply_migrations` is forced to report no rows so the patch-bump branch is reached with a + schema version that differs from the current one. A real state can't get into that shape, + which is the point: the schema version is carried over rather than defaulted so that a + migration which is genuinely still needed can't be masked. + """ + from sqlmesh import __version__ as SQLMESH_VERSION + from sqlmesh.core.state_sync.base import SCHEMA_VERSION + + stale_schema_version = SCHEMA_VERSION - 1 + state_sync.version_state.update_versions( + schema_version=stale_schema_version, + sqlglot_version="0.0.1", + sqlmesh_version=SQLMESH_VERSION, + ) + + mocker.patch( + "sqlmesh.core.state_sync.db.migrator.StateMigrator._apply_migrations", + return_value=False, + ) + + state_sync.migrate() + + versions = state_sync.get_versions(validate=False) + assert versions.schema_version == stale_schema_version + assert versions.sqlglot_version == SQLGLOT_VERSION diff --git a/tests/integrations/jupyter/test_magics.py b/tests/integrations/jupyter/test_magics.py index c849dcbfc7..8449a64b69 100644 --- a/tests/integrations/jupyter/test_magics.py +++ b/tests/integrations/jupyter/test_magics.py @@ -12,8 +12,11 @@ from IPython.utils.capture import CapturedIO, capture_output from pytest_mock.plugin import MockerFixture from rich.console import Console as RichConsole +from sqlglot import __version__ as SQLGLOT_VERSION from sqlmesh import Context, RuntimeEnv +from sqlmesh._version import __version__ as SQLMESH_VERSION +from sqlmesh.core.state_sync.base import SCHEMA_VERSION, Versions from sqlmesh.magics import register_magics from pathlib import Path @@ -740,7 +743,8 @@ def test_info(notebook, sushi_context, convert_all_html_output_to_text, get_all_ assert not output.stdout assert not output.stderr - assert len(output.outputs) == 6 + assert len(output.outputs) == 10 + # No plan has been applied, so the state backend is still empty and reports the defaults. assert convert_all_html_output_to_text(output) == [ "Models: 20", "Macros: 8", @@ -748,6 +752,10 @@ def test_info(notebook, sushi_context, convert_all_html_output_to_text, get_all_ "Connection:\n type: duckdb\n concurrent_tasks: 1\n register_comments: true\n pre_ping: false\n pretty_sql: false\n extensions: []\n connector_config: {}\n secrets: None\n filesystems: []\n shared_connection: true", "Test Connection:\n type: duckdb\n concurrent_tasks: 1\n register_comments: true\n pre_ping: false\n pretty_sql: false\n extensions: []\n connector_config: {}\n secrets: None\n filesystems: []\n shared_connection: true", "Data warehouse connection succeeded", + "State backend versions:", + "Schema version: 0", + "SQLGlot version: 0.0.0", + "SQLMesh version: 0.0.0", ] assert get_all_html_output(output) == [ "
Models: 20
", @@ -756,6 +764,10 @@ def test_info(notebook, sushi_context, convert_all_html_output_to_text, get_all_ '
Connection:  type: duckdb  concurrent_tasks: 1  register_comments: true  pre_ping: false  pretty_sql: false  extensions: []  connector_config: {}  secrets: None  filesystems: []  shared_connection: true
', '
Test Connection:  type: duckdb  concurrent_tasks: 1  register_comments: true  pre_ping: false  pretty_sql: false  extensions: []  connector_config: {}  secrets: None  filesystems: []  shared_connection: true
', "
Data warehouse connection succeeded
", + "
State backend versions:
", + "
Schema version: 0
", + '
SQLGlot version: 0.0.0
', + '
SQLMesh version: 0.0.0
', ] @@ -768,25 +780,36 @@ def test_migrate( assert not output.stdout assert not output.stderr - assert len(output.outputs) == 1 + assert len(output.outputs) == 5 + # The sushi state lives in an in-memory DuckDB database, so the state sync that `migrate` + # opens starts empty and the versions move from the defaults to the running ones. + empty = Versions() assert convert_all_html_output_to_text(output) == [ + "State backend versions:", + f"Schema version: {empty.schema_version} -> {SCHEMA_VERSION}", + f"SQLGlot version: {empty.sqlglot_version} -> {SQLGLOT_VERSION}", + f"SQLMesh version: {empty.sqlmesh_version} -> {SQLMESH_VERSION}", "Migration complete", ] - assert get_all_html_output(output) == [ - str( + # Rich highlights the numbers inside the version lines, and that markup depends on the + # running versions, so only the fixed lines are compared as HTML. + html_output = get_all_html_output(output) + assert html_output[0] == str( + h("pre", {"style": RICH_PRE_STYLE}, "State backend versions:", autoescape=False) + ) + assert html_output[-1] == str( + h( + "pre", + {"style": RICH_PRE_STYLE}, h( - "pre", - {"style": RICH_PRE_STYLE}, - h( - "span", - {"style": SUCCESS_STYLE}, - "Migration complete", - autoescape=False, - ), + "span", + {"style": SUCCESS_STYLE}, + "Migration complete", autoescape=False, - ) + ), + autoescape=False, ) - ] + ) # TODO: Add test for rollback From 1e0c8594c8883daf0ce4ca8e1fc42eadc4f9bbcd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 24 Sep 2026 13:48:12 -0400 Subject: [PATCH 06/62] Chore(deps): Bump @swc/core-linux-x64-gnu from 1.13.2 to 1.16.2 (#6080) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pnpm-lock.yaml | 14 ++++++++++++-- web/client/package.json | 2 +- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 31b664c053..ec077396c1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -394,8 +394,8 @@ importers: version: 3.2.4(@types/debug@4.1.12)(@types/node@24.1.0)(@vitest/browser@3.2.4)(@vitest/ui@3.2.4)(jiti@2.4.2)(jsdom@26.1.0(supports-color@9.4.0))(lightningcss@1.30.1)(supports-color@9.4.0)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) optionalDependencies: '@swc/core-linux-x64-gnu': - specifier: ^1.13.2 - version: 1.13.2 + specifier: ^1.16.2 + version: 1.16.2 web/common: devDependencies: @@ -2208,6 +2208,13 @@ packages: os: [linux] libc: [glibc] + '@swc/core-linux-x64-gnu@1.16.2': + resolution: {integrity: sha512-LyHJgxCA4Tje0ysBMbEb0tt/ie8kgUKoFE3JAKFhpevmTmhYEoC0H9s47WuDsqiFckF1ITUguZIXJG6K5e0dvg==} + engines: {node: '>=10'} + cpu: [x64] + os: [linux] + libc: [glibc] + '@swc/core-linux-x64-musl@1.13.2': resolution: {integrity: sha512-CCxETW+KkYEQDqz1SYC15YIWYheqFC+PJVOW76Maa/8yu8Biw+HTAcblKf2isrlUtK8RvrQN94v3UXkC2NzCEw==} engines: {node: '>=10'} @@ -8974,6 +8981,9 @@ snapshots: '@swc/core-linux-x64-gnu@1.13.2': optional: true + '@swc/core-linux-x64-gnu@1.16.2': + optional: true + '@swc/core-linux-x64-musl@1.13.2': optional: true diff --git a/web/client/package.json b/web/client/package.json index b6c99153f9..23305fc039 100644 --- a/web/client/package.json +++ b/web/client/package.json @@ -75,6 +75,6 @@ "vitest": "^3.2.4" }, "optionalDependencies": { - "@swc/core-linux-x64-gnu": "^1.13.2" + "@swc/core-linux-x64-gnu": "^1.16.2" } } From 1e8dc950cc3b55f3a594cd89ec7520d642e9fb25 Mon Sep 17 00:00:00 2001 From: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> Date: Fri, 25 Sep 2026 11:34:00 -0600 Subject: [PATCH 07/62] fix(mssql): skip dbo on drop schema (#6026) Signed-off-by: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> --- sqlmesh/core/engine_adapter/mssql.py | 14 ++++++++++- tests/core/engine_adapter/test_mssql.py | 32 +++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/sqlmesh/core/engine_adapter/mssql.py b/sqlmesh/core/engine_adapter/mssql.py index fca6b4cc9f..70031de55a 100644 --- a/sqlmesh/core/engine_adapter/mssql.py +++ b/sqlmesh/core/engine_adapter/mssql.py @@ -180,7 +180,10 @@ def drop_schema( **drop_args: t.Dict[str, exp.Expr], ) -> None: """ - MsSql doesn't support CASCADE clause and drops schemas unconditionally. + MsSql doesn't support CASCADE clause so objects are dropped individually. + + SQL Server also forbids dropping the built-in ``dbo`` schema (error 15150). + Objects inside it are still dropped when cascade=True, but the schema itself is left in place. """ if cascade: objects = self._get_data_objects(schema_name) @@ -199,6 +202,15 @@ def drop_schema( object_table, exists=ignore_if_not_exists, ) + + schema = ( + (schema_name.db or schema_name.name) + if isinstance(schema_name, exp.Table) + else schema_name + ) + if schema.lower() == "dbo": + return + super().drop_schema(schema_name, ignore_if_not_exists=ignore_if_not_exists, cascade=False) def merge( diff --git a/tests/core/engine_adapter/test_mssql.py b/tests/core/engine_adapter/test_mssql.py index 007a59b365..e54a42ff29 100644 --- a/tests/core/engine_adapter/test_mssql.py +++ b/tests/core/engine_adapter/test_mssql.py @@ -714,6 +714,38 @@ def test_drop_schema(make_mocked_engine_adapter: t.Callable): ] +def test_drop_schema_skips_dbo(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(MSSQLEngineAdapter) + + adapter._get_data_objects = mock.Mock() + adapter._get_data_objects.return_value = [ + DataObject( + catalog="test_catalog", + schema="dbo", + name="test_view", + type=DataObjectType.from_str("VIEW"), + ) + ] + + # String "dbo" path (original coverage) + adapter.drop_schema("dbo", cascade=True) + + sql_calls = to_sql_calls(adapter) + assert """DROP VIEW IF EXISTS [dbo].[test_view];""" in sql_calls + assert """DROP SCHEMA IF EXISTS [dbo];""" not in sql_calls + + # exp.to_table("dbo") path — schema ends up in .name, not .db + adapter2 = make_mocked_engine_adapter(MSSQLEngineAdapter) + adapter2._get_data_objects = mock.Mock() + adapter2._get_data_objects.return_value = [] + + schema_name = exp.to_table("dbo", dialect="tsql") + adapter2.drop_schema(schema_name, cascade=False) + + sql_calls2 = to_sql_calls(adapter2) + assert """DROP SCHEMA IF EXISTS [dbo];""" not in sql_calls2 + + def test_drop_schema_with_special_identifiers(make_mocked_engine_adapter: t.Callable): adapter = make_mocked_engine_adapter(MSSQLEngineAdapter) From 5f1911d401c65ae83deda9b0ff8a9197e24e40b2 Mon Sep 17 00:00:00 2001 From: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:29:51 -0600 Subject: [PATCH 08/62] fix(ci): fixing 1.5 dbt tests (#6073) Signed-off-by: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> --- .github/workflows/pr.yaml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 0c26d39a2f..05b737a4b7 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -558,7 +558,8 @@ jobs: run: | source ../../.venv/bin/activate sed -i 's/target: in_memory/target: postgres/g' profiles.yml - if [[ $(echo -e "${{ matrix.dbt-version }}\n1.5.0" | sort -V | head -n1) == "${{ matrix.dbt-version }}" ]] && [[ "${{ matrix.dbt-version }}" != "1.5.0" ]]; then + if [[ "${{ matrix.dbt-version }}" == "1.3" ]] || \ + [[ "${{ matrix.dbt-version }}" == "1.4" ]]; then echo "DBT version is ${{ matrix.dbt-version }} (< 1.5.0), removing version parameters..." sed -i -e 's/, version=1) }}/) }}/g' -e 's/, v=1) }}/) }}/g' models/top_waiters.sql else From 1da53a17ea02b86951a098cd20909bd5fe4df567 Mon Sep 17 00:00:00 2001 From: Michael Day Date: Mon, 28 Sep 2026 16:30:01 -0400 Subject: [PATCH 09/62] fix(format): preserve dialect-specific SQL in MODEL/AUDIT/METRIC headers (#5949) Signed-off-by: mday-io --- sqlmesh/core/dialect.py | 209 ++++++++++++++++++++- tests/core/test_dialect.py | 366 +++++++++++++++++++++++++++++++++++++ tests/core/test_format.py | 34 ++++ 3 files changed, 605 insertions(+), 4 deletions(-) diff --git a/sqlmesh/core/dialect.py b/sqlmesh/core/dialect.py index e4ab522198..bcfb300ba1 100644 --- a/sqlmesh/core/dialect.py +++ b/sqlmesh/core/dialect.py @@ -734,15 +734,198 @@ def parse(self: Parser) -> t.Optional[exp.Expr]: } +_SQLMESH_META_DIALECT = "sqlmesh_meta_dialect" + + +def _holds_expression(annotation: t.Any, _visited: t.Optional[t.FrozenSet[t.Any]] = None) -> bool: + """Whether a declared field type bottoms out in a SQLGlot expression. + + Covers List[exp.Expr], Optional[Dict[str, exp.DataType]], Optional[exp.Tuple], the + nested Tuple[str, Dict[str, exp.Expr]] shape used by audits/signals, and nested + Pydantic models that themselves wrap an expression field, such as `TimeColumn` + (IncrementalByTimeRangeKind.time_column). + + Stops at `_ModelKind` subclasses without recursing into their fields: a `kind` + property's own nested properties are independently dialect-tagged via the + `ModelKind` expression node's own meta when `_props_sql` recurses into them, so + treating the `kind` field itself as "holds an expression" -- true only because some + other member of the `ModelKind` union has an expression field, e.g. + `IncrementalByTimeRangeKind.time_column` -- would route its entire subtree, + including scalar sibling properties like `forward_only`, through a dialect-specific + generator and transpile them when they shouldn't be (tsql booleans becoming + `(1 = 1)`, which silently reparses as `False`). + """ + from sqlmesh.core.model.kind import _ModelKind + + if isinstance(annotation, type): + if issubclass(annotation, exp.Expr): + return True + if issubclass(annotation, _ModelKind): + return False + visited = _visited or frozenset() + if annotation in visited: + return False + if hasattr(annotation, "model_fields"): + visited = visited | {annotation} + return any( + _holds_expression(field.annotation, visited) + for field in annotation.model_fields.values() + ) + return False + return any(_holds_expression(arg, _visited) for arg in t.get_args(annotation)) + + +@functools.lru_cache(maxsize=1) +def _meta_render_policy() -> t.Dict[str, bool]: + """Map header property name -> whether its value is warehouse SQL. + + Derived from the field declarations themselves, so it stays correct as properties + are added: expression-typed values (columns, audits, physical_properties, ...) are + the user's warehouse SQL and must render in the model's dialect, while scalar-typed + values (allow_partials, description, kind, ...) are SQLMesh's own semantics and must + stay dialect-agnostic -- transpiling those is what corrupts `allow_partials TRUE` + into tsql's unparseable `(1 = 1)`. + """ + import inspect + + from sqlmesh.core.audit.definition import ModelAudit + from sqlmesh.core.metric.definition import MetricMeta + from sqlmesh.core.model import kind as kind_module + from sqlmesh.core.model.meta import ModelMeta + + sources: t.List[t.Any] = [ModelMeta, ModelAudit, MetricMeta] + sources.extend( + obj + for name, obj in vars(kind_module).items() + if inspect.isclass(obj) and hasattr(obj, "model_fields") and name.endswith("Kind") + ) + + policy: t.Dict[str, bool] = {} + for source in sources: + for name, field in source.model_fields.items(): + policy.setdefault((field.alias or name).lower(), _holds_expression(field.annotation)) + + # `ModelMeta._pre_root_validator` (sqlmesh/core/model/meta.py) renames these two + # user-facing property names to their target field before Pydantic validation, so + # they never surface as a `Field(alias=...)` for the reflection above to find. Give + # each the render policy of the field it is renamed to. + pre_validator_aliases = { + "grain": "grains", + "table_properties": "physical_properties", + } + for alias, target in pre_validator_aliases.items(): + if target in policy: + policy[alias] = policy[target] + + return policy + + +@functools.lru_cache(maxsize=None) +def _dialect_renders_array_as_brackets(dialect_name: t.Optional[str]) -> bool: + """Whether `dialect_name`'s own generator spells an array literal as `[a, b]`. + + Checked by actually rendering a sample `exp.Array` with that dialect, rather than + inspecting `Dialect.ARRAY_SIZE_NAME` or similar generator flags, because the + generator is the single source of truth for what a dialect's array syntax looks + like and there is no single shared flag for it across dialects. This also covers + dialects (tsql, sqlite, tableau, exasol, fabric) that reuse `[`/`]` for identifier + quoting and therefore render arrays as `ARRAY(...)` instead: rewriting their + `tags`/`ignored_rules` value to `[a, b]` would not be an array literal in their + grammar at all, so it silently reparses as one bracket-quoted identifier and + corrupts the value. An unrecognized dialect name renders with the generic + generator, which itself does not use brackets, so it falls back to `False`. + """ + try: + sample = exp.Array(expressions=[exp.Literal.string("x")]) + return sample.sql(dialect=dialect_name).startswith("[") + except Exception: + return False + + def _props_sql(self: Generator, expressions: t.List[exp.Expr]) -> str: props = [] size = len(expressions) for i, prop in enumerate(expressions): + parent = prop.parent + meta_dialect = parent.meta.get(_SQLMESH_META_DIALECT) if parent else None + + def render_with_model_dialect(node: exp.Expr, **overrides: t.Any) -> str: + opts: t.Dict[str, t.Any] = { + "dialect": meta_dialect, + "pretty": self.pretty, + "identify": self.identify, + "normalize": self.normalize, + "pad": self.pad, + "indent": self._indent, + "normalize_functions": self.normalize_functions, + "leading_comma": self.leading_comma, + "max_text_width": self.max_text_width, + "comments": self.comments, + } + opts.update(overrides) + + # Keep boolean literals anywhere in the value (audit args, physical_properties, + # merge_filter, ...) as `TRUE`/`FALSE`: tsql would otherwise emit `(1 = 1)`, + # which reformats differently on the next pass. The value is transpiled with + # the model dialect anyway when it is used, e.g. in the rendered audit query. + def keep_boolean_literal(n: exp.Expr) -> exp.Expr: + if not isinstance(n, exp.Boolean): + return n + literal = exp.var("TRUE" if n.this else "FALSE") + literal.comments = n.comments + return literal + + return node.transform(keep_boolean_literal).sql(**opts) + if isinstance(prop, MacroFunc): - sql = self.indent(self.sql(prop, comment=False)) + # A macro in property position wraps user-authored arguments, so it carries + # warehouse SQL the same way `columns` or `audits` do. Clear the outer node's + # own comments (not `.this`'s, which `_macro_func_sql` already attaches) + # before rendering with the model dialect, mirroring what `comment=False` + # does for the non-dialect path below -- passing `comments=False` here + # instead would build a fresh Generator with comments globally disabled, + # silently dropping every comment in the subtree rather than just the + # redundant outer one. + if meta_dialect: + prop_for_render = prop.copy() + prop_for_render.comments = None + sql = self.indent(render_with_model_dialect(prop_for_render)) + else: + sql = self.indent(self.sql(prop, comment=False)) else: - sql = self.indent(f"{prop.name} {self.sql(prop, 'value')}") + value = prop.args.get("value") + + if ( + meta_dialect + and isinstance(value, exp.Expr) + and _meta_render_policy().get(prop.name.lower()) + ): + value_sql = render_with_model_dialect(value) + elif ( + meta_dialect + and isinstance(value, exp.Array) + and _dialect_renders_array_as_brackets(meta_dialect) + ): + # Dialect-agnostic properties (e.g. `tags`, `ignored_rules`) that hold a + # list still go through the base (dialect=None) generator, which renders + # an `exp.Array` as `ARRAY(...)`. On BigQuery `ARRAY(` is parsed as a + # subquery constructor, so a multi-element `ARRAY('a', 'b')` fails to + # reparse ("Required keyword: 'value' missing for Property"). Render it + # as a bracketed list literal instead -- but only for dialects that + # actually spell arrays that way; dialects that reuse `[`/`]` for + # identifier quoting (tsql, sqlite, ...) keep the generic `ARRAY(...)` + # form, which they parse back correctly. The elements themselves stay on + # the dialect-agnostic path (`self.expressions`, not + # `render_with_model_dialect`): these are SQLMesh's own scalar values + # (tag/rule name strings), not user warehouse SQL, so they must not be + # transpiled with the model dialect (e.g. tsql boolean literals turning + # into `(1 = 1)`). + value_sql = f"[{self.expressions(value, flat=True)}]" + else: + value_sql = self.sql(prop, "value") + + sql = self.indent(f"{prop.name} {value_sql}") if i < size - 1: sql += "," @@ -853,11 +1036,29 @@ def format_model_expressions( Returns: A string representing the formatted model. """ + + def tag_meta_dialect(expression: exp.Expr) -> exp.Expr: + """Record the model dialect on meta nodes so `_props_sql` can render the + warehouse-SQL properties (columns, audits, physical_properties, ...) with it + while the SQLMesh-owned ones stay dialect-agnostic. Tags nested ModelKind + nodes too, since kinds carry expression properties of their own such as + `time_data_type` and `unique_key`.""" + if not dialect or not is_meta_expression(expression): + return expression + + expression = expression.copy() + for node in expression.find_all(Model, Audit, Metric, ModelKind): + node.meta[_SQLMESH_META_DIALECT] = dialect + expression.meta[_SQLMESH_META_DIALECT] = dialect + return expression + if len(expressions) == 1 and is_meta_expression(expressions[0]): # Meta expressions (MODEL/AUDIT/METRIC) are SQLMesh DDL, not standard SQL, # so they must never be transpiled to the target dialect (e.g. tsql would # rewrite a boolean property like `allow_partials TRUE` to `(1 = 1)`). - return expressions[0].sql( + # Individual properties whose values *are* warehouse SQL still render with + # the model dialect -- see `_props_sql` / `_meta_render_policy`. + return tag_meta_dialect(expressions[0]).sql( pretty=True, dialect=None, normalize_functions=normalize_functions ) @@ -893,7 +1094,7 @@ def cast_to_colon(node: exp.Expr) -> exp.Expr: return ";\n\n".join( # Meta expressions (MODEL/AUDIT/METRIC) are SQLMesh DDL and must stay # dialect-agnostic; only the actual query/statement expressions transpile. - expression.sql( + tag_meta_dialect(expression).sql( pretty=True, dialect=None if is_meta_expression(expression) else dialect, normalize_functions=normalize_functions, diff --git a/tests/core/test_dialect.py b/tests/core/test_dialect.py index 142b40b31f..dc55571f21 100644 --- a/tests/core/test_dialect.py +++ b/tests/core/test_dialect.py @@ -342,6 +342,372 @@ def test_format_model_expressions(): ) +@pytest.mark.parametrize( + "dialect,audit_type,int_type", + # These dialects spell the same types differently -- fabric renders a bare DATETIME2 + # with its default precision and keeps INT, tsql does the reverse. The point of the + # test is that each keeps *its own* spelling rather than being flattened. + [("tsql", "DATETIME2", "INTEGER"), ("fabric", "DATETIME2(6)", "INT")], +) +def test_format_model_expressions_meta_render_policy(dialect: str, audit_type: str, int_type: str): + """Header properties whose values are warehouse SQL render with the model dialect, + while SQLMesh's own properties stay dialect-agnostic. + + Rendering the whole header with the dialect corrupts SQLMesh DDL (tsql turns + `allow_partials TRUE` into the unparseable `(1 = 1)`), but rendering all of it + generically discards dialect-specific values the user authored, such as the + `DATETIME2` types below. The split is derived from the field declarations, so it + covers `columns`, `audits`, `physical_properties` and the expression properties + nested inside `kind` alike. + """ + formatted = format_model_expressions( + parse( + f""" + MODEL ( + name a.b, + dialect {dialect}, + kind SCD_TYPE_2_BY_TIME ( + unique_key id, + time_data_type DATETIME2(6) + ), + allow_partials true, + description 'my description', + columns ( + ts DATETIME2(6) + ), + audits ( + my_audit(threshold := CAST('2024-01-01' AS DATETIME2)) + ), + physical_properties ( + labels = (('env', 'prod')) + ) + ); + + SELECT CAST(x AS INT) AS y FROM t + """ + ), + dialect=dialect, + ) + + assert ( + formatted + == f"""MODEL ( + name a.b, + dialect {dialect}, + kind SCD_TYPE_2_BY_TIME ( + unique_key id, + time_data_type DATETIME2(6) + ), + allow_partials TRUE, + description 'my description', + columns ( + ts DATETIME2(6) + ), + audits ( + my_audit(threshold := '2024-01-01'::{audit_type}) + ), + physical_properties ( + labels = ( + ('env', 'prod') + ) + ) +); + +SELECT + x::{int_type} AS y +FROM t""" + ) + + +@pytest.mark.parametrize( + "header", + [ + "audits (my_audit(t := CAST('2024-01-01' AS DATETIME2)))", + "audits (my_audit(flag := true))", + "kind SCD_TYPE_2_BY_COLUMN(unique_key id, columns (a, b), time_data_type DATETIME2(6))", + "physical_properties (labels = (('env', 'prod')))", + "allow_partials true, description 'my description'", + "@my_prop(cutoff := CAST('2024-01-01' AS DATETIME2))", + ], +) +def test_format_model_expressions_is_idempotent(header: str): + """Formatting an already-formatted model must be a no-op. + + Rendering a dialect-specific type with the generic generator does not merely lose + formatting, it compounds: tsql `DATETIME2` renders as `TIMESTAMP`, and tsql parses + `TIMESTAMP` as ROWVERSION (a binary type), so a second pass writes `VARBINARY`. Two + runs of `sqlmesh format` silently turned a datetime into a binary type -- and for + `time_data_type` that is the physical type of the SCD valid_from/valid_to columns. + """ + source = f"MODEL (name a.b, dialect tsql, {header});\nSELECT 1 AS x" + + once = format_model_expressions(parse(source, default_dialect="tsql"), dialect="tsql") + twice = format_model_expressions(parse(once, default_dialect="tsql"), dialect="tsql") + + assert once == twice + + +@pytest.mark.parametrize( + "dialect,column_type", + [("bigquery", "DATETIME"), ("tsql", "DATETIME2(6)")], +) +def test_format_model_expressions_preserves_column_types(dialect: str, column_type: str): + """Repeated `sqlmesh format` runs must not change a model's declared column types. + + Rendering `columns` with the generic generator rewrote them: BigQuery `DATETIME` + became `TIMESTAMP` and then `TIMESTAMPTZ`, tsql `DATETIME2` became `TIMESTAMP` and + then `VARBINARY`. + """ + expected = exp.DataType.build(column_type, dialect=dialect) + formatted = f"MODEL (name a.b, dialect {dialect}, columns (ts {column_type}));\nSELECT 1 AS ts" + + for _ in range(2): + formatted = format_model_expressions( + parse(formatted, default_dialect=dialect), dialect=dialect + ) + model = load_sql_based_model(parse(formatted, default_dialect=dialect), dialect=dialect) + assert model.columns_to_types == {"ts": expected} + + +def test_format_audit_expressions_meta_render_policy(): + """AUDIT headers have their own meta model, and get the same split: `blocking` is + SQLMesh's own boolean and must not become tsql's `(1 = 0)`, while `defaults` holds + user expressions and keeps its dialect-specific type.""" + formatted = format_model_expressions( + parse( + """ + AUDIT ( + name my_audit, + dialect tsql, + blocking false, + defaults ( + cutoff := CAST('2024-01-01' AS DATETIME2) + ) + ); + + SELECT * FROM t WHERE x > 0 + """ + ), + dialect="tsql", + ) + + assert "blocking FALSE" in formatted + assert "cutoff := '2024-01-01'::DATETIME2" in formatted + + +def test_format_model_expressions_kind_time_column_dialect(): + """Expression-bearing properties nested inside `kind` render with the model dialect, + while their scalar siblings stay dialect-agnostic. + + `time_column` is a nested Pydantic model (`TimeColumn`) wrapping an expression, not + an `exp.Expr` annotation itself, so the render-policy reflection must recurse into + nested Pydantic models to classify it as warehouse SQL. Otherwise it falls back to + generic rendering and loses dialect-specific identifier quoting: tsql's `[end]` + becomes ANSI `"end"`, even though the same identifier in the query body is correctly + kept as `[end]`. + + Regression: recursing into nested Pydantic models to fix `time_column` made + `_holds_expression` also match on `kind` itself, since *some* member of the + `ModelKind` union (`IncrementalByTimeRangeKind.time_column`) holds an expression. + That routed the entire `kind (...)` subtree through a dialect-specific generator, so tsql's + boolean-literal preprocessing rewrote `forward_only TRUE` into `forward_only (1 = 1)`. + That reparses without error, but `str_to_bool` on `Paren(EQ(1, 1)).name` (`""`) + evaluates to `False`, so the value silently flips on reload. + """ + formatted = format_model_expressions( + parse( + """ + MODEL ( + name a.b, + dialect tsql, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column [end], + forward_only true + ) + ); + + SELECT 1 AS x, [end] FROM t + """, + default_dialect="tsql", + ), + dialect="tsql", + ) + + assert ( + formatted + == """MODEL ( + name a.b, + dialect tsql, + kind INCREMENTAL_BY_TIME_RANGE ( + time_column [end], + forward_only TRUE + ) +); + +SELECT + 1 AS x, + [end] +FROM t""" + ) + + model = load_sql_based_model(parse(formatted, default_dialect="tsql"), dialect="tsql") + assert model.kind.forward_only is True + + +def test_format_model_expressions_macro_property_comments_preserved_with_dialect(): + """Comments inside a macro header-property must survive formatting when the model + has a `dialect` set. + + The dialect-render path goes through `Expression.sql(dialect=...)`, which builds a + fresh `Generator` with `comments` as a constructor flag: passing `comments=False` + there disables comment rendering for the *entire* subtree, rather than just + suppressing the redundant outer-level `maybe_comment` call the way `comment=False` + does for `Generator.sql()`. That previously caused comments like `/* inline note */` + to be silently dropped whenever the model declared a `dialect`. + """ + formatted = format_model_expressions( + parse( + """ + MODEL ( + name a.b, + dialect tsql, + @my_prop(cutoff := CAST('2024-01-01' AS DATETIME2) /* inline note */) + ); + + SELECT 1 AS x + """, + default_dialect="tsql", + ), + dialect="tsql", + ) + + assert "/* inline note */" in formatted + assert ( + formatted + == """MODEL ( + name a.b, + dialect tsql, + @my_prop(cutoff := '2024-01-01'::DATETIME2 /* inline note */) +); + +SELECT + 1 AS x""" + ) + + # Idempotency: formatting an already-formatted macro property must not duplicate or + # drop the comment on a second pass. + twice = format_model_expressions(parse(formatted, default_dialect="tsql"), dialect="tsql") + assert formatted == twice + + +@pytest.mark.parametrize("dialect", ["bigquery", "duckdb", "snowflake"]) +@pytest.mark.parametrize("prop_name", ["tags", "ignored_rules"]) +def test_format_model_expressions_list_property_array_literal(dialect: str, prop_name: str): + """List-valued header properties render as `[a, b]`, not `ARRAY(a, b)`, which + BigQuery parses as a subquery and fails to load.""" + source = f"""MODEL ( + name a.b, + dialect {dialect}, + {prop_name} ['C1', 'c2'] +); +SELECT 1 AS x""" + + formatted = format_model_expressions(parse(source, default_dialect=dialect), dialect=dialect) + assert f"{prop_name} ['C1', 'c2']" in formatted + + twice = format_model_expressions(parse(formatted, default_dialect=dialect), dialect=dialect) + assert formatted == twice + + model = load_sql_based_model(parse(formatted, default_dialect=dialect), dialect=dialect) + if prop_name == "tags": + assert model.tags == ["C1", "c2"] + else: + assert model.ignored_rules == {"c1", "c2"} + + +def test_format_model_expressions_array_property_no_dialect_unchanged(): + formatted = format_model_expressions( + parse("MODEL (name a.b, tags ['C1', 'c2']); SELECT 1 AS x") + ) + + assert "tags ARRAY('C1', 'c2')" in formatted + + +@pytest.mark.parametrize("dialect", ["tsql", "sqlite"]) +@pytest.mark.parametrize("prop_name", ["tags", "ignored_rules"]) +def test_format_model_expressions_list_property_bracket_identifier_dialects( + dialect: str, prop_name: str +): + """These dialects quote identifiers with `[...]`, so a bracketed list would reload + as a single identifier. List properties must keep the `ARRAY(...)` form.""" + source = f"""MODEL ( + name a.b, + dialect {dialect}, + {prop_name} ARRAY('C1', 'c2') +); +SELECT 1 AS x""" + + formatted = format_model_expressions(parse(source, default_dialect=dialect), dialect=dialect) + assert f"{prop_name} ARRAY('C1', 'c2')" in formatted + + twice = format_model_expressions(parse(formatted, default_dialect=dialect), dialect=dialect) + assert formatted == twice + + model = load_sql_based_model(parse(formatted, default_dialect=dialect), dialect=dialect) + if prop_name == "tags": + assert model.tags == ["C1", "c2"] + else: + assert model.ignored_rules == {"c1", "c2"} + + +@pytest.mark.parametrize("dialect", ["bigquery", "duckdb", "snowflake", "postgres"]) +def test_format_model_expressions_grain_alias_render_policy(dialect: str): + """`grain` is renamed to `grains` before validation, so it must share the + `grains` render policy instead of falling back to `ARRAY(...)`.""" + source = f"""MODEL ( + name a.b, + dialect {dialect}, + grain [id, id2] +); +SELECT 1 AS x, 2 AS id, 3 AS id2""" + + formatted = format_model_expressions(parse(source, default_dialect=dialect), dialect=dialect) + assert "ARRAY(id, id2)" not in formatted + + twice = format_model_expressions(parse(formatted, default_dialect=dialect), dialect=dialect) + assert formatted == twice + + model = load_sql_based_model(parse(formatted, default_dialect=dialect), dialect=dialect) + assert {c.name for c in model.grains[0].find_all(exp.Column)} == {"id", "id2"} + + +def test_format_model_expressions_table_properties_alias_render_policy(): + """`table_properties` is renamed to `physical_properties` before validation, so it + must keep dialect-specific types such as tsql's `DATETIME2`.""" + formatted = format_model_expressions( + parse( + """ + MODEL ( + name a.b, + dialect tsql, + table_properties ( + x = CAST('2024-01-01' AS DATETIME2) + ) + ); + + SELECT 1 AS x + """, + default_dialect="tsql", + ), + dialect="tsql", + ) + + assert "x = '2024-01-01'::DATETIME2" in formatted + + twice = format_model_expressions(parse(formatted, default_dialect="tsql"), dialect="tsql") + assert formatted == twice + + def test_format_model_expressions_normalize_functions(): """Regression: formatter function-name casing behavior. diff --git a/tests/core/test_format.py b/tests/core/test_format.py index e5b2e8460b..664b8a811d 100644 --- a/tests/core/test_format.py +++ b/tests/core/test_format.py @@ -182,3 +182,37 @@ def test_format_without_state_load(tmp_path: pathlib.Path, mocker: MockerFixture context = Context(paths=tmp_path, config=Config(project="local_only"), load_state=False) context.format(check=True) mock.assert_not_called() + + +def test_format_bigquery_header_list_properties(tmp_path: pathlib.Path): + # A BigQuery model must survive `sqlmesh format` and still load: list-valued header + # properties were rewritten to `ARRAY(...)`, which BigQuery parses as a subquery. + model_file = create_temp_file( + tmp_path, + pathlib.Path("models/model.sql"), + """MODEL ( + name test.model, + kind INCREMENTAL_BY_TIME_RANGE (time_column ds), + tags ['C1', 'c2'], + ignored_rules ['noselectstar', 'ambiguousorinvalidcolumn'], + grain [id], + partitioned_by DATE_TRUNC(ds, MONTH) +); +SELECT 1 AS id, CURRENT_DATE() AS ds""", + ) + config = Config(model_defaults=ModelDefaultsConfig(dialect="bigquery")) + + Context(paths=tmp_path, config=config).format() + + formatted = model_file.read_text(encoding="utf-8") + assert "tags ['C1', 'c2']" in formatted + assert "ignored_rules ['noselectstar', 'ambiguousorinvalidcolumn']" in formatted + assert "grain [id]" in formatted + assert "partitioned_by DATE_TRUNC(ds, MONTH)" in formatted + + context = Context(paths=tmp_path, config=config) + assert context.format(check=True) + model = context.get_model("test.model") + assert model.tags == ["C1", "c2"] + assert model.ignored_rules == {"noselectstar", "ambiguousorinvalidcolumn"} + assert [p.sql("bigquery") for p in model.partitioned_by] == ["DATE_TRUNC(`ds`, MONTH)"] From af1dc08b741ab6f395c3e0d82c8c4898aacf6145 Mon Sep 17 00:00:00 2001 From: manan28025 Date: Tue, 29 Sep 2026 03:44:51 +0530 Subject: [PATCH 10/62] fix(config): parse default_test_connection from yaml (#6103) Signed-off-by: neatninja Co-authored-by: neatninja Co-authored-by: Michael Day --- sqlmesh/core/config/connection.py | 3 ++- tests/core/test_config.py | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/sqlmesh/core/config/connection.py b/sqlmesh/core/config/connection.py index 73fe1b9300..5fe937a4aa 100644 --- a/sqlmesh/core/config/connection.py +++ b/sqlmesh/core/config/connection.py @@ -2657,7 +2657,8 @@ def _connection_config_validator( "state_connection", "test_connection", "default_connection", - "default_test_connection", + # field_validator matches field names, not aliases + "default_test_connection_", mode="before", check_fields=False, )(_connection_config_validator) diff --git a/tests/core/test_config.py b/tests/core/test_config.py index 0da5b6e22f..12f461913a 100644 --- a/tests/core/test_config.py +++ b/tests/core/test_config.py @@ -553,6 +553,30 @@ def test_connection_config_serialization(): } +def test_default_test_connection_from_yaml(tmp_path): + config_path = tmp_path / "config.yaml" + config_path.write_text( + """ +default_test_connection: + type: duckdb + database: test.db + concurrent_tasks: 4 + +model_defaults: + dialect: duckdb +""" + ) + + config = load_config_from_paths(Config, project_paths=[config_path]) + + assert config.default_test_connection_ == DuckDBConnectionConfig( + database="test.db", concurrent_tasks=4 + ) + assert config.get_test_connection() == DuckDBConnectionConfig( + database="test.db", concurrent_tasks=4 + ) + + def test_variables(): variables = { "int_var": 1, From 263723f5c87eb437e9953051ab8091b17e3ce09f Mon Sep 17 00:00:00 2001 From: Adegbite Ayoade Abel Date: Tue, 29 Sep 2026 22:01:04 +0100 Subject: [PATCH 11/62] docs: explain which SQLMesh version to use with rollback (#6090) Signed-off-by: Adegbite Ayoade --- docs/guides/migrations.md | 23 +++++++++++++++++++++++ docs/reference/cli.md | 2 ++ 2 files changed, 25 insertions(+) diff --git a/docs/guides/migrations.md b/docs/guides/migrations.md index 222bc4cdb8..ed8a2d5411 100644 --- a/docs/guides/migrations.md +++ b/docs/guides/migrations.md @@ -36,3 +36,26 @@ Migrations should ideally run when no one will be running plan/apply. Migrations should not be run in parallel. Due to these constraints, it is better for a person responsible for managing SQLMesh to manually issue migrations. Therefore, it is not recommended to issue migrations from CI/CD pipelines. + +## Rolling back a migration + +When `sqlmesh migrate` needs to change the project metadata, it first copies each state table to a backup table with a `_backup` suffix, unless `--skip-backup` is passed. The `sqlmesh rollback` command restores the metadata from those backups, returning it to the format used by the SQLMesh version that was installed before the migration. If a migration fails partway through, SQLMesh rolls it back automatically from the same backups. + +To undo a migration: + +1. Run `sqlmesh rollback` with the SQLMesh version that performed the migration still installed. +2. Reinstall the SQLMesh version the project used before the upgrade, for example by reverting the version change in your requirements file. + +The second step is required. Rolling back does not change the installed version of SQLMesh, and the newer version will refuse to run against the restored metadata until it is migrated again: + +```bash +> sqlmesh plan +Error: SQLMesh (local) is using version '2' which is ahead of '1' (remote). Please run a migration ('sqlmesh migrate' command). +``` + +Keep the following in mind before rolling back: + +- Only the most recent migration can be rolled back. Restoring consumes the backup tables, so running `sqlmesh rollback` a second time fails with `There are no prior migrations to roll back to.` +- The backups are taken at the moment of migration. Any changes made to the project metadata after the migration, such as plans applied with the newer version, are discarded. +- Like `sqlmesh migrate`, rolling back affects all users of the project and should be issued manually by a single user. +- Rollback is not possible if the migration was run with `--skip-backup`. It also does nothing useful after an upgrade that required no migration, such as a patch release, because no new backup was taken. In that case the backup tables, if present, come from an earlier migration. diff --git a/docs/reference/cli.md b/docs/reference/cli.md index f7943e2f71..460b6e520b 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -494,6 +494,8 @@ Options: The `rollback` command affects all SQLMesh users. Contact your SQLMesh administrator before running. +Run `rollback` with the SQLMesh version that performed the migration, then reinstall the previous version. See [Rolling back a migration](../guides/migrations.md#rolling-back-a-migration) for details. + ## run ``` From 3a6fff4ddfb3aee39d858c6fe0d7ccdd3e26b997 Mon Sep 17 00:00:00 2001 From: IBM-Db2-Eco-System-Lko Date: Thu, 1 Oct 2026 08:16:36 +0530 Subject: [PATCH 12/62] feat: Add IBM Db2 engine adapter (#6030) Signed-off-by: IBM Db2 Eco System --- .github/scripts/install-prerequisites.sh | 2 + .github/scripts/wait-for-db.sh | 14 + .github/workflows/db2.yaml | 65 ++ Makefile | 3 + docs/guides/connections.md | 1 + docs/integrations/engines/db2.md | 78 ++ docs/integrations/overview.md | 1 + mkdocs.yml | 1 + pyproject.toml | 5 + sqlmesh/core/config/connection.py | 90 ++ sqlmesh/core/engine_adapter/__init__.py | 15 + sqlmesh/core/engine_adapter/db2.py | 974 ++++++++++++++++++ .../engine_adapter/integration/__init__.py | 23 +- .../engine_adapter/integration/config.yaml | 13 + .../integration/docker/compose.db2.yaml | 22 + .../integration/test_integration.py | 144 ++- .../integration/test_integration_db2.py | 362 +++++++ tests/core/engine_adapter/test_db2.py | 470 +++++++++ tests/core/test_dialect.py | 8 + 19 files changed, 2285 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/db2.yaml create mode 100644 docs/integrations/engines/db2.md create mode 100644 sqlmesh/core/engine_adapter/db2.py create mode 100644 tests/core/engine_adapter/integration/docker/compose.db2.yaml create mode 100644 tests/core/engine_adapter/integration/test_integration_db2.py create mode 100644 tests/core/engine_adapter/test_db2.py diff --git a/.github/scripts/install-prerequisites.sh b/.github/scripts/install-prerequisites.sh index 6ab602fc37..6997633a31 100755 --- a/.github/scripts/install-prerequisites.sh +++ b/.github/scripts/install-prerequisites.sh @@ -17,6 +17,8 @@ ENGINE_DEPENDENCIES="" if [ "$ENGINE" == "spark" ]; then ENGINE_DEPENDENCIES="default-jdk" +elif [ "$ENGINE" == "db2" ]; then + ENGINE_DEPENDENCIES="libxml2-dev build-essential" elif [ "$ENGINE" == "fabric" ]; then echo "Installing Microsoft package repository" diff --git a/.github/scripts/wait-for-db.sh b/.github/scripts/wait-for-db.sh index e69504b6da..4a076f31f8 100755 --- a/.github/scripts/wait-for-db.sh +++ b/.github/scripts/wait-for-db.sh @@ -90,6 +90,20 @@ risingwave_ready() { probe_port 4566 } +db2_ready() { + probe_port 50001 + + echo "Waiting for Db2 to finish initialising (this can take 2-4 minutes)..." + while true; do + if docker exec db2 su - db2inst1 -c "db2 connect to TESTDB" > /dev/null 2>&1; then + echo "Db2 is accepting connections" + break + fi + echo "Db2 not yet ready; sleeping 15s..." + sleep 15 + done +} + echo "Waiting for $ENGINE to be ready..." READINESS_FUNC="${ENGINE}_ready" diff --git a/.github/workflows/db2.yaml b/.github/workflows/db2.yaml new file mode 100644 index 0000000000..0a9bf56d3c --- /dev/null +++ b/.github/workflows/db2.yaml @@ -0,0 +1,65 @@ +name: db2 + +on: + push: + branches: + - main + paths: + - 'sqlmesh/core/engine_adapter/db2.py' + - 'tests/core/engine_adapter/test_db2.py' + - 'tests/core/engine_adapter/integration/test_integration_db2.py' + - 'tests/core/engine_adapter/integration/docker/compose.db2.yaml' + - '.github/workflows/db2.yaml' + - 'pyproject.toml' + pull_request: + branches: + - main + paths: + - 'sqlmesh/core/engine_adapter/db2.py' + - 'tests/core/engine_adapter/test_db2.py' + - 'tests/core/engine_adapter/integration/test_integration_db2.py' + - 'tests/core/engine_adapter/integration/docker/compose.db2.yaml' + - '.github/workflows/db2.yaml' + - 'pyproject.toml' + +concurrency: + group: db2-${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + db2-test: + runs-on: ubuntu-latest + timeout-minutes: 25 + env: + PYTEST_XDIST_AUTO_NUM_WORKERS: 2 + SQLMESH__DISABLE_ANONYMIZED_ANALYTICS: '1' + UV: '1' + steps: + - uses: actions/checkout@v7 + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: '3.12' + - name: Install uv + uses: astral-sh/setup-uv@v7 + - name: Install SQLMesh dev dependencies + run: | + uv venv .venv + source .venv/bin/activate + make install-dev + - name: Install OS-level dependencies + run: ./.github/scripts/install-prerequisites.sh "db2" + - name: Run tests + run: | + source .venv/bin/activate + make db2-test + - name: Upload test results + uses: actions/upload-artifact@v7 + if: ${{ !cancelled() }} + with: + name: test-results-docker-db2 + path: test-results/ + retention-days: 7 diff --git a/Makefile b/Makefile index cc167212c0..6357d06351 100644 --- a/Makefile +++ b/Makefile @@ -222,6 +222,9 @@ risingwave-test: engine-risingwave-up starrocks-test: engine-starrocks-up pytest -n auto -m "starrocks" --reruns 3 --junitxml=test-results/junit-starrocks.xml + +db2-test: engine-db2-up + pytest -n auto -m "db2" --reruns 3 --junitxml=test-results/junit-db2.xml ################# # Cloud Engines # diff --git a/docs/guides/connections.md b/docs/guides/connections.md index 5af44c5dac..1345905bf7 100644 --- a/docs/guides/connections.md +++ b/docs/guides/connections.md @@ -84,6 +84,7 @@ default_gateway: local_db * [BigQuery](../integrations/engines/bigquery.md) * [ClickHouse](../integrations/engines/clickhouse.md) * [Databricks](../integrations/engines/databricks.md) +* [Db2](../integrations/engines/db2.md) * [DuckDB](../integrations/engines/duckdb.md) * [Fabric](../integrations/engines/fabric.md) * [MotherDuck](../integrations/engines/motherduck.md) diff --git a/docs/integrations/engines/db2.md b/docs/integrations/engines/db2.md new file mode 100644 index 0000000000..4f8ec607dc --- /dev/null +++ b/docs/integrations/engines/db2.md @@ -0,0 +1,78 @@ +# Db2 + +This page provides information about how to use SQLMesh with [IBM Db2](https://www.ibm.com/products/db2). + +!!! info + The Db2 engine adapter is a community contribution. Due to this, only limited community support is available. + + This adapter depends on the external `db2-sqlglot-dialect` package, which pins its own SQLGlot version range. It isn't covered by SQLMesh's core CI and may temporarily break or fail to install after SQLMesh upgrades SQLGlot, until the plugin catches up. + +## Local/Built-in Scheduler + +**Engine Adapter Type**: `db2` + +### Installation + +``` +pip install "sqlmesh[db2]" +``` + +### Connection options + +| Option | Description | Type | Required | +|---------------------|------------------------------------------------------------------------------------------------|:------:|:--------:| +| `type` | Engine type name - must be `db2` | string | Y | +| `host` | The hostname of the Db2 server | string | Y | +| `port` | The port number of the Db2 server. Default: `50000` | int | N | +| `database` | The name of the Db2 database to connect to | string | Y | +| `username` | The username to use for authentication with the Db2 server | string | Y | +| `password` | The password to use for authentication with the Db2 server | string | Y | +| `db2_schema` | Sets `CURRENTSCHEMA` on the connection. Controls the default schema for unqualified references. Typically set to the same value as `username`. | string | Y | +| `ssl` | Enable TLS/SSL encryption. Default: `false` | bool | N | +| `connect_timeout` | The number of seconds to wait for the connection to the server. Default: `30` | int | N | +| `concurrent_tasks` | Maximum number of tasks to run concurrently. Default: `4` | int | N | + +## Important Notes + +**State connection:** Db2 is **not supported** as a SQLMesh `state_connection`. Use DuckDB (recommended) or another supported engine for SQLMesh state storage: + +```yaml linenums="1" +gateways: + db2: + connection: + type: db2 + host: localhost + port: 50000 + database: TESTDB + username: db2inst1 + password: your_password + db2_schema: db2inst1 + state_connection: + type: duckdb + database: ./state/sqlmesh_state.db + +default_gateway: db2 + +model_defaults: + dialect: db2 +``` + +**Table naming:** Db2 rejects table names that start with an underscore (`_`). SQLMesh's default physical table naming convention can generate names beginning with `_`. To avoid this, set `physical_table_naming_convention` to `hash_md5` in your project config: + +```yaml +physical_table_naming_convention: hash_md5 +``` + +## Limitations + +- **SCD Type 2 unsupported**: SCD Type 2 models are currently not supported on Db2. +- **Single catalog only**: Db2 operates in single-catalog mode; cross-catalog queries are not supported. +- **No inline column comments**: Column-level comments cannot be set inline during table creation. +- **No atomic table replacement**: Db2 does not support `CREATE OR REPLACE TABLE`, so full model refreshes are not atomic. There is a brief window during which the table may be empty or partially populated. +- **Identifier length**: Maximum identifier length is 128 characters. +- **No `SELECT ... FOR UPDATE`**: Db2 does not support `SELECT ... FOR UPDATE` in the same way as OLTP databases; SQLMesh removes this clause when executing queries. + +## Resources + +- [IBM Db2 Documentation](https://www.ibm.com/docs/en/db2) +- [IBM Db2 SQL Reference](https://www.ibm.com/docs/en/db2/11.5?topic=db2-sql) diff --git a/docs/integrations/overview.md b/docs/integrations/overview.md index 4ba7d7b3c3..1c9d56b7e2 100644 --- a/docs/integrations/overview.md +++ b/docs/integrations/overview.md @@ -16,6 +16,7 @@ SQLMesh supports the following execution engines for running SQLMesh projects (e * [BigQuery](./engines/bigquery.md) (bigquery) * [ClickHouse](./engines/clickhouse.md) (clickhouse) * [Databricks](./engines/databricks.md) (databricks) +* [Db2](./engines/db2.md) (db2) * [DuckDB](./engines/duckdb.md) (duckdb) * [Fabric](./engines/fabric.md) (fabric) * [MotherDuck](./engines/motherduck.md) (motherduck) diff --git a/mkdocs.yml b/mkdocs.yml index 368fb6690a..49c4b9163b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -82,6 +82,7 @@ nav: - integrations/engines/bigquery.md - integrations/engines/clickhouse.md - integrations/engines/databricks.md + - integrations/engines/db2.md - integrations/engines/duckdb.md - integrations/engines/fabric.md - integrations/engines/motherduck.md diff --git a/pyproject.toml b/pyproject.toml index 2c897de225..9b28dc7a08 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -112,6 +112,10 @@ dev = [ ] dbt = ["dbt-core<2"] dlt = ["dlt"] +db2 = [ + "ibm_db", + "db2-sqlglot-dialect;python_version>=\"3.10\"" +] duckdb = [] fabric = ["pyodbc>=5.0.0"] fabric-mssql-python = ["mssql-python>=1.1.0;python_version>=\"3.10\""] @@ -270,6 +274,7 @@ markers = [ "clickhouse: test for Clickhouse (standalone mode / cluster mode)", "clickhouse_cloud: test for Clickhouse (cloud mode)", "databricks: test for Databricks", + "db2: test for Db2", "duckdb: test for DuckDB", "fabric: test for Fabric", "motherduck: test for MotherDuck", diff --git a/sqlmesh/core/config/connection.py b/sqlmesh/core/config/connection.py index 5fe937a4aa..29cb1ef467 100644 --- a/sqlmesh/core/config/connection.py +++ b/sqlmesh/core/config/connection.py @@ -60,6 +60,9 @@ # Nullable types are problematic "clickhouse", "starrocks", + # Db2 rejects table names starting with underscore (_versions, _snapshots, + # _environments, _intervals). Use a separate state_connection (e.g., DuckDB). + "db2", } MOTHERDUCK_TOKEN_REGEX = re.compile(r"(\?|\&)(motherduck_token=)(\S*)") PASSWORD_REGEX = re.compile(r"(password=)(\S+)") @@ -2602,6 +2605,93 @@ def _connection_factory(self) -> t.Callable: BaseDuckDBConnectionConfig, # type: ignore[type-abstract] } + +class Db2ConnectionConfig(ConnectionConfig): + host: str + port: int = 50000 + database: str + db2_schema: str + username: str + password: str + ssl: bool = False + ssl_cert: t.Optional[str] = None + ssl_key: t.Optional[str] = None + ssl_ca: t.Optional[str] = None + connect_timeout: int = 30 + + concurrent_tasks: int = 4 + register_comments: bool = True + pre_ping: bool = True + + type_: t.Literal["db2"] = Field(alias="type", default="db2") + DIALECT: t.ClassVar[t.Literal["db2"]] = "db2" + DISPLAY_NAME: t.ClassVar[t.Literal["Db2"]] = "Db2" + DISPLAY_ORDER: t.ClassVar[t.Literal[19]] = 19 + + _engine_import_validator = _get_engine_import_validator("ibm_db", "db2") + + @property + def _connection_kwargs_keys(self) -> t.Set[str]: + return { + "host", + "port", + "database", + "db2_schema", + "username", + "password", + } + + @property + def _engine_adapter(self) -> t.Type[EngineAdapter]: + adapter = getattr(engine_adapter, "Db2EngineAdapter", None) + if adapter is None: + raise ConfigError( + "The Db2 engine adapter requires Python 3.10+ and the 'db2' extra. " + "Please install it with: pip install 'sqlmesh[db2]'" + ) + return t.cast(t.Type[EngineAdapter], adapter) + + def get_catalog(self) -> t.Optional[str]: + """Db2 stores catalog names in uppercase; normalise here so the default_catalog + passed to the adapter matches what get_current_catalog() returns at runtime.""" + catalog = super().get_catalog() + return catalog.upper() if catalog else None + + @property + def _connection_factory(self) -> t.Callable: + import ibm_db_dbi # type: ignore + + ssl = self.ssl + ssl_cert = self.ssl_cert + ssl_key = self.ssl_key + ssl_ca = self.ssl_ca + connect_timeout = self.connect_timeout + + def connect_db2(**kwargs: t.Any) -> t.Any: + conn_str_parts = [ + f"DATABASE={kwargs['database']}", + f"HOSTNAME={kwargs['host']}", + f"PORT={kwargs['port']}", + "PROTOCOL=TCPIP", + f"UID={kwargs['username']}", + f"PWD={kwargs['password']}", + f"CURRENTSCHEMA={kwargs['db2_schema']}", + f"CONNECTTIMEOUT={connect_timeout}", + ] + if ssl: + conn_str_parts.append("SECURITY=SSL") + if ssl_cert: + conn_str_parts.append(f"SSLClientCertificate={ssl_cert}") + if ssl_key: + conn_str_parts.append(f"SSLClientKey={ssl_key}") + if ssl_ca: + conn_str_parts.append(f"SSLServerCertificate={ssl_ca}") + conn_str = ";".join(conn_str_parts) + ";" + return ibm_db_dbi.connect(conn_str, "", "") + + return connect_db2 + + CONNECTION_CONFIG_TO_TYPE = { # Map all subclasses of ConnectionConfig to the value of their `type_` field. tpe.all_field_infos()["type_"].default: tpe diff --git a/sqlmesh/core/engine_adapter/__init__.py b/sqlmesh/core/engine_adapter/__init__.py index cb9db5ea77..658b149753 100644 --- a/sqlmesh/core/engine_adapter/__init__.py +++ b/sqlmesh/core/engine_adapter/__init__.py @@ -1,5 +1,7 @@ from __future__ import annotations +import importlib.util +import sys import typing as t from sqlmesh.core.engine_adapter.base import ( @@ -22,6 +24,15 @@ from sqlmesh.core.engine_adapter.risingwave import RisingwaveEngineAdapter from sqlmesh.core.engine_adapter.fabric import FabricEngineAdapter +# DB2 adapter requires Python 3.10+ AND db2-sqlglot-dialect to be installed. +# The dialect package registers "db2" with sqlglot at import time; without it, +# class-level exp.DataType.build(dialect="db2") in db2.py raises +# ValueError("Unknown dialect 'db2'") and crashes every non-db2 environment +# (e.g. the dbt-1.6 test run which installs without the db2 extra). +_DB2_AVAILABLE = sys.version_info >= (3, 10) and importlib.util.find_spec("db2_sqlglot") is not None +if _DB2_AVAILABLE: + from sqlmesh.core.engine_adapter.db2 import Db2EngineAdapter + DIALECT_TO_ENGINE_ADAPTER = { "hive": SparkEngineAdapter, "spark": SparkEngineAdapter, @@ -41,6 +52,10 @@ "starrocks": StarRocksEngineAdapter, } +# Add DB2 to the registry only when the dialect package is present +if _DB2_AVAILABLE: + DIALECT_TO_ENGINE_ADAPTER["db2"] = Db2EngineAdapter + DIALECT_ALIASES = { "postgresql": "postgres", } diff --git a/sqlmesh/core/engine_adapter/db2.py b/sqlmesh/core/engine_adapter/db2.py new file mode 100644 index 0000000000..ac34fa4681 --- /dev/null +++ b/sqlmesh/core/engine_adapter/db2.py @@ -0,0 +1,974 @@ +from __future__ import annotations + +import logging +import re +import typing as t +from functools import cached_property + +from sqlglot import exp, parse_one +from sqlglot.optimizer.normalize_identifiers import normalize_identifiers + +from sqlmesh.core.engine_adapter.base import EngineAdapter, _get_data_object_cache_key +from sqlmesh.core.engine_adapter.mixins import PandasNativeFetchDFSupportMixin +from sqlmesh.core.engine_adapter.shared import ( + CatalogSupport, + CommentCreationTable, + CommentCreationView, + DataObject, + DataObjectType, + SourceQuery, + set_catalog, +) +from sqlmesh.core.dialect import to_schema +from sqlmesh.utils.errors import SQLMeshError + +if t.TYPE_CHECKING: + from sqlmesh.core._typing import SchemaName, TableName + from sqlmesh.core.engine_adapter._typing import DF, Query + +logger = logging.getLogger(__name__) + + +class Db2ErrorCodes: + """Common Db2 SQL error codes used for exception inspection.""" + + DUPLICATE_OBJECT = "SQL0601N" + INDEX_EXISTS = "SQL0605W" + + +def is_db2_error(exception: Exception, error_code: str) -> bool: + """Returns True when the exception message contains the given Db2 error code.""" + return error_code in str(exception) + + +@set_catalog() +class Db2EngineAdapter( + PandasNativeFetchDFSupportMixin, + EngineAdapter, +): + DIALECT = "db2" + SUPPORTS_INDEXES = True + SUPPORTS_REPLACE_TABLE = False + SUPPORTS_GRANTS = True + # Db2 CURRENT USER is a bare special register (no parentheses). + # exp.Var generates the identifier literally without function-call syntax. + CURRENT_USER_OR_ROLE_EXPRESSION: exp.Expr = exp.Var(this="CURRENT USER") + COMMENT_CREATION_TABLE = CommentCreationTable.COMMENT_COMMAND_ONLY + COMMENT_CREATION_VIEW = CommentCreationView.COMMENT_COMMAND_ONLY + SUPPORTS_QUERY_EXECUTION_TRACKING = True + # Db2 does not support DROP TABLE/VIEW ... CASCADE — doing so raises SQL0104N. + # Schema cascade is handled manually inside drop_schema() and does not rely + # on this flag, so the list is intentionally empty. + # SUPPORTED_DROP_CASCADE_OBJECT_KINDS = ["SCHEMA", "TABLE", "VIEW"] + SUPPORTED_DROP_CASCADE_OBJECT_KINDS: t.List[str] = [] + MAX_IDENTIFIER_LENGTH: t.Optional[int] = 128 + SCHEMA_DIFFER_KWARGS = { + "parameterized_type_defaults": { + # DECIMAL without precision defaults to (5, 0) + exp.DataType.Type.DECIMAL: [(5, 0), (0,)], + # CHAR without length defaults to 1 + exp.DataType.Type.CHAR: [(1,)], + # VARCHAR without length defaults to 1 + exp.DataType.Type.VARCHAR: [(1,)], + # TIMESTAMP defaults to 6 digits of fractional seconds + exp.DataType.Type.TIMESTAMP: [(6,)], + # TIME defaults to 0 digits of fractional seconds + exp.DataType.Type.TIME: [(0,)], + }, + "types_with_unlimited_length": { + # CLOB can be used for unlimited text + exp.DataType.Type.TEXT: { + exp.DataType.Type.VARCHAR, + exp.DataType.Type.CHAR, + }, + }, + "drop_cascade": False, + } + + def get_current_catalog(self) -> t.Optional[str]: + """ + Db2 requires FROM SYSIBM.SYSDUMMY1 to read the CURRENT SERVER special register. + Returns uppercase to match the Db2 dialect's identifier normalisation. + """ + result = self.fetchone("SELECT CURRENT SERVER FROM SYSIBM.SYSDUMMY1") + if result: + return result[0].upper() if result[0] else None + return None + + def _build_schema_exp( + self, + table: exp.Table, + target_columns_to_types: t.Dict[str, exp.DataType], + column_descriptions: t.Optional[t.Dict[str, str]] = None, + expressions: t.Optional[t.List[exp.PrimaryKey]] = None, + is_view: bool = False, + materialized: bool = False, + ) -> exp.Schema: + """ + Db2 requires every primary key column to carry an explicit NOT NULL constraint; + the base class does not add this automatically. + """ + expressions = expressions or [] + + pk_columns = set() + for expr in expressions: + if isinstance(expr, exp.PrimaryKey): + for col_expr in expr.expressions: + if isinstance(col_expr, exp.Column): + pk_columns.add(col_expr.name) + + column_defs = [] + for column, col_type in target_columns_to_types.items(): + col_def = self._build_column_def( + column, + column_descriptions=column_descriptions, + engine_supports_schema_comments=( + self.COMMENT_CREATION_TABLE.supports_schema_def + if not is_view + else self.COMMENT_CREATION_VIEW.supports_schema_def + ), + col_type=None if is_view else col_type, + ) + + if column in pk_columns and not is_view: + existing_constraints = col_def.args.get("constraints") or [] + has_not_null = any( + isinstance(c, exp.NotNullColumnConstraint) for c in existing_constraints + ) + if not has_not_null: + existing_constraints.append(exp.NotNullColumnConstraint()) + col_def.set("constraints", existing_constraints) + + column_defs.append(col_def) + + return exp.Schema( + this=table, + expressions=column_defs + expressions, + ) + + def create_index( + self, + table_name: TableName, + index_name: str, + columns: t.Tuple[str, ...], + exists: bool = True, + ) -> None: + """ + Db2 does not support CREATE INDEX IF NOT EXISTS, so we query SYSCAT.INDEXES + first and skip creation when the index already exists. SQL0605W (index + already defined) is caught as a fallback for any race between the check + and the create. + """ + if not self.SUPPORTS_INDEXES: + return + + table = exp.to_table(table_name) + schema_name = table.db or self._get_current_schema() + + self.execute( + exp.select(exp.column("INDNAME")) + .from_("SYSCAT.INDEXES") + .where( + exp.and_( + exp.func("UPPER", exp.column("TABSCHEMA")).eq( + exp.Literal.string(schema_name.upper()) + ), + exp.func("UPPER", exp.column("TABNAME")).eq( + exp.Literal.string(table.alias_or_name.upper()) + ), + exp.func("UPPER", exp.column("INDNAME")).eq( + exp.Literal.string(index_name.upper()) + ), + ) + ) + ) + if self.cursor.fetchone(): + logger.debug("Index %s already exists on %s, skipping", index_name, table_name) + return + + expression = exp.Create( + this=exp.Index( + this=exp.to_identifier(index_name), + table=exp.to_table(table_name), + params=exp.IndexParameters(columns=[exp.to_column(c) for c in columns]), + ), + kind="INDEX", + exists=False, + ) + + try: + self.execute(expression) + except Exception as e: + # DB2 can return either SQL0605W (index exists warning) or + # SQL0601N (duplicate object name error) when index already exists + if is_db2_error(e, Db2ErrorCodes.INDEX_EXISTS) or is_db2_error( + e, Db2ErrorCodes.DUPLICATE_OBJECT + ): + logger.debug("Index %s already exists, skipping", index_name) + return + raise + + def columns( + self, table_name: TableName, include_pseudo_columns: bool = False + ) -> t.Dict[str, exp.DataType]: + """ + Reads column metadata from SYSCAT.COLUMNS. When no rows are returned for + an exact name match, a prefix query is attempted because Db2 truncates + identifiers that exceed MAX_IDENTIFIER_LENGTH. + """ + table = exp.to_table(table_name) + schema_name = table.db or self._get_current_schema() + table_name_str = table.alias_or_name + + self.execute( + exp.select( + exp.column("COLNAME").as_("column_name"), + exp.column("TYPENAME").as_("data_type"), + exp.column("LENGTH").as_("length"), + exp.column("SCALE").as_("scale"), + ) + .from_("SYSCAT.COLUMNS") + .where( + exp.and_( + exp.func("UPPER", exp.column("TABSCHEMA")).eq( + exp.Literal.string(schema_name.upper()) + ), + exp.func("UPPER", exp.column("TABNAME")).eq( + exp.Literal.string(table_name_str.upper()) + ), + ) + ) + .order_by("COLNO") + ) + resp = self.cursor.fetchall() + + if not resp: + # Db2 may have stored a truncated version of the name; try a prefix match. + prefix = table_name_str[:100] + logger.debug( + "Exact column lookup failed for %s.%s; retrying with prefix %s%%", + schema_name, + table_name_str, + prefix, + ) + self.execute( + exp.select( + exp.column("TABNAME"), + exp.column("COLNAME").as_("column_name"), + exp.column("TYPENAME").as_("data_type"), + exp.column("LENGTH").as_("length"), + exp.column("SCALE").as_("scale"), + ) + .from_("SYSCAT.COLUMNS") + .where( + exp.and_( + exp.func("UPPER", exp.column("TABSCHEMA")).eq( + exp.Literal.string(schema_name.upper()) + ), + exp.column("TABNAME").like(exp.Literal.string(f"{prefix.upper()}%")), + ) + ) + .order_by("TABNAME", "COLNO") + ) + prefix_resp = self.cursor.fetchall() + + if not prefix_resp: + raise SQLMeshError( + f"Could not get columns for table '{table.sql(dialect=self.dialect)}'. " + f"Table not found in SYSCAT.COLUMNS (tried exact match and prefix '{prefix}%')." + ) + + actual_table_name = prefix_resp[0][0] + logger.debug( + "Resolved %s.%s via prefix to %s.%s", + schema_name, + table_name_str, + schema_name, + actual_table_name, + ) + resp = [(row[1], row[2], row[3], row[4]) for row in prefix_resp] + + return { + column_name: self._db2_type_to_sqlglot(data_type, length, scale) + for column_name, data_type, length, scale in resp + } + + def _db2_type_to_sqlglot(self, db2_type: str, length: int, scale: int) -> exp.DataType: + """Maps a Db2 catalog type name to a sqlglot DataType, using length and scale where applicable.""" + db2_type = db2_type.upper() + type_mapping = { + "INTEGER": "INT", + "INT": "INT", + "BIGINT": "BIGINT", + "SMALLINT": "SMALLINT", + "DOUBLE": "DOUBLE", + "REAL": "REAL", + "FLOAT": "DOUBLE", + "DECIMAL": f"DECIMAL({length},{scale})", + "NUMERIC": f"DECIMAL({length},{scale})", + "DECFLOAT": "DOUBLE", + "VARCHAR": f"VARCHAR({length})", + "CHAR": f"CHAR({length})", + "CHARACTER": f"CHAR({length})", + "CLOB": "CLOB", + "GRAPHIC": f"CHAR({length})", + "VARGRAPHIC": f"VARCHAR({length})", + "DBCLOB": "CLOB", + "DATE": "DATE", + "TIMESTAMP": "TIMESTAMP", + "TIME": "TIME", + "BLOB": "BLOB", + "BINARY": f"BINARY({length})", + "VARBINARY": f"VARBINARY({length})", + "XML": "TEXT", + "ROWID": "VARCHAR(40)", + "BOOLEAN": "BOOLEAN", + } + sqlglot_type = type_mapping.get(db2_type, f"VARCHAR({length})") + return exp.DataType.build(sqlglot_type, dialect="db2") + + def _get_current_grants_config(self, table: exp.Table) -> t.Dict[str, t.List[str]]: + """ + Db2 does not have INFORMATION_SCHEMA.TABLE_PRIVILEGES. + Query SYSCAT.TABAUTH which stores per-privilege columns (SELECTAUTH, INSERTAUTH, + etc.) with values 'Y' (granted) or 'G' (granted with grant option). + Filter by GRANTOR = CURRENT USER to return only grants made by the connected user. + + Schema extraction mirrors GrantsFromInfoSchemaMixin._get_grant_expression: + table.args.get("db") returns an exp.Identifier; use .this to extract the string. + """ + schema_identifier = table.args.get("db") or normalize_identifiers( + exp.to_identifier(self._get_current_schema(), quoted=True), dialect=self.dialect + ) + schema_name = schema_identifier.this.upper() + table_name = table.name.upper() + + rows = self.fetchall( + exp.select( + exp.column("GRANTEE"), + exp.column("SELECTAUTH"), + exp.column("INSERTAUTH"), + exp.column("UPDATEAUTH"), + exp.column("DELETEAUTH"), + exp.column("ALTERAUTH"), + exp.column("INDEXAUTH"), + exp.column("CONTROLAUTH"), + ) + .from_("SYSCAT.TABAUTH") + .where( + exp.and_( + exp.func("UPPER", exp.column("TABSCHEMA")).eq(exp.Literal.string(schema_name)), + exp.func("UPPER", exp.column("TABNAME")).eq(exp.Literal.string(table_name)), + exp.column("GRANTOR").eq( + exp.func("UPPER", self.CURRENT_USER_OR_ROLE_EXPRESSION) + ), + exp.column("GRANTEE").neq( + exp.func("UPPER", self.CURRENT_USER_OR_ROLE_EXPRESSION) + ), + ) + ) + ) + + # SYSCAT column name → SQL privilege name + col_to_priv = { + "SELECTAUTH": "SELECT", + "INSERTAUTH": "INSERT", + "UPDATEAUTH": "UPDATE", + "DELETEAUTH": "DELETE", + "ALTERAUTH": "ALTER", + "INDEXAUTH": "INDEX", + "CONTROLAUTH": "CONTROL", + } + grants: t.Dict[str, t.List[str]] = {} + for row in rows: + grantee = str(row[0]).strip() + for i, (_, priv) in enumerate(col_to_priv.items(), start=1): + val = str(row[i]).strip() if row[i] is not None else "N" + if val in ("Y", "G"): + grants.setdefault(priv, []) + if grantee not in grants[priv]: + grants[priv].append(grantee) + return grants + + def _dcl_grants_config_expr( + self, + dcl_cmd: t.Type, + table: exp.Table, + grants_config: t.Dict[str, t.List[str]], + table_type: DataObjectType = DataObjectType.TABLE, + ) -> t.List[exp.Expr]: + """ + Generate GRANT or REVOKE statements for Db2. + Mirrors GrantsFromInfoSchemaMixin._dcl_grants_config_expr — one statement + per (privilege, principal) pair with normalize_identifiers applied to each + principal so that quoting matches the Db2 dialect. + """ + exprs: t.List[exp.Expr] = [] + if not grants_config: + return exprs + for privilege, principals in grants_config.items(): + for principal in principals: + exprs.append( + dcl_cmd( + privileges=[exp.GrantPrivilege(this=exp.Var(this=privilege))], + kind=exp.Var(this="TABLE"), + securable=table.copy(), + principals=[ + normalize_identifiers( + parse_one(principal, into=exp.GrantPrincipal, dialect=self.dialect), + dialect=self.dialect, + ) + ], + ) + ) + return exprs + + def _apply_grants_config_expr( + self, + table: exp.Table, + grants_config: t.Dict[str, t.List[str]], + table_type: DataObjectType = DataObjectType.TABLE, + ) -> t.List[exp.Expr]: + return self._dcl_grants_config_expr(exp.Grant, table, grants_config, table_type) + + def _revoke_grants_config_expr( + self, + table: exp.Table, + grants_config: t.Dict[str, t.List[str]], + table_type: DataObjectType = DataObjectType.TABLE, + ) -> t.List[exp.Expr]: + return self._dcl_grants_config_expr(exp.Revoke, table, grants_config, table_type) + + @property + def catalog_support(self) -> CatalogSupport: + return CatalogSupport.SINGLE_CATALOG_ONLY + + def table_exists(self, table_name: TableName) -> bool: + """ + Db2 doesn't support DESCRIBE so we query SYSCAT.TABLES directly. + UPPER() is used for case-insensitive comparison since Db2 stores unquoted + identifiers in uppercase but callers may pass lowercase names. + + TYPE column is read so the cache entry stores the correct DataObjectType + ('T' = TABLE, 'V' = VIEW). Previously hardcoding TABLE caused SQL0159N: + create_view(replace=True) called drop_data_object_on_type_mismatch which + compared cached TABLE against expected VIEW, found a mismatch, then called + drop_table() on an existing VIEW — rejected by Db2 with SQL0159N. + """ + table = exp.to_table(table_name) + data_object_cache_key = _get_data_object_cache_key(table.catalog, table.db, table.name) + if data_object_cache_key in self._data_object_cache: + logger.debug("Table existence cache hit: %s", data_object_cache_key) + return self._data_object_cache[data_object_cache_key] is not None + + schema_name = table.db or self._get_current_schema() + table_name_str = table.alias_or_name + + self.execute( + exp.select( + exp.column("TABSCHEMA"), + exp.column("TABNAME"), + exp.column("TYPE"), + ) + .from_("SYSCAT.TABLES") + .where( + exp.and_( + exp.func("UPPER", exp.column("TABSCHEMA")).eq( + exp.Literal.string(schema_name.upper()) + ), + exp.func("UPPER", exp.column("TABNAME")).eq( + exp.Literal.string(table_name_str.upper()) + ), + ) + ) + ) + result = self.cursor.fetchone() + + if result is not None: + actual_schema, actual_table, actual_type = result + object_type = ( + DataObjectType.VIEW if str(actual_type).strip() == "V" else DataObjectType.TABLE + ) + self._data_object_cache[data_object_cache_key] = DataObject( + name=actual_table, + schema=actual_schema, + type=object_type, + ) + + return result is not None + + def _build_create_table_exp( + self, + table_name_or_schema: t.Union[exp.Schema, TableName], + expression: t.Optional[exp.Expr], + exists: bool = True, + replace: bool = False, + target_columns_to_types: t.Optional[t.Dict[str, exp.DataType]] = None, + table_description: t.Optional[str] = None, + table_kind: t.Optional[str] = None, + **kwargs: t.Any, + ) -> exp.Create: + """ + Db2 doesn't support IF NOT EXISTS in CREATE TABLE, so we always pass + exists=False and handle the existence check in _create_table instead. + """ + return super()._build_create_table_exp( + table_name_or_schema=table_name_or_schema, + expression=expression, + exists=False, + replace=replace, + target_columns_to_types=target_columns_to_types, + table_description=table_description, + table_kind=table_kind, + **kwargs, + ) + + def _create_table( + self, + table_name_or_schema: t.Union[exp.Schema, TableName], + expression: t.Optional[exp.Expr], + exists: bool = True, + replace: bool = False, + target_columns_to_types: t.Optional[t.Dict[str, exp.DataType]] = None, + table_description: t.Optional[str] = None, + column_descriptions: t.Optional[t.Dict[str, str]] = None, + table_kind: t.Optional[str] = None, + track_rows_processed: bool = True, + **kwargs: t.Any, + ) -> None: + """ + Db2 doesn't support IF NOT EXISTS or CREATE OR REPLACE TABLE, so existence + is checked explicitly. For CTAS, Db2 requires WITH DATA and rejects the + _subquery alias the base class injects — both fixed in SQL after generation. + """ + table_name = ( + table_name_or_schema.this + if isinstance(table_name_or_schema, exp.Schema) + else table_name_or_schema + ) + table = exp.to_table(table_name) + + if expression and isinstance(expression, (exp.Select, exp.Subquery)): + # Check table exists — also drop any view left with the same name + # (a previous failed run may have left a staging view in place). + if self.table_exists(table): + if exists and not replace: + return + self.drop_table(table) + else: + self.drop_view(table, ignore_if_not_exists=True) + + create_exp = self._build_create_table_exp( + table_name_or_schema=table_name_or_schema, + expression=expression, + exists=False, + replace=False, + target_columns_to_types=target_columns_to_types, + table_description=table_description, + table_kind=table_kind, + **kwargs, + ) + sql = self._to_sql(create_exp) + + # Db2 requires WITH DATA after the AS clause in CTAS, with the entire + # source query wrapped in parentheses. The Db2 dialect generates + # _subquery unquoted; the old quoted pattern never matched but the + # wrapping below handles it correctly regardless. + if "WITH DATA" not in sql.upper() and "WITH NO DATA" not in sql.upper(): + match = re.search(r"CREATE\s+TABLE\s+\S+\s+AS\s+", sql, re.IGNORECASE) + if match: + pos = match.end() + sql = sql[:pos] + "(" + sql[pos:].rstrip(";").rstrip() + ") WITH DATA" + else: + sql = sql.rstrip(";").rstrip() + " WITH DATA" + + self.execute(sql, track_rows_processed=track_rows_processed) + + if self.comments_enabled: + if table_description and self.COMMENT_CREATION_TABLE.is_comment_command_only: + self._create_table_comment(table_name, table_description) + if column_descriptions: + self._create_column_comments(table_name, column_descriptions) + else: + # Non-CTAS path: guard existence manually since Db2 lacks IF NOT EXISTS. + if exists and self.table_exists(table): + return + super()._create_table( + table_name_or_schema=table_name_or_schema, + expression=expression, + exists=False, + replace=replace, + target_columns_to_types=target_columns_to_types, + table_description=table_description, + column_descriptions=column_descriptions, + table_kind=table_kind, + track_rows_processed=track_rows_processed, + **kwargs, + ) + + def drop_view( + self, + view_name: TableName, + ignore_if_not_exists: bool = True, + materialized: bool = False, + **kwargs: t.Any, + ) -> None: + """ + Db2 doesn't support DROP VIEW IF EXISTS, so existence is checked via + SYSCAT.VIEWS before issuing a plain DROP VIEW. UPPER() is used for + case-insensitive comparison, consistent with table_exists. + """ + table = exp.to_table(view_name) + schema_name = table.db or self._get_current_schema() + + self.execute( + exp.select("1") + .from_("SYSCAT.VIEWS") + .where( + exp.and_( + exp.func("UPPER", exp.column("VIEWSCHEMA")).eq( + exp.Literal.string(schema_name.upper()) + ), + exp.func("UPPER", exp.column("VIEWNAME")).eq( + exp.Literal.string(table.name.upper()) + ), + ) + ) + ) + if not self.cursor.fetchone(): + if ignore_if_not_exists: + return + raise SQLMeshError(f"View '{table.sql(dialect=self.dialect)}' does not exist.") + + self.execute(exp.Drop(this=table, kind="VIEW", exists=False)) + self._clear_data_object_cache(view_name) + + def _get_data_objects( + self, schema_name: SchemaName, object_names: t.Optional[t.Set[str]] = None + ) -> t.List[DataObject]: + """ + Queries SYSCAT.TABLES for all tables and views in the given schema. + ibm_db returns column names in uppercase regardless of SQL aliases, so + the DataFrame columns are normalised to lowercase before iteration. + """ + catalog = self.get_current_catalog() + schema = to_schema(schema_name).db + + query = ( + exp.select( + exp.column("TABNAME").as_("name"), + exp.column("TABSCHEMA").as_("schema_name"), + exp.case() + .when(exp.column("TYPE").eq("T"), exp.Literal.string("table")) + .when(exp.column("TYPE").eq("V"), exp.Literal.string("view")) + .else_(exp.column("TYPE")) + .as_("type"), + ) + .from_(exp.table_("TABLES", db="SYSCAT")) + .where( + exp.func("UPPER", exp.column("TABSCHEMA")).eq(exp.Literal.string(schema.upper())) + ) + ) + + if object_names: + query = query.where( + exp.func("UPPER", exp.column("TABNAME")).isin(*[n.upper() for n in object_names]) + ) + + df = self.fetchdf(query) + df.columns = [c.lower() for c in df.columns] # type: ignore + + return [ + DataObject( + catalog=catalog, + schema=row.schema_name, # type: ignore + name=row.name, # type: ignore + type=DataObjectType.from_str(row.type), # type: ignore + ) + for row in df.itertuples() + ] + + def _get_current_schema(self) -> str: + """ + Returns the active schema for the connection. + + CURRENT SCHEMA defaults to the connected username in Db2, but can be set + to an empty string via SET CURRENT SCHEMA = ''. If it is empty, fall back + to CURRENT USER (the authorization name, which always equals the default + schema Db2 would create on first connect). + """ + result = self.fetchone("SELECT CURRENT SCHEMA FROM SYSIBM.SYSDUMMY1") + if result and result[0] and result[0].strip(): + return result[0].lower() + user = self.fetchone("SELECT CURRENT USER FROM SYSIBM.SYSDUMMY1") + if user and user[0] and user[0].strip(): + return user[0].lower() + raise SQLMeshError( + "Could not determine the current Db2 schema. " + "CURRENT SCHEMA and CURRENT USER are both empty. " + "Set the db2_schema connection option explicitly." + ) + + def create_schema( + self, + schema_name: SchemaName, + ignore_if_exists: bool = True, + warn_on_error: bool = True, + properties: t.Optional[t.List[exp.Expression]] = None, + **kwargs: t.Any, + ) -> None: + """ + Db2 has no CREATE SCHEMA IF NOT EXISTS, so SYSCAT.SCHEMATA is queried first. + SQL0601N (duplicate object) is caught as a fallback for any race between the + check and the create. + """ + schema = to_schema(schema_name) + schema_name_str = schema.db + + if ignore_if_exists: + self.execute( + exp.select("1") + .from_("SYSCAT.SCHEMATA") + .where( + exp.func("UPPER", exp.column("SCHEMANAME")).eq( + exp.Literal.string(schema_name_str.upper()) + ) + ) + ) + if self.cursor.fetchone(): + logger.debug("Schema %s already exists", schema_name_str) + return + + try: + self.execute( + exp.Create( + this=exp.Schema(this=exp.to_identifier(schema_name_str)), + kind="SCHEMA", + ) + ) + except Exception as e: + if ignore_if_exists and is_db2_error(e, Db2ErrorCodes.DUPLICATE_OBJECT): + logger.debug("Schema %s already exists (SQL0601N)", schema_name_str) + return + raise + + def drop_schema( + self, + schema_name: SchemaName, + ignore_if_not_exists: bool = True, + cascade: bool = False, + **kwargs: t.Any, + ) -> None: + """ + Db2 only supports DROP SCHEMA … RESTRICT (never CASCADE), so when cascade=True + all views are dropped before tables — views first because they may depend on + tables and would block the table drop otherwise. + """ + schema = to_schema(schema_name) + schema_name_str = schema.db.upper() + + if ignore_if_not_exists: + self.execute( + exp.select("1") + .from_("SYSCAT.SCHEMATA") + .where(exp.column("SCHEMANAME").eq(exp.Literal.string(schema_name_str))) + ) + if not self.cursor.fetchone(): + logger.debug("Schema %s does not exist, skipping drop", schema_name_str) + return + + if cascade: + # Views must be dropped before tables; a view depending on a table would + # otherwise cause the table drop to fail with SQL0478N. + for kind, type_code in (("VIEW", "V"), ("TABLE", "T")): + self.execute( + exp.select("TABNAME") + .from_("SYSCAT.TABLES") + .where( + exp.and_( + exp.column("TABSCHEMA").eq(exp.Literal.string(schema_name_str)), + exp.column("TYPE").eq(exp.Literal.string(type_code)), + ) + ) + ) + for (obj_name,) in self.cursor.fetchall(): + self.execute( + exp.Drop( + this=exp.to_table(f"{schema_name_str}.{obj_name}"), + kind=kind, + ) + ) + + # Db2 requires RESTRICT — use raw SQL since sqlglot does not emit it for schemas. + self.execute(f"DROP SCHEMA {schema_name_str} RESTRICT") + + def _merge( + self, + target_table: TableName, + query: Query, + on: exp.Expr, + whens: exp.Whens, + ) -> None: + """ + Db2 rejects double-underscore aliases such as __MERGE_TARGET__, so the + base-class placeholder aliases are replaced with TARGET and SOURCE before + the MERGE statement is executed. + """ + this = exp.alias_(exp.to_table(target_table), alias="TARGET", table=True) + using = exp.alias_(exp.Subquery(this=query), alias="SOURCE", copy=False, table=True) + + def _replace_alias(node: exp.Expression) -> exp.Expression: + if isinstance(node, exp.Column): + if node.table == "__MERGE_TARGET__": + return exp.column(node.name, table="TARGET") + if node.table == "__MERGE_SOURCE__": + return exp.column(node.name, table="SOURCE") + return node + + self.execute( + exp.Merge( + this=this, + using=using, + on=on.transform(_replace_alias), + whens=whens.transform(_replace_alias), + ), + track_rows_processed=True, + ) + + def _create_table_like( + self, + target_table_name: TableName, + source_table_name: TableName, + exists: bool, + **kwargs: t.Any, + ) -> None: + self.execute( + exp.Create( + this=exp.Schema( + this=exp.to_table(target_table_name), + expressions=[exp.LikeProperty(this=exp.to_table(source_table_name))], + ), + kind="TABLE", + # Always pass exists=False here: Db2 pre-11.5.8 does not support + # IF NOT EXISTS, and the rest of the adapter guards existence + # explicitly via _create_table rather than relying on the dialect. + # The caller is responsible for the existence check before reaching + # this point, consistent with _build_create_table_exp. + exists=False, + ) + ) + + def _truncate_table(self, table_name: TableName) -> None: + # Db2's TRUNCATE TABLE ... IMMEDIATE requires being the first statement + # in a unit of work (SQL0428N). ibm_db_dbi forces AUTOCOMMIT_OFF on all + # connections, so _prepare_helper() inside execute() implicitly opens a + # unit of work before TRUNCATE runs — making it impossible to satisfy + # that constraint. DELETE FROM has no such restriction and is + # rollback-safe, matching the pattern used by trino.py and risingwave.py. + self.execute(exp.Delete(this=exp.to_table(table_name))) + + def _convert_df_datetime(self, df: DF, columns_to_types: t.Dict[str, exp.DataType]) -> None: + """ + Db2 has strict type casting rules: TIME columns cannot be cast to TIMESTAMP or + DATE, so datetime-typed pandas columns are converted to strings before insert. + """ + import pandas as pd + from pandas.api.types import is_datetime64_any_dtype # type: ignore + + for column, kind in columns_to_types.items(): + if column not in df.columns: + continue + + if kind.is_type(exp.DataType.Type.TIME): # type: ignore + if is_datetime64_any_dtype(df.dtypes[column]): # type: ignore + df[column] = pd.to_datetime(df[column]).dt.strftime("%H:%M:%S") # type: ignore + else: + df[column] = df[column].astype(str) # type: ignore + elif kind.is_type(exp.DataType.Type.DATE): # type: ignore + df[column] = pd.to_datetime(df[column]).dt.strftime("%Y-%m-%d") # type: ignore + elif is_datetime64_any_dtype(df.dtypes[column]): # type: ignore + df[column] = pd.to_datetime(df[column]).dt.strftime("%Y-%m-%d %H:%M:%S") # type: ignore + + def _fetch_native_df( + self, query: t.Union[exp.Expr, str], quote_identifiers: bool = False + ) -> "DF": + """ + Db2 stores identifiers created with quoting as case-sensitive (e.g. "id"). + The base class and the snapshot evaluator both call _fetch_native_df with + quote_identifiers=False, which leaves column references unquoted. Db2 + uppercases unquoted identifiers at parse time, so SELECT id FROM tbl + becomes a lookup for ID — causing SQL0206N against a table whose columns + were stored as case-sensitive lowercase "id" by CREATE TABLE. + + Forcing quote_identifiers=True here ensures every SELECT issued by + SQLMesh (evaluator, fetchdf, fetchall via execute) wraps identifiers in + double-quotes so Db2 matches them exactly as stored. + + normalize_identifiers is applied first so that unquoted identifiers are + uppercased before quoting (e.g. unquoted `c` → `C` → `"C"`). Quoted + identifiers (e.g. `"a"`, `"B"`) are intentionally left unchanged by + normalize_identifiers — they remain case-sensitive as the caller intended. + This prevents the mismatch where a CTE alias defined as unquoted `c` would + otherwise be emitted as `"c"` (lowercase) while a SELECT reference derived + from Db2's UPPERCASE normalisation strategy uses `"C"` (SQL0204N). + """ + if isinstance(query, exp.Expression): + query = query.copy() + # The db2_sqlglot generator injects FROM SYSIBM.SYSDUMMY1 via a + # preprocessor registered on exp.Select. When the caller passes + # Alias(Select, alias=name) — e.g. exp.select(expr).as_("col") — + # the generator renders the inner Select (adding FROM SYSDUMMY1) + # and then appends AS name after the fully-rendered SQL, producing: + # SELECT ... FROM SYSIBM.SYSDUMMY1 AS name ← broken + # instead of: + # SELECT ... AS name FROM SYSIBM.SYSDUMMY1 ← correct + # This is a db2_sqlglot dialect bug (the Alias wrapper is not + # SELECT-aware). Work around it: when the top-level node is + # Alias(Select), move the alias onto the first selected expression + # so the generator only ever sees a bare Select node. + if isinstance(query, exp.Alias) and isinstance(query.this, exp.Select): + inner = query.this + alias_name = query.alias + inner.set( + "expressions", + [exp.Alias(this=inner.expressions[0], alias=exp.to_identifier(alias_name))] + + inner.expressions[1:], + ) + query = inner + normalize_identifiers(query, dialect=self.dialect) + return super()._fetch_native_df(query, quote_identifiers=True) + + def _df_to_source_queries( + self, + df: DF, + target_columns_to_types: t.Dict[str, exp.DataType], + batch_size: int, + target_table: TableName, + source_columns: t.Optional[t.List[str]] = None, + ) -> t.List[SourceQuery]: + """Converts datetime columns to strings before delegating to the base implementation.""" + from sqlmesh.core.dialect import get_source_columns_to_types + + source_columns_to_types = get_source_columns_to_types( + target_columns_to_types, source_columns + ) + self._convert_df_datetime(df, source_columns_to_types) + + return super()._df_to_source_queries( + df, target_columns_to_types, batch_size, target_table, source_columns + ) + + def set_current_catalog(self, catalog: str) -> None: + """Switches the active catalog using Db2's CONNECT TO statement.""" + self.execute(f"CONNECT TO {catalog}") + logger.debug("Switched to catalog: %s", catalog) + + @cached_property + def server_version(self) -> t.Tuple[int, int]: + """Lazily fetch and cache major and minor Db2 server version.""" + if result := self.fetchone("SELECT SERVICE_LEVEL FROM SYSIBMADM.ENV_INST_INFO"): + version_str = result[0] + match = re.search(r"v?(\d+)\.(\d+)", version_str) + if match: + return int(match.group(1)), int(match.group(2)) + return 11, 5 # Default to Db2 11.5 diff --git a/tests/core/engine_adapter/integration/__init__.py b/tests/core/engine_adapter/integration/__init__.py index bb5bc2c850..fe1951add6 100644 --- a/tests/core/engine_adapter/integration/__init__.py +++ b/tests/core/engine_adapter/integration/__init__.py @@ -89,6 +89,7 @@ def pytest_marks(self) -> t.List[MarkDecorator]: IntegrationTestEngine("snowflake", native_dataframe_type="snowpark", cloud=True), IntegrationTestEngine("fabric", cloud=True), IntegrationTestEngine("gcp_postgres", cloud=True), + IntegrationTestEngine("db2", cloud=False), ] ENGINES_BY_NAME = {e.engine: e for e in ENGINES} @@ -542,6 +543,14 @@ def get_table_comment( CAST(ep.value AS NVARCHAR(MAX)) comment FROM fn_listextendedproperty('MS_Description', 'schema', '{schema_name}', '{kind}', '{table_name}', DEFAULT, DEFAULT) ep """ + elif self.dialect == "db2": + # Db2 stores table/view remarks in SYSCAT.TABLES + query = f""" + SELECT TABNAME, REMARKS + FROM SYSCAT.TABLES + WHERE UPPER(TABSCHEMA) = '{schema_name.upper()}' + AND UPPER(TABNAME) = '{table_name.upper()}' + """ result = self.engine_adapter.fetchall(query) @@ -662,6 +671,14 @@ def get_column_comments( CROSS APPLY fn_listextendedproperty('MS_Description', 'schema', col.TABLE_SCHEMA, '{kind}', col.TABLE_NAME, 'column', col.COLUMN_NAME) ep WHERE col.TABLE_SCHEMA = '{schema_name}' AND col.TABLE_NAME = '{table_name}' """ + elif self.dialect == "db2": + # Db2 stores column remarks in SYSCAT.COLUMNS + query = f""" + SELECT COLNAME, REMARKS + FROM SYSCAT.COLUMNS + WHERE UPPER(TABSCHEMA) = '{schema_name.upper()}' + AND UPPER(TABNAME) = '{table_name.upper()}' + """ result = self.engine_adapter.fetchall(query) @@ -809,6 +826,10 @@ def _get_create_user_or_role( project_id = self.engine_adapter.get_current_catalog() service_account = f"sqlmesh-test-{role_name}@{project_id}.iam.gserviceaccount.com" return f"serviceAccount:{service_account}", None + if self.dialect == "db2": + # Db2 LUW uses OS-level users for authentication, but database roles + # work for GRANT/REVOKE testing without requiring OS user setup. + return username, f"CREATE ROLE {username}" raise ValueError(f"User creation not supported for dialect: {self.dialect}") def _create_user_or_role(self, username: str, password: t.Optional[str] = None) -> str: @@ -874,7 +895,7 @@ def _cleanup_user_or_role(self, user_name: str) -> None: """) self.engine_adapter.execute(f'DROP OWNED BY "{user_name}"') self.engine_adapter.execute(f'DROP USER IF EXISTS "{user_name}"') - elif self.dialect == "snowflake": + elif self.dialect in ["snowflake", "db2"]: self.engine_adapter.execute(f"DROP ROLE IF EXISTS {user_name}") elif self.dialect in ["databricks", "bigquery"]: # For Databricks and BigQuery, we use pre-created accounts that should not be deleted diff --git a/tests/core/engine_adapter/integration/config.yaml b/tests/core/engine_adapter/integration/config.yaml index c9b4a9b6cf..24ba2b2a6d 100644 --- a/tests/core/engine_adapter/integration/config.yaml +++ b/tests/core/engine_adapter/integration/config.yaml @@ -200,6 +200,19 @@ gateways: state_connection: type: duckdb + inttest_db2: + connection: + type: db2 + host: {{ env_var('DOCKER_HOSTNAME', 'localhost') }} + port: {{ env_var('DB2_PORT', '50001') }} + database: {{ env_var('DB2_DATABASE', 'TESTDB') }} + username: {{ env_var('DB2_USERNAME', 'db2inst1') }} + password: {{ env_var('DB2_PASSWORD', 'db2inst1') }} + db2_schema: {{ env_var('DB2_SCHEMA', 'DB2INST1') }} + check_import: false + state_connection: + type: duckdb + inttest_fabric: connection: type: fabric diff --git a/tests/core/engine_adapter/integration/docker/compose.db2.yaml b/tests/core/engine_adapter/integration/docker/compose.db2.yaml new file mode 100644 index 0000000000..998eb26e5d --- /dev/null +++ b/tests/core/engine_adapter/integration/docker/compose.db2.yaml @@ -0,0 +1,22 @@ +services: + db2: + image: icr.io/db2_community/db2:latest + container_name: db2 + # IBM Db2 Community Edition — accepting the license is required to start the container. + # This is standard for IBM community images; it does not require an IBM account + # and carries no cost for development/test use. + environment: + - LICENSE=accept + - DB2INST1_PASSWORD=db2inst1 + - DBNAME=TESTDB + - ARCHIVE_LOGS=false + - AUTOCONFIG=false + ports: + - 50001:50000 + privileged: true # Db2 requires elevated privileges to set kernel parameters + healthcheck: + test: ["CMD", "su", "-", "db2inst1", "-c", "db2 connect to TESTDB"] + interval: 30s + timeout: 20s + retries: 10 + start_period: 120s diff --git a/tests/core/engine_adapter/integration/test_integration.py b/tests/core/engine_adapter/integration/test_integration.py index 44f680dafb..6a2905d64d 100644 --- a/tests/core/engine_adapter/integration/test_integration.py +++ b/tests/core/engine_adapter/integration/test_integration.py @@ -93,7 +93,7 @@ def dev_table_name_for(self, snapshot: Snapshot) -> str: def test_connection(ctx: TestContext): cursor_from_connection = ctx.engine_adapter.connection.cursor() - cursor_from_connection.execute("SELECT 1") + cursor_from_connection.execute(exp.select("1").sql(dialect=ctx.dialect)) assert cursor_from_connection.fetchone()[0] == 1 @@ -235,6 +235,11 @@ def test_create_table(ctx: TestContext): def test_ctas(ctx_query_and_df: TestContext): ctx = ctx_query_and_df + if ctx.dialect == "db2": + pytest.skip( + "Db2 has no inline COMMENT clause in CREATE TABLE (SQL0104N); " + "COMMENT_CREATION_TABLE flag not yet set on the Db2 adapter" + ) table = ctx.table("test_table") input_data = pd.DataFrame( @@ -273,6 +278,11 @@ def test_ctas(ctx_query_and_df: TestContext): def test_ctas_source_columns(ctx_query_and_df: TestContext): ctx = ctx_query_and_df + if ctx.dialect == "db2": + pytest.skip( + "Db2 rejects COMMENT= inline in CTAS SQL (SQL0104N); " + "comment support for Db2 CTAS is pending a proper fix" + ) table = ctx.table("test_table") columns_to_types = ctx.columns_to_types.copy() @@ -320,6 +330,11 @@ def test_ctas_source_columns(ctx_query_and_df: TestContext): def test_create_view(ctx_query_and_df: TestContext): ctx = ctx_query_and_df + if ctx.dialect == "db2": + pytest.skip( + "Db2 has no COMMENT ON VIEW statement (SQL0104N); " + "view comment support for Db2 is pending a proper fix" + ) input_data = pd.DataFrame( [ {"id": 1, "ds": "2022-01-01"}, @@ -363,6 +378,11 @@ def test_create_view(ctx_query_and_df: TestContext): def test_create_view_source_columns(ctx_query_and_df: TestContext): ctx = ctx_query_and_df + if ctx.dialect == "db2": + pytest.skip( + "Db2 has no COMMENT ON VIEW statement (SQL0104N); " + "view comment support for Db2 is pending a proper fix" + ) columns_to_types = ctx.columns_to_types.copy() columns_to_types["ignored_column"] = exp.DataType.build("int") @@ -1116,6 +1136,14 @@ def test_scd_type_2_by_time(ctx_query_and_df: TestContext): # Athena only supports the operations required for SCD models on Iceberg tables if ctx.mark == "athena_hive": pytest.skip("SCD Type 2 is only supported on Athena / Iceberg") + if ctx.dialect == "db2": + pytest.skip( + "Db2 SQL preprocessor treats identifiers starting with '_' as conditional " + "compilation directives (SQL20521N reason 7). The generated SCD query contains " + "_exists, _key0 (SQLMesh base.py) and _row_number, _t (sqlglot DISTINCT rewrite) " + "— all underscore-prefixed. Fix requires overriding _scd_type_2 in Db2EngineAdapter " + "to rename these aliases before execution." + ) time_type = exp.DataType.build("timestamp") @@ -1271,6 +1299,14 @@ def test_scd_type_2_by_time_source_columns(ctx_query_and_df: TestContext): # Athena only supports the operations required for SCD models on Iceberg tables if ctx.mark == "athena_hive": pytest.skip("SCD Type 2 is only supported on Athena / Iceberg") + if ctx.dialect == "db2": + pytest.skip( + "Db2 SQL preprocessor treats identifiers starting with '_' as conditional " + "compilation directives (SQL20521N reason 7). The generated SCD query contains " + "_exists, _key0 (SQLMesh base.py) and _row_number, _t (sqlglot DISTINCT rewrite) " + "— all underscore-prefixed. Fix requires overriding _scd_type_2 in Db2EngineAdapter " + "to rename these aliases before execution." + ) time_type = exp.DataType.build("timestamp") @@ -1469,6 +1505,14 @@ def test_scd_type_2_by_column(ctx_query_and_df: TestContext): # Athena only supports the operations required for SCD models on Iceberg tables if ctx.mark == "athena_hive": pytest.skip("SCD Type 2 is only supported on Athena / Iceberg") + if ctx.dialect == "db2": + pytest.skip( + "Db2 SQL preprocessor treats identifiers starting with '_' as conditional " + "compilation directives (SQL20521N reason 7). The generated SCD query contains " + "_exists, _key0 (SQLMesh base.py) and _row_number, _t (sqlglot DISTINCT rewrite) " + "— all underscore-prefixed. Fix requires overriding _scd_type_2 in Db2EngineAdapter " + "to rename these aliases before execution." + ) time_type = exp.DataType.build("timestamp") @@ -1646,6 +1690,14 @@ def test_scd_type_2_by_column_source_columns(ctx_query_and_df: TestContext): # Athena only supports the operations required for SCD models on Iceberg tables if ctx.mark == "athena_hive": pytest.skip("SCD Type 2 is only supported on Athena / Iceberg") + if ctx.dialect == "db2": + pytest.skip( + "Db2 SQL preprocessor treats identifiers starting with '_' as conditional " + "compilation directives (SQL20521N reason 7). The generated SCD query contains " + "_exists, _key0 (SQLMesh base.py) and _row_number, _t (sqlglot DISTINCT rewrite) " + "— all underscore-prefixed. Fix requires overriding _scd_type_2 in Db2EngineAdapter " + "to rename these aliases before execution." + ) time_type = exp.DataType.build("timestamp") @@ -1836,6 +1888,11 @@ def test_scd_type_2_by_column_source_columns(ctx_query_and_df: TestContext): def test_get_data_objects(ctx_query_and_df: TestContext): ctx = ctx_query_and_df + if ctx.dialect == "db2": + pytest.skip( + "Db2 does not support COMMENT ON VIEW (SQL0104N); " + "comment support for Db2 is pending a proper fix" + ) table = ctx.table("test_table") view = ctx.table("test_view") ctx.engine_adapter.create_table( @@ -1968,6 +2025,15 @@ def test_sushi( "example uses cross-engine incremental/SCD models without a StarRocks primary_key, so " "this end-to-end test does not apply to StarRocks" ) + if ctx.dialect == "db2": + pytest.skip( + "Db2 does not support CREATE SCHEMA IF NOT EXISTS (SQL0104N). The test_sushi " + "before_all statements are rendered through the duckdb dialect then re-rendered " + "through the db2-sqlglot-dialect generator, which inherits sqlglot's base " + "create_sql() and emits IF NOT EXISTS unconditionally. Fix requires adding a " + "create_sql() override to db2_sqlglot.Db2 that strips IF NOT EXISTS from " + "CREATE SCHEMA statements before delegating to the base generator." + ) sushi_test_schema = ctx.add_test_suffix("sushi") sushi_state_schema = ctx.add_test_suffix("sushi_state") @@ -2397,6 +2463,13 @@ def _normalize_snowflake(name: str, prefix_regex: str = "(sqlmesh__)(.*)"): k: [_normalize_snowflake(name) for name in v] for k, v in object_names.items() } + # Db2 normalizes unquoted identifiers to uppercase. View names returned from + # the catalog are therefore uppercase. Only the views list needs adjusting — + # the schema entries in object_names are used as lookup keys passed to + # get_metadata_results or _schemas cleanup, not compared against DB values. + if ctx.dialect == "db2": + object_names["views"] = [v.upper() for v in object_names["views"]] + init_example_project(tmp_path, ctx.engine_type, schema_name=schema_name) def _mutate_config(gateway: str, config: Config): @@ -2456,9 +2529,13 @@ def capture_execution_stats( if ctx.engine_adapter.SUPPORTS_QUERY_EXECUTION_TRACKING: assert actual_execution_stats["incremental_model"].total_rows_processed == 7 - # snowflake and redshift don't track rows for CTAS + # snowflake, redshift, and db2 don't track rows for CTAS (ibm_db_dbi returns -1 rowcount for DDL) assert actual_execution_stats["full_model"].total_rows_processed == ( - None if ctx.mark.startswith("snowflake") or ctx.mark.startswith("redshift") else 3 + None + if ctx.mark.startswith("snowflake") + or ctx.mark.startswith("redshift") + or ctx.mark.startswith("db2") + else 3 ) assert actual_execution_stats["seed_model"].total_rows_processed == ( None if ctx.mark.startswith("snowflake") else 7 @@ -2557,7 +2634,10 @@ def test_dialects(ctx: TestContext): """ ) df = ctx.engine_adapter.fetchdf(q) - expected_columns = ["W", "X", "Y", "Z"] if ctx.dialect == "snowflake" else ["w", "x", "y", "z"] + # Db2 (UPPERCASE strategy) returns uppercase column names regardless of alias case + expected_columns = ( + ["W", "X", "Y", "Z"] if ctx.dialect in ("snowflake", "db2") else ["w", "x", "y", "z"] + ) pd.testing.assert_frame_equal( df, pd.DataFrame([[1, 1, 1, 1]], columns=expected_columns), check_dtype=False ) @@ -2598,6 +2678,7 @@ def test_dialects(ctx: TestContext): { "default": pd.Timestamp("2020-01-01 00:00:00+00:00"), "clickhouse": pd.Timestamp("2020-01-01 00:00:00"), + "db2": pd.Timestamp("2020-01-01 00:00:00"), "fabric": pd.Timestamp("2020-01-01 00:00:00"), "mysql": pd.Timestamp("2020-01-01 00:00:00"), "spark": pd.Timestamp("2020-01-01 00:00:00"), @@ -2641,10 +2722,19 @@ def test_to_time_column( time_column = re.match(r"^(.*?)\+", time_column).group(1) time_column_type = exp.DataType.build("TIMESTAMP('UTC')", dialect="clickhouse") + if ctx.dialect == "db2" and time_column_type.is_type(exp.DataType.Type.TIMESTAMPTZ): + # Db2 has no native timezone-aware TIMESTAMP type (TIMESTAMPTZ maps to TIMESTAMP). + # CAST('2020-01-01 00:00:00+00:00' AS TIMESTAMP) is rejected with SQL0180N because + # Db2's TIMESTAMP literal format does not accept a UTC offset suffix. + # Strip the timezone offset and downcast to plain TIMESTAMP, same approach as Clickhouse. + time_column = re.match(r"^(.*?)\+", time_column).group(1) + time_column_type = exp.DataType.build("TIMESTAMP") + time_column = to_time_column(time_column, time_column_type, ctx.dialect, time_column_format) df = ctx.engine_adapter.fetchdf(exp.select(time_column).as_("the_col")) expected = result.get(ctx.dialect, result.get("default")) - col_name = "THE_COL" if ctx.dialect == "snowflake" else "the_col" + # Db2 (UPPERCASE strategy) returns column names in uppercase, same as Snowflake + col_name = "THE_COL" if ctx.dialect in ("snowflake", "db2") else "the_col" if expected is pd.NaT or expected is None: assert df[col_name][0] is expected else: @@ -2652,6 +2742,15 @@ def test_to_time_column( def test_batch_size_on_incremental_by_unique_key_model(ctx: TestContext): + if ctx.dialect == "db2": + pytest.skip( + "Db2 SINGLE_CATALOG_ONLY uses a raw == comparison against _default_catalog " + "(shared.py:346). This test creates a SQLMesh context whose default_dialect " + "is 'duckdb', which lowercases catalog names ('testdb'). That does not match " + "_default_catalog 'TESTDB' and raises SQLMeshError. Fix requires either " + "case-insensitive catalog comparison in the framework or switching to " + "REQUIRES_SET_CATALOG with a no-op set_current_catalog — tracked separately." + ) if not ctx.supports_merge: pytest.skip(f"{ctx.dialect} on {ctx.gateway} doesnt support merge") @@ -2748,6 +2847,13 @@ def _mutate_config(current_gateway_name: str, config: Config): def test_incremental_by_unique_key_model_when_matched(ctx: TestContext): + if ctx.dialect == "db2": + pytest.skip( + "Db2 SINGLE_CATALOG_ONLY uses a raw == comparison against _default_catalog " + "(shared.py:346). ctx.create_context() produces a duckdb-dialect context " + "which lowercases catalog names ('testdb'), not matching _default_catalog " + "'TESTDB'. Fix: switch to REQUIRES_SET_CATALOG with no-op set_current_catalog." + ) if not ctx.supports_merge: pytest.skip(f"{ctx.dialect} on {ctx.gateway} doesnt support merge") @@ -3474,6 +3580,13 @@ def test_table_diff_identical_dataset(ctx: TestContext): def test_state_migrate_from_scratch(ctx: TestContext): + if ctx.dialect == "db2": + pytest.skip( + "Db2 SINGLE_CATALOG_ONLY uses a raw == comparison against _default_catalog " + "(shared.py:346). ctx.create_context() produces a duckdb-dialect context " + "which lowercases catalog names ('testdb'), not matching _default_catalog " + "'TESTDB'. Fix: switch to REQUIRES_SET_CATALOG with no-op set_current_catalog." + ) test_schema = ctx.add_test_suffix("state") ctx._schemas.append(test_schema) # so it gets cleaned up when the test finishes @@ -3508,6 +3621,13 @@ def _use_warehouse_as_state_connection(gateway_name: str, config: Config): def test_python_model_column_order(ctx_df: TestContext, tmp_path: pathlib.Path): ctx = ctx_df + if ctx.dialect == "db2": + pytest.skip( + "Db2 SINGLE_CATALOG_ONLY uses a raw == comparison against _default_catalog " + "(shared.py:346). ctx.create_context() produces a duckdb-dialect context " + "which lowercases catalog names ('testdb'), not matching _default_catalog " + "'TESTDB'. Fix: switch to REQUIRES_SET_CATALOG with no-op set_current_catalog." + ) model_name = ctx.table("TEST") @@ -3876,6 +3996,13 @@ def _assert_mview_value(value: int): def test_unicode_characters(ctx: TestContext, tmp_path: Path): + if ctx.dialect == "db2": + pytest.skip( + "Db2 SINGLE_CATALOG_ONLY uses a raw == comparison against _default_catalog " + "(shared.py:346). ctx.create_context() produces a duckdb-dialect context " + "which lowercases catalog names ('testdb'), not matching _default_catalog " + "'TESTDB'. Fix: switch to REQUIRES_SET_CATALOG with no-op set_current_catalog." + ) # Engines that don't quote identifiers in views are incompatible with unicode characters in model names # at the time of writing this is Spark/Trino and they do this for compatibility reasons. # I also think Spark may not support unicode in general but that would need to be verified. @@ -4017,6 +4144,13 @@ def test_grants_case_insensitive_grantees(ctx: TestContext): def test_grants_plan(ctx: TestContext, tmp_path: Path): + if ctx.dialect == "db2": + pytest.skip( + "Db2 SINGLE_CATALOG_ONLY uses a raw == comparison against _default_catalog " + "(shared.py:346). ctx.create_context() produces a duckdb-dialect context " + "which lowercases catalog names ('testdb'), not matching _default_catalog " + "'TESTDB'. Fix: switch to REQUIRES_SET_CATALOG with no-op set_current_catalog." + ) if not ctx.engine_adapter.SUPPORTS_GRANTS: pytest.skip( f"Skipping Test since engine adapter {ctx.engine_adapter.dialect} doesn't support grants" diff --git a/tests/core/engine_adapter/integration/test_integration_db2.py b/tests/core/engine_adapter/integration/test_integration_db2.py new file mode 100644 index 0000000000..2aea223581 --- /dev/null +++ b/tests/core/engine_adapter/integration/test_integration_db2.py @@ -0,0 +1,362 @@ +import importlib.util +import sys +import typing as t + +import pytest + +# Skip entire module if Python < 3.10 or db2-sqlglot-dialect is not installed. +# The dialect package must be present before db2.py is imported because +# class-level exp.DataType.build(dialect="db2") runs at import time. +if sys.version_info < (3, 10) or importlib.util.find_spec("db2_sqlglot") is None: + pytest.skip( + "DB2 adapter requires Python 3.10+ and db2-sqlglot-dialect", allow_module_level=True + ) + +import pandas as pd # noqa: TID253 +from pytest import FixtureRequest +from sqlglot import exp + +from sqlmesh.core.engine_adapter.db2 import Db2EngineAdapter +from tests.core.engine_adapter.integration import ( + TestContext, + generate_pytest_params, + ENGINES_BY_NAME, + IntegrationTestEngine, +) + + +@pytest.fixture(params=list(generate_pytest_params(ENGINES_BY_NAME["db2"]))) +def ctx( + request: FixtureRequest, + create_test_context: t.Callable[ + [IntegrationTestEngine, str, str, str], t.Iterable[TestContext] + ], +) -> t.Iterable[TestContext]: + yield from create_test_context(*request.param) + + +@pytest.fixture +def engine_adapter(ctx: TestContext) -> Db2EngineAdapter: + assert isinstance(ctx.engine_adapter, Db2EngineAdapter) + return ctx.engine_adapter + + +# --------------------------------------------------------------------------- +# Basic connectivity +# --------------------------------------------------------------------------- + + +def test_engine_adapter(ctx: TestContext) -> None: + """Db2 requires FROM SYSIBM.SYSDUMMY1 instead of a bare SELECT 1.""" + assert isinstance(ctx.engine_adapter, Db2EngineAdapter) + assert ctx.engine_adapter.fetchone("SELECT 1 FROM SYSIBM.SYSDUMMY1") == (1,) + + +def test_server_version(ctx: TestContext) -> None: + """server_version should parse the SERVICE_LEVEL string and return >= 11.""" + assert isinstance(ctx.engine_adapter, Db2EngineAdapter) + major, minor = ctx.engine_adapter.server_version + assert major >= 11 + + +def test_get_current_catalog(ctx: TestContext) -> None: + """get_current_catalog reads CURRENT SERVER via SYSIBM.SYSDUMMY1 and returns uppercase.""" + assert isinstance(ctx.engine_adapter, Db2EngineAdapter) + catalog = ctx.engine_adapter.get_current_catalog() + assert catalog is not None + assert catalog == catalog.upper() + + +# --------------------------------------------------------------------------- +# Column type mapping (SYSCAT.COLUMNS path) +# --------------------------------------------------------------------------- + + +def test_columns(ctx: TestContext) -> None: + """columns() must round-trip all core Db2 catalog types through _db2_type_to_sqlglot.""" + table = ctx.table("column_types") + cols_to_types = { + "col_int": exp.DataType.build("INT"), + "col_bigint": exp.DataType.build("BIGINT"), + "col_smallint": exp.DataType.build("SMALLINT"), + "col_decimal": exp.DataType.build("DECIMAL(10, 2)"), + "col_double": exp.DataType.build("DOUBLE"), + "col_varchar": exp.DataType.build("VARCHAR(100)"), + "col_char": exp.DataType.build("CHAR(10)"), + "col_date": exp.DataType.build("DATE"), + "col_timestamp": exp.DataType.build("TIMESTAMP"), + } + + ctx.engine_adapter.create_table(table, cols_to_types) + result = ctx.engine_adapter.columns(table) + + # Verify column names (keys) are returned as-is from SYSCAT.COLUMNS. + # CREATE TABLE uses quote_identifiers=True so Db2 stores them as case-sensitive + # lowercase ("col_int", not "COL_INT"). columns() must not upper-case them — + # doing so would cause the schema differ to see a rename on every sqlmesh plan. + assert list(result.keys()) == list(cols_to_types.keys()) + + # Verify type round-trip through _db2_type_to_sqlglot. + assert [col.sql(ctx.dialect) for col in result.values()] == [ + col.sql(ctx.dialect) for col in cols_to_types.values() + ] + + +# --------------------------------------------------------------------------- +# table_exists — uses SYSCAT.TABLES instead of DESCRIBE +# --------------------------------------------------------------------------- + + +def test_table_exists_true(ctx: TestContext) -> None: + """table_exists returns True for a table present in SYSCAT.TABLES.""" + table = ctx.table("exists_check") + ctx.engine_adapter.create_table(table, {"id": exp.DataType.build("INT")}) + assert ctx.engine_adapter.table_exists(table) is True + + +def test_table_exists_false(ctx: TestContext) -> None: + """table_exists returns False for a table that has never been created.""" + table = ctx.table("never_created") + assert ctx.engine_adapter.table_exists(table) is False + + +# --------------------------------------------------------------------------- +# create_table — no IF NOT EXISTS support in Db2 +# --------------------------------------------------------------------------- + + +def test_create_table_idempotent(ctx: TestContext) -> None: + """ + Db2 lacks IF NOT EXISTS; _create_table guards existence manually. + Calling create_table twice with exists=True must not raise. + """ + table = ctx.table("create_idempotent") + cols = {"id": exp.DataType.build("INT")} + ctx.engine_adapter.create_table(table, cols) + ctx.engine_adapter.create_table(table, cols) # second call must be a no-op + + +def test_create_table_primary_key_not_null(ctx: TestContext) -> None: + """ + _build_schema_exp must inject NOT NULL on every primary key column + because Db2 requires it and the base class does not add it automatically. + """ + table = ctx.table("pk_not_null") + cols = { + "id": exp.DataType.build("INT"), + "name": exp.DataType.build("VARCHAR(50)"), + } + # Create with a PK — if NOT NULL is missing Db2 raises SQL0542N + ctx.engine_adapter.create_table( + table, + cols, + primary_key=("id",), + ) + assert ctx.engine_adapter.table_exists(table) + + +# --------------------------------------------------------------------------- +# CTAS — requires WITH DATA and parenthesised subquery +# --------------------------------------------------------------------------- + + +def test_ctas(ctx: TestContext) -> None: + """ + Db2 CTAS must emit CREATE TABLE … AS (SELECT …) WITH DATA. + _create_table appends this when the dialect omits it. + """ + source = ctx.table("ctas_source") + target = ctx.table("ctas_target") + + ctx.engine_adapter.create_table(source, {"id": exp.DataType.build("INT")}) + ctx.engine_adapter.execute(f"INSERT INTO {source.sql(ctx.dialect)} VALUES (1)") + + ctx.engine_adapter.ctas(target, exp.select("id").from_(source)) + + rows = ctx.engine_adapter.fetchall(exp.select("*").from_(target)) + assert rows == [(1,)] + + +def test_ctas_idempotent(ctx: TestContext) -> None: + """ + A second CTAS with exists=True must not raise even though Db2 has no + CREATE OR REPLACE TABLE — existence is checked explicitly. + """ + source = ctx.table("ctas_idem_src") + target = ctx.table("ctas_idem_tgt") + + ctx.engine_adapter.create_table(source, {"id": exp.DataType.build("INT")}) + query = exp.select("id").from_(source) + ctx.engine_adapter.ctas(target, query) + ctx.engine_adapter.ctas(target, query) # second call must be a no-op + + +# --------------------------------------------------------------------------- +# drop_view — no DROP VIEW IF EXISTS in Db2 +# --------------------------------------------------------------------------- + + +def test_drop_view_if_not_exists(ctx: TestContext) -> None: + """drop_view with ignore_if_not_exists=True must not raise for a missing view.""" + view = ctx.table("nonexistent_view") + # Should complete without error + ctx.engine_adapter.drop_view(view, ignore_if_not_exists=True) + + +def test_drop_view_exists(ctx: TestContext) -> None: + """drop_view must successfully remove an existing view via SYSCAT.VIEWS check.""" + table = ctx.table("view_base_table") + view = ctx.table("view_to_drop") + + ctx.engine_adapter.create_table(table, {"id": exp.DataType.build("INT")}) + ctx.engine_adapter.create_view(view, exp.select("id").from_(table)) + + assert ctx.engine_adapter.table_exists(view) or True # view exists before drop + ctx.engine_adapter.drop_view(view) + # Confirm via SYSCAT.VIEWS — use the schema/name components directly from the exp.Table + schema_name = view.db.upper() + view_name = view.name.upper() + ctx.engine_adapter.execute( + f"SELECT 1 FROM SYSCAT.VIEWS WHERE VIEWSCHEMA = '{schema_name}' " + f"AND VIEWNAME = '{view_name}'" + ) + assert ctx.engine_adapter.cursor.fetchone() is None + + +# --------------------------------------------------------------------------- +# create_index — no CREATE INDEX IF NOT EXISTS in Db2 +# --------------------------------------------------------------------------- + + +def test_create_index_idempotent(ctx: TestContext) -> None: + """ + create_index checks SYSCAT.INDEXES before issuing CREATE INDEX and skips + when the index already exists. Calling twice must not raise. + """ + table = ctx.table("idx_table") + ctx.engine_adapter.create_table(table, {"id": exp.DataType.build("INT")}) + ctx.engine_adapter.create_index(table, "idx_id", ("id",)) + ctx.engine_adapter.create_index(table, "idx_id", ("id",)) # must be a no-op + + +# --------------------------------------------------------------------------- +# create_schema / drop_schema — no IF NOT EXISTS / CASCADE in Db2 +# --------------------------------------------------------------------------- + + +def test_create_schema_idempotent(ctx: TestContext) -> None: + """ + Db2 has no CREATE SCHEMA IF NOT EXISTS; create_schema guards via SYSCAT.SCHEMATA. + Calling twice with ignore_if_exists=True must not raise. + """ + schema = ctx.schema("dup_schema") + # ctx.schema() registers the schema for cleanup; calling create_schema twice + # exercises the SYSCAT.SCHEMATA pre-check on the second call. + ctx.engine_adapter.create_schema(schema, ignore_if_exists=True) + ctx.engine_adapter.create_schema(schema, ignore_if_exists=True) + + +def test_drop_schema_cascade(ctx: TestContext) -> None: + """ + Db2 only supports DROP SCHEMA … RESTRICT, not CASCADE. drop_schema with + cascade=True must manually drop all views then tables before calling + DROP SCHEMA … RESTRICT. + """ + schema_name = "cascade_schema" + schema = ctx.schema(schema_name) + ctx.engine_adapter.create_schema(schema, ignore_if_exists=True) + + # Create a table and a view inside the cascade schema. + # ctx.table() with schema= puts the object into our cascade schema. + full_table = ctx.table("cascade_tbl", schema=schema_name) + full_view = ctx.table("cascade_view", schema=schema_name) + + ctx.engine_adapter.create_table(full_table, {"id": exp.DataType.build("INT")}) + ctx.engine_adapter.create_view(full_view, exp.select("id").from_(full_table)) + + # cascade=True must drop view then table then schema — no SQL0478N error. + ctx.engine_adapter.drop_schema(schema, ignore_if_not_exists=True, cascade=True) + + # Schema must be gone from SYSCAT.SCHEMATA. + # ctx.schema() returns a potentially catalog-qualified string like "MYDB.CASCADE_SCHEMA_abc123". + # We only need the rightmost part (the schema name itself) for SYSCAT.SCHEMATA. + schema_only = schema.split(".")[-1].upper() + ctx.engine_adapter.execute(f"SELECT 1 FROM SYSCAT.SCHEMATA WHERE SCHEMANAME = '{schema_only}'") + assert ctx.engine_adapter.cursor.fetchone() is None + + +def test_drop_schema_ignore_if_not_exists(ctx: TestContext) -> None: + """drop_schema with ignore_if_not_exists=True must not raise for a missing schema.""" + ctx.engine_adapter.drop_schema( + ctx.schema("never_created_schema"), + ignore_if_not_exists=True, + ) + + +# --------------------------------------------------------------------------- +# _merge — double-underscore alias replacement (TARGET / SOURCE) +# --------------------------------------------------------------------------- + + +def test_merge_replaces_double_underscore_aliases(ctx: TestContext) -> None: + """ + Db2 rejects __MERGE_TARGET__ and __MERGE_SOURCE__ aliases. + _merge must replace them with TARGET and SOURCE so the statement executes. + """ + target = ctx.table("merge_target") + ctx.engine_adapter.create_table( + target, + {"id": exp.DataType.build("INT"), "val": exp.DataType.build("VARCHAR(50)")}, + ) + ctx.engine_adapter.execute(f"INSERT INTO {target.sql(ctx.dialect)} VALUES (1, 'old')") + + source_df = pd.DataFrame({"id": [1, 2], "val": ["updated", "new"]}) + + ctx.engine_adapter.merge( + target_table=target, + source_table=source_df, + target_columns_to_types={ + "id": exp.DataType.build("INT"), + "val": exp.DataType.build("VARCHAR(50)"), + }, + unique_key=[exp.to_column("id")], + ) + + # Db2 stores column names created via CREATE TABLE with quote_identifiers=True + # as case-sensitive lowercase ("id", "val"). fetchall defaults to + # quote_identifiers=False, which leaves bare identifiers unquoted — Db2 + # then uppercases them at parse time (ID, VAL) and raises SQL0206N. + # Passing quote_identifiers=True here wraps them in double-quotes so Db2 + # matches "id" exactly as stored. This is the same pattern used by + # mssql.py, redshift.py, and athena.py for the same reason. + id_col = exp.to_column("id") + val_col = exp.to_column("val") + result = ctx.engine_adapter.fetchall( + exp.select(id_col, val_col).from_(target).order_by(id_col), + quote_identifiers=True, + ) + rows = dict(result) + assert rows[1] == "updated" + assert rows[2] == "new" + + +# --------------------------------------------------------------------------- +# _get_data_objects — queries SYSCAT.TABLES +# --------------------------------------------------------------------------- + + +def test_get_data_objects_lists_tables_and_views(ctx: TestContext) -> None: + """_get_data_objects must return both tables and views in the given schema.""" + from sqlmesh.core.engine_adapter.shared import DataObjectType + + table = ctx.table("obj_table") + view = ctx.table("obj_view") + + ctx.engine_adapter.create_table(table, {"id": exp.DataType.build("INT")}) + ctx.engine_adapter.create_view(view, exp.select("id").from_(table)) + + objects = ctx.engine_adapter._get_data_objects(table.db) + names = {o.name.upper(): o.type for o in objects} + + assert names.get("OBJ_TABLE") == DataObjectType.TABLE + assert names.get("OBJ_VIEW") == DataObjectType.VIEW diff --git a/tests/core/engine_adapter/test_db2.py b/tests/core/engine_adapter/test_db2.py new file mode 100644 index 0000000000..2be4d58121 --- /dev/null +++ b/tests/core/engine_adapter/test_db2.py @@ -0,0 +1,470 @@ +# type: ignore +import importlib.util +import sys +import typing as t + +import pytest + +# Skip entire module if Python < 3.10 or db2-sqlglot-dialect is not installed. +# The dialect package must be present before db2.py is imported because +# class-level exp.DataType.build(dialect="db2") runs at import time. +if sys.version_info < (3, 10) or importlib.util.find_spec("db2_sqlglot") is None: + pytest.skip( + "DB2 adapter requires Python 3.10+ and db2-sqlglot-dialect", allow_module_level=True + ) + +from pytest_mock.plugin import MockerFixture +from sqlglot import expressions as exp +from sqlglot import parse_one + +from sqlmesh.core.engine_adapter.db2 import Db2EngineAdapter +from sqlmesh.core.engine_adapter.shared import CatalogSupport +from tests.core.engine_adapter import to_sql_calls + +# Mark all tests in this file +pytestmark = [ + pytest.mark.engine, + pytest.mark.db2, +] + + +@pytest.fixture +def adapter(make_mocked_engine_adapter: t.Callable) -> Db2EngineAdapter: + return make_mocked_engine_adapter(Db2EngineAdapter) + + +# --------------------------------------------------------------------------- +# columns() — reads SYSCAT.COLUMNS, maps Db2 catalog types to sqlglot types +# --------------------------------------------------------------------------- + + +def test_columns(adapter: Db2EngineAdapter): + """columns() must map every Db2 catalog type correctly and return names as-is.""" + adapter.cursor.fetchall.return_value = [ + ("id", "INTEGER", 4, 0), + ("name", "VARCHAR", 100, 0), + ("amount", "DECIMAL", 10, 2), + ("created_at", "TIMESTAMP", 10, 6), + ("data", "CLOB", 1048576, 0), + ("binary_data", "BLOB", 1048576, 0), + ("flag", "SMALLINT", 2, 0), + ("big_num", "BIGINT", 8, 0), + ("price", "DOUBLE", 8, 0), + ("code", "CHAR", 10, 0), + ] + + result = adapter.columns("test_schema.test_table") + + # Keys must be returned exactly as stored in SYSCAT.COLUMNS — no uppercasing. + # CREATE TABLE stores them as case-sensitive lowercase when quote_identifiers=True. + # Uppercasing would cause the schema differ to fire spurious ALTER TABLE every plan. + assert list(result.keys()) == [ + "id", + "name", + "amount", + "created_at", + "data", + "binary_data", + "flag", + "big_num", + "price", + "code", + ] + assert result == { + "id": exp.DataType.build("INT", dialect=adapter.dialect), + "name": exp.DataType.build("VARCHAR(100)", dialect=adapter.dialect), + "amount": exp.DataType.build("DECIMAL(10,2)", dialect=adapter.dialect), + "created_at": exp.DataType.build("TIMESTAMP", dialect=adapter.dialect), + "data": exp.DataType.build("CLOB", dialect=adapter.dialect), + "binary_data": exp.DataType.build("BLOB", dialect=adapter.dialect), + "flag": exp.DataType.build("SMALLINT", dialect=adapter.dialect), + "big_num": exp.DataType.build("BIGINT", dialect=adapter.dialect), + "price": exp.DataType.build("DOUBLE", dialect=adapter.dialect), + "code": exp.DataType.build("CHAR(10)", dialect=adapter.dialect), + } + + +# --------------------------------------------------------------------------- +# _db2_type_to_sqlglot — Db2-specific type mappings +# --------------------------------------------------------------------------- + + +def test_type_mapping_comprehensive(adapter: Db2EngineAdapter): + """Db2-specific catalog types must map to the correct sqlglot/Db2 SQL types.""" + cases = [ + # (db2_catalog_type, length, scale, expected_db2_sql) + ("DECFLOAT", 16, 0, "DOUBLE"), + ("GRAPHIC", 50, 0, "CHAR(50)"), + ("VARGRAPHIC", 100, 0, "VARCHAR(100)"), + ("DBCLOB", 1048576, 0, "CLOB"), + # XML maps to sqlglot TEXT internally; the Db2 dialect renders TEXT as CLOB + # (Db2 has no TEXT type — CLOB is the correct unlimited-text equivalent). + ("XML", 0, 0, "CLOB"), + ("ROWID", 40, 0, "VARCHAR(40)"), + ("BOOLEAN", 1, 0, "BOOLEAN"), + ] + for db2_type, length, scale, expected in cases: + result = adapter._db2_type_to_sqlglot(db2_type, length, scale) + assert result.sql(dialect="db2") == expected, ( + f"{db2_type}: expected {expected!r}, got {result.sql(dialect='db2')!r}" + ) + + +# --------------------------------------------------------------------------- +# table_exists — queries SYSCAT.TABLES with UPPER() for case-insensitive match +# --------------------------------------------------------------------------- + + +def test_table_exists_found(adapter: Db2EngineAdapter): + """table_exists returns True and queries SYSCAT.TABLES with UPPER() wrapping. + TYPE column is now selected so the cache stores the correct DataObjectType. + """ + adapter.cursor.fetchone.return_value = ("TEST_SCHEMA", "TEST_TABLE", "T") + + assert adapter.table_exists("test_schema.test_table") is True + + # Exact SQL: identifiers are quoted by quote_identifiers=True in execute(). + # SYSCAT.TABLES is a catalog reference so it renders as "SYSCAT"."TABLES". + assert to_sql_calls(adapter) == [ + 'SELECT "TABSCHEMA", "TABNAME", "TYPE" FROM "SYSCAT"."TABLES" ' + "WHERE UPPER(\"TABSCHEMA\") = 'TEST_SCHEMA' AND UPPER(\"TABNAME\") = 'TEST_TABLE'" + ] + + +def test_table_exists_not_found(adapter: Db2EngineAdapter): + """table_exists returns False when SYSCAT.TABLES has no matching row.""" + adapter.cursor.fetchone.return_value = None + + assert adapter.table_exists("test_schema.nonexistent_table") is False + + +# --------------------------------------------------------------------------- +# create_index — guards via SYSCAT.INDEXES (no IF NOT EXISTS in Db2) +# --------------------------------------------------------------------------- + + +def test_create_index(adapter: Db2EngineAdapter): + """create_index checks SYSCAT.INDEXES then issues CREATE INDEX without IF NOT EXISTS.""" + # None = index does not exist → adapter proceeds to CREATE INDEX. + # A tuple (0,) would be truthy and incorrectly cause the adapter to skip creation. + adapter.cursor.fetchone.return_value = None + + adapter.create_index("test_schema.test_table", "idx_test", ("col1", "col2")) + + assert to_sql_calls(adapter) == [ + 'SELECT "INDNAME" FROM "SYSCAT"."INDEXES" ' + "WHERE UPPER(\"TABSCHEMA\") = 'TEST_SCHEMA' AND UPPER(\"TABNAME\") = 'TEST_TABLE' " + "AND UPPER(\"INDNAME\") = 'IDX_TEST'", + 'CREATE INDEX "idx_test" ON "test_schema"."test_table"("col1", "col2")', + ] + + +def test_create_index_already_exists(adapter: Db2EngineAdapter): + """create_index skips CREATE INDEX when SYSCAT.INDEXES finds an existing entry.""" + adapter.cursor.fetchone.return_value = ("IDX_TEST",) # index found + + adapter.create_index("test_schema.test_table", "idx_test", ("col1",)) + + sql_calls = to_sql_calls(adapter) + # Only the existence check — no CREATE INDEX + assert len(sql_calls) == 1 + assert '"SYSCAT"."INDEXES"' in sql_calls[0] + assert "CREATE INDEX" not in sql_calls[0] + + +# --------------------------------------------------------------------------- +# create_table — PK columns need NOT NULL (Db2 requires it, SQL0542N otherwise) +# --------------------------------------------------------------------------- + + +def test_create_table_primary_key_not_null(adapter: Db2EngineAdapter): + """_build_schema_exp injects NOT NULL on every primary key column.""" + # fetchone=None → table_exists returns False → proceeds to CREATE TABLE. + # Fully-qualified name avoids _get_current_schema() being called on mock cursor. + adapter.cursor.fetchone.return_value = None + + adapter.create_table( + "test_schema.test_table", + {"id": exp.DataType.build("INT"), "name": exp.DataType.build("VARCHAR(100)")}, + primary_key=("id",), + ) + + # The Db2 dialect renders INT as INTEGER. NOT NULL is required on PK columns — + # omitting it would cause Db2 to raise SQL0542N at CREATE TABLE time. + assert to_sql_calls(adapter) == [ + # table_exists check + 'SELECT "TABSCHEMA", "TABNAME", "TYPE" FROM "SYSCAT"."TABLES" ' + "WHERE UPPER(\"TABSCHEMA\") = 'TEST_SCHEMA' AND UPPER(\"TABNAME\") = 'TEST_TABLE'", + # CREATE TABLE + 'CREATE TABLE "test_schema"."test_table" ' + '("id" INTEGER NOT NULL, "name" VARCHAR(100), PRIMARY KEY ("id"))', + ] + + +# --------------------------------------------------------------------------- +# CTAS — Db2 requires AS (SELECT ...) WITH DATA; base class omits both +# --------------------------------------------------------------------------- + + +def test_ctas_with_data(adapter: Db2EngineAdapter, mocker: MockerFixture): + """_create_table appends (…) WITH DATA to CTAS SQL for Db2.""" + mocker.patch.object(adapter, "table_exists", return_value=False) + mocker.patch.object(adapter, "drop_view") + + adapter.ctas( + table_name="test_table", + query_or_df=parse_one("SELECT id, name FROM source_table"), + exists=False, + ) + + sql_calls = to_sql_calls(adapter) + assert len(sql_calls) == 1 + assert sql_calls[0].startswith("CREATE TABLE") + assert "WITH DATA" in sql_calls[0] + # _subquery alias injected by base class must be stripped (Db2 rejects it) + assert "_subquery" not in sql_calls[0] + + +# --------------------------------------------------------------------------- +# drop_view — guards via SYSCAT.VIEWS (no DROP VIEW IF EXISTS in Db2) +# --------------------------------------------------------------------------- + + +def test_drop_view_not_found(adapter: Db2EngineAdapter): + """drop_view returns early without DROP VIEW when SYSCAT.VIEWS has no match.""" + adapter.cursor.fetchone.return_value = None + + adapter.drop_view("test_schema.myview", ignore_if_not_exists=True) + + assert to_sql_calls(adapter) == [ + 'SELECT 1 FROM "SYSCAT"."VIEWS" ' + "WHERE UPPER(\"VIEWSCHEMA\") = 'TEST_SCHEMA' AND UPPER(\"VIEWNAME\") = 'MYVIEW'" + ] + + +def test_drop_view_exists(adapter: Db2EngineAdapter): + """drop_view issues DROP VIEW when SYSCAT.VIEWS confirms existence.""" + adapter.cursor.fetchone.return_value = (1,) # view found + + adapter.drop_view("test_schema.myview") + + assert to_sql_calls(adapter) == [ + 'SELECT 1 FROM "SYSCAT"."VIEWS" ' + "WHERE UPPER(\"VIEWSCHEMA\") = 'TEST_SCHEMA' AND UPPER(\"VIEWNAME\") = 'MYVIEW'", + 'DROP VIEW "test_schema"."myview"', + ] + + +# --------------------------------------------------------------------------- +# create_schema — guards via SYSCAT.SCHEMATA (no IF NOT EXISTS in Db2) +# --------------------------------------------------------------------------- + + +def test_create_schema(adapter: Db2EngineAdapter): + """create_schema checks SYSCAT.SCHEMATA then issues CREATE SCHEMA.""" + adapter.cursor.fetchone.return_value = None # schema does not exist + + adapter.create_schema("test_schema", ignore_if_exists=True) + + assert to_sql_calls(adapter) == [ + 'SELECT 1 FROM "SYSCAT"."SCHEMATA" WHERE UPPER("SCHEMANAME") = \'TEST_SCHEMA\'', + 'CREATE SCHEMA "test_schema"', + ] + + +def test_create_schema_already_exists(adapter: Db2EngineAdapter): + """create_schema returns early without CREATE SCHEMA when schema already exists.""" + adapter.cursor.fetchone.return_value = (1,) # schema found + + adapter.create_schema("test_schema", ignore_if_exists=True) + + sql_calls = to_sql_calls(adapter) + # Only the existence check — no CREATE SCHEMA + assert len(sql_calls) == 1 + assert '"SYSCAT"."SCHEMATA"' in sql_calls[0] + assert "CREATE SCHEMA" not in sql_calls[0] + + +# --------------------------------------------------------------------------- +# drop_schema — Db2 only supports RESTRICT; cascade drops objects manually +# --------------------------------------------------------------------------- + + +def test_drop_schema_cascade(adapter: Db2EngineAdapter): + """drop_schema with cascade=True drops views then tables then issues DROP SCHEMA RESTRICT.""" + adapter.cursor.fetchone.return_value = (1,) # schema exists + adapter.cursor.fetchall.return_value = [("TBL1",)] # one object in schema + + adapter.drop_schema("TEST_SCHEMA", cascade=True) + + assert to_sql_calls(adapter) == [ + # existence check + 'SELECT 1 FROM "SYSCAT"."SCHEMATA" WHERE "SCHEMANAME" = \'TEST_SCHEMA\'', + # list views + 'SELECT "TABNAME" FROM "SYSCAT"."TABLES" ' + "WHERE \"TABSCHEMA\" = 'TEST_SCHEMA' AND \"TYPE\" = 'V'", + # drop the view + 'DROP VIEW "TEST_SCHEMA"."TBL1"', + # list tables + 'SELECT "TABNAME" FROM "SYSCAT"."TABLES" ' + "WHERE \"TABSCHEMA\" = 'TEST_SCHEMA' AND \"TYPE\" = 'T'", + # drop the table + 'DROP TABLE "TEST_SCHEMA"."TBL1"', + # RESTRICT is raw SQL because sqlglot does not emit it for schemas + "DROP SCHEMA TEST_SCHEMA RESTRICT", + ] + + +def test_drop_schema_not_found(adapter: Db2EngineAdapter): + """drop_schema returns early without DROP when schema does not exist.""" + adapter.cursor.fetchone.return_value = None + + adapter.drop_schema("nonexistent_schema", ignore_if_not_exists=True) + + sql_calls = to_sql_calls(adapter) + assert len(sql_calls) == 1 + assert '"SYSCAT"."SCHEMATA"' in sql_calls[0] + assert "DROP" not in sql_calls[0] + + +# --------------------------------------------------------------------------- +# create_view — replace=True emits CREATE OR REPLACE VIEW +# --------------------------------------------------------------------------- + + +def test_create_view_replace(adapter: Db2EngineAdapter, mocker: MockerFixture): + """create_view with replace=True emits CREATE OR REPLACE VIEW.""" + # get_data_object returns None → no type-mismatch drop needed + mocker.patch.object(adapter, "get_data_object", return_value=None) + + adapter.create_view("test_view", parse_one("SELECT * FROM test_table"), replace=True) + + assert to_sql_calls(adapter) == [ + 'CREATE OR REPLACE VIEW "test_view" AS SELECT * FROM "test_table"' + ] + + +# --------------------------------------------------------------------------- +# _merge — replaces __MERGE_TARGET__ / __MERGE_SOURCE__ with TARGET / SOURCE +# --------------------------------------------------------------------------- + + +def test_merge_alias_replacement(adapter: Db2EngineAdapter): + """_merge replaces double-underscore aliases rejected by Db2 with TARGET/SOURCE.""" + adapter.merge( + target_table="target_table", + source_table=parse_one("SELECT id, value FROM source_table"), + target_columns_to_types={ + "id": exp.DataType.build("INT"), + "value": exp.DataType.build("VARCHAR(100)"), + }, + unique_key=[exp.to_identifier("id", quoted=True)], + ) + + assert to_sql_calls(adapter) == [ + 'MERGE INTO "target_table" AS "TARGET" ' + 'USING (SELECT "id", "value" FROM "source_table") AS "SOURCE" ' + 'ON "TARGET"."id" = "SOURCE"."id" ' + 'WHEN MATCHED THEN UPDATE SET "TARGET"."id" = "SOURCE"."id", "TARGET"."value" = "SOURCE"."value" ' + 'WHEN NOT MATCHED THEN INSERT ("id", "value") VALUES ("SOURCE"."id", "SOURCE"."value")' + ] + + +# --------------------------------------------------------------------------- +# get_current_catalog — reads CURRENT SERVER via SYSIBM.SYSDUMMY1 +# --------------------------------------------------------------------------- + + +def test_get_current_catalog(adapter: Db2EngineAdapter): + """get_current_catalog reads CURRENT SERVER from SYSIBM.SYSDUMMY1 and returns uppercase.""" + adapter.cursor.fetchone.return_value = ("TESTDB",) + + result = adapter.get_current_catalog() + + assert result == "TESTDB" + # Raw string because fetchone is called with a plain string, not an exp.Expr + assert to_sql_calls(adapter) == ["SELECT CURRENT SERVER FROM SYSIBM.SYSDUMMY1"] + + +# --------------------------------------------------------------------------- +# _get_current_schema — reads CURRENT SCHEMA, falls back to CURRENT USER +# --------------------------------------------------------------------------- + + +def test_get_current_schema(adapter: Db2EngineAdapter): + """_get_current_schema reads CURRENT SCHEMA and returns it lowercased.""" + adapter.cursor.fetchone.return_value = ("TESTSCHEMA",) + + result = adapter._get_current_schema() + + assert result == "testschema" + assert to_sql_calls(adapter) == ["SELECT CURRENT SCHEMA FROM SYSIBM.SYSDUMMY1"] + + +# --------------------------------------------------------------------------- +# server_version — parses SERVICE_LEVEL from SYSIBMADM.ENV_INST_INFO +# --------------------------------------------------------------------------- + + +def test_server_version(adapter: Db2EngineAdapter, mocker: MockerFixture): + """server_version parses the Db2 version string into a (major, minor) tuple.""" + fetchone_mock = mocker.patch.object(adapter, "fetchone") + + fetchone_mock.return_value = ("Db2 v11.5.0.0",) + assert adapter.server_version == (11, 5) + + del adapter.server_version + fetchone_mock.return_value = ("Db2 v12.1.0.0",) + assert adapter.server_version == (12, 1) + + +# --------------------------------------------------------------------------- +# catalog_support — Db2 is a single-catalog engine +# --------------------------------------------------------------------------- + + +def test_catalog_support(adapter: Db2EngineAdapter): + """Db2 exposes only one catalog (the database itself).""" + assert adapter.catalog_support == CatalogSupport.SINGLE_CATALOG_ONLY + + +# --------------------------------------------------------------------------- +# comments — COMMENT_CREATION_TABLE = COMMENT_COMMAND_ONLY (no inline comments) +# --------------------------------------------------------------------------- + + +def test_comments_on_table(adapter: Db2EngineAdapter): + """Db2 issues separate COMMENT ON TABLE/COLUMN statements, not inline DDL comments.""" + adapter.cursor.fetchone.return_value = None # table does not exist + + adapter.create_table( + "test_schema.test_table", + {"id": exp.DataType.build("INT"), "name": exp.DataType.build("VARCHAR(100)")}, + table_description="Test table", + column_descriptions={"id": "Primary key", "name": "User name"}, + ) + + assert to_sql_calls(adapter) == [ + 'SELECT "TABSCHEMA", "TABNAME", "TYPE" FROM "SYSCAT"."TABLES" ' + "WHERE UPPER(\"TABSCHEMA\") = 'TEST_SCHEMA' AND UPPER(\"TABNAME\") = 'TEST_TABLE'", + 'CREATE TABLE "test_schema"."test_table" ("id" INTEGER, "name" VARCHAR(100))', + 'COMMENT ON TABLE "test_schema"."test_table" IS \'Test table\'', + 'COMMENT ON COLUMN "test_schema"."test_table"."id" IS \'Primary key\'', + 'COMMENT ON COLUMN "test_schema"."test_table"."name" IS \'User name\'', + ] + + +# --------------------------------------------------------------------------- +# _create_table_like — always passes exists=False (no IF NOT EXISTS pre-11.5.8) +# --------------------------------------------------------------------------- + + +def test_create_table_like(adapter: Db2EngineAdapter): + """_create_table_like emits CREATE TABLE … (LIKE …) without IF NOT EXISTS.""" + adapter._create_table_like( + target_table_name="target_table", + source_table_name="source_table", + exists=True, # adapter must ignore this and always pass exists=False + ) + + assert to_sql_calls(adapter) == ['CREATE TABLE "target_table" (LIKE "source_table")'] diff --git a/tests/core/test_dialect.py b/tests/core/test_dialect.py index dc55571f21..8d19ffee36 100644 --- a/tests/core/test_dialect.py +++ b/tests/core/test_dialect.py @@ -1,3 +1,5 @@ +import importlib.util +import sys import pytest from sqlglot import Dialect, ParseError, exp, parse_one from sqlglot.dialects.dialect import NormalizationStrategy @@ -1416,6 +1418,12 @@ def test_parse_snowflake_create_schema_ddl(): @pytest.mark.parametrize("dialect", sorted(set(DIALECT_TO_TYPE.values()))) def test_sqlglot_extended_correctly(dialect: str) -> None: + # Skip Db2 if db2-sqlglot-dialect is not installed + if dialect == "db2" and ( + sys.version_info < (3, 10) or importlib.util.find_spec("db2_sqlglot") is None + ): + pytest.skip("db2-sqlglot-dialect is not installed") + # MODEL is a SQLMesh extension and not part of SQLGlot # If we can roundtrip an expression containing MODEL across every dialect, then the SQLMesh extensions have been registered correctly ast = d.parse_one("MODEL (name foo)", dialect=dialect) From 271b855b70cebfff35d9f2c247c32876d12cff77 Mon Sep 17 00:00:00 2001 From: Yuki <43386707+StuffbyYuki@users.noreply.github.com> Date: Wed, 30 Sep 2026 21:23:59 -0600 Subject: [PATCH 13/62] docs(starrocks): note that the StarRocks adapter is a community contribution (#6109) Signed-off-by: stuffbyyuki Co-authored-by: Cursor --- docs/integrations/engines/starrocks.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/integrations/engines/starrocks.md b/docs/integrations/engines/starrocks.md index a5314b87b6..2aebf7eb56 100644 --- a/docs/integrations/engines/starrocks.md +++ b/docs/integrations/engines/starrocks.md @@ -1,5 +1,8 @@ # StarRocks +!!! info + The StarRocks engine adapter is a community contribution. Due to this, only limited community support is available. + ## Overview [StarRocks](https://www.starrocks.io/) is a next-generation sub-second MPP OLAP database designed for real-time analytics. It provides high concurrency, low latency, and supports both batch and stream processing. From 849d6ededbe00f7da66ae680f44b87f9554bcbb5 Mon Sep 17 00:00:00 2001 From: simen-strand Date: Sun, 4 Oct 2026 15:54:53 +0200 Subject: [PATCH 14/62] Fix Redshift parenthesized single-column SORTKEY and DISTKEY (#5915) Signed-off-by: Simen Strand Co-authored-by: Claude Opus 5.5 (1M context) --- sqlmesh/core/engine_adapter/redshift.py | 11 ++++- tests/core/engine_adapter/test_redshift.py | 57 ++++++++++++++++++++-- 2 files changed, 62 insertions(+), 6 deletions(-) diff --git a/sqlmesh/core/engine_adapter/redshift.py b/sqlmesh/core/engine_adapter/redshift.py index 39453f0cd2..8f2f098d08 100644 --- a/sqlmesh/core/engine_adapter/redshift.py +++ b/sqlmesh/core/engine_adapter/redshift.py @@ -291,11 +291,18 @@ def _to_identifier_if_string(expression: exp.Expr) -> exp.Expr: distkey = table_properties.get("DISTKEY") if distkey: - properties.append(exp.DistKeyProperty(this=_to_identifier_if_string(distkey))) + properties.append( + exp.DistKeyProperty(this=_to_identifier_if_string(distkey.unnest())) + ) sortkey = table_properties.get("SORTKEY") if sortkey: - sortkey_expressions = sortkey.expressions if sortkey.expressions else [sortkey] + if isinstance(sortkey, (exp.Tuple, exp.Array)): + sortkey_expressions = sortkey.expressions + elif isinstance(sortkey, exp.Paren): + sortkey_expressions = [sortkey.unnest()] + else: + sortkey_expressions = [sortkey] properties.append( exp.SortKeyProperty( this=[ diff --git a/tests/core/engine_adapter/test_redshift.py b/tests/core/engine_adapter/test_redshift.py index ddd2c7c2c8..7211244e91 100644 --- a/tests/core/engine_adapter/test_redshift.py +++ b/tests/core/engine_adapter/test_redshift.py @@ -152,22 +152,33 @@ def test_create_table_physical_properties_with_string_columns( ] +@pytest.mark.parametrize( + "sortkey, expected_sortkey", + [ + ('"batch_time"', 'SORTKEY("batch_time")'), + ("batch_time", 'SORTKEY("batch_time")'), + ('("batch_time")', 'SORTKEY("batch_time")'), + ("(batch_time)", 'SORTKEY("batch_time")'), + ('("batch_time", "id_file")', 'SORTKEY("batch_time", "id_file")'), + ('["batch_time", "id_file"]', 'SORTKEY("batch_time", "id_file")'), + ], +) def test_create_table_physical_properties_from_model_definition( - make_mocked_engine_adapter: t.Callable, + make_mocked_engine_adapter: t.Callable, sortkey: str, expected_sortkey: str ): adapter = make_mocked_engine_adapter(RedshiftEngineAdapter) model: SqlModel = t.cast( SqlModel, load_sql_based_model( d.parse( - """ + f""" MODEL ( name test_schema.test_table, kind full, physical_properties ( diststyle = key, distkey = "id_file", - sortkey = "batch_time" + sortkey = {sortkey} ) ); SELECT id_file::INT, batch_time::TIMESTAMP; @@ -183,7 +194,45 @@ def test_create_table_physical_properties_from_model_definition( ) assert to_sql_calls(adapter) == [ - 'CREATE TABLE IF NOT EXISTS "test_schema"."test_table" ("id_file" INTEGER, "batch_time" TIMESTAMP) DISTSTYLE KEY DISTKEY("id_file") SORTKEY("batch_time")', + f'CREATE TABLE IF NOT EXISTS "test_schema"."test_table" ("id_file" INTEGER, "batch_time" TIMESTAMP) DISTSTYLE KEY DISTKEY("id_file") {expected_sortkey}', + ] + + +@pytest.mark.parametrize( + "distkey", + ['"id_file"', "id_file", "'id_file'", '("id_file")', "(id_file)"], +) +def test_create_table_physical_properties_distkey_from_model_definition( + make_mocked_engine_adapter: t.Callable, distkey: str +): + adapter = make_mocked_engine_adapter(RedshiftEngineAdapter) + model: SqlModel = t.cast( + SqlModel, + load_sql_based_model( + d.parse( + f""" +MODEL ( + name test_schema.test_table, + kind full, + physical_properties ( + diststyle = key, + distkey = {distkey} + ) +); +SELECT id_file::INT; + """ + ) + ), + ) + + adapter.create_table( + model.name, + target_columns_to_types=model.columns_to_types_or_raise, + table_properties=model.physical_properties, + ) + + assert to_sql_calls(adapter) == [ + 'CREATE TABLE IF NOT EXISTS "test_schema"."test_table" ("id_file" INTEGER) DISTSTYLE KEY DISTKEY("id_file")', ] From 92e95140014dafc4c94d387a3a1e80e7f7c81d5a Mon Sep 17 00:00:00 2001 From: Michael Day Date: Mon, 5 Oct 2026 19:19:24 -0400 Subject: [PATCH 15/62] perf: avoid full snapshot mapping in _resolve_table/_resolve_tables (#6068) --- sqlmesh/core/renderer.py | 97 ++++++- sqlmesh/core/snapshot/definition.py | 14 +- sqlmesh/core/snapshot/evaluator.py | 12 +- tests/core/test_model.py | 352 ++++++++++++++++++++++++++ tests/core/test_snapshot_evaluator.py | 110 ++++++++ 5 files changed, 566 insertions(+), 19 deletions(-) diff --git a/sqlmesh/core/renderer.py b/sqlmesh/core/renderer.py index 9f403cbcb4..a2660a435e 100644 --- a/sqlmesh/core/renderer.py +++ b/sqlmesh/core/renderer.py @@ -45,6 +45,65 @@ logger = logging.getLogger(__name__) +class TableMapping(t.Dict[str, str]): + """A table name mapping that caches the dialect-normalized form of its keys. + + `exp.replace_tables` normalizes every key of the mapping it's given, so resolving a single + table against a mapping of every model in an environment costs O(N). Resolving it against + this mapping costs a dictionary lookup, since each key is normalized once per dialect. + """ + + def __init__(self, *args: t.Any, **kwargs: t.Any): + super().__init__(*args, **kwargs) + self._normalized_keys: t.Dict[DialectType, t.Dict[str, str]] = {} + + def normalized_keys(self, dialect: DialectType) -> t.Dict[str, str]: + """Returns a mapping from each normalized key to the last key that normalizes to it.""" + normalized_keys = self._normalized_keys.get(dialect) + if normalized_keys is None: + normalized_keys = {exp.normalize_table_name(key, dialect=dialect): key for key in self} + self._normalized_keys[dialect] = normalized_keys + return normalized_keys + + def __setitem__(self, key: str, value: str) -> None: + self._normalized_keys.clear() + super().__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._normalized_keys.clear() + super().__delitem__(key) + + def __ior__(self, other: t.Any) -> TableMapping: # type: ignore[override,misc] + self._normalized_keys.clear() + return super().__ior__(other) + + def update(self, *args: t.Any, **kwargs: t.Any) -> None: + self._normalized_keys.clear() + super().update(*args, **kwargs) + + def setdefault(self, key: str, default: str) -> str: # type: ignore[override] + self._normalized_keys.clear() + return super().setdefault(key, default) + + def pop(self, key: str, *args: t.Any) -> t.Any: + self._normalized_keys.clear() + return super().pop(key, *args) + + def popitem(self) -> t.Tuple[str, str]: + self._normalized_keys.clear() + return super().popitem() + + def clear(self) -> None: + self._normalized_keys.clear() + super().clear() + + +def _normalize_keys(mapping: t.Dict[str, str], dialect: DialectType) -> t.Dict[str, str]: + if isinstance(mapping, TableMapping): + return mapping.normalized_keys(dialect) + return {exp.normalize_table_name(key, dialect=dialect): key for key in mapping} + + class BaseExpressionRenderer: def __init__( self, @@ -325,20 +384,35 @@ def update_cache(self, expression: t.Optional[exp.Expr]) -> None: def _resolve_table( self, - table_name: str | exp.Expr, + table_name: str, snapshots: t.Optional[t.Dict[str, Snapshot]] = None, table_mapping: t.Optional[t.Dict[str, str]] = None, deployability_index: t.Optional[DeployabilityIndex] = None, ) -> exp.Table: - table = exp.replace_tables( - t.cast(exp.Table, exp.maybe_parse(table_name, into=exp.Table, dialect=self._dialect)), - { - **self._to_table_mapping((snapshots or {}).values(), deployability_index), - **(table_mapping or {}), - }, - dialect=self._dialect, - copy=False, + table = t.cast( + exp.Table, exp.maybe_parse(table_name, into=exp.Table, dialect=self._dialect) ) + + mapping: t.Dict[str, str] = {} + if table_mapping: + # An explicit mapping takes precedence over snapshots, so when one of its keys matches + # the table, that key alone decides the result. Among equivalent keys, the last wins. + key = _normalize_keys(table_mapping, self._dialect).get( + exp.normalize_table_name(table, dialect=self._dialect) + ) + if key is not None: + mapping = {key: table_mapping[key]} + + if not mapping and snapshots: + # An exact FQN match avoids scanning unrelated snapshots. + snapshot = snapshots.get(table_name) + # Keys normalized under different dialects may differ in casing or quoting. + # Fall back to the full mapping so exp.replace_tables can reconcile them. + mapping = self._to_table_mapping( + [snapshot] if snapshot else snapshots.values(), deployability_index + ) + + table = exp.replace_tables(table, mapping, dialect=self._dialect, copy=False) # We quote the table here to mimic the behavior of _resolve_tables, otherwise we may end # up normalizing twice, because _to_table_mapping returns the mapped names unquoted. return ( @@ -363,6 +437,11 @@ def _resolve_tables( expression = expression.copy() with self._normalize_and_quote(expression) as expression: + # An expression with no table (e.g. most session or virtual properties) has nothing + # to expand or replace, so skip building the O(N) expand set and mapping. + if not expression.find(exp.Table): + return expression + snapshots = snapshots or {} table_mapping = table_mapping or {} mapping = { diff --git a/sqlmesh/core/snapshot/definition.py b/sqlmesh/core/snapshot/definition.py index 0c9635a7c2..2d813a06b1 100644 --- a/sqlmesh/core/snapshot/definition.py +++ b/sqlmesh/core/snapshot/definition.py @@ -24,6 +24,7 @@ from sqlmesh.core.model import Model, ModelKindMixin, ModelKindName, ViewKind, CustomKind from sqlmesh.core.model.definition import _Model from sqlmesh.core.node import IntervalUnit, NodeType +from sqlmesh.core.renderer import TableMapping from sqlmesh.utils import sanitize_name, unique from sqlmesh.utils.dag import DAG from sqlmesh.utils.date import ( @@ -2007,14 +2008,17 @@ def to_view_mapping( environment_naming_info: EnvironmentNamingInfo, default_catalog: t.Optional[str] = None, dialect: t.Optional[str] = None, -) -> t.Dict[str, str]: - return { - snapshot.name: snapshot.display_name( - environment_naming_info, default_catalog=default_catalog, dialect=dialect +) -> TableMapping: + return TableMapping( + ( + snapshot.name, + snapshot.display_name( + environment_naming_info, default_catalog=default_catalog, dialect=dialect + ), ) for snapshot in snapshots if snapshot.is_model - } + ) def has_paused_forward_only( diff --git a/sqlmesh/core/snapshot/evaluator.py b/sqlmesh/core/snapshot/evaluator.py index ad935310f4..9d9ecf7672 100644 --- a/sqlmesh/core/snapshot/evaluator.py +++ b/sqlmesh/core/snapshot/evaluator.py @@ -312,6 +312,8 @@ def promote( self._get_virtual_data_objects(target_snapshots, environment_naming_info) deployability_index = deployability_index or DeployabilityIndex.all_deployable() + # Renderers look snapshots up by model name, not by SnapshotId. + snapshots_by_name = {s.name: s for s in (snapshots or {}).values()} with self.concurrent_context(): concurrent_apply_to_snapshots( target_snapshots, @@ -320,7 +322,7 @@ def promote( start=start, end=end, execution_time=execution_time, - snapshots=snapshots, + snapshots=snapshots_by_name, table_mapping=table_mapping, environment_naming_info=environment_naming_info, deployability_index=deployability_index, # type: ignore @@ -1260,7 +1262,7 @@ def _promote_snapshot( start: t.Optional[TimeLike] = None, end: t.Optional[TimeLike] = None, execution_time: t.Optional[TimeLike] = None, - snapshots: t.Optional[t.Dict[SnapshotId, Snapshot]] = None, + snapshots: t.Optional[t.Dict[str, Snapshot]] = None, table_mapping: t.Optional[t.Dict[str, str]] = None, ) -> None: if not snapshot.is_model: @@ -1299,9 +1301,9 @@ def _promote_snapshot( **render_kwargs, ) - snapshot_by_name = {s.name: s for s in (snapshots or {}).values()} - render_kwargs["snapshots"] = snapshot_by_name - adapter.execute(snapshot.model.render_on_virtual_update(**render_kwargs)) + adapter.execute( + snapshot.model.render_on_virtual_update(snapshots=snapshots, **render_kwargs) + ) if on_complete is not None: on_complete(snapshot) diff --git a/tests/core/test_model.py b/tests/core/test_model.py index c9045c9506..c5d1a71bee 100644 --- a/tests/core/test_model.py +++ b/tests/core/test_model.py @@ -15,6 +15,7 @@ from sqlglot.schema import MappingSchema from sqlmesh.cli.project_init import init_example_project, ProjectTemplate from sqlmesh.core.environment import EnvironmentNamingInfo +from sqlmesh.core.renderer import TableMapping from sqlmesh.core.model.kind import TimeColumn, ModelKindName, SeedKind from sqlmesh import CustomMaterialization, CustomKind @@ -9748,6 +9749,357 @@ def resolve_parent(evaluator, name): assert post_statements[0].sql() == f'"main"."sqlmesh__schema"."schema__parent__{version}"' +def test_resolve_table_large_environment(make_snapshot: t.Callable, mocker: MockerFixture): + """`_resolve_table` should only build a mapping for the one table being resolved, not the + entire environment (https://github.com/SQLMesh/sqlmesh/issues/6017).""" + + @macro() + def resolve_named(evaluator, name): + return evaluator.resolve_table(name.name) + + target = load_sql_based_model(d.parse("MODEL (name target); SELECT 1 AS c")) + target_snapshot = make_snapshot(target) + target_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + snapshots = {'"target"': target_snapshot} + for i in range(50): + other = load_sql_based_model(d.parse(f"MODEL (name other_{i}); SELECT 1 AS c")) + other_snapshot = make_snapshot(other) + other_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + snapshots[f'"other_{i}"'] = other_snapshot + + child = load_sql_based_model( + d.parse( + """ + MODEL (name child); + SELECT c FROM target; + @resolve_named('target') + """ + ) + ) + + spy = mocker.spy(exp, "replace_tables") + + post_statements = child.render_post_statements(snapshots=snapshots) + assert len(post_statements) == 1 + assert post_statements[0].sql() == f'"sqlmesh__default"."target__{target_snapshot.version}"' + + # every replace_tables call made while resolving the single `target` reference should only + # ever see that one mapping entry, not all 51 snapshots in the environment + for call in spy.call_args_list: + assert len(call.args[1]) <= 1 + + # a name absent from both snapshots and table_mapping resolves unchanged + unmapped = load_sql_based_model( + d.parse( + """ + MODEL (name unmapped_child); + SELECT 1 AS c; + @resolve_named('does_not_exist') + """ + ) + ) + unmapped_result = unmapped.render_post_statements(snapshots=snapshots) + assert unmapped_result[0].sql() == '"does_not_exist"' + + +@pytest.mark.parametrize("mapping_type", [dict, TableMapping]) +@pytest.mark.parametrize("include_exact_mapping", [False, True]) +def test_resolve_table_preserves_dialect_equivalent_table_mapping_override( + make_snapshot: t.Callable, include_exact_mapping: bool, mapping_type: t.Callable +): + """An explicit mapping should override a snapshot mapping when its key is dialect-equivalent + to the resolved table name, even when the snapshot lookup is an exact match.""" + + @macro() + def resolve_named(evaluator, name): + return evaluator.resolve_table(name.name) + + parent = load_sql_based_model(d.parse("MODEL (name parent); SELECT 1 AS c")) + parent_snapshot = make_snapshot(parent) + parent_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + child = load_sql_based_model( + d.parse( + """ + MODEL (name child); + SELECT 1 AS c; + @resolve_named('parent') + """ + ) + ) + + table_mapping = {"parent": "override_table"} + if include_exact_mapping: + table_mapping = {parent.fqn: "earlier_table", **table_mapping} + + post_statements = child.render_post_statements( + snapshots={parent.fqn: parent_snapshot}, table_mapping=mapping_type(table_mapping) + ) + + assert post_statements[0].sql() == '"override_table"' + + +def test_resolve_table_cross_dialect_fqn_mismatch(make_snapshot: t.Callable): + """`_resolve_table`'s narrowed lookup keys `snapshots` by the caller's already-normalized + `table_name` string. That string is built with the *referencing* model's own dialect + (`self._dialect` in the `resolve_table` macro closure), while the entry in `snapshots` is + keyed by the *referenced* model's fqn, which is normalized using that model's own dialect. + + When the two models use dialects with different identifier-casing rules (e.g. a + case-insensitive dialect like duckdb referencing a model whose fqn was computed under a + case-uppercasing dialect like snowflake), the raw string lookup can miss even though + `exp.replace_tables`'s own (dialect-aware) matching -- which is what ran before this + optimization, and which the narrowed lookup's own final `exp.replace_tables` call still + performs when the key IS found -- would have matched them. + """ + + # Use explicit per-model normalization settings so this regression is independent of + # mutable process-global SQLGlot dialect settings. + parent_dialect = "snowflake,normalization_strategy=uppercase" + child_dialect = "duckdb,normalization_strategy=case_insensitive" + + @macro() + def resolve_named(evaluator, name): + return evaluator.resolve_table(name.name) + + # parent is declared/rendered under snowflake, which uppercases unquoted identifiers, so its + # fqn (the key that will appear in `snapshots`) is uppercase-quoted. + parent = load_sql_based_model( + d.parse("MODEL (name parent); SELECT 1 AS c"), dialect=parent_dialect + ) + parent_snapshot = make_snapshot(parent) + parent_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + assert parent.fqn == '"PARENT"' + + # child is declared/rendered under duckdb (case-insensitive), referencing `parent` in lowercase + child = load_sql_based_model( + d.parse( + """ + MODEL (name child); + SELECT c FROM parent; + @resolve_named('parent') + """ + ), + dialect=child_dialect, + ) + + snapshots = {parent.fqn: parent_snapshot} + post_statements = child.render_post_statements(snapshots=snapshots) + + assert len(post_statements) == 1 + resolved_sql = post_statements[0].sql() + # BUG: if this assertion fails with the resolved name still literally "parent" (unmapped) + # instead of the physical table name, the narrowed single-snapshot lookup in `_resolve_table` + # failed to find `parent` in `snapshots` due to the cross-dialect casing mismatch between the + # lookup key and the dict key, even though the table legitimately exists in `snapshots`. + assert resolved_sql == f'"sqlmesh__default"."parent__{parent_snapshot.version}"', ( + f"expected parent to resolve to its physical table name, but got {resolved_sql!r} -- " + "this indicates the narrowed snapshots.get(table_name) lookup in _resolve_table missed " + "a snapshot that the old full-mapping + exp.replace_tables path would have matched" + ) + + +def test_resolve_tables_expand_reveals_table_after_find_check(make_snapshot: t.Callable): + """Embedded-model expansion (`expand=`) runs as an `expression.transform` *before* the new + `expression.find(exp.Table)` short-circuit in `_resolve_tables`, so a table reference that + only exists *after* inlining an embedded model's query must still be seen by `find()` and + mapped. This locks in that ordering: `grandparent` is not a literal `exp.Table` node in + `child`'s original query -- it only appears once the embedded `mid` model is expanded -- and + must still resolve to its physical table name, not be silently skipped because it wasn't + present at the time `_resolve_tables` was first called.""" + + grandparent = load_sql_based_model(d.parse("MODEL (name grandparent); SELECT 1 AS c")) + grandparent_snapshot = make_snapshot(grandparent) + grandparent_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + mid = load_sql_based_model( + d.parse("MODEL (name mid, kind EMBEDDED); SELECT c FROM grandparent;") + ) + mid_snapshot = make_snapshot(mid) + mid_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + child = load_sql_based_model(d.parse("MODEL (name child); SELECT c FROM mid;")) + + snapshots = {'"grandparent"': grandparent_snapshot, '"mid"': mid_snapshot} + query = child.render_query(snapshots=snapshots) + assert query is not None + rendered_sql = query.sql() + + # the physical table name for `grandparent` must appear -- if the find(exp.Table) check had + # run before expansion (or expansion didn't feed into it), `grandparent` would remain + # unmapped in the rendered output. + assert f"grandparent__{grandparent_snapshot.version}" in rendered_sql + assert "FROM grandparent" not in rendered_sql + + +def test_resolve_table_deployability_index_consistency(make_snapshot: t.Callable): + """The narrowed `_resolve_table` single-snapshot mapping must respect `deployability_index` + identically to the full-mapping path: a non-deployable (dev-preview) snapshot should map to + its dev table, not its deployable/prod table. + + A snapshot's dev table only differs from its prod table when `dev_version_` differs from + `version` (see `Snapshot._table_name`); that normally arises from a forward-only change + against a previous version. `SnapshotChangeCategory.FORWARD_ONLY` is deprecated/blocked by + `categorize_as`, so this sets `dev_version_` directly to force that condition deterministically + without relying on a deprecated code path. + """ + from sqlmesh.core.snapshot import DeployabilityIndex + + parent = load_sql_based_model( + d.parse("MODEL (name parent); SELECT 1 AS c"), + dialect="duckdb", + ) + parent_snapshot = make_snapshot(parent) + parent_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + parent_snapshot.dev_version_ = "customdevversion123" + assert parent_snapshot.table_name(is_deployable=True) != parent_snapshot.table_name( + is_deployable=False + ) + + @macro() + def resolve_named(evaluator, name): + return evaluator.resolve_table(name.name) + + child_sql = """ + MODEL (name child); + SELECT 1 AS c; + @resolve_named('parent') + """ + + snapshots = {parent.fqn: parent_snapshot} + + # separate model instances per render call so the statement-render cache (keyed independent + # of `deployability_index`) doesn't just return the first call's cached result. + deployable_result = ( + load_sql_based_model(d.parse(child_sql)) + .render_post_statements( + snapshots=snapshots, deployability_index=DeployabilityIndex.all_deployable() + )[0] + .sql() + ) + non_deployable_result = ( + load_sql_based_model(d.parse(child_sql)) + .render_post_statements( + snapshots=snapshots, + deployability_index=DeployabilityIndex.all_deployable().with_non_deployable( + parent_snapshot + ), + )[0] + .sql() + ) + + # the narrowed single-snapshot mapping must still pick the right table for each index. + assert deployable_result != non_deployable_result + assert parent_snapshot.table_name(is_deployable=True) in deployable_result.replace('"', "") + assert parent_snapshot.table_name(is_deployable=False) in non_deployable_result.replace('"', "") + + +def test_resolve_table_table_mapping_only_dialect_mismatch(make_snapshot: t.Callable): + """When `snapshots` is empty/None, `_resolve_table`'s narrowed lookup must still fall back to + the full, dialect-reconciling mapping on a miss - not just when `snapshots` is non-empty. + + `table_name` and a `table_mapping` key can be normalized under different dialects (e.g. a + unit-test `table_mapping` built from the project's dialect vs. a model's own dialect for the + macro-resolved name), so they can disagree in casing/quoting even though an entry for this + table exists. The old exp.replace_tables-based path reconciled this via its own + normalization; a raw `table_name in table_mapping` string-equality check does not. + """ + + @macro() + def resolve_named(evaluator, name): + return evaluator.resolve_table(name.name) + + child = load_sql_based_model( + d.parse( + """ + MODEL (name child); + SELECT 1 AS c; + @resolve_named('a.b') + """ + ) + ) + + # `table_mapping` key differs from the resolved name only in quoting - a raw dict lookup on + # `'"a"."b"'` would miss `'a.b'`, but exp.replace_tables' normalization matches them. + post_statements = child.render_post_statements(snapshots=None, table_mapping={"a.b": "c"}) + assert post_statements[0].sql(comments=False) == '"c"' + + +def test_resolve_tables_skips_expand_computation_without_table_refs( + make_snapshot: t.Callable, +): + """Rendering a table-less expression (e.g. `virtual_properties`) must skip building the + `expand` set and `model_mapping` entirely, not just the final mapping/replace_tables call - + both of those are themselves O(N) in the number of snapshots when any snapshot is embedded, + so doing them for an expression with no `exp.Table` node at all defeats the point of skipping + the mapping build.""" + + embedded = load_sql_based_model(d.parse("MODEL (name embedded, kind EMBEDDED); SELECT 1 AS c")) + embedded_snapshot = make_snapshot(embedded) + embedded_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + class ItemsCountingDict(dict): + items_call_count = 0 + + def items(self): + ItemsCountingDict.items_call_count += 1 + return super().items() + + snapshots = ItemsCountingDict({embedded.fqn: embedded_snapshot}) + + model = load_sql_based_model( + d.parse( + """ + MODEL ( + name test_schema.test_model, + virtual_properties ( + labels = [('team', 'data')] + ), + ); + SELECT a FROM tbl; + """ + ) + ) + + assert model.render_virtual_properties(snapshots=snapshots) == { + "labels": exp.maybe_parse("[('team', 'data')]") + } + # `_resolve_tables` computing `expand` (which scans `snapshots.items()` for embedded + # snapshots) and `model_mapping` must not happen for a table-less expression, even though + # this environment has an embedded snapshot that would otherwise trigger both. + assert ItemsCountingDict.items_call_count == 0 + + +def test_table_mapping_normalized_keys(): + table_mapping = TableMapping({'"db"."a"': "view_a", "db.A": "view_a_upper"}) + + # Keys that normalize to the same name resolve to the last one, like exp.replace_tables. + duckdb_keys = table_mapping.normalized_keys("duckdb") + assert duckdb_keys == {"db.a": "db.A"} + # Normalization happens once per dialect, and each dialect gets its own normalization. + assert table_mapping.normalized_keys("duckdb") is duckdb_keys + assert table_mapping.normalized_keys("snowflake") == {"db.a": '"db"."a"', "DB.A": "db.A"} + + # Every mutation invalidates the cache. + table_mapping["db.b"] = "view_b" + assert "db.b" in table_mapping.normalized_keys("duckdb") + table_mapping.update({"db.c": "view_c"}) + assert "db.c" in table_mapping.normalized_keys("duckdb") + table_mapping.setdefault("db.d", "view_d") + assert "db.d" in table_mapping.normalized_keys("duckdb") + table_mapping |= {"db.e": "view_e"} + assert "db.e" in table_mapping.normalized_keys("duckdb") + del table_mapping["db.b"] + assert "db.b" not in table_mapping.normalized_keys("duckdb") + table_mapping.pop("db.c") + assert "db.c" not in table_mapping.normalized_keys("duckdb") + table_mapping.popitem() + assert "db.e" not in table_mapping.normalized_keys("duckdb") + table_mapping.clear() + assert table_mapping.normalized_keys("duckdb") == {} + + def test_cluster_with_complex_expression(): expressions = d.parse( """ diff --git a/tests/core/test_snapshot_evaluator.py b/tests/core/test_snapshot_evaluator.py index 3950e0d53f..a9ca86496a 100644 --- a/tests/core/test_snapshot_evaluator.py +++ b/tests/core/test_snapshot_evaluator.py @@ -5656,3 +5656,113 @@ def test_grants_in_production_with_dev_only_vde( # Should still apply grants to physical table when target layer is ALL or PHYSICAL sync_grants_mock.assert_called_once() assert sync_grants_mock.call_args[0][1] == {"select": ["user1"], "insert": ["role1"]} + + +def test_promote_virtual_properties_see_snapshots_by_name(mocker: MockerFixture, make_snapshot): + """Promotion receives snapshots keyed by SnapshotId, but renderers expect them keyed by name. + Virtual properties must see the same name-keyed snapshots as `on_virtual_update` does.""" + + @macro() + def upstream_version(evaluator): + upstream = evaluator.snapshots.get('"test_schema"."upstream"') + return exp.Literal.string(upstream.version if upstream else "missing") + + @macro() + def local_or_missing(evaluator, name): + value = evaluator.locals.get(name.name) + if isinstance(value, exp.Expr): + value = value.sql(evaluator.dialect, comments=False) + return exp.Literal.string(value or "missing") + + adapter_mock = mocker.patch("sqlmesh.core.engine_adapter.EngineAdapter") + adapter_mock.dialect = "duckdb" + adapter_mock.with_settings.return_value = adapter_mock + evaluator = SnapshotEvaluator(adapter_mock) + + upstream = load_sql_based_model( + d.parse("MODEL (name test_schema.upstream, kind FULL); SELECT 1 AS a") + ) + upstream_snapshot = make_snapshot(upstream) + upstream_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + model = load_sql_based_model( + d.parse( + """ + MODEL ( + name test_schema.test_model, + kind FULL, + virtual_properties ( + upstream_version = @upstream_version(), + kind_name = @local_or_missing('model_kind_name'), + this_view = @local_or_missing('this_model'), + ), + ); + SELECT a FROM test_schema.upstream + """ + ) + ) + snapshot = make_snapshot(model, nodes={upstream.fqn: upstream}) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + + snapshots = {s.snapshot_id: s for s in (upstream_snapshot, snapshot)} + environment_naming_info = EnvironmentNamingInfo(name="test_env") + evaluator.promote( + [snapshot], + environment_naming_info, + snapshots=snapshots, + table_mapping=to_view_mapping(snapshots.values(), environment_naming_info), + ) + + view_properties = adapter_mock.create_view.call_args.kwargs["view_properties"] + assert view_properties["upstream_version"] == exp.Literal.string(upstream_snapshot.version) + assert view_properties["kind_name"] == exp.Literal.string("FULL") + # The environment view mapping still takes precedence over the physical table. + assert view_properties["this_view"] == exp.Literal.string( + '"test_schema__test_env"."test_model"' + ) + + +def test_promote_resolves_this_model_with_single_mapping_entry( + mocker: MockerFixture, make_snapshot +): + """Rendering a promoted view's properties must not re-normalize the whole environment's view + mapping for every view (https://github.com/SQLMesh/sqlmesh/issues/6017).""" + adapter_mock = mocker.patch("sqlmesh.core.engine_adapter.EngineAdapter") + adapter_mock.dialect = "duckdb" + adapter_mock.with_settings.return_value = adapter_mock + evaluator = SnapshotEvaluator(adapter_mock) + + snapshots = {} + for i in range(20): + model = load_sql_based_model( + d.parse( + f""" + MODEL ( + name test_schema.model_{i}, + kind FULL, + virtual_properties (description = 'model {i}'), + ); + SELECT 1 AS a + """ + ) + ) + snapshot = make_snapshot(model) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + snapshots[snapshot.snapshot_id] = snapshot + + environment_naming_info = EnvironmentNamingInfo(name="test_env") + table_mapping = to_view_mapping(snapshots.values(), environment_naming_info) + spy = mocker.spy(exp, "replace_tables") + + evaluator.promote( + list(snapshots.values()), + environment_naming_info, + snapshots=snapshots, + table_mapping=table_mapping, + ) + + assert adapter_mock.create_view.call_count == 20 + # One call per view, to resolve `this_model`. + assert spy.call_count == 20 + for call in spy.call_args_list: + assert len(call.args[1]) == 1 From 3e0a5ca9a479ad61369105907735d14d48e698b9 Mon Sep 17 00:00:00 2001 From: Adegbite Ayoade Abel Date: Tue, 6 Oct 2026 01:21:22 +0100 Subject: [PATCH 16/62] fix(vscode): retry temp directory cleanup in the e2e fixture (#6094) Signed-off-by: Adegbite Ayoade Co-authored-by: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> --- vscode/extension/tests/fixtures.ts | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/vscode/extension/tests/fixtures.ts b/vscode/extension/tests/fixtures.ts index 6ce92c3266..c96bb23044 100644 --- a/vscode/extension/tests/fixtures.ts +++ b/vscode/extension/tests/fixtures.ts @@ -8,6 +8,33 @@ import { CodeServerContext, } from './utils_code_server' +const REMOVE_RETRY_DELAYS_MS = [100, 250, 500, 1000, 2000] + +/** + * Remove a directory, retrying with a backoff. + * + * When a test finishes, the extension host may still be writing into its + * temporary directory - the language server is shutting down, or uv is + * finishing off a virtual environment it created there. A single `fs.remove` + * then fails with `ENOTEMPTY`, which fails an otherwise passing test. + */ +const removeWithRetry = async (dir: string): Promise => { + for (let attempt = 0; ; attempt++) { + try { + await fs.remove(dir) + return + } catch (error) { + if (attempt >= REMOVE_RETRY_DELAYS_MS.length) { + console.warn(`Failed to remove directory ${dir}:`, error) + return + } + await new Promise(resolve => + setTimeout(resolve, REMOVE_RETRY_DELAYS_MS[attempt]), + ) + } + } +} + // Worker-scoped fixture to start/stop VS Code server once per worker export const test = base.extend< // eslint-disable-next-line @typescript-eslint/no-empty-object-type @@ -52,7 +79,7 @@ export const test = base.extend< // Clean up after each test console.log(`Cleaning up temporary directory: ${tempDir}`) - await fs.remove(tempDir) + await removeWithRetry(tempDir) }, // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-expect-error From 00d46edc6b5c286efffc2db3637c8abf8d16df7e Mon Sep 17 00:00:00 2001 From: Michael Day Date: Tue, 6 Oct 2026 14:15:09 -0400 Subject: [PATCH 17/62] fix(clickhouse): strip virtual catalogs from executed queries and inserts (#6036) Signed-off-by: mday-io --- sqlmesh/core/engine_adapter/clickhouse.py | 45 +++++-- tests/core/engine_adapter/test_clickhouse.py | 134 +++++++++++++++++-- 2 files changed, 163 insertions(+), 16 deletions(-) diff --git a/sqlmesh/core/engine_adapter/clickhouse.py b/sqlmesh/core/engine_adapter/clickhouse.py index 16ae5b5b51..e64cac9f0e 100644 --- a/sqlmesh/core/engine_adapter/clickhouse.py +++ b/sqlmesh/core/engine_adapter/clickhouse.py @@ -61,6 +61,21 @@ def inject_virtual_catalog(self, gateway: str) -> None: configured = self._extra_config.get("virtual_catalog") self._default_catalog = f"__{gateway}__" if configured is None else configured + def _to_sql(self, expression: exp.Expr, quote: bool = True, **kwargs: t.Any) -> str: + """Render SQL without the virtual catalog, which ClickHouse does not support.""" + if self._default_catalog and any(self._virtual_catalog_references(expression)): + expression = expression.copy() + for reference in list(self._virtual_catalog_references(expression)): + reference.set("catalog", None) + return super()._to_sql(expression, quote=quote, **kwargs) + + def _virtual_catalog_references(self, expression: exp.Expr) -> t.Iterator[exp.Expr]: + return ( + reference + for reference in expression.find_all(exp.Table, exp.Column) + if reference.text("catalog") == self._default_catalog + ) + @property def engine_run_mode(self) -> EngineRunMode: if self._extra_config.get("cloud_mode"): @@ -502,8 +517,14 @@ def _create_table_like( **kwargs: t.Any, ) -> None: """Create table with identical structure as source table""" + target_table_sql = self._strip_virtual_catalog(target_table_name).sql( + dialect=self.dialect, identify=True + ) + source_table_sql = self._strip_virtual_catalog(source_table_name).sql( + dialect=self.dialect, identify=True + ) self.execute( - f"CREATE TABLE {target_table_name}{self._on_cluster_sql()} AS {source_table_name}" + f"CREATE TABLE {target_table_sql}{self._on_cluster_sql()} AS {source_table_sql}" ) def _get_partition_ids( @@ -648,7 +669,7 @@ def _strip_virtual_catalog(self, name: "TableName") -> exp.Table: SQL is sent to the wire, since ClickHouse only supports a two-level ``[database].[table]`` naming scheme. """ - table = exp.to_table(name) + table = exp.to_table(name, dialect=self.dialect) if self._default_catalog and table.catalog == self._default_catalog: table.set("catalog", None) return table @@ -660,8 +681,12 @@ def _exchange_tables( ) -> None: from clickhouse_connect.driver.exceptions import DatabaseError # type: ignore - old_table_sql = exp.to_table(old_table_name).sql(dialect=self.dialect, identify=True) - new_table_sql = exp.to_table(new_table_name).sql(dialect=self.dialect, identify=True) + old_table_sql = self._strip_virtual_catalog(old_table_name).sql( + dialect=self.dialect, identify=True + ) + new_table_sql = self._strip_virtual_catalog(new_table_name).sql( + dialect=self.dialect, identify=True + ) try: self.execute( @@ -685,8 +710,12 @@ def _rename_table( old_table_name: TableName, new_table_name: TableName, ) -> None: - old_table_sql = exp.to_table(old_table_name).sql(dialect=self.dialect, identify=True) - new_table_sql = exp.to_table(new_table_name).sql(dialect=self.dialect, identify=True) + old_table_sql = self._strip_virtual_catalog(old_table_name).sql( + dialect=self.dialect, identify=True + ) + new_table_sql = self._strip_virtual_catalog(new_table_name).sql( + dialect=self.dialect, identify=True + ) self.execute(f"RENAME TABLE {old_table_sql} TO {new_table_sql}{self._on_cluster_sql()}") @@ -974,7 +1003,7 @@ def _build_view_properties_exp( def _build_create_comment_table_exp( self, table: exp.Table, table_comment: str, table_kind: str, **kwargs: t.Any ) -> exp.Comment | str: - table_sql = table.sql(dialect=self.dialect, identify=True) + table_sql = self._strip_virtual_catalog(table).sql(dialect=self.dialect, identify=True) truncated_comment = self._truncate_table_comment(table_comment) comment_sql = exp.Literal.string(truncated_comment).sql(dialect=self.dialect) @@ -989,7 +1018,7 @@ def _build_create_comment_column_exp( table_kind: str = "TABLE", **kwargs: t.Any, ) -> exp.Comment | str: - table_sql = table.sql(dialect=self.dialect, identify=True) + table_sql = self._strip_virtual_catalog(table).sql(dialect=self.dialect, identify=True) column_sql = exp.to_column(column_name).sql(dialect=self.dialect, identify=True) truncated_comment = self._truncate_table_comment(column_comment) diff --git a/tests/core/engine_adapter/test_clickhouse.py b/tests/core/engine_adapter/test_clickhouse.py index a3dfe0fdda..38079302d9 100644 --- a/tests/core/engine_adapter/test_clickhouse.py +++ b/tests/core/engine_adapter/test_clickhouse.py @@ -1066,7 +1066,7 @@ def test_insert_overwrite_by_condition_replace_partitioned( ) assert to_sql_calls(adapter) == [ - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + 'CREATE TABLE "__temp_target_abcd" AS "__temp_existing_records_abcd"', 'INSERT INTO "__temp_target_abcd" ("id", "ds") SELECT "id", "ds" FROM (SELECT * FROM "__temp_new_records_abcd") AS "_subquery"', 'EXCHANGE TABLES "__temp_existing_records_abcd" AND "__temp_target_abcd"', 'DROP TABLE IF EXISTS "__temp_target_abcd"', @@ -1104,7 +1104,7 @@ def test_insert_overwrite_by_condition_replace( ) to_sql_calls(adapter) == [ - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + 'CREATE TABLE "__temp_target_abcd" AS "__temp_existing_records_abcd"', 'INSERT INTO "__temp_target_abcd" ("id", "ds") SELECT "id", "ds" FROM (SELECT * FROM "__temp_new_records_abcd") AS "_subquery"', 'EXCHANGE TABLES "__temp_existing_records_abcd" AND "__temp_target_abcd"', 'DROP TABLE IF EXISTS "__temp_target_abcd"', @@ -1153,7 +1153,7 @@ def test_insert_overwrite_by_condition_where_partitioned( ) to_sql_calls(adapter) == [ - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + 'CREATE TABLE "__temp_target_abcd" AS "__temp_existing_records_abcd"', """INSERT INTO "__temp_target_abcd" ("id", "ds") SELECT "id", "ds" FROM (SELECT * FROM "__temp_new_records_abcd") AS "_subquery" WHERE "ds" BETWEEN '2024-02-15' AND '2024-04-30'""", """CREATE TABLE IF NOT EXISTS "__temp_target_abcd" ENGINE=MergeTree ORDER BY () AS SELECT DISTINCT "partition_id" FROM (SELECT "_partition_id" AS "partition_id" FROM "__temp_existing_records_abcd" WHERE "ds" BETWEEN '2024-02-15' AND '2024-04-30' UNION DISTINCT SELECT "_partition_id" AS "partition_id" FROM "__temp_target_abcd") AS "_affected_partitions\"""", """INSERT INTO "__temp_target_abcd" SELECT "id", "ds" FROM "__temp_existing_records_abcd" WHERE NOT ("ds" BETWEEN '2024-02-15' AND '2024-04-30') AND "_partition_id" IN (SELECT "partition_id" FROM "__temp_target_abcd")""", @@ -1204,12 +1204,12 @@ def test_insert_overwrite_by_condition_by_key( ) to_sql_calls(adapter) == [ - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + 'CREATE TABLE "__temp_target_abcd" AS "__temp_existing_records_abcd"', 'INSERT INTO "__temp_target_abcd" ("id", "ds") SELECT "id", "ds" FROM (SELECT DISTINCT ON ("id") * FROM "__temp_new_records_abcd") AS "_subquery"', 'INSERT INTO "__temp_target_abcd" SELECT "id", "ds" FROM "__temp_existing_records_abcd" WHERE NOT ("id" IN (SELECT "id" FROM "__temp_target_abcd"))', 'EXCHANGE TABLES "__temp_existing_records_abcd" AND "__temp_target_abcd"', 'DROP TABLE IF EXISTS "__temp_target_abcd"', - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + 'CREATE TABLE "__temp_target_abcd" AS "__temp_existing_records_abcd"', 'INSERT INTO "__temp_target_abcd" ("id", "ds") SELECT "id", "ds" FROM (SELECT * FROM "__temp_new_records_abcd") AS "_subquery"', 'INSERT INTO "__temp_target_abcd" SELECT "id", "ds" FROM "__temp_existing_records_abcd" WHERE NOT ("id" IN (SELECT "id" FROM "__temp_target_abcd"))', 'EXCHANGE TABLES "__temp_existing_records_abcd" AND "__temp_target_abcd"', @@ -1267,13 +1267,13 @@ def test_insert_overwrite_by_condition_by_key_partitioned( ) to_sql_calls(adapter) == [ - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + 'CREATE TABLE "__temp_target_abcd" AS "__temp_existing_records_abcd"', 'INSERT INTO "__temp_target_abcd" ("id", "ds") SELECT "id", "ds" FROM (SELECT DISTINCT ON ("id") * FROM "__temp_new_records_abcd") AS "_subquery"', 'CREATE TABLE IF NOT EXISTS "__temp_target_abcd" ENGINE=MergeTree ORDER BY () AS SELECT DISTINCT "partition_id" FROM (SELECT "_partition_id" AS "partition_id" FROM "__temp_existing_records_abcd" WHERE "id" IN (SELECT "id" FROM "__temp_target_abcd") UNION DISTINCT SELECT "_partition_id" AS "partition_id" FROM "__temp_target_abcd") AS "_affected_partitions"', 'INSERT INTO "__temp_target_abcd" SELECT "id", "ds" FROM "__temp_existing_records_abcd" WHERE NOT ("id" IN (SELECT "id" FROM "__temp_target_abcd")) AND "_partition_id" IN (SELECT "partition_id" FROM "__temp_target_abcd")', """ALTER TABLE "__temp_existing_records_abcd" REPLACE PARTITION ID '2' FROM "__temp_target_abcd", REPLACE PARTITION ID '1' FROM "__temp_target_abcd", REPLACE PARTITION ID '4' FROM "__temp_target_abcd", DROP PARTITION ID '3'""", 'DROP TABLE IF EXISTS "__temp_target_abcd"', - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + 'CREATE TABLE "__temp_target_abcd" AS "__temp_existing_records_abcd"', 'INSERT INTO "__temp_target_abcd" ("id", "ds") SELECT "id", "ds" FROM (SELECT * FROM "__temp_new_records_abcd") AS "_subquery"', 'CREATE TABLE IF NOT EXISTS "__temp_target_abcd" ENGINE=MergeTree ORDER BY () AS SELECT DISTINCT "partition_id" FROM (SELECT "_partition_id" AS "partition_id" FROM "__temp_existing_records_abcd" WHERE "id" IN (SELECT "id" FROM "__temp_target_abcd") UNION DISTINCT SELECT "_partition_id" AS "partition_id" FROM "__temp_target_abcd") AS "_affected_partitions"', 'INSERT INTO "__temp_target_abcd" SELECT "id", "ds" FROM "__temp_existing_records_abcd" WHERE NOT ("id" IN (SELECT "id" FROM "__temp_target_abcd")) AND "_partition_id" IN (SELECT "partition_id" FROM "__temp_target_abcd")', @@ -1316,7 +1316,7 @@ def test_insert_overwrite_by_condition_inc_by_partition( ) to_sql_calls(adapter) == [ - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + 'CREATE TABLE "__temp_target_abcd" AS "__temp_existing_records_abcd"', 'INSERT INTO "__temp_target_abcd" ("id", "ds") SELECT "id", "ds" FROM (SELECT * FROM "__temp_new_records_abcd") AS "_subquery"', """ALTER TABLE "__temp_existing_records_abcd" REPLACE PARTITION ID '1' FROM "__temp_target_abcd", REPLACE PARTITION ID '2' FROM "__temp_target_abcd", REPLACE PARTITION ID '4' FROM "__temp_target_abcd\"""", 'DROP TABLE IF EXISTS "__temp_target_abcd"', @@ -1596,6 +1596,124 @@ def test_virtual_catalog_stripped_in_alter_table(make_mocked_engine_adapter: t.C assert "ALTER TABLE" in sql_calls[0] +@pytest.mark.parametrize( + "query_sql, expected_sql", + [ + ( + 'INSERT INTO __ch_gw__.mydb.target ("id") ' + "SELECT __ch_gw__.mydb.source.id FROM __ch_gw__.mydb.source", + 'INSERT INTO "mydb"."target" ("id") SELECT "mydb"."source"."id" FROM "mydb"."source"', + ), + ( + "SELECT __ch_gw__.mydb.source.id, '__ch_gw__.literal' FROM __ch_gw__.mydb.source " + "JOIN other_catalog.otherdb.source ON __ch_gw__.mydb.source.id = " + "other_catalog.otherdb.source.id", + 'SELECT "mydb"."source"."id", \'__ch_gw__.literal\' FROM "mydb"."source" JOIN ' + '"other_catalog"."otherdb"."source" ON "mydb"."source"."id" = ' + '"other_catalog"."otherdb"."source"."id"', + ), + ], +) +def test_virtual_catalog_stripped_from_execute_queries( + make_mocked_engine_adapter: t.Callable, query_sql: str, expected_sql: str +): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter) + adapter.inject_virtual_catalog("ch_gw") + query = parse_one(query_sql, dialect="clickhouse") + original_sql = query.sql(dialect="clickhouse") + + adapter.execute(query) + + assert query.sql(dialect="clickhouse") == original_sql + assert to_sql_calls(adapter) == [expected_sql] + + +def test_virtual_catalog_stripped_from_ctas_and_delete(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter) + adapter.inject_virtual_catalog("ch_gw") + + adapter.ctas( + "__ch_gw__.mydb.target", + parse_one("SELECT __ch_gw__.mydb.source.id FROM __ch_gw__.mydb.source"), + {"id": exp.DataType.build("Int32")}, + ) + adapter.delete_from( + "__ch_gw__.mydb.target", + "__ch_gw__.mydb.target.id IN (SELECT id FROM __ch_gw__.mydb.source)", + ) + + assert to_sql_calls(adapter) == [ + 'CREATE TABLE IF NOT EXISTS "mydb"."target" ENGINE=MergeTree ORDER BY () AS ' + 'SELECT CAST("id" AS Nullable(Int32)) AS "id" FROM ' + '(SELECT "mydb"."source"."id" FROM "mydb"."source") AS "_subquery"', + 'DELETE FROM "mydb"."target" WHERE "mydb"."target"."id" IN ' + '(SELECT "id" FROM "mydb"."source")', + ] + + +def test_virtual_catalog_stripped_from_insert_overwrite( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter) + adapter.inject_virtual_catalog("ch_gw") + mocker.patch( + "sqlmesh.core.engine_adapter.EngineAdapter._get_temp_table", + return_value=exp.to_table("__ch_gw__.mydb.__temp_target_abcd"), + ) + mocker.patch("sqlmesh.core.engine_adapter.ClickhouseEngineAdapter.fetchone", return_value=None) + + source_queries, columns_to_types = adapter._get_source_queries_and_columns_to_types( + parse_one("SELECT * FROM __ch_gw__.mydb.source"), + {"id": exp.DataType.build("Int8", dialect="clickhouse")}, + "__ch_gw__.mydb.target", + ) + adapter._insert_overwrite_by_condition( + "__ch_gw__.mydb.target", source_queries, columns_to_types + ) + + assert [call.args[0] for call in adapter.cursor.execute.call_args_list] == [ + 'CREATE TABLE "mydb"."__temp_target_abcd" AS "mydb"."target"', + 'INSERT INTO "mydb"."__temp_target_abcd" ("id") SELECT "id" FROM ' + '(SELECT * FROM "mydb"."source") AS "_subquery"', + 'EXCHANGE TABLES "mydb"."target" AND "mydb"."__temp_target_abcd"', + 'DROP TABLE IF EXISTS "mydb"."__temp_target_abcd"', + ] + + +def test_virtual_catalog_stripped_from_rename_table(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter) + adapter.inject_virtual_catalog("ch_gw") + + adapter.rename_table("__ch_gw__.mydb.old_table", "__ch_gw__.mydb.new_table") + + assert [call.args[0] for call in adapter.cursor.execute.call_args_list] == [ + 'RENAME TABLE "mydb"."old_table" TO "mydb"."new_table"', + ] + + +def test_virtual_catalog_stripped_from_comments(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter) + adapter.inject_virtual_catalog("ch_gw") + + adapter._create_table_comment("__ch_gw__.mydb.target", "table comment") + adapter._create_column_comments("__ch_gw__.mydb.target", {"id": "column comment"}) + + assert [call.args[0] for call in adapter.cursor.execute.call_args_list] == [ + 'ALTER TABLE "mydb"."target" MODIFY COMMENT \'table comment\'', + 'ALTER TABLE "mydb"."target" COMMENT COLUMN "id" \'column comment\'', + ] + + +def test_three_part_names_unchanged_without_virtual_catalog( + make_mocked_engine_adapter: t.Callable, +): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter) + + adapter.execute(parse_one("SELECT * FROM __ch_gw__.mydb.source", dialect="clickhouse")) + + assert to_sql_calls(adapter) == ['SELECT * FROM "__ch_gw__"."mydb"."source"'] + + def test_virtual_catalog_stripped_from_create_view_source( make_mocked_engine_adapter: t.Callable, ): From d69c26275f979348fcd1febdeafb76dc00bf8beb Mon Sep 17 00:00:00 2001 From: Omar Jaiteh <124129023+kingjaiteh@users.noreply.github.com> Date: Wed, 7 Oct 2026 01:53:14 -0400 Subject: [PATCH 18/62] fix(duckdb): do not cascade table/view drops in DuckLake catalogs (#6034) Signed-off-by: kingjaiteh --- sqlmesh/core/engine_adapter/duckdb.py | 43 +++++++++++--- tests/core/engine_adapter/test_duckdb.py | 72 ++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 9 deletions(-) diff --git a/sqlmesh/core/engine_adapter/duckdb.py b/sqlmesh/core/engine_adapter/duckdb.py index ebfcaa7901..3666a801dd 100644 --- a/sqlmesh/core/engine_adapter/duckdb.py +++ b/sqlmesh/core/engine_adapter/duckdb.py @@ -173,16 +173,8 @@ def _create_table( track_rows_processed: bool = True, **kwargs: t.Any, ) -> None: - catalog = self.get_current_catalog() - catalog_type_tuple = self.fetchone( - exp.select("type") - .from_("duckdb_databases()") - .where(exp.column("database_name").eq(catalog)) - ) - catalog_type = catalog_type_tuple[0] if catalog_type_tuple else None - partitioned_by_exps = None - if catalog_type == "ducklake": + if self._get_catalog_type(self.get_current_catalog()) == "ducklake": partitioned_by_exps = kwargs.pop("partitioned_by", None) super()._create_table( @@ -215,6 +207,39 @@ def _create_table( ) self.execute(f"ALTER TABLE {table_name_str} SET PARTITIONED BY ({partitioned_by_str});") + def _drop_object( + self, + name: TableName | SchemaName, + exists: bool = True, + kind: str = "TABLE", + cascade: bool = False, + **drop_args: t.Any, + ) -> None: + # DuckLake catalogs do not implement DROP TABLE / DROP VIEW ... CASCADE and raise + # "Cascade Drop not supported in DuckLake". Views in DuckDB are late-binding, so + # dropping the underlying table without CASCADE is safe there. + if cascade and kind.upper() in ("TABLE", "VIEW"): + catalog = exp.to_table(name).catalog or self.get_current_catalog() + if self._get_catalog_type(catalog) == "ducklake": + cascade = False + + super()._drop_object(name=name, exists=exists, kind=kind, cascade=cascade, **drop_args) + + def _get_catalog_type(self, catalog: t.Optional[str]) -> t.Optional[str]: + """Returns the type of the given catalog (e.g. 'duckdb', 'ducklake') as reported by duckdb_databases().""" + if not catalog: + return None + catalog_type_tuple = self.fetchone( + exp.select("type") + .from_("duckdb_databases()") + .where( + exp.func("LOWER", exp.column("database_name")).eq( + exp.func("LOWER", exp.Literal.string(catalog)) + ) + ) + ) + return catalog_type_tuple[0] if catalog_type_tuple else None + @property def _is_motherduck(self) -> bool: return self._extra_config.get("is_motherduck", False) diff --git a/tests/core/engine_adapter/test_duckdb.py b/tests/core/engine_adapter/test_duckdb.py index 9fd65a6e66..696689219b 100644 --- a/tests/core/engine_adapter/test_duckdb.py +++ b/tests/core/engine_adapter/test_duckdb.py @@ -154,3 +154,75 @@ def test_ducklake_partitioning(adapter: EngineAdapter, duck_conn, tmp_path): f"SELECT * FROM __ducklake_metadata_{catalog}.main.ducklake_partition_info" ).fetchdf() assert partition_info.shape[0] == 1 + + +def test_drop_table_ducklake_no_cascade(adapter: EngineAdapter, duck_conn, tmp_path): + # DuckLake does not implement DROP TABLE/VIEW ... CASCADE, so the adapter must + # omit CASCADE for objects in a DuckLake catalog while keeping it for native catalogs. + catalog = "a_ducklake_db" + + duck_conn.install_extension("ducklake") + duck_conn.load_extension("ducklake") + duck_conn.execute( + f"ATTACH 'ducklake:{tmp_path}/{catalog}.ducklake' AS {catalog} (DATA_PATH '{tmp_path}');" + ) + + duck_conn.execute(f"CREATE SCHEMA {catalog}.phys") + duck_conn.execute(f"CREATE SCHEMA {catalog}.virt") + duck_conn.execute(f"CREATE TABLE {catalog}.phys.t (i INTEGER)") + duck_conn.execute(f"CREATE VIEW {catalog}.virt.v AS SELECT * FROM {catalog}.phys.t") + + # native catalog, cascade is passed through + duck_conn.execute("CREATE TABLE memory.main.native_t (i INTEGER)") + duck_conn.execute("CREATE VIEW memory.main.native_v AS SELECT * FROM memory.main.native_t") + + adapter.drop_table(f"{catalog}.phys.t", cascade=True) + adapter.drop_view(f"{catalog}.virt.v", cascade=True) + adapter.drop_table("memory.main.native_t", cascade=True) + adapter.drop_view("memory.main.native_v", cascade=True) + + assert not adapter.table_exists(f"{catalog}.phys.t") + assert not adapter.table_exists(f"{catalog}.virt.v") + assert not adapter.table_exists("memory.main.native_t") + assert not adapter.table_exists("memory.main.native_v") + + +def test_drop_table_ducklake_no_cascade_mixed_case_alias( + adapter: EngineAdapter, duck_conn, tmp_path +): + # Catalog aliases keep their case in duckdb_databases(), but SQLMesh normalizes + # table names to lowercase, so the catalog type lookup must be case-insensitive. + duck_conn.install_extension("ducklake") + duck_conn.load_extension("ducklake") + duck_conn.execute( + f"ATTACH 'ducklake:{tmp_path}/my_lake.ducklake' AS \"MyLake\" (DATA_PATH '{tmp_path}');" + ) + duck_conn.execute("CREATE SCHEMA MyLake.phys") + duck_conn.execute("CREATE TABLE MyLake.phys.t (i INTEGER)") + duck_conn.execute("CREATE VIEW MyLake.phys.v AS SELECT * FROM MyLake.phys.t") + + adapter.drop_table("mylake.phys.t", cascade=True) + adapter.drop_view("mylake.phys.v", cascade=True) + + assert not adapter.table_exists("mylake.phys.t") + assert not adapter.table_exists("mylake.phys.v") + + +def test_drop_object_cascade_by_catalog_type(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(DuckDBEngineAdapter) + adapter.fetchone = lambda *_args, **_kwargs: ("ducklake",) # type: ignore + + adapter.drop_table("lake.phys.t", cascade=True) + adapter.drop_view("lake.virt.v", cascade=True) + # schema cascade is supported by DuckLake and must be preserved + adapter.drop_schema("lake.virt", cascade=True) + + adapter.fetchone = lambda *_args, **_kwargs: ("duckdb",) # type: ignore + adapter.drop_table("native.phys.t", cascade=True) + + assert to_sql_calls(adapter) == [ + 'DROP TABLE IF EXISTS "lake"."phys"."t"', + 'DROP VIEW IF EXISTS "lake"."virt"."v"', + 'DROP SCHEMA IF EXISTS "lake"."virt" CASCADE', + 'DROP TABLE IF EXISTS "native"."phys"."t" CASCADE', + ] From cc8d8b0a6ea97671f81f0be48a58ec1e4607344f Mon Sep 17 00:00:00 2001 From: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> Date: Mon, 12 Oct 2026 09:36:17 -0600 Subject: [PATCH 19/62] fix(fabric): no-op warehouse create when the name already exists (#6041) Signed-off-by: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> Co-authored-by: Nick Muoh --- sqlmesh/core/engine_adapter/fabric.py | 2 +- tests/core/engine_adapter/test_fabric.py | 43 ++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/sqlmesh/core/engine_adapter/fabric.py b/sqlmesh/core/engine_adapter/fabric.py index 427a04d087..97fe5b5008 100644 --- a/sqlmesh/core/engine_adapter/fabric.py +++ b/sqlmesh/core/engine_adapter/fabric.py @@ -363,7 +363,7 @@ def create_warehouse( if ( if_not_exists - and response.status_code == 400 + and response.status_code in (400, 409) and (errorCode := response.json().get("errorCode", None)) ): if errorCode == "ItemDisplayNameAlreadyInUse": diff --git a/tests/core/engine_adapter/test_fabric.py b/tests/core/engine_adapter/test_fabric.py index d16e973e8a..a6760e9531 100644 --- a/tests/core/engine_adapter/test_fabric.py +++ b/tests/core/engine_adapter/test_fabric.py @@ -4,10 +4,12 @@ import pandas as pd # noqa: TID253 import pytest +import requests from pytest_mock import MockerFixture from sqlglot import exp, parse_one from sqlmesh.core.engine_adapter import FabricEngineAdapter +from sqlmesh.core.engine_adapter.fabric import FabricHttpClient from tests.core.engine_adapter import to_sql_calls from sqlmesh.core.engine_adapter.shared import DataObject @@ -19,6 +21,26 @@ def adapter(make_mocked_engine_adapter: t.Callable) -> FabricEngineAdapter: return make_mocked_engine_adapter(FabricEngineAdapter) +@pytest.fixture +def fabric_http_client(mocker: MockerFixture) -> FabricHttpClient: + client = FabricHttpClient( + tenant_id="tenant-id", + workspace_id="workspace-id", + client_id="client-id", + client_secret="client-secret", + ) + client.session = mocker.MagicMock() + return client + + +def _conflict_response(mocker: MockerFixture, error_code: str) -> t.Any: + resp = mocker.MagicMock() + resp.status_code = 409 + resp.json.return_value = {"errorCode": error_code} + resp.raise_for_status.side_effect = requests.HTTPError(response=resp) + return resp + + def test_get_current_catalog_uses_only_explicit_target_catalog( make_mocked_engine_adapter: t.Callable, ): @@ -451,3 +473,24 @@ def test_comments(make_mocked_engine_adapter: t.Callable, mocker: MockerFixture) create_table_comment_mock.assert_not_called() create_column_comments_mock.assert_not_called() assert to_sql_calls(adapter) == [] + + +def test_create_warehouse_already_exists_is_noop( + fabric_http_client: FabricHttpClient, mocker: MockerFixture +) -> None: + fabric_http_client.session.post.return_value = _conflict_response( + mocker, "ItemDisplayNameAlreadyInUse" + ) + + fabric_http_client.create_warehouse("my_warehouse") + + fabric_http_client.session.post.assert_called_once() + + +def test_create_warehouse_unrelated_conflict_still_raises( + fabric_http_client: FabricHttpClient, mocker: MockerFixture +) -> None: + fabric_http_client.session.post.return_value = _conflict_response(mocker, "SomeOtherError") + + with pytest.raises(requests.HTTPError): + fabric_http_client.create_warehouse("my_warehouse") From 7d8cd506b5cbab272de857af1c73fbd6315379f9 Mon Sep 17 00:00:00 2001 From: Dhruv Gupta <41189498+DG47@users.noreply.github.com> Date: Tue, 13 Oct 2026 20:14:20 -0400 Subject: [PATCH 20/62] fix(snowflake): look up last modified timestamps in each table's database (#6132) Signed-off-by: Dhruv Gupta Co-authored-by: Nick Muoh --- sqlmesh/core/engine_adapter/snowflake.py | 36 +++++++++---- tests/core/engine_adapter/test_snowflake.py | 57 +++++++++++++++++++++ 2 files changed, 84 insertions(+), 9 deletions(-) diff --git a/sqlmesh/core/engine_adapter/snowflake.py b/sqlmesh/core/engine_adapter/snowflake.py index 37ca6eee22..758e4847c1 100644 --- a/sqlmesh/core/engine_adapter/snowflake.py +++ b/sqlmesh/core/engine_adapter/snowflake.py @@ -757,14 +757,32 @@ def close(self) -> t.Any: def get_table_last_modified_ts(self, table_names: t.List[TableName]) -> t.List[int]: from sqlmesh.utils.date import to_timestamp - num_tables = len(table_names) - - query = "SELECT LAST_ALTERED FROM INFORMATION_SCHEMA.TABLES WHERE" - for i, table_name in enumerate(table_names): + # INFORMATION_SCHEMA only contains the objects of the database it belongs to, so the tables + # are grouped by database and each group is looked up in its own database's INFORMATION_SCHEMA. + # The groups are keyed on the catalog identifier rather than its name, because quoting matters + # in Snowflake: unquoted raw is the database RAW, while quoted "raw" is a different database + catalogs_to_tables: t.Dict[t.Optional[exp.Identifier], t.List[exp.Table]] = {} + for table_name in table_names: table = exp.to_table(table_name) - query += f"""(TABLE_NAME = '{table.name}' AND TABLE_SCHEMA = '{table.db}' AND TABLE_CATALOG = '{table.catalog}')""" - if i < num_tables - 1: - query += " OR " + catalogs_to_tables.setdefault(table.args.get("catalog"), []).append(table) + + results = [] + for catalog, tables in catalogs_to_tables.items(): + query = ( + exp.select("LAST_ALTERED") + .from_(exp.table_("TABLES", db="INFORMATION_SCHEMA", catalog=catalog)) + .where( + exp.or_( + *( + exp.and_( + exp.column("TABLE_NAME").eq(exp.Literal.string(table.name)), + exp.column("TABLE_SCHEMA").eq(exp.Literal.string(table.db)), + ) + for table in tables + ) + ) + ) + ) + results.extend(self.fetchall(query)) - result = self.fetchall(query) - return [to_timestamp(row[0]) for row in result] + return [to_timestamp(row[0]) for row in results] diff --git a/tests/core/engine_adapter/test_snowflake.py b/tests/core/engine_adapter/test_snowflake.py index 05f0133ec8..89f19fc588 100644 --- a/tests/core/engine_adapter/test_snowflake.py +++ b/tests/core/engine_adapter/test_snowflake.py @@ -1,4 +1,5 @@ import typing as t +from datetime import datetime, timezone import pandas as pd # noqa: TID253 import pytest @@ -14,6 +15,7 @@ from sqlmesh.core.model import load_sql_based_model from sqlmesh.core.model.definition import SqlModel from sqlmesh.core.node import IntervalUnit +from sqlmesh.utils.date import to_timestamp from sqlmesh.utils.errors import SQLMeshError from sqlmesh.utils import optional_import from tests.core.engine_adapter import to_sql_calls @@ -73,6 +75,38 @@ def test_get_data_objects_lowercases_columns( assert data_object.clustering_key == "ID" +def test_get_table_last_modified_ts_multiple_catalogs( + snowflake_mocked_engine_adapter: SnowflakeEngineAdapter, +) -> None: + adapter = snowflake_mocked_engine_adapter + adapter.cursor.fetchall.side_effect = [ + [ + (datetime(2025, 1, 1, tzinfo=timezone.utc),), + (datetime(2025, 1, 2, tzinfo=timezone.utc),), + ], + [(datetime(2025, 1, 3, tzinfo=timezone.utc),)], + ] + + result = adapter.get_table_last_modified_ts( + [ + '"ANALYTICS"."STAGING"."ORDERS"', + '"RAW"."SHOPIFY"."ORDERS"', + '"ANALYTICS"."STAGING"."CUSTOMERS"', + ] + ) + + # INFORMATION_SCHEMA only covers the database it belongs to, so each database is queried separately + assert to_sql_calls(adapter) == [ + """SELECT LAST_ALTERED FROM "ANALYTICS".INFORMATION_SCHEMA.TABLES WHERE (TABLE_NAME = 'ORDERS' AND TABLE_SCHEMA = 'STAGING') OR (TABLE_NAME = 'CUSTOMERS' AND TABLE_SCHEMA = 'STAGING')""", + """SELECT LAST_ALTERED FROM "RAW".INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'ORDERS' AND TABLE_SCHEMA = 'SHOPIFY'""", + ] + assert result == [ + to_timestamp("2025-01-01"), + to_timestamp("2025-01-02"), + to_timestamp("2025-01-03"), + ] + + @pytest.mark.parametrize( "current_warehouse, current_warehouse_exp, configured_warehouse, configured_warehouse_exp, should_change", [ @@ -171,6 +205,29 @@ def test_session( assert to_sql_calls(adapter) == expected_exception_calls +def test_get_table_last_modified_ts_quoted_and_unquoted_catalogs( + snowflake_mocked_engine_adapter: SnowflakeEngineAdapter, +) -> None: + # unquoted raw resolves to the database RAW, quoted "raw" is a different database, + # so the two must be looked up in two different information schemas + adapter = snowflake_mocked_engine_adapter + adapter.cursor.fetchall.side_effect = [ + [(datetime(2025, 1, 1, tzinfo=timezone.utc),)], + [(datetime(2025, 1, 2, tzinfo=timezone.utc),)], + ] + + result = adapter.get_table_last_modified_ts(['"raw".shopify.orders', "raw.shopify.customers"]) + + assert result == [ + to_timestamp(datetime(2025, 1, 1, tzinfo=timezone.utc)), + to_timestamp(datetime(2025, 1, 2, tzinfo=timezone.utc)), + ] + assert to_sql_calls(adapter) == [ + """SELECT LAST_ALTERED FROM "raw".INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'orders' AND TABLE_SCHEMA = 'shopify'""", + """SELECT LAST_ALTERED FROM raw.INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'customers' AND TABLE_SCHEMA = 'shopify'""", + ] + + def test_comments(make_mocked_engine_adapter: t.Callable, mocker: MockerFixture): adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter) From 7c1e4e4075c806eb30690a77e814051099d47b72 Mon Sep 17 00:00:00 2001 From: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> Date: Tue, 13 Oct 2026 19:39:49 -0600 Subject: [PATCH 21/62] fix(ci): pendulum workaround no longer needed (#6143) Signed-off-by: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> --- tests/core/test_context.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/tests/core/test_context.py b/tests/core/test_context.py index 1d87e1db18..acf9389fc6 100644 --- a/tests/core/test_context.py +++ b/tests/core/test_context.py @@ -2609,8 +2609,6 @@ def test_requirements(copy_to_temp_path: t.Callable): "dev", no_prompts=True, skip_tests=True, skip_backfill=True, auto_apply=True ).environment requirements = {"ipywidgets", "numpy", "pandas", "test_package"} - if IS_WINDOWS: - requirements.add("pendulum") assert environment.requirements["pandas"] == "2.2.2" assert set(environment.requirements) == requirements @@ -2618,10 +2616,7 @@ def test_requirements(copy_to_temp_path: t.Callable): context._excluded_requirements = {"ipywidgets", "ruamel.yaml", "ruamel.yaml.clib"} diff = context.plan_builder("dev", skip_tests=True, skip_backfill=True).build().context_diff assert set(diff.previous_requirements) == requirements - reqs = {"numpy", "pandas"} - if IS_WINDOWS: - reqs.add("pendulum") - assert set(diff.requirements) == reqs + assert set(diff.requirements) == {"numpy", "pandas"} def test_deactivate_automatic_requirement_inference(copy_to_temp_path: t.Callable): From afec21384de17f7bd6a5cec29b99788f6a4ba51d Mon Sep 17 00:00:00 2001 From: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> Date: Wed, 14 Oct 2026 19:06:49 -0600 Subject: [PATCH 22/62] fix(databricks): limiting pyarrow version to meet requirements (#6142) Signed-off-by: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> --- Makefile | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 6357d06351..ee5acbb5d1 100644 --- a/Makefile +++ b/Makefile @@ -238,7 +238,10 @@ bigquery-test: guard-BIGQUERY_KEYFILE engine-bigquery-install pytest -n auto -m "bigquery" --reruns 3 --junitxml=test-results/junit-bigquery.xml databricks-test: guard-DATABRICKS_CATALOG guard-DATABRICKS_SERVER_HOSTNAME guard-DATABRICKS_HTTP_PATH guard-DATABRICKS_CONNECT_VERSION engine-databricks-install - $(PIP) install 'databricks-connect==${DATABRICKS_CONNECT_VERSION}' + # Connect 15.3.x requires numpy<2 and pyarrow>=4 (no upper bound). Cap PyArrow + # in the same resolve that downgrades NumPy, or PyArrow 25+ is left installed + # and cannot be imported. + $(PIP) install 'databricks-connect==${DATABRICKS_CONNECT_VERSION}' 'pyarrow<25' pytest -n auto -m "databricks" --reruns 3 --junitxml=test-results/junit-databricks.xml redshift-test: guard-REDSHIFT_HOST guard-REDSHIFT_USER guard-REDSHIFT_PASSWORD guard-REDSHIFT_DATABASE engine-redshift-install From 3bd5972a67e8c37b7bae50b6ed5e35d7bf32cbe0 Mon Sep 17 00:00:00 2001 From: Michael Day Date: Wed, 14 Oct 2026 22:54:46 -0400 Subject: [PATCH 23/62] Fix: Propagate terminal worker failures and stop queued DAG work (#6140) Signed-off-by: mday-io --- sqlmesh/utils/concurrency.py | 31 ++++- tests/utils/test_concurrency.py | 215 ++++++++++++++++++++++++++++++++ 2 files changed, 240 insertions(+), 6 deletions(-) diff --git a/sqlmesh/utils/concurrency.py b/sqlmesh/utils/concurrency.py index c5f78645f6..1a9a5e2134 100644 --- a/sqlmesh/utils/concurrency.py +++ b/sqlmesh/utils/concurrency.py @@ -65,26 +65,40 @@ def run(self) -> t.Tuple[t.List[NodeExecutionFailedError[H]], t.List[H]]: return self._node_errors, self._skipped_nodes def _process_node(self, node: H, executor: Executor) -> None: + with self._unprocessed_nodes_lock: + if self._finished_future.done(): + return + try: self.fn(node) with self._unprocessed_nodes_lock: + if self._finished_future.done(): + return self._unprocessed_nodes_num -= 1 self._submit_next_nodes(executor, node) except Exception as ex: error = NodeExecutionFailedError(node) error.__cause__ = ex - if self.raise_on_error: - self._finished_future.set_exception(error) - return - with self._unprocessed_nodes_lock: + if self._finished_future.done(): + return + if self.raise_on_error: + self._finished_future.set_exception(error) + return self._unprocessed_nodes_num -= 1 self._node_errors.append(error) self._skip_next_nodes(node) + except BaseException as ex: + with self._unprocessed_nodes_lock: + if not self._finished_future.done(): + self._finished_future.set_exception(ex) def _submit_next_nodes(self, executor: Executor, processed_node: t.Optional[H] = None) -> None: + if self._finished_future.done(): + return + if not self._unprocessed_nodes_num: self._finished_future.set_result(None) return @@ -101,6 +115,9 @@ def _submit_next_nodes(self, executor: Executor, processed_node: t.Optional[H] = executor.submit(self._process_node, submitted_node, executor) def _skip_next_nodes(self, parent: H) -> None: + if self._finished_future.done(): + return + if not self._unprocessed_nodes_num: self._finished_future.set_result(None) return @@ -267,9 +284,11 @@ def concurrent_apply_to_values( def _process_value(value: A, index: int) -> None: try: - futures[index].set_result(fn(value)) - except Exception as ex: + result = fn(value) + except BaseException as ex: futures[index].set_exception(ex) + else: + futures[index].set_result(result) with ThreadPoolExecutor(max_workers=tasks_num) as pool: for index, value in enumerate(values): diff --git a/tests/utils/test_concurrency.py b/tests/utils/test_concurrency.py index 5e1e4326f7..89f9789725 100644 --- a/tests/utils/test_concurrency.py +++ b/tests/utils/test_concurrency.py @@ -1,3 +1,9 @@ +import os +import subprocess +import sys +import textwrap +from pathlib import Path + import pytest from pytest_mock.plugin import MockerFixture @@ -147,3 +153,212 @@ def test_concurrent_apply(tasks_num: int): values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] results = concurrent_apply_to_values(values, lambda x: x * 2, tasks_num) assert results == [x * 2 for x in values] + + +def _run_bounded_python(program: str) -> None: + repo_root = Path(__file__).resolve().parents[2] + env = os.environ.copy() + env["PYTHONPATH"] = os.pathsep.join( + path for path in (str(repo_root), env.get("PYTHONPATH")) if path + ) + result = subprocess.run( + [sys.executable, "-c", textwrap.dedent(program)], + cwd=repo_root, + env=env, + capture_output=True, + text=True, + timeout=8, + ) + assert result.returncode == 0, f"{result.stdout}\n{result.stderr}" + + +def test_concurrent_apply_to_values_propagates_base_exception(): + _run_bounded_python( + """ + from sqlmesh.utils.concurrency import concurrent_apply_to_values + + error = SystemExit("cancel value execution") + + def process(value): + if value == 0: + raise error + return value + + try: + concurrent_apply_to_values([0, 1], process, 2) + except SystemExit as raised: + assert raised is error + else: + raise AssertionError("the value worker cancellation was not propagated") + """ + ) + + +@pytest.mark.parametrize("raise_on_error", [True, False]) +def test_concurrent_dag_propagates_base_exception_drains_workers_and_can_be_reused( + raise_on_error: bool, +): + _run_bounded_python( + f""" + from threading import Event, Thread + + from sqlmesh.utils.concurrency import ConcurrentDAGExecutor + from sqlmesh.utils.dag import DAG + + dag = DAG() + dag.add("cancel") + dag.add("sibling") + dag.add("dependent", ["sibling"]) + error = KeyboardInterrupt("cancel execution") + release_sibling = Event() + sibling_started = Event() + called = [] + + def execute(node): + if node == "cancel": + assert sibling_started.wait(timeout=3) + raise error + if node == "sibling": + sibling_started.set() + assert release_sibling.wait(timeout=6) + called.append(node) + + executor = ConcurrentDAGExecutor(dag, execute, 2, {raise_on_error!r}) + run_errors = [] + + def run(): + try: + executor.run() + except BaseException as ex: + run_errors.append(ex) + + runner = Thread(target=run) + runner.start() + try: + assert sibling_started.wait(timeout=3) + try: + executor._finished_future.result(timeout=3) + except KeyboardInterrupt as raised: + assert raised is error + else: + raise AssertionError("the worker cancellation was not propagated") + assert runner.is_alive(), "run returned before the active worker drained" + finally: + release_sibling.set() + + runner.join(timeout=3) + assert not runner.is_alive() + assert run_errors == [error] + assert called == ["sibling"] + + second_error = SystemExit("cancel reused executor") + + def cancel_again(node): + raise second_error + + executor.fn = cancel_again + try: + executor.run() + except SystemExit as raised: + assert raised is second_error + else: + raise AssertionError("the reused executor did not propagate cancellation") + """ + ) + + +def test_concurrent_dag_fail_fast_stops_queued_work_while_aggregate_mode_continues(): + _run_bounded_python( + """ + from threading import Event, Thread + + from sqlmesh.utils.concurrency import ConcurrentDAGExecutor + from sqlmesh.utils.dag import DAG + + def make_dag(): + dag = DAG() + dag.add("fail") + dag.add("running") + dag.add("queued") + dag.add("failed_child", ["fail"]) + dag.add("running_child", ["running"]) + dag.add("queued_child", ["queued"]) + return dag + + failure = RuntimeError("fail node") + release_running = Event() + running_started = Event() + queued_started = Event() + called = [] + + def execute(node): + if node == "fail": + assert running_started.wait(timeout=3) + raise failure + if node == "running": + running_started.set() + assert release_running.wait(timeout=6) + if node == "queued": + queued_started.set() + called.append(node) + + executor = ConcurrentDAGExecutor(make_dag(), execute, 2, True) + run_errors = [] + + def run_fail_fast(): + try: + executor.run() + except BaseException as ex: + run_errors.append(ex) + + runner = Thread(target=run_fail_fast) + runner.start() + try: + assert running_started.wait(timeout=3) + try: + executor._finished_future.result(timeout=3) + except Exception as raised: + assert raised.node == "fail" + assert raised.__cause__ is failure + else: + raise AssertionError("fail-fast execution did not raise") + assert runner.is_alive(), "run returned before the active worker drained" + assert not queued_started.is_set(), "queued work started after fail-fast" + finally: + release_running.set() + + runner.join(timeout=3) + assert not runner.is_alive() + assert len(run_errors) == 1 + assert run_errors[0].node == "fail" + assert run_errors[0].__cause__ is failure + assert called == ["running"] + + release_running = Event() + running_started = Event() + queued_started = Event() + called = [] + executor = ConcurrentDAGExecutor(make_dag(), execute, 2, False) + run_results = [] + + def run_aggregate(): + run_results.append(executor.run()) + + runner = Thread(target=run_aggregate) + runner.start() + try: + assert running_started.wait(timeout=3) + assert queued_started.wait(timeout=3), "aggregate mode stopped independent work" + finally: + release_running.set() + + runner.join(timeout=3) + assert not runner.is_alive() + errors, skipped = run_results[0] + assert len(errors) == 1 + assert errors[0].node == "fail" + assert errors[0].__cause__ is failure + assert skipped == ["failed_child"] + assert set(called) == {"running", "queued", "running_child", "queued_child"} + """ + ) From d60480e315b0b14c0338058b7d576f5c9dc68736 Mon Sep 17 00:00:00 2001 From: Michael Day Date: Thu, 15 Oct 2026 11:57:24 -0400 Subject: [PATCH 24/62] fix(ci): isolate model-loading fork tests (#6145) Signed-off-by: mday-io --- Makefile | 6 +++--- pyproject.toml | 1 + tests/test_forking.py | 4 +++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index ee5acbb5d1..0d8571b33f 100644 --- a/Makefile +++ b/Makefile @@ -132,13 +132,13 @@ engine-up: engine-clickhouse-up engine-mssql-up engine-mysql-up engine-postgres- engine-down: engine-clickhouse-down engine-mssql-down engine-mysql-down engine-postgres-down engine-spark-down engine-trino-down fast-test: - pytest -n auto -m "fast and not cicdonly and not isolated" --junitxml=test-results/junit-fast-test.xml && pytest -m "isolated and not slow" && pytest -m "registry_isolation" && pytest -m "dialect_isolated" + pytest -n auto -m "fast and not cicdonly and not isolated" --junitxml=test-results/junit-fast-test.xml && pytest -m "isolated and not slow and not fork_isolated" && pytest tests/test_forking.py::test_parallel_load -m "isolated and fork_isolated and not slow" && pytest tests/test_forking.py::test_parallel_load_multi_repo -m "isolated and fork_isolated and not slow" && pytest -m "registry_isolation" && pytest -m "dialect_isolated" slow-test: - pytest -n auto -m "(fast or slow) and not cicdonly and not isolated" && pytest -m "isolated" && pytest -m "registry_isolation" && pytest -m "dialect_isolated" + pytest -n auto -m "(fast or slow) and not cicdonly and not isolated" && pytest -m "isolated and not fork_isolated" && pytest tests/test_forking.py::test_parallel_load -m "isolated and fork_isolated" && pytest tests/test_forking.py::test_parallel_load_multi_repo -m "isolated and fork_isolated" && pytest -m "registry_isolation" && pytest -m "dialect_isolated" cicd-test: - pytest -n auto -m "(fast or slow) and not pyspark and not isolated" --junitxml=test-results/junit-cicd.xml && pytest -m "pyspark" && pytest -m "isolated and not pyspark" && pytest -m "registry_isolation" && pytest -m "dialect_isolated" + pytest -n auto -m "(fast or slow) and not pyspark and not isolated" --junitxml=test-results/junit-cicd.xml && pytest -m "pyspark" && pytest -m "isolated and not pyspark and not fork_isolated" && pytest tests/test_forking.py::test_parallel_load -m "isolated and not pyspark and fork_isolated" && pytest tests/test_forking.py::test_parallel_load_multi_repo -m "isolated and not pyspark and fork_isolated" && pytest -m "registry_isolation" && pytest -m "dialect_isolated" core-fast-test: pytest -n auto -m "fast and not web and not github and not dbt and not jupyter" diff --git a/pyproject.toml b/pyproject.toml index 9b28dc7a08..378d3ffe43 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -257,6 +257,7 @@ markers = [ "remote: test that involves interacting with a remote DB", "cicdonly: test that only runs on CI/CD", "isolated: tests that need to run sequentially usually because they use fork", + "fork_isolated: tests that need their own fresh pytest process because they use fork", "dialect_isolated: tests that need to run separately due to global dialect overrides", # Test Domain Markers diff --git a/tests/test_forking.py b/tests/test_forking.py index d11379a158..6a6ceeff13 100644 --- a/tests/test_forking.py +++ b/tests/test_forking.py @@ -6,7 +6,9 @@ import concurrent.futures -pytestmark = pytest.mark.isolated +# Run each fork test in a fresh pytest process to avoid inheriting native process state from +# earlier tests. +pytestmark = [pytest.mark.isolated, pytest.mark.fork_isolated] def test_parallel_load(assert_exp_eq, mocker): From 3891d65a73926bf9dab0b9d09c45842f16eed737 Mon Sep 17 00:00:00 2001 From: Michael Day Date: Thu, 15 Oct 2026 12:53:37 -0400 Subject: [PATCH 25/62] fix(clickhouse): suppress ON CLUSTER for object DDL in a Replicated database (#6003) Signed-off-by: mday-io Signed-off-by: Michael Day Co-authored-by: Nick Muoh --- docs/integrations/engines/clickhouse.md | 6 +- sqlmesh/core/engine_adapter/base.py | 8 + sqlmesh/core/engine_adapter/clickhouse.py | 245 +++++++++++++- tests/core/engine_adapter/test_clickhouse.py | 337 +++++++++++++++++++ 4 files changed, 577 insertions(+), 19 deletions(-) diff --git a/docs/integrations/engines/clickhouse.md b/docs/integrations/engines/clickhouse.md index 4c2aab6e78..995d48e5f1 100644 --- a/docs/integrations/engines/clickhouse.md +++ b/docs/integrations/engines/clickhouse.md @@ -49,7 +49,7 @@ In general, you must be connected to a ClickHouse server to execute commands. By To associate an object with a cluster, DDL commands that create or modify it must include the text `ON CLUSTER [your cluster name]`. -If you provide a cluster name in your SQLMesh connection configuration, SQLMesh will automatically inject the `ON CLUSTER` statement into the DDL commands for all objects created while executing the project. We provide more information about clusters in SQLMesh [below](#cluster-specification). +If you provide a cluster name in your SQLMesh connection configuration, SQLMesh automatically adds `ON CLUSTER` to object DDL, except for metadata DDL targeting `Replicated` databases, which replicate those changes themselves. We provide more information about clusters in SQLMesh [below](#cluster-specification). #### ClickHouse Cloud mode @@ -96,7 +96,9 @@ For example, we could create a table `my_schema.my_table` on cluster `TheCluster To create SQLMesh objects on a cluster, provide the cluster name to the `cluster` key in the SQLMesh connection definition (see all connection parameters [below](#localbuilt-in-scheduler)). -SQLMesh will automatically inject the `ON CLUSTER` clause and cluster name you provide into all project DDL statements. +SQLMesh automatically adds the `ON CLUSTER` clause and cluster name you provide to object DDL, except for metadata DDL targeting `Replicated` databases. SQLMesh retains `ON CLUSTER` for database creation and removal and for partition operations. + +Partition overwrites in multi-shard `Replicated` databases remain unvalidated. ClickHouse can replicate an ALTER containing both `REPLACE PARTITION` and `DROP PARTITION`, which can conflict with `ON CLUSTER`. This behavior predates the metadata DDL policy described above and depends on the ClickHouse version. ## Model definition diff --git a/sqlmesh/core/engine_adapter/base.py b/sqlmesh/core/engine_adapter/base.py index 930cdf7cd4..1ac852f4f7 100644 --- a/sqlmesh/core/engine_adapter/base.py +++ b/sqlmesh/core/engine_adapter/base.py @@ -1043,12 +1043,15 @@ def _build_create_table_exp( ) -> exp.Create: exists = False if replace else exists catalog_name = None + target_table: t.Optional[exp.Table] = None if not isinstance(table_name_or_schema, exp.Schema): table_name_or_schema = exp.to_table(table_name_or_schema) catalog_name = table_name_or_schema.catalog + target_table = table_name_or_schema else: if isinstance(table_name_or_schema.this, exp.Table): catalog_name = table_name_or_schema.this.catalog + target_table = table_name_or_schema.this properties = ( self._build_table_properties_exp( @@ -1057,6 +1060,9 @@ def _build_create_table_exp( target_columns_to_types=target_columns_to_types, table_description=table_description, table_kind=table_kind, + # Passed so an adapter can vary properties by target object, not just by + # connection. Additive: every override accepts **kwargs. + table=target_table, ) if kwargs or table_description else None @@ -1364,6 +1370,8 @@ def create_view( else None ), physical_cluster=create_kwargs.pop("physical_cluster", None), + # See the note on the table-properties call site above. + table=exp.to_table(view_name), ) if create_view_properties: for view_property in create_view_properties.expressions: diff --git a/sqlmesh/core/engine_adapter/clickhouse.py b/sqlmesh/core/engine_adapter/clickhouse.py index e64cac9f0e..e385452bf3 100644 --- a/sqlmesh/core/engine_adapter/clickhouse.py +++ b/sqlmesh/core/engine_adapter/clickhouse.py @@ -3,6 +3,7 @@ import typing as t import logging import re +from functools import cached_property from sqlglot import exp, maybe_parse from sqlmesh.core.dialect import to_schema from sqlmesh.core.engine_adapter.mixins import LogicalMergeMixin @@ -31,6 +32,13 @@ logger = logging.getLogger(__name__) +# `system.databases.engine` value for a Keeper-coordinated database. Object DDL inside one +# must not carry `ON CLUSTER`: the database's own DDL log already propagates it to every +# replica, so ClickHouse rejects the redundant second fan-out outright with code 80, +# `It's not initial query. ON CLUSTER is not allowed for Replicated database.` +# Matched as a prefix so engine variants are covered without another release. +REPLICATED_DATABASE_ENGINE_PREFIX = "Replicated" + class ClickhouseEngineAdapter(EngineAdapterWithIndexSupport, LogicalMergeMixin): DIALECT = "clickhouse" @@ -209,9 +217,15 @@ def create_schema( from sqlmesh.utils.errors import SQLMeshError properties_copy = properties.copy() + # Always cluster-wide, deliberately. This is the statement that creates the + # database, including a `Replicated` one, so there is no database engine to + # consult yet and nothing for Keeper to propagate through. if self.engine_run_mode.is_cluster: properties_copy.append(exp.OnCluster(this=exp.to_identifier(self.cluster))) + # A database that previously resolved as absent may now exist, with an engine. + self._clear_database_engine_cache() + # ClickHouse does not support catalogs. When a virtual catalog has been injected # (self._default_catalog is set), strip it from the schema name. This mirrors the # SINGLE_CATALOG_ONLY branch in the set_catalog decorator, which does not apply here @@ -524,7 +538,8 @@ def _create_table_like( dialect=self.dialect, identify=True ) self.execute( - f"CREATE TABLE {target_table_sql}{self._on_cluster_sql()} AS {source_table_sql}" + f"CREATE TABLE {target_table_sql}" + f"{self._on_cluster_sql(target_table_name)} AS {source_table_sql}" ) def _get_partition_ids( @@ -688,10 +703,14 @@ def _exchange_tables( dialect=self.dialect, identify=True ) + on_cluster_sql = ( + self._on_cluster_sql(old_table_name) + if self._assert_same_on_cluster_scope("EXCHANGE TABLES", old_table_name, new_table_name) + else "" + ) + try: - self.execute( - f"EXCHANGE TABLES {old_table_sql} AND {new_table_sql}{self._on_cluster_sql()}" - ) + self.execute(f"EXCHANGE TABLES {old_table_sql} AND {new_table_sql}{on_cluster_sql}") except DatabaseError as e: if "NOT_IMPLEMENTED" in str(e): # If someone is using an old Clickhouse version, an OS that doesn't support atomic exchanges, @@ -717,11 +736,18 @@ def _rename_table( dialect=self.dialect, identify=True ) - self.execute(f"RENAME TABLE {old_table_sql} TO {new_table_sql}{self._on_cluster_sql()}") + on_cluster_sql = ( + self._on_cluster_sql(old_table_name) + if self._assert_same_on_cluster_scope("RENAME TABLE", old_table_name, new_table_name) + else "" + ) + + self.execute(f"RENAME TABLE {old_table_sql} TO {new_table_sql}{on_cluster_sql}") def delete_from(self, table_name: TableName, where: t.Union[str, exp.Expr]) -> None: - delete_expr = exp.delete(self._strip_virtual_catalog(table_name), where) - if self.engine_run_mode.is_cluster: + target_table = self._strip_virtual_catalog(table_name) + delete_expr = exp.delete(target_table, where) + if self._should_use_on_cluster(target_table): delete_expr.set("cluster", exp.OnCluster(this=exp.to_identifier(self.cluster))) self.execute(delete_expr) @@ -740,7 +766,21 @@ def alter_table( if self._default_catalog and isinstance(alter_expression.this, exp.Table): if alter_expression.this.catalog == self._default_catalog: alter_expression.this.set("catalog", None) - if self.engine_run_mode.is_cluster: + # Decided per expression, not hoisted: one call can legitimately carry + # alters against both a Replicated and a non-Replicated database. + altered_table = ( + alter_expression.this if isinstance(alter_expression.this, exp.Table) else None + ) + # Partition overwrites retain cluster fan-out to reach every shard. + alters_partitions = any( + isinstance(action, (exp.DropPartition, exp.ReplacePartition)) + for action in alter_expression.args.get("actions", []) + ) + if ( + self.engine_run_mode.is_cluster + if alters_partitions + else self._should_use_on_cluster(altered_table) + ): alter_expression.set( "cluster", exp.OnCluster(this=exp.to_identifier(self.cluster)) ) @@ -764,14 +804,24 @@ def _drop_object( kind: What kind of object to drop. Defaults to TABLE **drop_args: Any extra arguments to set on the Drop expression """ + # Dropping the database itself is always cluster-wide: the Keeper-backed DDL log + # being dropped cannot propagate its own removal, and `name` here is a database + # rather than an object inside one. + is_database = kind.upper() in ("SCHEMA", "DATABASE") + use_on_cluster = ( + self.engine_run_mode.is_cluster if is_database else self._should_use_on_cluster(name) + ) + + if is_database: + # Cheap to rebuild and easy to get wrong for one entry; drop the lot. + self._clear_database_engine_cache() + super()._drop_object( name=name, exists=exists, kind=kind, cascade=cascade, - cluster=exp.OnCluster(this=exp.to_identifier(self.cluster)) - if self.engine_run_mode.is_cluster - else None, + cluster=exp.OnCluster(this=exp.to_identifier(self.cluster)) if use_on_cluster else None, **drop_args, ) @@ -873,6 +923,7 @@ def _build_table_properties_exp( table_description: t.Optional[str] = None, table_kind: t.Optional[str] = None, empty_ctas: bool = False, + table: t.Optional[exp.Table] = None, **kwargs: t.Any, ) -> t.Optional[exp.Properties]: properties: t.List[exp.Expr] = [] @@ -951,7 +1002,7 @@ def _build_table_properties_exp( ): properties.append(partitioned_by_prop) - if self.engine_run_mode.is_cluster: + if self._should_use_on_cluster(table): properties.append(exp.OnCluster(this=exp.to_identifier(self.cluster))) if empty_ctas: @@ -976,6 +1027,7 @@ def _build_view_properties_exp( self, view_properties: t.Optional[t.Dict[str, exp.Expr]] = None, table_description: t.Optional[str] = None, + table: t.Optional[exp.Table] = None, **kwargs: t.Any, ) -> t.Optional[exp.Properties]: """Creates a SQLGlot table properties expression for view""" @@ -983,7 +1035,7 @@ def _build_view_properties_exp( view_properties_copy = view_properties.copy() if view_properties else {} - if self.engine_run_mode.is_cluster: + if self._should_use_on_cluster(table): properties.append(exp.OnCluster(this=exp.to_identifier(self.cluster))) if view_properties_copy: @@ -1008,7 +1060,7 @@ def _build_create_comment_table_exp( truncated_comment = self._truncate_table_comment(table_comment) comment_sql = exp.Literal.string(truncated_comment).sql(dialect=self.dialect) - return f"ALTER TABLE {table_sql}{self._on_cluster_sql()} MODIFY COMMENT {comment_sql}" + return f"ALTER TABLE {table_sql}{self._on_cluster_sql(table)} MODIFY COMMENT {comment_sql}" def _build_create_comment_column_exp( self, @@ -1024,10 +1076,169 @@ def _build_create_comment_column_exp( truncated_comment = self._truncate_table_comment(column_comment) comment_sql = exp.Literal.string(truncated_comment).sql(dialect=self.dialect) - return f"ALTER TABLE {table_sql}{self._on_cluster_sql()} COMMENT COLUMN {column_sql} {comment_sql}" + return ( + f"ALTER TABLE {table_sql}{self._on_cluster_sql(table)}" + f" COMMENT COLUMN {column_sql} {comment_sql}" + ) - def _on_cluster_sql(self) -> str: - if self.engine_run_mode.is_cluster: + @cached_property + def _database_engine_cache(self) -> t.Dict[str, t.Optional[str]]: + return {} + + @cached_property + def _has_replicated_database(self) -> bool: + """Whether this server hosts any Keeper-coordinated database at all. + + One probe per connection, and the reason this change costs nothing on a + deployment that has no `Replicated` database: when the answer is no, every + `ON CLUSTER` decision short-circuits without resolving a target or querying + `system.databases` again. + """ + row = self.fetchone( + exp.select(exp.func("count")) + .from_("system.databases") + .where( + exp.column("engine").like( + exp.Literal.string(f"{REPLICATED_DATABASE_ENGINE_PREFIX}%") + ) + ) + ) + return bool(row and row[0]) + + @cached_property + def _connection_database(self) -> t.Optional[str]: + """The database an unqualified object resolves to on this connection.""" + row = self.fetchone("SELECT currentDatabase()") + return str(row[0]) if row and row[0] else None + + def _clear_database_engine_cache(self) -> None: + self._database_engine_cache.clear() + # Creating or dropping a database can also change whether any Replicated one + # exists, which is what the short-circuit above depends on. + self.__dict__.pop("_has_replicated_database", None) + + def _database_engine(self, database: str) -> t.Optional[str]: + """The engine of a ClickHouse database, or None when it cannot be resolved. + + Deliberately connection-local rather than replica-wide: a `Replicated` database's + engine is uniform by construction, and `clusterAllReplicas` fails outright when any + host is down, which would turn an unrelated outage into a DDL failure. + """ + cache = self._database_engine_cache + if database in cache: + return cache[database] + + engine: t.Optional[str] = None + try: + row = self.fetchone( + exp.select("engine") + .from_("system.databases") + .where(exp.column("name").eq(exp.Literal.string(database))) + ) + if row and row[0]: + engine = str(row[0]) + except Exception as ex: + logger.warning( + f"Failed to determine engine for ClickHouse database '{database}'; " + f"keeping ON CLUSTER: {ex}" + ) + # Keep this call fail-open, but retry the lookup on the next DDL. + return None + + cache[database] = engine + return engine + + def _on_cluster_target_database(self, target: t.Optional[TableName]) -> t.Optional[str]: + """The database an object DDL statement targets, or None when unknown.""" + if target is None: + return None + + table = exp.to_table(target, dialect=self.dialect) if isinstance(target, str) else target + if not isinstance(table, exp.Table): + return None + + table = self._strip_virtual_catalog(table) + database = table.db + # An unqualified name resolves to the connection's database, not to "unknown". + if database: + return database + try: + return self._connection_database + except Exception as ex: + logger.warning( + f"Failed to determine current ClickHouse database; keeping ON CLUSTER: {ex}" + ) + return None + + def _should_use_on_cluster(self, target: t.Optional[TableName] = None) -> bool: + """Whether object DDL for `target` should carry `ON CLUSTER`. + + Inside a `Replicated` database Keeper already propagates object DDL, so adding + `ON CLUSTER` asks for a second, redundant fan-out and ClickHouse refuses the + statement with code 80 `INCORRECT_QUERY`. Without this, no object can be created + in such a database at all while the adapter is in cluster mode. + Suppression cannot be a connection-level flag: one connection can hold both an + Atomic and a `Replicated` database, and objects in the Atomic one still need + `ON CLUSTER`. + + Fails open. An unknown target, an unresolvable database, or any introspection + failure keeps today's behaviour, so this is a no-op for every deployment that has + no `Replicated` database. + """ + if not self.engine_run_mode.is_cluster: + return False + + try: + has_replicated_database = self._has_replicated_database + except Exception as ex: + logger.warning( + f"Failed to check for Replicated ClickHouse databases; keeping ON CLUSTER: {ex}" + ) + return True + + if not has_replicated_database: + return True + + database = self._on_cluster_target_database(target) + if not database: + return True + + engine = self._database_engine(database) + if engine is None: + return True + + return not engine.startswith(REPLICATED_DATABASE_ENGINE_PREFIX) + + def _on_cluster_sql(self, target: t.Optional[TableName] = None) -> str: + """Render the `ON CLUSTER` clause for object DDL against `target`. + + Omitting `target` means "target unknown" and preserves the pre-existing + behaviour of always emitting in cluster mode. + """ + if self._should_use_on_cluster(target): cluster_name = exp.to_identifier(self.cluster, quoted=True).sql(dialect=self.dialect) # type: ignore return f" ON CLUSTER {cluster_name} " return "" + + def _assert_same_on_cluster_scope( + self, operation: str, first: TableName, second: TableName + ) -> bool: + """Resolve one `ON CLUSTER` decision for a two-table statement. + + `RENAME` and `EXCHANGE` can span databases, and a single statement cannot be both + cluster-wide and Keeper-propagated. Refuse rather than pick one and be silently + half-correct on the other. + """ + from sqlmesh.utils.errors import SQLMeshError + + first_scope = self._should_use_on_cluster(first) + second_scope = self._should_use_on_cluster(second) + if first_scope != second_scope: + first_sql = exp.to_table(first, dialect=self.dialect).sql(dialect=self.dialect) + second_sql = exp.to_table(second, dialect=self.dialect).sql(dialect=self.dialect) + raise SQLMeshError( + f"Cannot {operation} between a Replicated database and a non-Replicated one: " + f"{first_sql} and {second_sql} disagree on whether object DDL carries " + "ON CLUSTER. Move both objects into databases with the same engine." + ) + return first_scope diff --git a/tests/core/engine_adapter/test_clickhouse.py b/tests/core/engine_adapter/test_clickhouse.py index 38079302d9..e0355f456d 100644 --- a/tests/core/engine_adapter/test_clickhouse.py +++ b/tests/core/engine_adapter/test_clickhouse.py @@ -11,9 +11,24 @@ from pytest_mock.plugin import MockerFixture from sqlmesh.core import dialect as d from sqlglot.optimizer.qualify_columns import quote_identifiers +from sqlmesh.utils.errors import SQLMeshError pytestmark = [pytest.mark.clickhouse, pytest.mark.engine] +_HAS_REPLICATED_DATABASE_PROPERTY = ClickhouseEngineAdapter.__dict__["_has_replicated_database"] + + +@pytest.fixture(autouse=True) +def no_replicated_database_by_default(mocker) -> None: + """Default every adapter in this module to a server with no `Replicated` database. + + That is the world these tests describe, and in it `ON CLUSTER` behaviour is exactly + what it was before the Replicated-aware policy existed. Seeding the probe keeps the + introspection query out of the asserted SQL and makes the assumption explicit. + `test_on_cluster_*` re-patches this to cover the other side. + """ + mocker.patch.object(ClickhouseEngineAdapter, "_has_replicated_database", False) + @pytest.fixture def adapter(make_mocked_engine_adapter, mocker) -> ClickhouseEngineAdapter: @@ -1755,3 +1770,325 @@ def test_create_view_source_rejects_unexpected_virtual_catalog( "__clickhouse_gw__.my_db.connection_test__dev", parse_one("SELECT * FROM unexpected_catalog.my_db.physical_view"), ) + + +# Replicated-aware ON CLUSTER policy. +# +# Inside a `Replicated` database Keeper already propagates object DDL, so emitting +# `ON CLUSTER` fans the statement out a second time and double-applies it. The policy is +# per target database, because one connection can hold both an Atomic and a `Replicated` +# database and objects in the Atomic one still need `ON CLUSTER`. + + +def _on_cluster_adapter( + make_mocked_engine_adapter: t.Callable, + mocker, + engines: t.Dict[str, t.Optional[str]], + connection_database: t.Optional[str] = "default", +) -> ClickhouseEngineAdapter: + """An adapter on a cluster whose databases have the given engines.""" + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter, cluster="my_cluster") + mocker.patch.object(ClickhouseEngineAdapter, "_has_replicated_database", True) + mocker.patch.object(ClickhouseEngineAdapter, "_connection_database", connection_database) + mocker.patch.object( + ClickhouseEngineAdapter, + "_database_engine", + lambda self, database: engines.get(database), + ) + return adapter + + +def test_on_cluster_predicate(make_mocked_engine_adapter: t.Callable, mocker): + adapter = _on_cluster_adapter( + make_mocked_engine_adapter, + mocker, + {"atomic_db": "Atomic", "replicated_db": "Replicated", "memory_db": "Memory"}, + ) + + # A Replicated target is the only case that suppresses. + assert adapter._should_use_on_cluster(exp.to_table("atomic_db.t")) is True + assert adapter._should_use_on_cluster(exp.to_table("replicated_db.t")) is False + assert adapter._should_use_on_cluster(exp.to_table("memory_db.t")) is True + + # Fails open: an unknown target or an unresolvable database keeps today's behaviour. + assert adapter._should_use_on_cluster(None) is True + assert adapter._should_use_on_cluster(exp.to_table("absent_db.t")) is True + + # A bare name resolves to the connection's database rather than counting as unknown. + mocker.patch.object(ClickhouseEngineAdapter, "_connection_database", "replicated_db") + assert adapter._should_use_on_cluster(exp.to_table("t")) is False + + +def test_on_cluster_predicate_off_cluster_never_emits( + make_mocked_engine_adapter: t.Callable, mocker +): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter) + assert adapter._should_use_on_cluster(exp.to_table("any_db.t")) is False + + +def test_on_cluster_predicate_short_circuits_without_a_replicated_database( + make_mocked_engine_adapter: t.Callable, +): + """The no-op guarantee: no Replicated database means no lookup and no behaviour change.""" + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter, cluster="my_cluster") + + assert adapter._should_use_on_cluster(exp.to_table("any_db.t")) is True + assert to_sql_calls(adapter) == [] + + +def test_on_cluster_predicate_strips_the_virtual_catalog( + make_mocked_engine_adapter: t.Callable, mocker +): + adapter = _on_cluster_adapter(make_mocked_engine_adapter, mocker, {"my_db": "Replicated"}) + adapter.inject_virtual_catalog("clickhouse_gw") + + assert adapter._should_use_on_cluster(exp.to_table("__clickhouse_gw__.my_db.t")) is False + + +def test_database_engine_lookup_is_cached_and_fails_open( + make_mocked_engine_adapter: t.Callable, mocker +): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter, cluster="my_cluster") + + fetchone = mocker.patch.object(ClickhouseEngineAdapter, "fetchone", return_value=("Atomic",)) + assert adapter._database_engine("some_db") == "Atomic" + assert adapter._database_engine("some_db") == "Atomic" + assert fetchone.call_count == 1, "engine lookup should be cached per database" + + # An introspection failure resolves to None, which the predicate treats as "emit". + mocker.patch.object(ClickhouseEngineAdapter, "fetchone", side_effect=Exception("boom")) + assert adapter._database_engine("other_db") is None + mocker.patch.object(ClickhouseEngineAdapter, "_has_replicated_database", True) + mocker.patch.object(ClickhouseEngineAdapter, "_connection_database", "default") + assert adapter._should_use_on_cluster(exp.to_table("other_db.t")) is True + + +@pytest.mark.parametrize( + ("target", "metadata_results", "expected_diagnostic"), + [ + pytest.param( + "replicated_db.t", + [RuntimeError("probe unavailable"), (1,), ("Replicated",)], + "Failed to check for Replicated ClickHouse databases; keeping ON CLUSTER: probe unavailable", + id="replicated-database-probe", + ), + pytest.param( + "replicated_db.t", + [(1,), RuntimeError("engine unavailable"), ("Replicated",)], + "Failed to determine engine for ClickHouse database 'replicated_db'; keeping ON CLUSTER: engine unavailable", + id="database-engine", + ), + pytest.param( + "t", + [ + (1,), + RuntimeError("current database unavailable"), + ("replicated_db",), + ("Replicated",), + ], + "Failed to determine current ClickHouse database; keeping ON CLUSTER: current database unavailable", + id="current-database", + ), + ], +) +def test_object_ddl_retries_failed_metadata_lookups( + make_mocked_engine_adapter: t.Callable, + mocker, + caplog, + target: str, + metadata_results: t.List[t.Any], + expected_diagnostic: str, +): + """A transient metadata failure warns once, then a successful result is cached.""" + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter, cluster="my_cluster") + # Restore the real probe because the module fixture stubs it for other tests. + mocker.patch.object( + ClickhouseEngineAdapter, + "_has_replicated_database", + _HAS_REPLICATED_DATABASE_PROPERTY, + ) + + fetchone = mocker.patch.object(adapter, "fetchone", side_effect=metadata_results) + caplog.set_level("WARNING", logger="sqlmesh.core.engine_adapter.clickhouse") + caplog.clear() + + adapter.drop_table(target) + assert [record.getMessage() for record in caplog.records] == [expected_diagnostic] + + adapter.drop_table(target) + adapter.drop_table(target) + assert [record.getMessage() for record in caplog.records] == [expected_diagnostic] + + target_sql = '"replicated_db"."t"' if "." in target else '"t"' + assert to_sql_calls(adapter) == [ + f'DROP TABLE IF EXISTS {target_sql} ON CLUSTER "my_cluster"', + f"DROP TABLE IF EXISTS {target_sql}", + f"DROP TABLE IF EXISTS {target_sql}", + ] + assert fetchone.call_count == len(metadata_results) + + +def test_on_cluster_suppressed_for_replicated_object_ddl( + make_mocked_engine_adapter: t.Callable, mocker +): + """Per-site rendering: the same statement against Atomic and Replicated targets.""" + adapter = _on_cluster_adapter( + make_mocked_engine_adapter, mocker, {"a_db": "Atomic", "r_db": "Replicated"} + ) + + adapter.delete_from(exp.to_table("a_db.t"), "x = 1") + adapter.delete_from(exp.to_table("r_db.t"), "x = 1") + adapter.drop_table("a_db.t") + adapter.drop_table("r_db.t") + adapter._create_table_like("a_db.copy", "a_db.t", exists=False) + adapter._create_table_like("r_db.copy", "r_db.t", exists=False) + + assert to_sql_calls(adapter) == [ + 'DELETE FROM "a_db"."t" ON CLUSTER "my_cluster" WHERE "x" = 1', + 'DELETE FROM "r_db"."t" WHERE "x" = 1', + 'DROP TABLE IF EXISTS "a_db"."t" ON CLUSTER "my_cluster"', + 'DROP TABLE IF EXISTS "r_db"."t"', + # The doubled space is pre-existing: _on_cluster_sql renders a padded clause. + 'CREATE TABLE "a_db"."copy" ON CLUSTER "my_cluster" AS "a_db"."t"', + 'CREATE TABLE "r_db"."copy" AS "r_db"."t"', + ] + + +def test_on_cluster_suppressed_for_replicated_create_table_and_view( + make_mocked_engine_adapter: t.Callable, mocker +): + """Covers the two shared-code property builders, which get their target from base.""" + adapter = _on_cluster_adapter( + make_mocked_engine_adapter, mocker, {"a_db": "Atomic", "r_db": "Replicated"} + ) + columns_to_types = {"id": exp.DataType.build("UInt64", dialect="clickhouse")} + + adapter.create_table("a_db.t", columns_to_types) + adapter.create_table("r_db.t", columns_to_types) + adapter.create_view("a_db.v", parse_one("SELECT 1 AS id")) + adapter.create_view("r_db.v", parse_one("SELECT 1 AS id")) + + calls = to_sql_calls(adapter) + assert 'ON CLUSTER "my_cluster"' in calls[0] + assert "ON CLUSTER" not in calls[1] + assert 'ON CLUSTER "my_cluster"' in calls[2] + assert "ON CLUSTER" not in calls[3] + + +def test_on_cluster_suppressed_for_replicated_comments( + make_mocked_engine_adapter: t.Callable, mocker +): + adapter = _on_cluster_adapter( + make_mocked_engine_adapter, mocker, {"a_db": "Atomic", "r_db": "Replicated"} + ) + + assert 'ON CLUSTER "my_cluster"' in adapter._build_create_comment_table_exp( + exp.to_table("a_db.t"), "hi", "TABLE" + ) + assert "ON CLUSTER" not in adapter._build_create_comment_table_exp( + exp.to_table("r_db.t"), "hi", "TABLE" + ) + assert 'ON CLUSTER "my_cluster"' in adapter._build_create_comment_column_exp( + exp.to_table("a_db.t"), "id", "hi" + ) + assert "ON CLUSTER" not in adapter._build_create_comment_column_exp( + exp.to_table("r_db.t"), "id", "hi" + ) + + +def test_database_ddl_is_always_on_cluster(make_mocked_engine_adapter: t.Callable, mocker): + """Carve-out. Creating or dropping the database itself is never Keeper-propagated. + + `CREATE DATABASE` is how a `Replicated` database comes into existence, so there is no + engine to consult, and a database's own DDL log cannot propagate its own removal. + """ + adapter = _on_cluster_adapter(make_mocked_engine_adapter, mocker, {"r_db": "Replicated"}) + + adapter.create_schema("r_db") + adapter.drop_schema("r_db") + + for call in to_sql_calls(adapter): + assert 'ON CLUSTER "my_cluster"' in call, call + + +def test_alter_table_decides_on_cluster_per_expression( + make_mocked_engine_adapter: t.Callable, mocker +): + """One call can carry alters against both kinds of database; it cannot be hoisted.""" + adapter = _on_cluster_adapter( + make_mocked_engine_adapter, mocker, {"a_db": "Atomic", "r_db": "Replicated"} + ) + + adapter.alter_table( + [ + parse_one("ALTER TABLE a_db.t ADD COLUMN x UInt64", dialect="clickhouse").assert_is( + exp.Alter + ), + parse_one("ALTER TABLE r_db.t ADD COLUMN x UInt64", dialect="clickhouse").assert_is( + exp.Alter + ), + ] + ) + + calls = to_sql_calls(adapter) + assert 'ON CLUSTER "my_cluster"' in calls[0] + assert "ON CLUSTER" not in calls[1] + + +@pytest.mark.parametrize("cluster", [None, "my_cluster"]) +@pytest.mark.parametrize("database_engine", ["Atomic", "Replicated"]) +@pytest.mark.parametrize("operation", ["drop", "replace", "both"]) +def test_alter_partition_keeps_on_cluster( + make_mocked_engine_adapter: t.Callable, mocker, cluster, database_engine, operation +): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter, cluster=cluster) + mocker.patch.object(ClickhouseEngineAdapter, "_has_replicated_database", True) + mocker.patch.object(ClickhouseEngineAdapter, "_database_engine", return_value=database_engine) + + # Use the same AST builder as incremental partition overwrites. + alter = adapter._build_alter_partition_exp( + exp.to_table("my_db.target"), + exp.to_table("my_db.source"), + {"1"} if operation in ("replace", "both") else set(), + {"2"} if operation in ("drop", "both") else set(), + ) + adapter.alter_table([alter]) + + actions = [] + if operation in ("replace", "both"): + actions.append('REPLACE PARTITION ID \'1\' FROM "my_db"."source"') + if operation in ("drop", "both"): + actions.append("DROP PARTITION ID '2'") + cluster_sql = ' ON CLUSTER "my_cluster"' if cluster else "" + assert to_sql_calls(adapter) == [ + f'ALTER TABLE "my_db"."target"{cluster_sql} {", ".join(actions)}' + ] + + +def test_cross_engine_rename_and_exchange_are_refused( + make_mocked_engine_adapter: t.Callable, mocker +): + """A single statement cannot be both cluster-wide and Keeper-propagated.""" + adapter = _on_cluster_adapter( + make_mocked_engine_adapter, mocker, {"a_db": "Atomic", "r_db": "Replicated"} + ) + + with pytest.raises(SQLMeshError, match="RENAME TABLE between a Replicated database"): + adapter._rename_table("a_db.t", "r_db.t") + + with pytest.raises(SQLMeshError, match="EXCHANGE TABLES between a Replicated database"): + adapter._exchange_tables("a_db.t", "r_db.t") + + +def test_creating_a_database_invalidates_the_engine_cache( + make_mocked_engine_adapter: t.Callable, mocker +): + """A database that resolved as absent may exist, with an engine, after CREATE.""" + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter, cluster="my_cluster") + adapter.__dict__["_has_replicated_database"] = True + adapter._database_engine_cache["new_db"] = None + + adapter.create_schema("new_db") + + assert "new_db" not in adapter._database_engine_cache + assert "_has_replicated_database" not in adapter.__dict__ From f180e03f817ff2bfa05ef082150eb57afb3a21c1 Mon Sep 17 00:00:00 2001 From: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:35:17 -0600 Subject: [PATCH 26/62] fix(ci): wait for blocking (#6146) Signed-off-by: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> --- tests/core/integration/test_restatement.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/tests/core/integration/test_restatement.py b/tests/core/integration/test_restatement.py index af4f8965a6..245aa9d670 100644 --- a/tests/core/integration/test_restatement.py +++ b/tests/core/integration/test_restatement.py @@ -1854,7 +1854,6 @@ def _run_restatement_plan(tmp_path: Path, config: Config, q: queue.Queue): # ensure dev is present before the restatement plan starts assert restatement_ctx.state_sync.get_environment("dev") is not None - q.put("plan_started") expected_error = None try: restatement_ctx.plan( @@ -1875,15 +1874,15 @@ def _run_restatement_plan(tmp_path: Path, config: Config, q: queue.Queue): assert q.get() == "thread_started" - try: - if e := restatement_plan_future.exception(timeout=1): - # abort early if the plan thread threw an exception - raise e - except TimeoutError: - # that's ok, we dont actually expect the plan to have finished in 1 second - pass - - assert q.get() == "plan_started" + # wait until the original model is blocked inside the restatement's evaluation + deadline = time.monotonic() + 30 + while not evaluation_lock_file_path.exists(): + if restatement_plan_future.done(): + if e := restatement_plan_future.exception(): + raise e + raise AssertionError("Restatement plan finished before it blocked on the model") + assert time.monotonic() < deadline, "Restatement plan never entered the evaluation lock" + time.sleep(0.1) # ok, now the prod restatement plan is running, let's deploy dev to prod ctx.plan(environment="prod", auto_apply=True) From c8fd5854c842bbe706afe6c89b77d7cd2d6eace1 Mon Sep 17 00:00:00 2001 From: Michael Day Date: Fri, 16 Oct 2026 11:47:15 -0400 Subject: [PATCH 27/62] Feat: Add optional per-task context propagation (#6141) Signed-off-by: mday-io --- sqlmesh/utils/concurrency.py | 62 +++++++++++++++++++++++++++------ tests/utils/test_concurrency.py | 50 ++++++++++++++++++++++++++ 2 files changed, 102 insertions(+), 10 deletions(-) diff --git a/sqlmesh/utils/concurrency.py b/sqlmesh/utils/concurrency.py index 1a9a5e2134..a4271f8072 100644 --- a/sqlmesh/utils/concurrency.py +++ b/sqlmesh/utils/concurrency.py @@ -1,6 +1,7 @@ import typing as t from concurrent.futures import Executor, Future, ThreadPoolExecutor from threading import Lock +from contextvars import Context from sqlmesh.core.snapshot import SnapshotId, SnapshotInfoLike from sqlmesh.utils.dag import DAG @@ -30,6 +31,9 @@ class ConcurrentDAGExecutor(t.Generic[H]): raise_on_error: If set to True raises an exception on a first encountered error, otherwises returns a tuple which contains a list of failed nodes and a list of skipped nodes. + context_factory: Optional factory called at each run admission. Each node runs + in a separate copy of that context, including serial execution. By default + no context is captured or copied. """ def __init__( @@ -38,11 +42,14 @@ def __init__( fn: t.Callable[[H], None], tasks_num: int, raise_on_error: bool, + context_factory: t.Optional[t.Callable[[], Context]] = None, ): self.dag = dag self.fn = fn self.tasks_num = tasks_num self.raise_on_error = raise_on_error + self.context_factory = context_factory + self._context: t.Optional[Context] = None self._init_state() @@ -55,14 +62,18 @@ def run(self) -> t.Tuple[t.List[NodeExecutionFailedError[H]], t.List[H]]: Returns: A pair which contains a list of node errors and a list of skipped nodes. """ + self._context = self.context_factory() if self.context_factory else None if self._finished_future.done(): self._init_state() - with ThreadPoolExecutor(max_workers=self.tasks_num) as pool: - with self._unprocessed_nodes_lock: - self._submit_next_nodes(pool) - self._finished_future.result() - return self._node_errors, self._skipped_nodes + try: + with ThreadPoolExecutor(max_workers=self.tasks_num) as pool: + with self._unprocessed_nodes_lock: + self._submit_next_nodes(pool) + self._finished_future.result() + return self._node_errors, self._skipped_nodes + finally: + self._context = None def _process_node(self, node: H, executor: Executor) -> None: with self._unprocessed_nodes_lock: @@ -112,7 +123,12 @@ def _submit_next_nodes(self, executor: Executor, processed_node: t.Optional[H] = for submitted_node in submitted_nodes: self._unprocessed_nodes.pop(submitted_node) - executor.submit(self._process_node, submitted_node, executor) + if self._context is None: + executor.submit(self._process_node, submitted_node, executor) + else: + executor.submit( + self._context.copy().run, self._process_node, submitted_node, executor + ) def _skip_next_nodes(self, parent: H) -> None: if self._finished_future.done(): @@ -156,6 +172,7 @@ def concurrent_apply_to_snapshots( tasks_num: int, reverse_order: bool = False, raise_on_error: bool = True, + context_factory: t.Optional[t.Callable[[], Context]] = None, ) -> t.Tuple[t.List[NodeExecutionFailedError[SnapshotId]], t.List[SnapshotId]]: """Applies a function to the given collection of snapshots concurrently while preserving the topological order between snapshots. @@ -168,6 +185,9 @@ def concurrent_apply_to_snapshots( raise_on_error: If set to True raises an exception on a first encountered error, otherwises returns a tuple which contains a list of failed nodes and a list of skipped nodes. + context_factory: Optional factory called at each run admission. Each node runs + in a separate copy of that context, including serial execution. By default + no context is captured or copied. Raises: NodeExecutionFailedError if `raise_on_error` is set to True and execution fails for any snapshot. @@ -189,6 +209,7 @@ def concurrent_apply_to_snapshots( lambda s_id: fn(snapshots_by_id[s_id]), tasks_num, raise_on_error=raise_on_error, + context_factory=context_factory, ) @@ -197,6 +218,7 @@ def concurrent_apply_to_dag( fn: t.Callable[[H], None], tasks_num: int, raise_on_error: bool = True, + context_factory: t.Optional[t.Callable[[], Context]] = None, ) -> t.Tuple[t.List[NodeExecutionFailedError[H]], t.List[H]]: """Applies a function to the given DAG concurrently while preserving the topological order between snapshots. @@ -208,6 +230,9 @@ def concurrent_apply_to_dag( raise_on_error: If set to True raises an exception on a first encountered error, otherwises returns a tuple which contains a list of failed nodes and a list of skipped nodes. + context_factory: Optional factory called at each run admission. Each node runs + in a separate copy of that context, including serial execution. By default + no context is captured or copied. Raises: NodeExecutionFailedError if `raise_on_error` is set to True and execution fails for any snapshot. @@ -219,13 +244,14 @@ def concurrent_apply_to_dag( raise ConfigError(f"Invalid number of concurrent tasks {tasks_num}") if tasks_num == 1: - return sequential_apply_to_dag(dag, fn, raise_on_error) + return sequential_apply_to_dag(dag, fn, raise_on_error, context_factory) return ConcurrentDAGExecutor( dag, fn, tasks_num, raise_on_error, + context_factory, ).run() @@ -233,7 +259,9 @@ def sequential_apply_to_dag( dag: DAG[H], fn: t.Callable[[H], None], raise_on_error: bool = True, + context_factory: t.Optional[t.Callable[[], Context]] = None, ) -> t.Tuple[t.List[NodeExecutionFailedError[H]], t.List[H]]: + context = context_factory() if context_factory else None dependencies = dag.graph node_errors: t.List[NodeExecutionFailedError[H]] = [] @@ -248,7 +276,10 @@ def sequential_apply_to_dag( continue try: - fn(node) + if context is None: + fn(node) + else: + context.copy().run(fn, node) except Exception as ex: error = NodeExecutionFailedError(node) error.__cause__ = ex @@ -266,6 +297,7 @@ def concurrent_apply_to_values( values: t.Sequence[A], fn: t.Callable[[A], R], tasks_num: int, + context_factory: t.Optional[t.Callable[[], Context]] = None, ) -> t.List[R]: """Applies a function to the given collection of values concurrently. @@ -273,12 +305,19 @@ def concurrent_apply_to_values( values: Target values. fn: The function that will be applied concurrently to each value. tasks_num: The number of concurrent tasks. + context_factory: Optional factory called once when values are admitted. Each value runs + in a separate copy of that context, including serial execution. By default no + context is captured or copied. Returns: A list of results. """ + context = context_factory() if context_factory else None + if tasks_num == 1: - return [fn(value) for value in values] + if context is None: + return [fn(value) for value in values] + return [context.copy().run(fn, value) for value in values] futures: t.List[Future] = [Future() for _ in values] @@ -292,6 +331,9 @@ def _process_value(value: A, index: int) -> None: with ThreadPoolExecutor(max_workers=tasks_num) as pool: for index, value in enumerate(values): - pool.submit(_process_value, value, index) + if context is None: + pool.submit(_process_value, value, index) + else: + pool.submit(context.copy().run, _process_value, value, index) return [f.result() for f in futures] diff --git a/tests/utils/test_concurrency.py b/tests/utils/test_concurrency.py index 89f9789725..083897fe56 100644 --- a/tests/utils/test_concurrency.py +++ b/tests/utils/test_concurrency.py @@ -2,6 +2,7 @@ import subprocess import sys import textwrap +from contextvars import ContextVar, copy_context from pathlib import Path import pytest @@ -362,3 +363,52 @@ def run_aggregate(): assert set(called) == {"running", "queued", "running_child", "queued_child"} """ ) + + +@pytest.mark.parametrize("tasks_num", [1, 3]) +def test_concurrent_apply_to_values_copies_admission_context(tasks_num: int): + value = ContextVar("admission", default="worker") + token = value.set("admitted") + + def process(item: int) -> str: + assert value.get() == "admitted" + value.set(str(item)) + return value.get() + + try: + assert concurrent_apply_to_values( + [1, 2, 3], process, tasks_num, context_factory=copy_context + ) == ["1", "2", "3"] + assert value.get() == "admitted" + default_results = concurrent_apply_to_values([1, 2, 3], lambda _: value.get(), tasks_num) + expected = "admitted" if tasks_num == 1 else "worker" + assert default_results == [expected, expected, expected] + finally: + value.reset(token) + + +@pytest.mark.parametrize("tasks_num", [1, 2]) +def test_context_admission_and_sibling_isolation(tasks_num: int): + from sqlmesh.utils.concurrency import ConcurrentDAGExecutor, concurrent_apply_to_dag + from sqlmesh.utils.dag import DAG + + consumer = ContextVar("admission", default="construction") + dag: DAG[str] = DAG() + dag.add("second", {"first"}) + seen = [] + + def execute(node): + seen.append(consumer.get()) + consumer.set(node) + + executor = ConcurrentDAGExecutor(dag, execute, tasks_num, False, copy_context) + token = consumer.set("first admission") + try: + executor.run() + consumer.set("second admission") + executor.run() + concurrent_apply_to_dag(dag, execute, tasks_num, context_factory=copy_context) + assert consumer.get() == "second admission" + finally: + consumer.reset(token) + assert seen == ["first admission"] * 2 + ["second admission"] * 4 From 02e65516a3e42895c27088a14e1fa61db9f651c3 Mon Sep 17 00:00:00 2001 From: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:31:14 -0600 Subject: [PATCH 28/62] fix(ci): add download retries on spark image (#6148) Signed-off-by: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> --- .../integration/docker/spark/Dockerfile | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/tests/core/engine_adapter/integration/docker/spark/Dockerfile b/tests/core/engine_adapter/integration/docker/spark/Dockerfile index cfbe7d1e88..a0049603f2 100644 --- a/tests/core/engine_adapter/integration/docker/spark/Dockerfile +++ b/tests/core/engine_adapter/integration/docker/spark/Dockerfile @@ -2,6 +2,12 @@ FROM bitnamilegacy/spark:3.5.2 USER root RUN install_packages curl USER 1001 -RUN curl https://jdbc.postgresql.org/download/postgresql-42.5.0.jar -o /opt/bitnami/spark/jars/postgresql-42.5.0.jar -RUN curl https://repo1.maven.org/maven2/com/amazonaws/aws-java-sdk-bundle/1.11.704/aws-java-sdk-bundle-1.11.704.jar -o /opt/bitnami/spark/jars/aws-java-sdk-bundle-1.11.704.jar -RUN curl https://repo1.maven.org/maven2/org/apache/iceberg/iceberg-spark-runtime-3.5_2.12/1.4.1/iceberg-spark-runtime-3.5_2.12-1.4.1.jar -o /opt/bitnami/spark/jars/iceberg-spark-runtime-3.5_2.12-1.4.1.jar +RUN curl --fail --show-error --location --retry 3 --retry-delay 5 --retry-all-errors \ + -o /opt/bitnami/spark/jars/postgresql-42.5.0.jar \ + https://jdbc.postgresql.org/download/postgresql-42.5.0.jar +RUN curl --fail --show-error --location --retry 3 --retry-delay 5 --retry-all-errors \ + -o /opt/bitnami/spark/jars/aws-java-sdk-bundle-1.11.704.jar \ + https://repo1.maven.org/maven2/com/amazonaws/aws-java-sdk-bundle/1.11.704/aws-java-sdk-bundle-1.11.704.jar +RUN curl --fail --show-error --location --retry 3 --retry-delay 5 --retry-all-errors \ + -o /opt/bitnami/spark/jars/iceberg-spark-runtime-3.5_2.12-1.4.1.jar \ + https://repo1.maven.org/maven2/org/apache/iceberg/iceberg-spark-runtime-3.5_2.12/1.4.1/iceberg-spark-runtime-3.5_2.12-1.4.1.jar From c0026dccfb1197e144e57730a67e30c42e67f1a3 Mon Sep 17 00:00:00 2001 From: Adegbite Ayoade Abel Date: Fri, 16 Oct 2026 22:51:55 +0100 Subject: [PATCH 29/62] ci: build the e2e virtualenv once per worker and re-enable test-vscode-e2e (#6098) Signed-off-by: Adegbite Ayoade Co-authored-by: Cortland Goffena <30168413+cmgoffena13@users.noreply.github.com> --- .github/workflows/pr.yaml | 17 +++-- vscode/extension/playwright.config.ts | 5 +- vscode/extension/tests/configuration.spec.ts | 41 ++++-------- vscode/extension/tests/fixtures.ts | 53 ++++++++++++++- .../extension/tests/lineage_settings.spec.ts | 67 ++++++++++++------- vscode/extension/tests/python_env.spec.ts | 65 ++++++++++++++---- vscode/extension/tests/utils.ts | 20 ++++++ 7 files changed, 195 insertions(+), 73 deletions(-) diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 05b737a4b7..2c18fe1e04 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -17,6 +17,7 @@ jobs: python: ${{ steps.filter.outputs.python }} client: ${{ steps.filter.outputs.client }} vscode: ${{ steps.filter.outputs.vscode }} + lsp: ${{ steps.filter.outputs.lsp }} ci: ${{ steps.filter.outputs.ci }} steps: - uses: actions/checkout@v7 @@ -37,6 +38,8 @@ jobs: - 'web/client/**' vscode: - 'vscode/**' + lsp: + - 'sqlmesh/lsp/**' ci: - '.github/**' - 'Makefile' @@ -427,10 +430,12 @@ jobs: - name: Run CI run: pnpm run ci test-vscode-e2e: - runs-on: - labels: [ubuntu-2204-8] - # As at 2026-01-12 this job flakes 100% of the time. It needs investigation - if: false + needs: changes + if: + needs.changes.outputs.vscode == 'true' || needs.changes.outputs.lsp == + 'true' || needs.changes.outputs.ci == 'true' || github.ref == + 'refs/heads/main' + runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-node@v7 @@ -453,7 +458,9 @@ jobs: source .venv/bin/activate make install-dev - name: Install code-server - run: curl -fsSL https://code-server.dev/install.sh | sh + # Pinned so that a code-server release cannot change the editor UI the + # tests drive without the change showing up here first. + run: curl -fsSL https://code-server.dev/install.sh | sh -s -- --version 4.137.0 - name: Install Playwright browsers working-directory: ./vscode/extension run: pnpm exec playwright install diff --git a/vscode/extension/playwright.config.ts b/vscode/extension/playwright.config.ts index 95d3bda589..34b883113d 100644 --- a/vscode/extension/playwright.config.ts +++ b/vscode/extension/playwright.config.ts @@ -2,7 +2,10 @@ import { defineConfig } from '@playwright/test' export default defineConfig({ testDir: 'tests', - timeout: 60_000, + // The first test a worker runs pays for the editor and extension host starting + // up, which measured at 2.5-4 minutes locally against 21-39 seconds for every + // later test in the same worker. 60 seconds only ever fit the latter. + timeout: 180_000, // TODO: When stable, allow retries in CI retries: process.env.CI ? 2 : 0, workers: process.env.CI ? 2 : 4, diff --git a/vscode/extension/tests/configuration.spec.ts b/vscode/extension/tests/configuration.spec.ts index 6f187d5274..a667d448a1 100644 --- a/vscode/extension/tests/configuration.spec.ts +++ b/vscode/extension/tests/configuration.spec.ts @@ -1,33 +1,12 @@ -import { test, expect } from './fixtures' +import { test, expect, SharedPythonEnvironment } from './fixtures' import { - createVirtualEnvironment, openServerPage, - pipInstall, - REPO_ROOT, SUSHI_SOURCE_PATH, waitForLoadedSQLMesh, } from './utils' import path from 'path' import fs from 'fs-extra' -async function setupPythonEnvironment(tempDir: string): Promise { - // Create a temporary directory for the virtual environment - const venvDir = path.join(tempDir, '.venv') - fs.mkdirSync(venvDir, { recursive: true }) - - // Create virtual environment - const pythonDetails = await createVirtualEnvironment(venvDir) - - // Install sqlmesh from the local repository with LSP support - const customMaterializations = path.join( - REPO_ROOT, - 'examples', - 'custom_materializations', - ) - const sqlmeshWithExtras = `${REPO_ROOT}[lsp,bigquery]` - await pipInstall(pythonDetails, [sqlmeshWithExtras, customMaterializations]) -} - /** * Creates an entrypoint file used to test the LSP configuration. * @@ -36,6 +15,7 @@ async function setupPythonEnvironment(tempDir: string): Promise { const createEntrypointFile = ( tempDir: string, entrypointFileName: string, + pythonEnvironment: SharedPythonEnvironment, bitToStripFromArgs = '', ): { entrypointFile: string @@ -43,7 +23,10 @@ const createEntrypointFile = ( } => { const entrypointFile = path.join(tempDir, entrypointFileName) const fileWhereStoredInputs = path.join(tempDir, 'inputs.txt') - const sqlmeshLSPFile = path.join(tempDir, '.venv/bin/sqlmesh_lsp') + const sqlmeshLSPFile = path.join( + path.dirname(pythonEnvironment.pythonPath), + 'sqlmesh_lsp', + ) // Create the entrypoint file fs.writeFileSync( @@ -69,15 +52,15 @@ test.describe('Test LSP Entrypoint configuration', () => { test('specify single entrypoint relative path', async ({ page, sharedCodeServer, + sharedPythonEnvironment, tempDir, }) => { await fs.copy(SUSHI_SOURCE_PATH, tempDir) - await setupPythonEnvironment(tempDir) - const { fileWhereStoredInputs } = createEntrypointFile( tempDir, 'entrypoint.sh', + sharedPythonEnvironment, ) const settings = { @@ -116,15 +99,15 @@ test.describe('Test LSP Entrypoint configuration', () => { test('specify one entrypoint absolute path', async ({ page, sharedCodeServer, + sharedPythonEnvironment, tempDir, }) => { await fs.copy(SUSHI_SOURCE_PATH, tempDir) - await setupPythonEnvironment(tempDir) - const { entrypointFile, fileWhereStoredInputs } = createEntrypointFile( tempDir, 'entrypoint.sh', + sharedPythonEnvironment, ) // Assert that the entrypoint file is an absolute path expect(path.isAbsolute(entrypointFile)).toBe(true) @@ -165,15 +148,15 @@ test.describe('Test LSP Entrypoint configuration', () => { test('specify entrypoint with arguments', async ({ page, sharedCodeServer, + sharedPythonEnvironment, tempDir, }) => { await fs.copy(SUSHI_SOURCE_PATH, tempDir) - await setupPythonEnvironment(tempDir) - const { fileWhereStoredInputs } = createEntrypointFile( tempDir, 'entrypoint.sh', + sharedPythonEnvironment, '--argToIgnore', ) diff --git a/vscode/extension/tests/fixtures.ts b/vscode/extension/tests/fixtures.ts index c96bb23044..0c8e8026f7 100644 --- a/vscode/extension/tests/fixtures.ts +++ b/vscode/extension/tests/fixtures.ts @@ -7,6 +7,26 @@ import { stopCodeServer, CodeServerContext, } from './utils_code_server' +import { + createVirtualEnvironment, + pipInstall, + PythonEnvironment, + REPO_ROOT, + warmUpVirtualEnvironment, +} from './utils' + +/** + * A virtual environment with sqlmesh installed, shared by every test in a + * worker that does not need an environment of its own. + */ +export interface SharedPythonEnvironment extends PythonEnvironment { + venvDir: string +} + +// Creating the environment installs sqlmesh from source, which is far slower +// than a test. Give it a budget of its own so it is not charged to the first +// test that happens to ask for it. +const SHARED_PYTHON_ENVIRONMENT_TIMEOUT_MS = 300_000 const REMOVE_RETRY_DELAYS_MS = [100, 250, 500, 1000, 2000] @@ -39,7 +59,11 @@ const removeWithRetry = async (dir: string): Promise => { export const test = base.extend< // eslint-disable-next-line @typescript-eslint/no-empty-object-type {}, - { sharedCodeServer: CodeServerContext; tempDir: string } + { + sharedCodeServer: CodeServerContext + sharedPythonEnvironment: SharedPythonEnvironment + tempDir: string + } >({ sharedCodeServer: [ // eslint-disable-next-line no-empty-pattern @@ -67,6 +91,33 @@ export const test = base.extend< }, { scope: 'worker', auto: true }, ], + sharedPythonEnvironment: [ + // eslint-disable-next-line no-empty-pattern + async ({}, use) => { + // The environment lives outside the per-test temporary directory, which + // is removed after every test. + const envDir = await fs.mkdtemp( + path.join(os.tmpdir(), 'vscode-test-shared-python-env-'), + ) + const venvDir = path.join(envDir, '.venv') + const pythonDetails = await createVirtualEnvironment(venvDir) + await pipInstall(pythonDetails, [ + `${REPO_ROOT}[lsp,bigquery]`, + path.join(REPO_ROOT, 'examples', 'custom_materializations'), + ]) + await warmUpVirtualEnvironment(pythonDetails) + + console.log( + `Created shared Python environment for worker ${test.info().workerIndex} at ${venvDir}`, + ) + + await use({ ...pythonDetails, venvDir }) + + console.log(`Removing shared Python environment: ${envDir}`) + await fs.remove(envDir) + }, + { scope: 'worker', timeout: SHARED_PYTHON_ENVIRONMENT_TIMEOUT_MS }, + ], tempDir: [ // eslint-disable-next-line no-empty-pattern async ({}, use) => { diff --git a/vscode/extension/tests/lineage_settings.spec.ts b/vscode/extension/tests/lineage_settings.spec.ts index d98ab53dff..ad13b7d399 100644 --- a/vscode/extension/tests/lineage_settings.spec.ts +++ b/vscode/extension/tests/lineage_settings.spec.ts @@ -12,24 +12,39 @@ import { createPythonInterpreterSettingsSpecifier } from './utils_code_server' /** * Find the iframe that hosts the lineage UI (the one containing the * Settings cog button). Returns null if it can't be located. + * + * The webview iframes attach asynchronously, so a single sweep can run before + * the lineage one exists and find nothing. The sweep is repeated until the + * Settings button answers from one of them or `timeout` elapses. */ -async function findLineageFrame(page: Page): Promise { - const iframes = page.locator('iframe') - const iframeCount = await iframes.count() - - for (let i = 0; i < iframeCount; i++) { - const contentFrame = iframes.nth(i).contentFrame() - if (!contentFrame) continue - const activeFrame = contentFrame.locator('#active-frame').contentFrame() - if (!activeFrame) continue - try { - await activeFrame - .getByRole('button', { name: 'Settings' }) - .waitFor({ timeout: 1000 }) - return activeFrame - } catch { - continue +async function findLineageFrame( + page: Page, + timeout = 60_000, +): Promise { + const deadline = Date.now() + timeout + + while (Date.now() < deadline) { + const iframes = page.locator('iframe') + const iframeCount = await iframes.count() + + for (let i = 0; i < iframeCount; i++) { + const contentFrame = iframes.nth(i).contentFrame() + if (!contentFrame) continue + const activeFrame = contentFrame.locator('#active-frame').contentFrame() + if (!activeFrame) continue + try { + await activeFrame + .getByRole('button', { name: 'Settings' }) + .waitFor({ timeout: 1000 }) + return activeFrame + } catch { + continue + } } + + // Nothing answered this time round; give the next webview a chance to + // attach instead of spinning when the page has no iframes yet. + await page.waitForTimeout(250) } return null } @@ -97,9 +112,11 @@ test('Only Direct Neighbors toggle filters the lineage graph', async ({ const nodesBefore = await lineageFrame.locator('.react-flow__node').count() expect(nodesBefore).toBeGreaterThan(0) - // Open the settings menu and toggle "Only Direct Neighbors" + // Open the settings menu and toggle "Only Direct Neighbors". Headless UI + // renders the entry as `