diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 5acbdac5d3..c82fc84c1e 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -4,6 +4,30 @@ updates: directory: '/' schedule: interval: 'weekly' + groups: + # Storybook add-ons declare a peer dependency on the matching `storybook` + # release, so they have to move together. Bump them in a single PR. + storybook: + patterns: + - 'storybook' + - '@storybook/*' + - '@chromatic-com/storybook' + - 'eslint-plugin-storybook' + update-types: + - 'minor' + - 'patch' + ignore: + # A Storybook major upgrade has to be done by hand as one coordinated + # migration (e.g. @storybook/addon-vitest 10 requires vitest 4+), so don't + # open per-package major-bump PRs, which break the Storybook build. + - dependency-name: 'storybook' + update-types: ['version-update:semver-major'] + - dependency-name: '@storybook/*' + update-types: ['version-update:semver-major'] + - dependency-name: '@chromatic-com/storybook' + update-types: ['version-update:semver-major'] + - dependency-name: 'eslint-plugin-storybook' + update-types: ['version-update:semver-major'] - package-ecosystem: 'github-actions' directory: '/' schedule: 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..9673dcb737 --- /dev/null +++ b/.github/workflows/db2.yaml @@ -0,0 +1,66 @@ +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 + +# Pin Ubuntu 24.04. ubuntu-latest now resolves to 26.04. +jobs: + db2-test: + runs-on: ubuntu-24.04 + 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/.github/workflows/dco.yml b/.github/workflows/dco.yml index a1c4e07300..47b5035156 100644 --- a/.github/workflows/dco.yml +++ b/.github/workflows/dco.yml @@ -1,9 +1,10 @@ name: Sanity check on: [pull_request] +# Pin Ubuntu 24.04. ubuntu-latest now resolves to 26.04. jobs: commits_check_job: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 name: Commits Check steps: - name: Get PR Commits diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 0c26d39a2f..c4a98586cf 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -10,13 +10,16 @@ concurrency: cancel-in-progress: true permissions: contents: read +# ubuntu-latest is Ubuntu 26.04. That image drops Python 3.9, installs OpenJDK 25 +# (Spark/Hadoop calls the removed Subject.getSubject), and has no Playwright Chromium. jobs: changes: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 outputs: 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 +40,8 @@ jobs: - 'web/client/**' vscode: - 'vscode/**' + lsp: + - 'sqlmesh/lsp/**' ci: - '.github/**' - 'Makefile' @@ -47,7 +52,7 @@ jobs: if: needs.changes.outputs.python == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: UV: '1' steps: @@ -73,7 +78,7 @@ jobs: if: needs.changes.outputs.python == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: @@ -147,6 +152,10 @@ jobs: . ./venv/Scripts/activate python.exe -m pip install --upgrade pip make install-dev + - name: Install DuckLake extension + run: | + . ./venv/Scripts/activate + python -c "import duckdb; duckdb.connect().install_extension('ducklake')" - name: Run fast unit tests run: | . ./venv/Scripts/activate @@ -166,7 +175,7 @@ jobs: if: needs.changes.outputs.python == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 env: SQLMESH__DISABLE_ANONYMIZED_ANALYTICS: '1' UV: '1' @@ -195,7 +204,7 @@ jobs: needs.changes.outputs.client == 'true' || needs.changes.outputs.vscode == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v7 - uses: actions/setup-node@v7 @@ -222,7 +231,7 @@ jobs: if: needs.changes.outputs.client == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 container: image: mcr.microsoft.com/playwright:v1.54.1-jammy steps: @@ -250,7 +259,7 @@ jobs: if: needs.changes.outputs.python == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 25 strategy: fail-fast: false @@ -264,6 +273,7 @@ jobs: trino, spark, clickhouse, + clickhouse-datalake, risingwave, starrocks, ] @@ -290,6 +300,9 @@ jobs: run: | source .venv/bin/activate make ${{ matrix.engine }}-test + - name: Stop DataLake services + if: ${{ always() && matrix.engine == 'clickhouse-datalake' }} + run: make clickhouse-datalake-down - name: Upload test results uses: actions/upload-artifact@v7 if: ${{ !cancelled() }} @@ -301,7 +314,7 @@ jobs: engine-tests-cloud: needs: engine-tests-docker if: github.ref == 'refs/heads/main' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 timeout-minutes: 25 strategy: fail-fast: false @@ -413,7 +426,7 @@ jobs: 'true' || github.ref == 'refs/heads/main' env: PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1 - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v7 - uses: actions/setup-node@v7 @@ -427,10 +440,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-24.04 steps: - uses: actions/checkout@v7 - uses: actions/setup-node@v7 @@ -453,7 +468,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 @@ -474,7 +491,7 @@ jobs: if: needs.changes.outputs.python == 'true' || needs.changes.outputs.ci == 'true' || github.ref == 'refs/heads/main' - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: @@ -558,7 +575,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 diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index 47fdd9ac7a..145f301769 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -5,9 +5,10 @@ on: - 'v*.*.*' permissions: contents: write +# Pin Ubuntu 24.04. ubuntu-latest now resolves to 26.04. jobs: ui-build: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v7 - uses: actions/setup-node@v7 @@ -29,7 +30,7 @@ jobs: publish: needs: ui-build - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v7 - name: Download UI build artifact @@ -40,9 +41,13 @@ jobs: - name: Set up Python uses: actions/setup-python@v7 with: - python-version: '3.10' + # 3.13.17+ bundles pip 26.2.2+, which no longer trusts the compromised eMudhra/emSign root CA. + python-version: '3.13' - name: Install uv uses: astral-sh/setup-uv@v7 + - name: Check pip includes the eMudhra/emSign CA removal + run: | + python -c "import sys, pip; v = tuple(int(p) for p in pip.__version__.split('.')[:3]); sys.exit(0 if v >= (26, 2, 2) else f'pip {pip.__version__} predates the eMudhra/emSign CA removal; need >= 26.2.2')" - name: Install build dependencies run: pip install build twine setuptools_scm - name: Publish Python package @@ -59,7 +64,7 @@ jobs: run: unset TWINE_USERNAME TWINE_PASSWORD && make publish-tests gh-release: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v7 with: diff --git a/.github/workflows/release_extension.yaml b/.github/workflows/release_extension.yaml index 832f3b466c..9abbfd82a7 100644 --- a/.github/workflows/release_extension.yaml +++ b/.github/workflows/release_extension.yaml @@ -6,9 +6,10 @@ on: description: 'Version to release (e.g., 1.0.0)' required: true type: string +# Pin Ubuntu 24.04. ubuntu-latest now resolves to 26.04. jobs: release: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - name: Checkout repository uses: actions/checkout@v7 diff --git a/.github/workflows/release_shared_js.yaml b/.github/workflows/release_shared_js.yaml index 98bc29d5df..37aed98fef 100644 --- a/.github/workflows/release_shared_js.yaml +++ b/.github/workflows/release_shared_js.yaml @@ -9,9 +9,10 @@ on: permissions: id-token: write contents: read +# Pin Ubuntu 24.04. ubuntu-latest now resolves to 26.04. jobs: release: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - name: Checkout repository uses: actions/checkout@v7 diff --git a/Makefile b/Makefile index cc167212c0..b5aebb53b5 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,5 @@ .PHONY: docs +.PHONY: clickhouse-datalake-up clickhouse-datalake-test clickhouse-datalake-down ifdef UV PIP := uv pip @@ -132,13 +133,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" @@ -192,6 +193,21 @@ engine-%-up: engine-%-install engine-docker-%-up engine-%-down: docker compose -f ./tests/core/engine_adapter/integration/docker/compose.${*}.yaml down -v +CLICKHOUSE_DATALAKE_COMPOSE = docker compose --project-name sqlmesh-clickhouse-datalake -f ./tests/core/engine_adapter/integration/docker/compose.clickhouse-datalake.yaml + +clickhouse-datalake-up: + $(CLICKHOUSE_DATALAKE_COMPOSE) up -d --wait --wait-timeout 120 clickhouse minio-init rest + $(CLICKHOUSE_DATALAKE_COMPOSE) run --build --rm seed + +clickhouse-datalake-test: + docker info >/dev/null + $(MAKE) engine-clickhouse-install + $(MAKE) clickhouse-datalake-up + SQLMESH_RUN_CLICKHOUSE_DATALAKE=1 pytest -n 0 -m "docker and clickhouse_datalake" tests/core/engine_adapter/integration/test_integration_clickhouse_datalake.py --junitxml=test-results/junit-clickhouse-datalake.xml + +clickhouse-datalake-down: + $(CLICKHOUSE_DATALAKE_COMPOSE) down -v --remove-orphans + ################## # Docker Engines # ################## @@ -222,6 +238,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 # @@ -235,7 +254,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 diff --git a/README.md b/README.md index 41f78cc138..cd375ca332 100644 --- a/README.md +++ b/README.md @@ -177,7 +177,7 @@ Follow this [example](https://sqlmesh.readthedocs.io/en/stable/examples/incremen ## Join Our Community Connect with us in the following ways: -* Join the [Tobiko Slack Community](https://tobikodata.com/slack) to ask questions, or just to say hi! +* Join the [Tobiko Slack Community](https://tobiko-data.slack.com/) to ask questions, or just to say hi! * File an issue on our [GitHub](https://github.com/SQLMesh/sqlmesh/issues/new) * Send us an email at [hello@tobikodata.com](mailto:hello@tobikodata.com) with your questions or feedback * Read our [blog](https://tobikodata.com/blog) diff --git a/docs/concepts/audits.md b/docs/concepts/audits.md index c7c7cbd190..18368cd103 100644 --- a/docs/concepts/audits.md +++ b/docs/concepts/audits.md @@ -477,7 +477,7 @@ MODEL ( #### valid_uuid, valid_uuid_non_blocking Ensures that all non-NULL rows of a column contain a string with the UUID structure. -UUID structure determined by matching regular expression `'^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`. +UUID structure determined by matching regular expression `'^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`. This example asserts that all `uuid` values have the UUID structure: 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/docs/concepts/models/managed_models.md b/docs/concepts/models/managed_models.md index 786c6aa89d..3a89434d79 100644 --- a/docs/concepts/models/managed_models.md +++ b/docs/concepts/models/managed_models.md @@ -41,7 +41,7 @@ Therefore, we try to not create managed tables unnecessarily. For example, in [f !!! warning Due to the use of normal tables for dev previews, it is possible to write a query that uses features that are available to normal tables in the target engine but not managed tables. This could result in a scenario where a plan works in a dev environment but fails when deployed to production. - We believe the cost savings are worth it, however please [reach out](https://tobikodata.com/slack) if this causes problems for you. + We believe the cost savings are worth it, however please [reach out](https://tobiko-data.slack.com/) if this causes problems for you. ## Supported Engines SQLMesh supports managed models in the following database engines: 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/guides/configuration.md b/docs/guides/configuration.md index 38f6814c8b..46c6a5da2d 100644 --- a/docs/guides/configuration.md +++ b/docs/guides/configuration.md @@ -1213,10 +1213,12 @@ Example configuration: #### Default connections/scheduler -The `default_connection`, `default_test_connection`, and `default_scheduler` keys are used to specify shared defaults across multiple gateways. +The `default_connection`, `default_test_connection`, and `default_scheduler` keys specify a connection or scheduler for gateways that do not define their own. For example, you might have a specific connection where your tests should run regardless of which gateway is being used. Instead of duplicating the test connection information in each gateway specification, specify it once in the `default_test_connection` key. +A default is only used when a gateway omits the corresponding key entirely. If a gateway specifies its own `connection`, `test_connection`, or `scheduler`, SQLMesh uses that configuration as written and ignores the default. Fields are not merged, so a gateway connection cannot inherit individual fields such as `type` from `default_connection`. Each gateway connection must be a complete connection configuration. + Example configuration specifying a Postgres default connection, in-memory DuckDB default test connection, and builtin default scheduler: === "YAML" 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/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/index.md b/docs/index.md index 83c1b0a431..05e16ef244 100644 --- a/docs/index.md +++ b/docs/index.md @@ -152,7 +152,7 @@ Follow this [example](https://sqlmesh.readthedocs.io/en/stable/examples/incremen ## Join Our Community Together, we want to build data transformation without the waste. Connect with us in the following ways: -* Join the [Tobiko Slack Community](https://tobikodata.com/slack) to ask questions, or just to say hi! +* Join the [Tobiko Slack Community](https://tobiko-data.slack.com/) to ask questions, or just to say hi! * File an issue on our [GitHub](https://github.com/SQLMesh/sqlmesh/issues/new) * Send us an email at [hello@tobikodata.com](mailto:hello@tobikodata.com) with your questions or feedback * Read our [blog](https://tobikodata.com/blog) diff --git a/docs/integrations/engines/clickhouse.md b/docs/integrations/engines/clickhouse.md index 4c2aab6e78..0fea1bda91 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 @@ -468,6 +470,57 @@ gateways: With this configuration, ClickHouse models will appear as `ch_virtual.mydb.mytable` in plan output instead of `__clickhouse__.mydb.mytable`. +### Reading catalog-backed physical tables + +When ClickHouse exposes a source catalog through a [`DataLakeCatalog`](https://clickhouse.com/docs/engines/database-engines/datalake), map that source catalog to its ClickHouse database in the connection configuration: + +```yaml +gateways: + clickhouse: + connection: + type: clickhouse + host: my-clickhouse-host + username: default + datalake_catalog_mapping: + lake: iceberg +``` + +SQLMesh renders `lake.analytics.orders` as `iceberg."analytics.orders"`. It combines the source +schema and table into one quoted table name because ClickHouse uses a two-level namespace. The +`iceberg` database must already exist and use the `DataLakeCatalog` engine. SQLMesh does not create +the database or manage its metastore or storage permissions. + +For parsed queries that read data without writing the result to a ClickHouse table, SQLMesh rewrites +mapped source catalogs and passes other foreign catalog-qualified references through unchanged. +During rendering, SQLMesh strips the configured virtual catalog prefix, even before injection. For +`INSERT ... SELECT` and other query materializations, SQLMesh rewrites mapped sources and validates +the remaining catalog-qualified sources. With a non-empty mapping, each source catalog must appear +in the mapping. When SQLMesh has injected a virtual catalog, a source can also use that catalog. +SQLMesh raises an error for other catalogs. Without a non-empty mapping or an injected virtual +catalog, SQLMesh does not apply DataLake mapping or catalog validation during materialization. + +This mapping rewrites parsed query sources. It does not rewrite table names used for metadata +operations such as `columns()` or `table_exists()`. The `sqlmesh create_external_models` command also +uses the source name as supplied when it fetches column types, so it cannot infer columns for a +source named `lake.analytics.orders` through the mapping. In a ClickHouse-only project, registering +that three-part logical name as an external model can also fail SQLMesh's schema nesting check, +because ClickHouse project models use two-part names. + +To register column metadata until mapped names are supported there, use ClickHouse's physical +two-part name in both the external model and the query. For example, use +`iceberg."analytics.orders"` for the table exposed by database `iceberg`. This matches ClickHouse's +`database."schema.table"` name and keeps the model at ClickHouse's two-part nesting level. The +mapping still lets SQLMesh render queries that use mapped logical names. Without registered +column metadata, SQLMesh cannot fully optimize those queries or produce column-level lineage. + +An injected virtual catalog takes precedence over a mapping key with the same name. SQLMesh treats +that name as its virtual catalog. Use different names for the virtual catalog and DataLakeCatalog +source catalogs. The mapping applies to query source references. It does not rewrite SQL strings +passed directly to the ClickHouse adapter or map `INSERT` targets. + +View creation rejects a source that uses another catalog when a virtual catalog is injected, even +if the mapping includes that source. Mapped-source views work when no virtual catalog is injected. + ## Local/Built-in Scheduler **Engine Adapter Type**: `clickhouse` @@ -496,3 +549,4 @@ With this configuration, ClickHouse models will appear as `ch_virtual.mydb.mytab | `connection_settings` | Additional [connection settings](https://clickhouse.com/docs/integrations/python#settings-argument) | dict | N | | `connection_pool_options` | Additional [options](https://clickhouse.com/docs/integrations/python#customizing-the-http-connection-pool) for the HTTP connection pool | dict | N | | `virtual_catalog` | Override the virtual catalog name used when ClickHouse runs alongside a catalog-aware gateway (e.g. Trino). Defaults to `__{gateway_name}__`. See [Multi-gateway setup](#multi-gateway-setup) for details. | string | N | +| `datalake_catalog_mapping` | Map source catalogs to ClickHouse DataLakeCatalog databases. See [Reading catalog-backed physical tables](#reading-catalog-backed-physical-tables). | dict | N | diff --git a/docs/integrations/engines/databricks.md b/docs/integrations/engines/databricks.md index 1a4308cd74..b50e3de494 100644 --- a/docs/integrations/engines/databricks.md +++ b/docs/integrations/engines/databricks.md @@ -270,6 +270,7 @@ The only relevant SQLMesh configuration parameter is the optional `catalog` para | `force_databricks_connect` | When running locally, force the use of Databricks Connect for all model operations (so don't use SQL Connector for SQL models) | bool | N | | `disable_databricks_connect` | When running locally, disable the use of Databricks Connect for all model operations (so use SQL Connector for all models) | bool | N | | `disable_spark_session` | Do not use SparkSession if it is available (like when running in a notebook). | bool | N | +| `force_shared_connection` | SQL Connector Only: Run all queries over a single connection instead of one per thread. With U2M OAuth, use this if the connector opens connections on its kernel backend (Reyden / Real-Time warehouses), which runs a separate browser login for each connection.| bool | N | ### Query tags 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/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. diff --git a/docs/integrations/engines/trino.md b/docs/integrations/engines/trino.md index db732f0cc1..10e7b0d9b8 100644 --- a/docs/integrations/engines/trino.md +++ b/docs/integrations/engines/trino.md @@ -19,7 +19,7 @@ pip install "trino[external-authentication-token-cache]" The trino engine adapter has been tested against the [Hive Connector](https://trino.io/docs/current/connector/hive.html), [Iceberg Connector](https://trino.io/docs/current/connector/iceberg.html), and [Delta Lake Connector](https://trino.io/docs/current/connector/delta-lake.html). -Please let us know on [Slack](https://tobikodata.com/slack) if you are wanting to use another connector or have tried another connector. +Please let us know on [Slack](https://tobiko-data.slack.com/) if you are wanting to use another connector or have tried another connector. #### Hive Connector Configuration 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/docs/quickstart/cli.md b/docs/quickstart/cli.md index 6aa4fc34ed..aac924cc71 100644 --- a/docs/quickstart/cli.md +++ b/docs/quickstart/cli.md @@ -161,7 +161,7 @@ https://sqlmesh.readthedocs.io/en/stable/quickstart/cli/ Need help? - Docs: https://sqlmesh.readthedocs.io -- Slack: https://www.tobikodata.com/slack +- Slack: https://tobiko-data.slack.com/ - GitHub: https://github.com/SQLMesh/sqlmesh/issues ``` @@ -737,4 +737,4 @@ From here, you can: * [Learn more about SQLMesh CLI commands](../reference/cli.md) * [Set up a connection to a database or SQL engine](../guides/connections.md) * [Learn more about SQLMesh concepts](../concepts/overview.md) -* [Join our Slack community](https://tobikodata.com/slack) \ No newline at end of file +* [Join our Slack community](https://tobiko-data.slack.com/) \ No newline at end of file diff --git a/docs/quickstart/notebook.md b/docs/quickstart/notebook.md index 0398fc7038..5929f0ecb8 100644 --- a/docs/quickstart/notebook.md +++ b/docs/quickstart/notebook.md @@ -333,4 +333,4 @@ From here, you can: * [Learn more about SQLMesh notebook commands](../reference/notebook.md) * [Set up a connection to a database or SQL engine](../guides/connections.md) * [Learn more about SQLMesh concepts](../concepts/overview.md) -* [Join our Slack community](https://tobikodata.com/slack) \ No newline at end of file +* [Join our Slack community](https://tobiko-data.slack.com/) \ No newline at end of file diff --git a/docs/quickstart/ui.md b/docs/quickstart/ui.md index 2891536876..2b04af9dec 100644 --- a/docs/quickstart/ui.md +++ b/docs/quickstart/ui.md @@ -416,4 +416,4 @@ From here, you can: * [Set up a connection to a database or SQL engine](../guides/connections.md) * [Learn more about SQLMesh concepts](../concepts/overview.md) -* [Join our Slack community](https://tobikodata.com/slack) \ No newline at end of file +* [Join our Slack community](https://tobiko-data.slack.com/) \ No newline at end of file diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 1ed03535b9..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 ``` @@ -623,6 +625,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/docs/reference/configuration.md b/docs/reference/configuration.md index ae036a7774..84e015e0b6 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -264,13 +264,15 @@ If a configuration contains multiple gateways, SQLMesh will use the first one in ### Default connections/scheduler -The `default_connection`, `default_test_connection`, and `default_scheduler` keys are used to specify shared defaults across multiple gateways. +The `default_connection`, `default_test_connection`, and `default_scheduler` keys specify a connection or scheduler for gateways that do not define their own. For example, you might have a specific connection where your tests should run regardless of which gateway is being used. Instead of duplicating the test connection information in each gateway specification, specify it once in the `default_test_connection` key. +A default is only used when a gateway omits the corresponding key entirely. If a gateway specifies its own `connection`, `test_connection`, or `scheduler`, SQLMesh uses that configuration as written and ignores the default. Fields are not merged, so a gateway connection cannot inherit individual fields such as `type` from `default_connection`. + | Option | Description | Type | Required | | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | :---------: | :------: | -| `default_connection` | The default connection to use if one is not specified in a gateway (Default: A DuckDB connection that creates an in-memory database) | connection | N | +| `default_connection` | The connection to use for any gateway that does not specify a `connection` | connection | N | | `default_test_connection` | The default connection to use when running tests if one is not specified in a gateway (Default: A DuckDB connection that creates an in-memory database) | connection | N | | `default_scheduler` | The default scheduler configuration to use if one is not specified in a gateway (Default: built-in scheduler) | scheduler | N | diff --git a/docs/reference/execution_observations.md b/docs/reference/execution_observations.md new file mode 100644 index 0000000000..316445d53b --- /dev/null +++ b/docs/reference/execution_observations.md @@ -0,0 +1,170 @@ +# Execution observations + +Execution observations expose native SQLMesh work to Python integrations through +an optional callback. They do not replace SQL generation, execution, retries, +transactions, or `Console` progress reporting. + +## Console observer registration + +`Console.get_execution_observer()` returns `None` by default. A `Console` +subclass can return an `Observer` callback from `sqlmesh.core.execution_observation`. +The callback receives a +phase, a read-only mapping of facts, and the original exception or `None`. +For general Python integration details, see the [Python API reference](./python.md). + +The following console prints the kind, action, and finish error for each observed +operation. The example uses `examples/sushi` relative to the SQLMesh repository root: + +```python +from typing import Any, Literal, Mapping, Optional + +from sqlmesh.core.console import TerminalConsole, set_console +from sqlmesh.core.context import Context +from sqlmesh.core.execution_observation import Observer + + +def observe( + phase: Literal["start", "finish"], + facts: Mapping[str, Any], + error: Optional[BaseException], +) -> None: + if phase == "finish": + print(f"{facts['kind']}/{facts['action']}: error={error!r}") + + +class ObservedConsole(TerminalConsole): + def get_execution_observer(self) -> Optional[Observer]: + return observe + + +set_console(ObservedConsole()) +context = Context(paths=["examples/sushi"]) +``` + +A `Context` uses the `Console` that was current when the context was created. +Unless an explicit `observer_scope()` is active, SQLMesh resolves +`get_execution_observer()` once for each outer plan evaluation or scheduler run. +Nested calls reuse that observer. If the getter raises an ordinary `Exception`, +SQLMesh disables observation for that plan evaluation or scheduler run and +continues native work. + +## Observer scopes + +`observer_scope(observer)` from `sqlmesh.core.execution_observation` sets the +observer for the duration of the scope. A nested scope restores the previously +active observer when it exits. `observer_scope(None)` disables observation inside +that scope, including automatic Console registration. + +## Callback lifecycle + +SQLMesh calls `start` before observed work with `error=None`. When `start` +returns or raises an ordinary `Exception`, SQLMesh continues the work and calls +`finish` from a `finally` block afterward. The `finish` callback receives the +original workload exception object or `None`. Both callbacks run synchronously +on the thread that performs the observed work. Callbacks for work dispatched to +a worker run on that worker's thread. + +Every invocation that reaches `finish` passes the same read-only mapping object +to `start` and `finish`. Distinct invocations use distinct mapping objects. +Consumers can pair the phases by mapping identity. SQLMesh may add facts while +the work runs, so values in the mapping at `finish` can differ from its values +at `start`. The mapping's supported lifetime ends when the matching `finish` +callback returns. + +Ordinary observer `Exception` failures are suppressed and do not replace the +workload result or error. SQLMesh does not suppress observer-raised +`BaseException` subclasses that are not `Exception` subclasses, such as +`KeyboardInterrupt` and `SystemExit`. If `start` raises a `BaseException` that +is not an `Exception`, the work and `finish` callback do not run. If `finish` +raises a `BaseException` that is not an `Exception`, that failure can replace +the workload error. + +If a worker raises a `BaseException`, the error can reach the caller after its +worker pool exits. If a DAG run records a terminal error, SQLMesh stops +scheduling nodes and waits for running workers to exit before it raises that +error. Parallel value operations also wait for their workers to finish before +raising a worker's `BaseException`. Blocking callbacks and process termination +are outside the observer failure guarantee. SQLMesh does not log observer +failures. + +Nested workload calls produce nested observations. Callbacks for concurrent +workers can interleave, and SQLMesh provides no global callback order. Observers +must support concurrent calls and return promptly. SQLMesh allocates no +execution IDs, timestamps, durations, or parent IDs. Consumers supply those +values when needed. + +While SQLMesh delivers a callback, it suppresses observations triggered by that +callback and ignores calls to `update_execution()`. The guard covers callback +delivery only. Normal model work can still contain observations for physical +operations, audits, and queries. + +## Native facts and limits + +Every facts mapping contains `kind` and `action`. Other fields depend on the +observed operation and can be absent when work exits early or fails. + +| Kind | Action | Native facts | +| --- | --- | --- | +| `stage` | Plan-stage class name | `native_plan_id` | +| `model` | `evaluate`, `audit_only` | `snapshot`, `interval`, `batch_index`, `execution_time`, `audit_only` | +| `physical` | `create`, `materialize`, `schema_migration` | `snapshot`; `target` when known; `creating` for materialization; `existed` for schema migration when known | +| `virtual` | `promote`, `demote` | `snapshot`; `target` when known; `source_table` for promotion when known | +| `audit` | `audit` | `audit_name`; `audit_result` at finish if produced | +| `query` | `execute` | `engine` dialect string | + +[`Snapshot`](../concepts/architecture/snapshots.md) and `AuditResult` values are +borrowed native objects. Consumers must +treat these objects and other nested values as read-only and must not retain them +beyond the matching `finish` callback. The mapping's read-only wrapper does not +freeze nested objects. Facts are not a JSON event schema. SQLMesh does not +interpret audit results as consumer statuses or inherit model facts into child +mappings. Consumers that need facts after `finish` copy and normalize those +values during the callback. + +SQLMesh calls `finish` for an audit before it runs later audits or completes +write-audit-publish (WAP). A later audit or WAP publication can still fail. An audit +query failure can produce a `finish` callback without an `AuditResult`. The +[audits guide](../concepts/audits.md) describes audit behavior in plans and +runs. + +For `physical/materialize`, `target` is the logical destination table from the +snapshot. During WAP, SQLMesh writes to a staging destination, but the `target` +fact remains the logical destination. The `finish` callback runs after the +materialization's transaction and session exit. It does not report the result +of later audits or WAP publication. + +An observed operation can do no work, issue multiple statements, or trigger +internal driver retries. The observation does not predict how many statements +the operation will issue or report each retry. + +The query observation surrounds the base adapter's existing SQL logging and +`_execute` call. It ends before a surrounding transaction commits and before +later fetch or result consumption. Some adapter operations do not call this +query hook. BigQuery session queries, BigQuery dataframe loads, and ClickHouse +dataframe inserts may not produce query observations. These hooks do not provide +a complete warehouse activity history or guarantee transaction success. + +SQL logging retains its existing behavior, including VALUES redaction for +non-query expressions. The callback receives no SQL text, adapter objects, or +warehouse query IDs. The `start` callback runs before SQL logging. Consumers can +use that ordering to associate existing log entries with the invocation. + +## Worker context + +When an observer is active outside callback delivery, SQLMesh copies the current +Python context for each task in scheduler and snapshot DAG work, snapshot schema creation, and +data-object listing. That context carries Python's [context variables](https://docs.python.org/3/library/contextvars.html). +Each task gets its own context copy, including during serial execution. DAG +successors use the context captured for the run. They do not inherit changes +made by earlier workers. Reusing a DAG executor captures a fresh context for +each run. + +Context copies are shallow. Mutable objects stored in `ContextVar` values remain +shared across copies. A parent identity stored in a consumer-owned `ContextVar` +is available to each worker. SQLMesh uses these copies in the scheduler and +snapshot DAG, schema creation, and data-object listing. Arbitrary consumer +threads and other concurrency helpers do not receive these copies. + +With no observer registered, these operations do not copy contexts. The concurrency +helpers retain their existing `ContextVar` behavior for serial and worker +execution. diff --git a/mkdocs.yml b/mkdocs.yml index 368fb6690a..27134e1146 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 @@ -105,6 +106,7 @@ nav: - reference/cli.md - reference/notebook.md - reference/python.md + - reference/execution_observations.md - Configuration: - reference/configuration.md - reference/model_configuration.md @@ -199,7 +201,7 @@ copyright: Tobiko Data Inc. extra: social: - icon: fontawesome/brands/slack - link: https://tobikodata.com/slack + link: https://tobiko-data.slack.com/ - icon: fontawesome/solid/paper-plane link: mailto:hello@tobikodata.com - icon: fontawesome/brands/github diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 31b664c053..5133bad2de 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -113,7 +113,7 @@ importers: version: 4.1.11 '@tailwindcss/vite': specifier: ^4.1.11 - version: 4.1.11(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) + version: 4.1.11(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) '@tanstack/react-query': specifier: ^5.83.0 version: 5.83.0(react@18.3.1) @@ -128,10 +128,10 @@ importers: version: 3.13.12(react-dom@18.3.1(react@18.3.1))(react@18.3.1) '@tanstack/router-plugin': specifier: ^1.129.8 - version: 1.129.8(@tanstack/react-router@1.129.8(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(supports-color@9.4.0)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(webpack@5.99.8(@swc/core@1.13.2(@swc/helpers@0.5.17))(esbuild@0.25.8)) + version: 1.129.8(@tanstack/react-router@1.129.8(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(supports-color@9.4.0)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(webpack@5.99.8(@swc/core@1.13.2(@swc/helpers@0.5.17))(esbuild@0.25.8)) apache-arrow: - specifier: ^19.0.1 - version: 19.0.1 + specifier: ^21.2.0 + version: 21.2.0 clsx: specifier: ^2.1.1 version: 2.1.1 @@ -177,7 +177,7 @@ importers: version: 9.0.18(@vitest/browser@3.2.3)(@vitest/runner@3.2.4)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(storybook@9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0))(vitest@3.2.4) '@storybook/react-vite': specifier: ^9.0.18 - version: 9.0.18(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(rollup@4.45.1)(storybook@9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0))(supports-color@9.4.0)(typescript@5.8.3)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) + version: 9.0.18(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(rollup@4.45.1)(storybook@9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0))(supports-color@9.4.0)(typescript@5.8.3)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) '@testing-library/dom': specifier: ^10.4.1 version: 10.4.1 @@ -192,13 +192,13 @@ importers: version: 18.3.7(@types/react@18.3.23) '@vitejs/plugin-react': specifier: ^4.7.0 - version: 4.7.0(supports-color@9.4.0)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) + version: 4.7.0(supports-color@9.4.0)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) '@vitest/browser': specifier: 3.2.3 - version: 3.2.3(playwright@1.54.1)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4) + version: 3.2.3(playwright@1.54.1)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4) '@vitest/coverage-v8': specifier: 3.2.3 - version: 3.2.3(@vitest/browser@3.2.3)(supports-color@8.1.1)(vitest@3.2.4) + version: 3.2.3(@vitest/browser@3.2.3)(supports-color@9.4.0)(vitest@3.2.4) jsdom: specifier: ^26.1.0 version: 26.1.0(supports-color@9.4.0) @@ -213,13 +213,13 @@ importers: version: 5.8.3 vite: specifier: ^6.3.5 - version: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + version: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) vitest: specifier: ^3.2.4 - version: 3.2.4(@types/debug@4.1.12)(@types/node@24.1.0)(@vitest/browser@3.2.3)(@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) + version: 3.2.4(@types/debug@4.1.12)(@types/node@25.9.7)(@vitest/browser@3.2.3)(@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) web-vitals: - specifier: ^4.2.4 - version: 4.2.4 + specifier: ^6.2.3 + version: 6.2.3 web/client: dependencies: @@ -281,8 +281,8 @@ importers: specifier: ^4.24.1 version: 4.24.1(@babel/runtime@7.28.2)(@codemirror/autocomplete@6.18.6)(@codemirror/language@6.11.2)(@codemirror/lint@6.8.5)(@codemirror/search@6.5.10)(@codemirror/state@6.5.2)(@codemirror/theme-one-dark@6.1.2)(@codemirror/view@6.38.1)(codemirror@6.0.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) apache-arrow: - specifier: ^19.0.1 - version: 19.0.1 + specifier: ^21.2.0 + version: 21.2.0 clsx: specifier: ^2.1.1 version: 2.1.1 @@ -300,7 +300,7 @@ importers: version: 18.3.1 react-dnd: specifier: ^16.0.1 - version: 16.0.1(@types/node@24.1.0)(@types/react@18.3.23)(react@18.3.1) + version: 16.0.1(@types/node@25.9.7)(@types/react@18.3.23)(react@18.3.1) react-dnd-html5-backend: specifier: ^16.0.1 version: 16.0.1 @@ -355,13 +355,13 @@ importers: version: 18.3.7(@types/react@18.3.23) '@vitejs/plugin-react-swc': specifier: ^3.11.0 - version: 3.11.0(@swc/helpers@0.5.17)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) + version: 3.11.0(@swc/helpers@0.5.17)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) ajv: specifier: ^8.17.1 version: 8.17.1 autoprefixer: - specifier: ^10.4.21 - version: 10.4.21(postcss@8.5.6) + specifier: ^10.6.1 + version: 10.6.1(postcss@8.5.6) eslint: specifier: ^9.31.0 version: 9.31.0(jiti@2.4.2)(supports-color@9.4.0) @@ -385,17 +385,17 @@ importers: version: 8.38.0(eslint@9.31.0(jiti@2.4.2)(supports-color@9.4.0))(supports-color@9.4.0)(typescript@5.8.3) vite: specifier: ^6.3.5 - version: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + version: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) vite-plugin-css-injected-by-js: specifier: ^3.5.2 - version: 3.5.2(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) + version: 3.5.2(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) vitest: specifier: ^3.2.4 - 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) + version: 3.2.4(@types/debug@4.1.12)(@types/node@25.9.7)(@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: @@ -454,8 +454,8 @@ importers: specifier: 12.8.4 version: 12.8.4(@types/react@18.3.23)(immer@9.0.21)(react-dom@18.3.1(react@18.3.1))(react@18.3.1) autoprefixer: - specifier: 10.4.21 - version: 10.4.21(postcss@8.5.6) + specifier: 10.6.1 + version: 10.6.1(postcss@8.5.6) browserslist: specifier: 4.26.2 version: 4.26.2 @@ -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'} @@ -2536,12 +2543,6 @@ packages: '@types/chai@5.2.2': resolution: {integrity: sha512-8kB30R7Hwqf40JPiKhVzodJs2Qc1ZJ5zuT3uzw5Hq/dhNCl3G3l83jfpdI1e20BP348+fV7VIL/+FxaXkqBmWg==} - '@types/command-line-args@5.2.3': - resolution: {integrity: sha512-uv0aG6R0Y8WHZLTamZwtfsDLVRnOa+n+n5rEvFWL5Na5gZ8V2Teab/duDPFzIIIhs9qizDpcavCusCLJZu62Kw==} - - '@types/command-line-usage@5.0.4': - resolution: {integrity: sha512-BwR5KP3Es/CSht0xqBcUXS3qCAUVXwpRKsV2+arxeb65atasuXG9LykC9Ab10Cw3s2raH92ZqOeILaQbsB2ACg==} - '@types/d3-array@3.2.1': resolution: {integrity: sha512-Y2Jn2idRrLzUfAKV2LyRImR+y4oa2AntrgID95SHJxuMUrkNXmanDSed71sRNZysveJVt1hLLemQZIady0FpEg==} @@ -2695,11 +2696,8 @@ packages: '@types/node@20.11.25': resolution: {integrity: sha512-TBHyJxk2b7HceLVGFcpAUjsa5zIdsPWlR6XHfyGzd0SFu+/NFgQgMAl96MSDZgQDvJAvV6BKsFOrt6zIL09JDw==} - '@types/node@20.19.9': - resolution: {integrity: sha512-cuVNgarYWZqxRJDQHEB58GEONhOK79QVR/qYx4S7kcUObQvUwvFnYxJuuHUKm2aieN9X3yZB4LZsuYNU1Qphsw==} - - '@types/node@24.1.0': - resolution: {integrity: sha512-ut5FthK5moxFKH2T1CUOC6ctR67rQRvvHdFLCD2Ql6KXmMuCrjsSsRI9UsLCm9M18BMwClv4pn327UvB7eeO1w==} + '@types/node@25.9.7': + resolution: {integrity: sha512-Y+axoNWOFLvDNFxNbDA+kqqV05imHwTu5bZWWO6tQM3Y2NX1jvzUJkYlf4nYnMCnvu4wQBKW6Nr+ok6yHWA9aQ==} '@types/normalize-package-data@2.4.4': resolution: {integrity: sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==} @@ -3205,8 +3203,8 @@ packages: resolution: {integrity: sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==} engines: {node: '>= 8'} - apache-arrow@19.0.1: - resolution: {integrity: sha512-APmMLzS4qbTivLrPdQXexGM4JRr+0g62QDaobzEvip/FdQIrv2qLy0mD5Qdmw4buydtVJgbFeKR8f59I6PPGDg==} + apache-arrow@21.2.0: + resolution: {integrity: sha512-Hxe6Agq26gQOM954qpzYSllJBPJl+e16U5CkfuMUhLrNba+5nKkttIVlflaovN6oaTratqMGAO8H5u/aNhmHWQ==} hasBin: true arg@5.0.2: @@ -3229,10 +3227,6 @@ packages: resolution: {integrity: sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==} engines: {node: '>= 0.4'} - array-back@6.2.2: - resolution: {integrity: sha512-gUAZ7HPyb4SJczXAMUXMGAvI976JoK3qEx9v1FTmeYuJj0IBiaKttG1ydtGKdkfqWkIkouke7nG8ufGy77+Cvw==} - engines: {node: '>=12.17'} - array-buffer-byte-length@1.0.2: resolution: {integrity: sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==} engines: {node: '>= 0.4'} @@ -3271,8 +3265,8 @@ packages: asynckit@0.4.0: resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} - autoprefixer@10.4.21: - resolution: {integrity: sha512-O+A6LWV5LDHSJD3LjHYoNi4VLsj/Whi7k6zG12xTYaU4cQ8oxQGckXNX8cRHK5yOZ/ppVHe0ZBXGzSV9jXdVbQ==} + autoprefixer@10.6.1: + resolution: {integrity: sha512-cL1Qz6ADZhcEbny/8HPfe99J6HhNoYtpX2LFLIbhgGE7Q1hlQVkYFdetDN7Id3KiQxhDrHwzlHr/YQCnZ8+xSA==} engines: {node: ^10 || ^12 || >=14} hasBin: true peerDependencies: @@ -3301,6 +3295,11 @@ packages: base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + baseline-browser-mapping@2.11.26: + resolution: {integrity: sha512-GLQdD3y6UF8iVuMJl5fHgE4jdn/ua7n+toKfLgNlg3BqQtOZjpy68T8Tup8/wGWZCDlm7KMg7tPb4MPn7oN0TQ==} + engines: {node: '>=6.0.0'} + hasBin: true + baseline-browser-mapping@2.8.9: resolution: {integrity: sha512-hY/u2lxLrbecMEWSB0IpGzGyDyeoMFQhCvZd2jGFSE5I17Fh01sYUBPCJtkWERw7zrac9+cIghxm/ytJa2X8iA==} hasBin: true @@ -3344,6 +3343,11 @@ packages: engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true + browserslist@4.29.1: + resolution: {integrity: sha512-AUdjuRyCNGUYtqpqfTmWyM4fXay8yIQhmLnvYe/THMGfT9B/34X7xQd3ifKxwyNPPpowVBjLb+64BN9Rn1mizw==} + engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} + hasBin: true + buffer-crc32@0.2.13: resolution: {integrity: sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==} @@ -3399,6 +3403,9 @@ packages: caniuse-lite@1.0.30001746: resolution: {integrity: sha512-eA7Ys/DGw+pnkWWSE/id29f2IcPHVoE8wxtvE5JdvD2V28VTDPy1yEeo11Guz0sJ4ZeGRcm3uaTcAqK1LXaphA==} + caniuse-lite@1.0.30001812: + resolution: {integrity: sha512-qN+QNNBr93TCmFrmte0bBCjSDMuRvt78VlHT99qIGPszm4QsqCX8lnyWUFkHi8B7ZBAPq8SH+UqyXNy/odMdng==} + ccount@2.0.1: resolution: {integrity: sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg==} @@ -3406,10 +3413,6 @@ packages: resolution: {integrity: sha512-5nFxhUrX0PqtyogoYOA8IPswy5sZFTOsBFl/9bNsmDLgsxYTzSZQJDPppDnZPTQbzSEm0hqGjWPzRemQCYbD6A==} engines: {node: '>=18'} - chalk-template@0.4.0: - resolution: {integrity: sha512-/ghrgmhfY8RaSdeo43hNXxpoHAtxdbskUHjPpfqUWGttFgycUhYPGx3YZBCnUCvOa7Doivn1IZec3DEGFoMgLg==} - engines: {node: '>=12'} - chalk-template@1.1.0: resolution: {integrity: sha512-T2VJbcDuZQ0Tb2EWwSotMPJjgpy1/tGee1BTpUNsGZ/qgNjV2t7Mvu+d4600U564nbLesN1x2dPL+xii174Ekg==} engines: {node: '>=14.16'} @@ -3526,19 +3529,6 @@ packages: comma-separated-tokens@2.0.3: resolution: {integrity: sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==} - command-line-args@6.0.1: - resolution: {integrity: sha512-Jr3eByUjqyK0qd8W0SGFW1nZwqCaNCtbXjRo2cRJC1OYxWl3MZ5t1US3jq+cO4sPavqgw4l9BMGX0CBe+trepg==} - engines: {node: '>=12.20'} - peerDependencies: - '@75lb/nature': latest - peerDependenciesMeta: - '@75lb/nature': - optional: true - - command-line-usage@7.0.3: - resolution: {integrity: sha512-PqMLy5+YGwhMh1wS04mVG44oqDsgyLRSKJBdOo1bnYhMKBW65gZF1dRp2OZRhiTjgUHljy99qkO7bsctLaw35Q==} - engines: {node: '>=12.20.0'} - commander@12.1.0: resolution: {integrity: sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==} engines: {node: '>=18'} @@ -3832,6 +3822,9 @@ packages: electron-to-chromium@1.5.227: resolution: {integrity: sha512-ITxuoPfJu3lsNWUi2lBM2PaBPYgH3uqmxut5vmBxgYvyI4AlJ6P3Cai1O76mOrkJCBzq0IxWg/NtqOrpu/0gKA==} + electron-to-chromium@1.5.439: + resolution: {integrity: sha512-qu6QIPXhsb+CRcAiTMNjR4A1y/7tCYKkKjr5CZXRVih6qkDf79peZ2BpEU3qoDBNCRrcy3Mra3X9nG5oruuA7Q==} + elkjs@0.8.2: resolution: {integrity: sha512-L6uRgvZTH+4OF5NE/MBbzQx/WYpru1xCBE9respNj6qznEewGUIfhzmm7horWWxbNO2M0WckQypGctR8lH79xQ==} @@ -4092,15 +4085,6 @@ packages: resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} engines: {node: '>=8'} - find-replace@5.0.2: - resolution: {integrity: sha512-Y45BAiE3mz2QsrN2fb5QEtO4qb44NcS7en/0y9PEVsg351HsLeVclP8QPMH79Le9sH3rs5RSwJu99W0WPZO43Q==} - engines: {node: '>=14'} - peerDependencies: - '@75lb/nature': latest - peerDependenciesMeta: - '@75lb/nature': - optional: true - find-up@5.0.0: resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} engines: {node: '>=10'} @@ -4117,8 +4101,8 @@ packages: resolution: {integrity: sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==} hasBin: true - flatbuffers@24.12.23: - resolution: {integrity: sha512-dLVCAISd5mhls514keQzmEG6QHmUUsNuWsb4tFafIUwvvgDjXhtfAYSKOzt5SWOy+qByV5pbsDZ+Vb7HUOBEdA==} + flatbuffers@25.9.23: + resolution: {integrity: sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ==} flatted@3.3.3: resolution: {integrity: sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==} @@ -4135,8 +4119,8 @@ packages: resolution: {integrity: sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==} engines: {node: '>= 6'} - fraction.js@4.3.7: - resolution: {integrity: sha512-ZsDfxO51wGAXREY55a7la9LScWpwv9RxIrYABrlvOFBlH/ShPnrtsXeuUIfXKKOVicNxQ+o8JTbJvjS4M89yew==} + fraction.js@5.3.4: + resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==} fs-constants@1.0.0: resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} @@ -4681,10 +4665,6 @@ packages: engines: {node: '>=6'} hasBin: true - json-bignum@0.0.3: - resolution: {integrity: sha512-2WHyXj3OfHSgNyuzDbSxI1w2jgw5gkWSWhS7Qg4bWXx1nLk3jnbwfUeS0PSba3IzpTUWdHxBieELUzXRjQB2zg==} - engines: {node: '>=0.8'} - json-buffer@3.0.1: resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} @@ -4700,6 +4680,9 @@ packages: json-stable-stringify-without-jsonify@1.0.1: resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} + json-with-bigint@3.5.12: + resolution: {integrity: sha512-uwbF/wSSuOgC7qqlq27Xp5B6a2MHVug3t0idZdTqu0JnlFvgJuH7ju+KAk/J06C7GfhoYy2gnb9wz2INqcne7w==} + json5@2.2.3: resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} engines: {node: '>=6'} @@ -4857,9 +4840,6 @@ packages: resolution: {integrity: sha512-gvVijfZvn7R+2qyPX8mAuKcFGDf6Nc61GdvGafQsHL0sBIxfKzA+usWn4GFC/bk+QdwPUD4kWFJLhElipq+0VA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - lodash.camelcase@4.3.0: - resolution: {integrity: sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==} - lodash.castarray@4.4.0: resolution: {integrity: sha512-aVx8ztPv7/2ULbArGJ2Y42bG1mEQ5mGjpdvrbJcJFU3TbYybe+QlLS4pst9zV52ymy2in1KpFPiZnAOATxD4+Q==} @@ -5216,6 +5196,10 @@ packages: node-releases@2.0.21: resolution: {integrity: sha512-5b0pgg78U3hwXkCM8Z9b2FJdPZlr9Psr9V2gQPESdGHqbntyFJKFW4r5TeWGFzafGY3hzs1JC62VEQMbl1JFkw==} + node-releases@2.0.57: + resolution: {integrity: sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==} + engines: {node: '>=18'} + node-sarif-builder@3.2.0: resolution: {integrity: sha512-kVIOdynrF2CRodHZeP/97Rh1syTUHBNiw17hUCIVhlhEsWlfJm19MuO56s4MdKbr22xWx6mzMnNAgXzVlIYM9Q==} engines: {node: '>=18'} @@ -5228,10 +5212,6 @@ packages: resolution: {integrity: sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==} engines: {node: '>=0.10.0'} - normalize-range@0.1.2: - resolution: {integrity: sha512-bdok/XvKII3nUpklnV6P2hxtMNrCboOjAcyBuQnWEhO665FwrSNRxU+AqpsyvO6LgGYPspN+lu5CLtw4jPRKNA==} - engines: {node: '>=0.10.0'} - npm-package-arg@12.0.2: resolution: {integrity: sha512-f1NpFjNI9O4VbKMOlA5QoBq/vSQPORHcTZ2feJpFkTHJ9eQkdlmZEKSjcAhxTGInC7RlEyScT9ui67NaOsjFWA==} engines: {node: ^18.17.0 || >=20.5.0} @@ -6188,10 +6168,6 @@ packages: tabbable@6.2.0: resolution: {integrity: sha512-Cat63mxsVJlzYvN51JmVXIgNoUokrIaT2zLclCXjRd8boZ0004U4KCs/sToJ75C6sdlByWxpYnb5Boif1VSFew==} - table-layout@4.1.1: - resolution: {integrity: sha512-iK5/YhZxq5GO5z8wb0bY1317uDF3Zjpha0QFFLA8/trAoiLbQD0HUbMesEaxyzUgDxi2QlcbM8IvqOlEjgoXBA==} - engines: {node: '>=12.17'} - table@6.9.0: resolution: {integrity: sha512-9kY+CygyYM6j02t5YFHbNz2FN5QmYGv9zAjVp4lCDjlCw7amdckXlEt/bjMhUIfj4ThGRE4gCUH5+yGnNuPo5A==} engines: {node: '>=10.0.0'} @@ -6468,10 +6444,6 @@ packages: engines: {node: '>=14.17'} hasBin: true - typical@7.3.0: - resolution: {integrity: sha512-ya4mg/30vm+DOWfBg4YK3j2WD6TWtRkCbasOJr40CseYENzCUby/7rIvXA99JGsQHeNxLbnXdyLLxKSv3tauFw==} - engines: {node: '>=12.17'} - uc.micro@2.1.0: resolution: {integrity: sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==} @@ -6488,11 +6460,8 @@ packages: undici-types@5.26.5: resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==} - undici-types@6.21.0: - resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} - - undici-types@7.8.0: - resolution: {integrity: sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw==} + undici-types@7.24.6: + resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} undici@7.12.0: resolution: {integrity: sha512-GrKEsc3ughskmGA9jevVlIOPMiiAHJ4OFUtaAH+NhfTUSiZ1wMPIQqQvAJUrJspFXJt3EBWgpAeoHEDVT1IBug==} @@ -6542,6 +6511,12 @@ packages: peerDependencies: browserslist: '>= 4.21.0' + update-browserslist-db@1.3.3: + resolution: {integrity: sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==} + hasBin: true + peerDependencies: + browserslist: '>= 4.21.0' + uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} @@ -6738,8 +6713,8 @@ packages: resolution: {integrity: sha512-c5EGNOiyxxV5qmTtAB7rbiXxi1ooX1pQKMLX/MIabJjRA0SJBQOjKF+KSVfHkr9U1cADPon0mRiVe/riyaiDUA==} engines: {node: '>=10.13.0'} - web-vitals@4.2.4: - resolution: {integrity: sha512-r4DIlprAGwJ7YM11VZp4R884m0Vmgr6EAKe3P+kO0PPj3Unqyvv59rczf6UiGcb9Z8QxZVcqKNwv/g0WNdWwsw==} + web-vitals@6.2.3: + resolution: {integrity: sha512-Dmy+vdO1UPMqXiAtZSNayhl4f794Bxfd94W4HIj2HlYtczEQfEOon969memlcpcHrTuOKLa5baFjX7WbgmOq+A==} webidl-conversions@3.0.1: resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} @@ -6811,10 +6786,6 @@ packages: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} - wordwrapjs@5.1.0: - resolution: {integrity: sha512-JNjcULU2e4KJwUNv6CHgI46UvDGitb6dGryHajXTDiLgg1/RiGoPSDw4kZfYnwGtEXf2ZMeIewDQgFGzkCB2Sg==} - engines: {node: '>=12.17'} - workerpool@6.5.1: resolution: {integrity: sha512-Fs4dNYcsdpYSAfVxhnl1L5zTksjvOJxtC5hzMNl+1t9B8hTJTdKDyZ5ju7ztgPy+ft9tBFXoOlDNiOT9WUXZlA==} @@ -7706,12 +7677,12 @@ snapshots: optionalDependencies: typescript: 5.8.3 - '@joshwooding/vite-plugin-react-docgen-typescript@0.6.1(typescript@5.8.3)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': + '@joshwooding/vite-plugin-react-docgen-typescript@0.6.1(typescript@5.8.3)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': dependencies: glob: 10.4.5 magic-string: 0.30.17 react-docgen-typescript: 2.4.0(typescript@5.8.3) - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) optionalDependencies: typescript: 5.8.3 @@ -8506,7 +8477,7 @@ snapshots: dependencies: ajv: 8.13.0 ajv-draft-04: 1.0.0(ajv@8.13.0) - ajv-formats: 3.0.1(ajv@8.13.0) + ajv-formats: 3.0.1 fs-extra: 11.3.0 import-lazy: 4.0.0 jju: 1.4.0 @@ -8691,7 +8662,7 @@ snapshots: '@types/json-schema': 7.0.15 ajv: 8.17.1 ajv-errors: 3.0.0(ajv@8.17.1) - ajv-formats: 2.1.1(ajv@8.17.1) + ajv-formats: 2.1.1 es-aggregate-error: 1.0.14 jsonpath-plus: 10.3.0 lodash: 4.17.21 @@ -8723,7 +8694,7 @@ snapshots: ajv: 8.17.1 ajv-draft-04: 1.0.0(ajv@8.17.1) ajv-errors: 3.0.0(ajv@8.17.1) - ajv-formats: 2.1.1(ajv@8.17.1) + ajv-formats: 2.1.1 lodash: 4.17.21 tslib: 2.8.1 transitivePeerDependencies: @@ -8758,7 +8729,7 @@ snapshots: '@stoplight/types': 13.20.0 '@types/json-schema': 7.0.15 ajv: 8.17.1 - ajv-formats: 2.1.1(ajv@8.17.1) + ajv-formats: 2.1.1 json-schema-traverse: 1.0.0 leven: 3.1.0 lodash: 4.17.21 @@ -8846,19 +8817,19 @@ snapshots: storybook: 9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0) ts-dedent: 2.2.0 optionalDependencies: - '@vitest/browser': 3.2.3(playwright@1.54.1)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4) + '@vitest/browser': 3.2.3(playwright@1.54.1)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4) '@vitest/runner': 3.2.4 - vitest: 3.2.4(@types/debug@4.1.12)(@types/node@24.1.0)(@vitest/browser@3.2.3)(@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) + vitest: 3.2.4(@types/debug@4.1.12)(@types/node@25.9.7)(@vitest/browser@3.2.3)(@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) transitivePeerDependencies: - react - react-dom - '@storybook/builder-vite@9.0.18(storybook@9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0))(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': + '@storybook/builder-vite@9.0.18(storybook@9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0))(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': dependencies: '@storybook/csf-plugin': 9.0.18(storybook@9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0)) storybook: 9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0) ts-dedent: 2.2.0 - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) '@storybook/builder-vite@9.1.5(storybook@9.1.5(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0)(vite@6.3.5(@types/node@20.11.25)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)))(vite@6.3.5(@types/node@20.11.25)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': dependencies: @@ -8896,11 +8867,11 @@ snapshots: react-dom: 18.3.1(react@18.3.1) storybook: 9.1.5(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0)(vite@6.3.5(@types/node@20.11.25)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) - '@storybook/react-vite@9.0.18(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(rollup@4.45.1)(storybook@9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0))(supports-color@9.4.0)(typescript@5.8.3)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': + '@storybook/react-vite@9.0.18(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(rollup@4.45.1)(storybook@9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0))(supports-color@9.4.0)(typescript@5.8.3)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': dependencies: - '@joshwooding/vite-plugin-react-docgen-typescript': 0.6.1(typescript@5.8.3)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) + '@joshwooding/vite-plugin-react-docgen-typescript': 0.6.1(typescript@5.8.3)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) '@rollup/pluginutils': 5.2.0(rollup@4.45.1) - '@storybook/builder-vite': 9.0.18(storybook@9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0))(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) + '@storybook/builder-vite': 9.0.18(storybook@9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0))(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) '@storybook/react': 9.0.18(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(storybook@9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0))(typescript@5.8.3) find-up: 7.0.0 magic-string: 0.30.17 @@ -8910,7 +8881,7 @@ snapshots: resolve: 1.22.10 storybook: 9.0.18(@testing-library/dom@10.4.1)(prettier@3.6.2)(supports-color@9.4.0) tsconfig-paths: 4.2.0 - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) transitivePeerDependencies: - rollup - supports-color @@ -8974,6 +8945,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 @@ -9097,12 +9071,12 @@ snapshots: postcss-selector-parser: 6.0.10 tailwindcss: 3.4.17 - '@tailwindcss/vite@4.1.11(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': + '@tailwindcss/vite@4.1.11(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': dependencies: '@tailwindcss/node': 4.1.11 '@tailwindcss/oxide': 4.1.11 tailwindcss: 4.1.11 - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) '@tanstack/history@1.129.7': {} @@ -9197,7 +9171,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@tanstack/router-plugin@1.129.8(@tanstack/react-router@1.129.8(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(supports-color@9.4.0)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(webpack@5.99.8(@swc/core@1.13.2(@swc/helpers@0.5.17))(esbuild@0.25.8))': + '@tanstack/router-plugin@1.129.8(@tanstack/react-router@1.129.8(react-dom@18.3.1(react@18.3.1))(react@18.3.1))(supports-color@9.4.0)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(webpack@5.99.8(@swc/core@1.13.2(@swc/helpers@0.5.17))(esbuild@0.25.8))': dependencies: '@babel/core': 7.28.0(supports-color@9.4.0) '@babel/plugin-syntax-jsx': 7.27.1(@babel/core@7.28.0(supports-color@9.4.0)) @@ -9215,7 +9189,7 @@ snapshots: zod: 3.25.76 optionalDependencies: '@tanstack/react-router': 1.129.8(react-dom@18.3.1(react@18.3.1))(react@18.3.1) - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) webpack: 5.99.8(@swc/core@1.13.2(@swc/helpers@0.5.17))(esbuild@0.25.8) transitivePeerDependencies: - supports-color @@ -9332,10 +9306,6 @@ snapshots: dependencies: '@types/deep-eql': 4.0.2 - '@types/command-line-args@5.2.3': {} - - '@types/command-line-usage@5.0.4': {} - '@types/d3-array@3.2.1': {} '@types/d3-axis@3.0.6': @@ -9516,14 +9486,9 @@ snapshots: dependencies: undici-types: 5.26.5 - '@types/node@20.19.9': + '@types/node@25.9.7': dependencies: - undici-types: 6.21.0 - - '@types/node@24.1.0': - dependencies: - undici-types: 7.8.0 - optional: true + undici-types: 7.24.6 '@types/normalize-package-data@2.4.4': {} @@ -9766,11 +9731,11 @@ snapshots: '@ungap/structured-clone@1.3.0': {} - '@vitejs/plugin-react-swc@3.11.0(@swc/helpers@0.5.17)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': + '@vitejs/plugin-react-swc@3.11.0(@swc/helpers@0.5.17)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': dependencies: '@rolldown/pluginutils': 1.0.0-beta.27 '@swc/core': 1.13.2(@swc/helpers@0.5.17) - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) transitivePeerDependencies: - '@swc/helpers' @@ -9786,7 +9751,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@vitejs/plugin-react@4.7.0(supports-color@9.4.0)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': + '@vitejs/plugin-react@4.7.0(supports-color@9.4.0)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': dependencies: '@babel/core': 7.28.0(supports-color@9.4.0) '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.0(supports-color@9.4.0)) @@ -9794,20 +9759,20 @@ snapshots: '@rolldown/pluginutils': 1.0.0-beta.27 '@types/babel__core': 7.20.5 react-refresh: 0.17.0 - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) transitivePeerDependencies: - supports-color - '@vitest/browser@3.2.3(playwright@1.54.1)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4)': + '@vitest/browser@3.2.3(playwright@1.54.1)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4)': dependencies: '@testing-library/dom': 10.4.1 '@testing-library/user-event': 14.6.1(@testing-library/dom@10.4.1) - '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) + '@vitest/mocker': 3.2.3(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) '@vitest/utils': 3.2.3 magic-string: 0.30.17 sirv: 3.0.1 tinyrainbow: 2.0.0 - vitest: 3.2.4(@types/debug@4.1.12)(@types/node@24.1.0)(@vitest/browser@3.2.3)(@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) + vitest: 3.2.4(@types/debug@4.1.12)(@types/node@25.9.7)(@vitest/browser@3.2.3)(@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) ws: 8.18.3 optionalDependencies: playwright: 1.54.1 @@ -9836,16 +9801,16 @@ snapshots: - utf-8-validate - vite - '@vitest/browser@3.2.4(playwright@1.54.1)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4)': + '@vitest/browser@3.2.4(playwright@1.54.1)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4)': dependencies: '@testing-library/dom': 10.4.1 '@testing-library/user-event': 14.6.1(@testing-library/dom@10.4.1) - '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) + '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) '@vitest/utils': 3.2.4 magic-string: 0.30.17 sirv: 3.0.1 tinyrainbow: 2.0.0 - vitest: 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) + vitest: 3.2.4(@types/debug@4.1.12)(@types/node@25.9.7)(@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) ws: 8.18.3 optionalDependencies: playwright: 1.54.1 @@ -9856,24 +9821,24 @@ snapshots: - vite optional: true - '@vitest/coverage-v8@3.2.3(@vitest/browser@3.2.3)(supports-color@8.1.1)(vitest@3.2.4)': + '@vitest/coverage-v8@3.2.3(@vitest/browser@3.2.3)(supports-color@9.4.0)(vitest@3.2.4)': dependencies: '@ampproject/remapping': 2.3.0 '@bcoe/v8-coverage': 1.0.2 ast-v8-to-istanbul: 0.3.3 - debug: 4.4.1(supports-color@8.1.1) + debug: 4.4.1(supports-color@9.4.0) istanbul-lib-coverage: 3.2.2 istanbul-lib-report: 3.0.1 - istanbul-lib-source-maps: 5.0.6(supports-color@8.1.1) + istanbul-lib-source-maps: 5.0.6(supports-color@9.4.0) istanbul-reports: 3.1.7 magic-string: 0.30.17 magicast: 0.3.5 std-env: 3.9.0 test-exclude: 7.0.1 tinyrainbow: 2.0.0 - vitest: 3.2.4(@types/debug@4.1.12)(@types/node@24.1.0)(@vitest/browser@3.2.3)(@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) + vitest: 3.2.4(@types/debug@4.1.12)(@types/node@25.9.7)(@vitest/browser@3.2.3)(@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: - '@vitest/browser': 3.2.3(playwright@1.54.1)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4) + '@vitest/browser': 3.2.3(playwright@1.54.1)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4) transitivePeerDependencies: - supports-color @@ -9885,13 +9850,13 @@ snapshots: chai: 5.2.1 tinyrainbow: 2.0.0 - '@vitest/mocker@3.2.3(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': + '@vitest/mocker@3.2.3(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': dependencies: '@vitest/spy': 3.2.3 estree-walker: 3.0.3 magic-string: 0.30.17 optionalDependencies: - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) '@vitest/mocker@3.2.4(vite@6.3.5(@types/node@20.11.25)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': dependencies: @@ -9901,13 +9866,13 @@ snapshots: optionalDependencies: vite: 6.3.5(@types/node@20.11.25)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) - '@vitest/mocker@3.2.4(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': + '@vitest/mocker@3.2.4(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))': dependencies: '@vitest/spy': 3.2.4 estree-walker: 3.0.3 magic-string: 0.30.17 optionalDependencies: - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) '@vitest/pretty-format@3.2.3': dependencies: @@ -10233,12 +10198,12 @@ snapshots: dependencies: ajv: 8.17.1 - ajv-formats@2.1.1(ajv@8.17.1): - optionalDependencies: + ajv-formats@2.1.1: + dependencies: ajv: 8.17.1 - ajv-formats@3.0.1(ajv@8.13.0): - optionalDependencies: + ajv-formats@3.0.1: + dependencies: ajv: 8.13.0 ajv-keywords@5.1.0(ajv@8.17.1): @@ -10303,19 +10268,12 @@ snapshots: normalize-path: 3.0.0 picomatch: 2.3.1 - apache-arrow@19.0.1: + apache-arrow@21.2.0: dependencies: - '@swc/helpers': 0.5.17 - '@types/command-line-args': 5.2.3 - '@types/command-line-usage': 5.0.4 - '@types/node': 20.19.9 - command-line-args: 6.0.1 - command-line-usage: 7.0.3 - flatbuffers: 24.12.23 - json-bignum: 0.0.3 + '@types/node': 25.9.7 + flatbuffers: 25.9.23 + json-with-bigint: 3.5.12 tslib: 2.8.1 - transitivePeerDependencies: - - '@75lb/nature' arg@5.0.2: {} @@ -10335,8 +10293,6 @@ snapshots: aria-query@5.3.2: {} - array-back@6.2.2: {} - array-buffer-byte-length@1.0.2: dependencies: call-bound: 1.0.4 @@ -10374,12 +10330,11 @@ snapshots: asynckit@0.4.0: {} - autoprefixer@10.4.21(postcss@8.5.6): + autoprefixer@10.6.1(postcss@8.5.6): dependencies: - browserslist: 4.26.2 - caniuse-lite: 1.0.30001746 - fraction.js: 4.3.7 - normalize-range: 0.1.2 + browserslist: 4.29.1 + caniuse-lite: 1.0.30001812 + fraction.js: 5.3.4 picocolors: 1.1.1 postcss: 8.5.6 postcss-value-parser: 4.2.0 @@ -10411,6 +10366,8 @@ snapshots: base64-js@1.5.1: optional: true + baseline-browser-mapping@2.11.26: {} + baseline-browser-mapping@2.8.9: {} better-opn@3.0.2: @@ -10457,6 +10414,14 @@ snapshots: node-releases: 2.0.21 update-browserslist-db: 1.1.3(browserslist@4.26.2) + browserslist@4.29.1: + dependencies: + baseline-browser-mapping: 2.11.26 + caniuse-lite: 1.0.30001812 + electron-to-chromium: 1.5.439 + node-releases: 2.0.57 + update-browserslist-db: 1.3.3(browserslist@4.29.1) + buffer-crc32@0.2.13: {} buffer-equal-constant-time@1.0.1: {} @@ -10516,6 +10481,8 @@ snapshots: caniuse-lite@1.0.30001746: {} + caniuse-lite@1.0.30001812: {} + ccount@2.0.1: {} chai@5.2.1: @@ -10526,10 +10493,6 @@ snapshots: loupe: 3.1.4 pathval: 2.0.1 - chalk-template@0.4.0: - dependencies: - chalk: 4.1.2 - chalk-template@1.1.0: dependencies: chalk: 5.4.1 @@ -10654,20 +10617,6 @@ snapshots: comma-separated-tokens@2.0.3: {} - command-line-args@6.0.1: - dependencies: - array-back: 6.2.2 - find-replace: 5.0.2 - lodash.camelcase: 4.3.0 - typical: 7.3.0 - - command-line-usage@7.0.3: - dependencies: - array-back: 6.2.2 - chalk-template: 0.4.0 - table-layout: 4.1.1 - typical: 7.3.0 - commander@12.1.0: {} commander@13.1.0: {} @@ -10938,6 +10887,8 @@ snapshots: electron-to-chromium@1.5.227: {} + electron-to-chromium@1.5.439: {} + elkjs@0.8.2: {} emoji-regex@10.4.0: {} @@ -11330,8 +11281,6 @@ snapshots: dependencies: to-regex-range: 5.0.1 - find-replace@5.0.2: {} - find-up@5.0.0: dependencies: locate-path: 6.0.0 @@ -11350,7 +11299,7 @@ snapshots: flat@5.0.2: {} - flatbuffers@24.12.23: {} + flatbuffers@25.9.23: {} flatted@3.3.3: {} @@ -11371,7 +11320,7 @@ snapshots: hasown: 2.0.2 mime-types: 2.1.35 - fraction.js@4.3.7: {} + fraction.js@5.3.4: {} fs-constants@1.0.0: optional: true @@ -11863,10 +11812,10 @@ snapshots: make-dir: 4.0.0 supports-color: 7.2.0 - istanbul-lib-source-maps@5.0.6(supports-color@8.1.1): + istanbul-lib-source-maps@5.0.6(supports-color@9.4.0): dependencies: '@jridgewell/trace-mapping': 0.3.29 - debug: 4.4.1(supports-color@8.1.1) + debug: 4.4.1(supports-color@9.4.0) istanbul-lib-coverage: 3.2.2 transitivePeerDependencies: - supports-color @@ -11976,8 +11925,6 @@ snapshots: jsesc@3.1.0: {} - json-bignum@0.0.3: {} - json-buffer@3.0.1: {} json-parse-even-better-errors@2.3.1: {} @@ -11988,6 +11935,8 @@ snapshots: json-stable-stringify-without-jsonify@1.0.1: {} + json-with-bigint@3.5.12: {} + json5@2.2.3: {} jsonc-parser@2.2.1: {} @@ -12135,8 +12084,6 @@ snapshots: dependencies: p-locate: 6.0.0 - lodash.camelcase@4.3.0: {} - lodash.castarray@4.4.0: {} lodash.includes@4.3.0: {} @@ -12606,6 +12553,8 @@ snapshots: node-releases@2.0.21: {} + node-releases@2.0.57: {} + node-sarif-builder@3.2.0: dependencies: '@types/sarif': 2.1.7 @@ -12619,8 +12568,6 @@ snapshots: normalize-path@3.0.0: {} - normalize-range@0.1.2: {} - npm-package-arg@12.0.2: dependencies: hosted-git-info: 8.1.0 @@ -13047,7 +12994,7 @@ snapshots: dependencies: dnd-core: 16.0.1 - react-dnd@16.0.1(@types/node@24.1.0)(@types/react@18.3.23)(react@18.3.1): + react-dnd@16.0.1(@types/node@25.9.7)(@types/react@18.3.23)(react@18.3.1): dependencies: '@react-dnd/invariant': 4.0.2 '@react-dnd/shallowequal': 4.0.2 @@ -13056,7 +13003,7 @@ snapshots: hoist-non-react-statics: 3.3.2 react: 18.3.1 optionalDependencies: - '@types/node': 24.1.0 + '@types/node': 25.9.7 '@types/react': 18.3.23 react-docgen-typescript@2.4.0(typescript@5.8.3): @@ -13363,7 +13310,7 @@ snapshots: dependencies: '@types/json-schema': 7.0.15 ajv: 8.17.1 - ajv-formats: 2.1.1(ajv@8.17.1) + ajv-formats: 2.1.1 ajv-keywords: 5.1.0(ajv@8.17.1) secretlint@10.2.1(supports-color@8.1.1): @@ -13798,11 +13745,6 @@ snapshots: tabbable@6.2.0: {} - table-layout@4.1.1: - dependencies: - array-back: 6.2.2 - wordwrapjs: 5.1.0 - table@6.9.0: dependencies: ajv: 8.17.1 @@ -14113,8 +14055,6 @@ snapshots: typescript@5.8.3: {} - typical@7.3.0: {} - uc.micro@2.1.0: {} ufo@1.6.1: {} @@ -14130,10 +14070,7 @@ snapshots: undici-types@5.26.5: {} - undici-types@6.21.0: {} - - undici-types@7.8.0: - optional: true + undici-types@7.24.6: {} undici@7.12.0: {} @@ -14193,6 +14130,12 @@ snapshots: escalade: 3.2.0 picocolors: 1.1.1 + update-browserslist-db@1.3.3(browserslist@4.29.1): + dependencies: + browserslist: 4.29.1 + escalade: 3.2.0 + picocolors: 1.1.1 + uri-js@4.4.1: dependencies: punycode: 2.3.1 @@ -14295,13 +14238,13 @@ snapshots: - tsx - yaml - vite-node@3.2.4(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(supports-color@9.4.0)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0): + vite-node@3.2.4(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(supports-color@9.4.0)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0): dependencies: cac: 6.7.14 debug: 4.4.1(supports-color@9.4.0) es-module-lexer: 1.7.0 pathe: 2.0.3 - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) transitivePeerDependencies: - '@types/node' - jiti @@ -14316,9 +14259,9 @@ snapshots: - tsx - yaml - vite-plugin-css-injected-by-js@3.5.2(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)): + vite-plugin-css-injected-by-js@3.5.2(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)): dependencies: - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) vite-plugin-dts@4.5.4(@types/node@20.11.25)(rollup@4.45.1)(supports-color@9.4.0)(typescript@5.8.3)(vite@6.3.5(@types/node@20.11.25)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)): dependencies: @@ -14365,7 +14308,7 @@ snapshots: tsx: 4.20.3 yaml: 2.9.0 - vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0): + vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0): dependencies: esbuild: 0.25.8 fdir: 6.4.6(picomatch@4.0.3) @@ -14374,7 +14317,7 @@ snapshots: rollup: 4.45.1 tinyglobby: 0.2.14 optionalDependencies: - '@types/node': 24.1.0 + '@types/node': 25.9.7 fsevents: 2.3.3 jiti: 2.4.2 lightningcss: 1.30.1 @@ -14472,11 +14415,11 @@ snapshots: - tsx - yaml - vitest@3.2.4(@types/debug@4.1.12)(@types/node@24.1.0)(@vitest/browser@3.2.3)(@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): + vitest@3.2.4(@types/debug@4.1.12)(@types/node@25.9.7)(@vitest/browser@3.2.3)(@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): dependencies: '@types/chai': 5.2.2 '@vitest/expect': 3.2.4 - '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) + '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) '@vitest/pretty-format': 3.2.4 '@vitest/runner': 3.2.4 '@vitest/snapshot': 3.2.4 @@ -14494,13 +14437,13 @@ snapshots: tinyglobby: 0.2.14 tinypool: 1.1.1 tinyrainbow: 2.0.0 - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) - vite-node: 3.2.4(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(supports-color@9.4.0)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite-node: 3.2.4(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(supports-color@9.4.0)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) why-is-node-running: 2.3.0 optionalDependencies: '@types/debug': 4.1.12 - '@types/node': 24.1.0 - '@vitest/browser': 3.2.3(playwright@1.54.1)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4) + '@types/node': 25.9.7 + '@vitest/browser': 3.2.3(playwright@1.54.1)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4) '@vitest/ui': 3.2.4(vitest@3.2.4) jsdom: 26.1.0(supports-color@9.4.0) transitivePeerDependencies: @@ -14517,11 +14460,11 @@ snapshots: - tsx - yaml - vitest@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): + vitest@3.2.4(@types/debug@4.1.12)(@types/node@25.9.7)(@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): dependencies: '@types/chai': 5.2.2 '@vitest/expect': 3.2.4 - '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) + '@vitest/mocker': 3.2.4(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0)) '@vitest/pretty-format': 3.2.4 '@vitest/runner': 3.2.4 '@vitest/snapshot': 3.2.4 @@ -14539,13 +14482,13 @@ snapshots: tinyglobby: 0.2.14 tinypool: 1.1.1 tinyrainbow: 2.0.0 - vite: 6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) - vite-node: 3.2.4(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(supports-color@9.4.0)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite: 6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) + vite-node: 3.2.4(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(supports-color@9.4.0)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0) why-is-node-running: 2.3.0 optionalDependencies: '@types/debug': 4.1.12 - '@types/node': 24.1.0 - '@vitest/browser': 3.2.4(playwright@1.54.1)(vite@6.3.5(@types/node@24.1.0)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4) + '@types/node': 25.9.7 + '@vitest/browser': 3.2.4(playwright@1.54.1)(vite@6.3.5(@types/node@25.9.7)(jiti@2.4.2)(lightningcss@1.30.1)(terser@5.44.0)(tsx@4.20.3)(yaml@2.9.0))(vitest@3.2.4) '@vitest/ui': 3.2.4(vitest@3.2.4) jsdom: 26.1.0(supports-color@9.4.0) transitivePeerDependencies: @@ -14592,7 +14535,7 @@ snapshots: glob-to-regexp: 0.4.1 graceful-fs: 4.2.11 - web-vitals@4.2.4: {} + web-vitals@6.2.3: {} webidl-conversions@3.0.1: {} @@ -14701,8 +14644,6 @@ snapshots: word-wrap@1.2.5: {} - wordwrapjs@5.1.0: {} - workerpool@6.5.1: {} wrap-ansi@7.0.0: diff --git a/posts/virtual_data_environments.md b/posts/virtual_data_environments.md index 5cde9dba51..792768ec1c 100644 --- a/posts/virtual_data_environments.md +++ b/posts/virtual_data_environments.md @@ -158,4 +158,4 @@ With **Virtual Data Environments**, SQLMesh is able to provide fully **isolated* To streamline deploying changes to production, our team is about to release the SQLMesh [CI/CD bot](https://github.com/SQLMesh/sqlmesh/blob/main/docs/integrations/github.md), which will help automate this process. -Don't miss out - join our [Slack channel](https://tobikodata.com/slack) and stay tuned! +Don't miss out - join our [Slack channel](https://tobiko-data.slack.com/) and stay tuned! diff --git a/pyproject.toml b/pyproject.toml index 2c897de225..3668b4cb6b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -9,7 +9,7 @@ requires-python = ">= 3.9" dependencies = [ "click", "croniter", - "duckdb>=0.10.0,!=0.10.3", + "duckdb>=0.10.0,!=0.10.3,<2", "dateparser<=1.2.1", "humanize", "hyperscript>=0.1.0", @@ -112,12 +112,16 @@ dev = [ ] dbt = ["dbt-core<2"] dlt = ["dlt"] +db2 = [ + "ibm_db", + "db2-sqlglot-dialect>=1.1.0;python_version>=\"3.10\"" +] duckdb = [] fabric = ["pyodbc>=5.0.0"] fabric-mssql-python = ["mssql-python>=1.1.0;python_version>=\"3.10\""] gcppostgres = ["cloud-sql-python-connector[pg8000]>=1.8.0"] github = ["PyGithub>=2.6.0"] -motherduck = ["duckdb>=1.3.2"] +motherduck = ["duckdb>=1.3.2,<2"] mssql = ["pymssql"] mssql-odbc = ["pyodbc>=5.0.0"] mssql-python = ["mssql-python>=1.1.0;python_version>=\"3.10\""] @@ -253,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 @@ -268,8 +273,10 @@ markers = [ "athena: test for Athena", "bigquery: test for BigQuery", "clickhouse: test for Clickhouse (standalone mode / cluster mode)", + "clickhouse_datalake: test for ClickHouse DataLakeCatalog mapping", "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/cli/main.py b/sqlmesh/cli/main.py index c2c81ada9c..896b47abd7 100644 --- a/sqlmesh/cli/main.py +++ b/sqlmesh/cli/main.py @@ -273,7 +273,7 @@ def init( Need help? • Docs: https://sqlmesh.readthedocs.io -• Slack: https://www.tobikodata.com/slack +• Slack: https://tobiko-data.slack.com/ • GitHub: https://github.com/SQLMesh/sqlmesh/issues """) @@ -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/audit/builtin.py b/sqlmesh/core/audit/builtin.py index b4eaab8d50..f20ce24dc0 100644 --- a/sqlmesh/core/audit/builtin.py +++ b/sqlmesh/core/audit/builtin.py @@ -297,7 +297,7 @@ def create_non_blocking_copy(audit: Audit) -> Audit: SELECT * FROM @this_model WHERE @AND( - NOT REGEXP_LIKE(LOWER(@column), '^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), + NOT REGEXP_LIKE(LOWER(@column), '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'), @condition, ) @@ -318,10 +318,14 @@ def create_non_blocking_copy(audit: Audit) -> Audit: # valid_http_method(column=column_name) valid_http_method_audit = ModelAudit( name="valid_http_method", + defaults={"condition": exp.true()}, query=""" SELECT * FROM @this_model -WHERE NOT @column IN ('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'TRACE', 'CONNECT') +WHERE @AND( + NOT @column IN ('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'TRACE', 'CONNECT'), + @condition, +) """, ) @@ -432,7 +436,7 @@ def create_non_blocking_copy(audit: Audit) -> Audit: @column, (@column - mean_@column) / NULLIF(stddev_@column, 0) AS z_score FROM @this_model, stats -WHERE ABS((@column - mean_@column) / NULLIF(stddev_@column, 0)) > @threshold +WHERE @AND(ABS((@column - mean_@column) / NULLIF(stddev_@column, 0)) > @threshold, @condition) """, ) diff --git a/sqlmesh/core/audit/definition.py b/sqlmesh/core/audit/definition.py index 4c90151ee4..13eb9d3219 100644 --- a/sqlmesh/core/audit/definition.py +++ b/sqlmesh/core/audit/definition.py @@ -528,6 +528,9 @@ def load_multiple_audits( yield load_audit( expressions=audit_block, path=path, + module_path=module_path, + macros=macros, + jinja_macros=jinja_macros, dialect=dialect, default_catalog=default_catalog, variables=variables, diff --git a/sqlmesh/core/config/connection.py b/sqlmesh/core/config/connection.py index 73fe1b9300..1fef730c95 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+)") @@ -820,6 +823,7 @@ class DatabricksConnectionConfig(ConnectionConfig): force_databricks_connect: bool = False disable_databricks_connect: bool = False disable_spark_session: bool = False + force_shared_connection: bool = False concurrent_tasks: int = 1 register_comments: bool = True @@ -836,8 +840,27 @@ class DatabricksConnectionConfig(ConnectionConfig): @computed_field # type: ignore[prop-decorator] @property def shared_connection(self) -> bool: - """The connection should only be shared if U2M OAuth is being used""" - return self.auth_type is not None and self.oauth_client_secret is None + """U2M OAuth connections share one login, so each thread can have its own connection. When the login can't + be shared, or `force_shared_connection` is set, a single connection is shared so only one browser flow runs.""" + return self.force_shared_connection or ( + self._uses_u2m_oauth and not self._uses_shared_u2m_login + ) + + @property + def _uses_shared_u2m_login(self) -> bool: + """Whether every connection is given the same U2M OAuth login, letting each thread have its own connection.""" + from sqlmesh.utils.databricks import supports_shared_u2m_login + + return bool( + self._uses_u2m_oauth + and self.server_hostname + and not self.force_shared_connection + and supports_shared_u2m_login() + ) + + @property + def _uses_u2m_oauth(self) -> bool: + return bool(self.auth_type and "oauth" in self.auth_type and not self.oauth_client_secret) @model_validator(mode="before") def _databricks_connect_validator(cls, data: t.Any) -> t.Any: @@ -989,6 +1012,19 @@ def _static_connection_kwargs(self) -> t.Dict[str, t.Any]: else: # if auth_type is set to an 'oauth' type but no client_id/secret are set, then we are using U2M # ref: https://docs.databricks.com/en/dev-tools/python-sql-connector.html#oauth-user-to-machine-u2m-authentication + # All connections share one login so that each thread can have its own connection without + # running its own browser flow. `credentials_provider` takes precedence over `auth_type` on the + # connector's Thrift and SEA backends. `auth_type` is still passed for the connector's kernel + # backend, which ignores `credentials_provider` and runs its own U2M flow for each connection + # (`force_shared_connection` avoids that by only opening one connection). + from sqlmesh.utils.databricks import get_shared_u2m_credentials_provider + + if self._uses_shared_u2m_login: + if t.TYPE_CHECKING: + assert self.server_hostname is not None + conn_kwargs["credentials_provider"] = get_shared_u2m_credentials_provider( + self.server_hostname, self.auth_type + ) conn_kwargs["auth_type"] = self.auth_type return conn_kwargs @@ -2241,6 +2277,7 @@ class ClickhouseConnectionConfig(ConnectionConfig): port: t.Optional[int] = None cluster: t.Optional[str] = None virtual_catalog: t.Optional[str] = None + datalake_catalog_mapping: t.Dict[str, str] = Field(default_factory=dict) connect_timeout: int = 10 send_receive_timeout: int = 300 query_limit: int = 0 @@ -2288,6 +2325,21 @@ def validate_virtual_catalog(cls, v: t.Optional[str]) -> t.Optional[str]: ) return v + @field_validator("datalake_catalog_mapping") + def validate_datalake_catalog_mapping(cls, v: t.Dict[str, str]) -> t.Dict[str, str]: + for source_catalog, target_database in v.items(): + if not source_catalog.strip() or "." in source_catalog: + raise ConfigError( + "datalake_catalog_mapping keys must be non-empty single identifiers " + f"(got: {source_catalog!r})" + ) + if not target_database.strip() or "." in target_database: + raise ConfigError( + "datalake_catalog_mapping values must be non-empty ClickHouse database " + f"identifiers (got: {target_database!r})" + ) + return v + @property def _connection_kwargs_keys(self) -> t.Set[str]: kwargs = { @@ -2354,6 +2406,7 @@ def _extra_engine_config(self) -> t.Dict[str, t.Any]: "cluster": self.cluster, "cloud_mode": self.cloud_mode, "virtual_catalog": self.virtual_catalog, + "datalake_catalog_mapping": self.datalake_catalog_mapping, } @property @@ -2602,6 +2655,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 @@ -2657,7 +2797,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/sqlmesh/core/console.py b/sqlmesh/core/console.py index ca11b6e607..7b9264537f 100644 --- a/sqlmesh/core/console.py +++ b/sqlmesh/core/console.py @@ -6,6 +6,7 @@ import unittest import uuid import logging +import re import textwrap from humanize import metric, naturalsize from itertools import zip_longest @@ -407,6 +408,20 @@ class Console( INDIRECTLY_MODIFIED_DISPLAY_THRESHOLD = 10 + def get_execution_observer( + self, + ) -> t.Optional[ + t.Callable[ + [t.Literal["start", "finish"], t.Mapping[str, t.Any], t.Optional[BaseException]], None + ] + ]: + """Optional start/finish hook receiving native facts and original errors. + + May run concurrently. No IDs, clocks or product status are supplied. + Implementations must return promptly; ordinary hook errors are isolated. + """ + return None + @abc.abstractmethod def start_plan_evaluation(self, plan: EvaluatablePlan) -> None: """Indicates that a new evaluation has begun.""" @@ -3354,10 +3369,13 @@ def show_environment_difference_summary( if context_diff.has_environment_statements_changes and not no_diff: self._print("\nEnvironment statements:\n") - for _, diff in context_diff.environment_statements_diff( + for language, diff in context_diff.environment_statements_diff( include_python_env=not context_diff.is_new_environment ): - self._print(diff) + if language == "sql": + self._print_diff(diff) + else: + self._print(diff) def show_model_difference_summary( self, @@ -3474,12 +3492,8 @@ def _print_modified_models( diff_text = context_diff.text_diff(snapshot.name) # sometimes there is no text_diff, like on a seed model where the data has been updated if diff_text: - diff_text = f"\n```diff\n{diff_text}\n```" # these are part of a Markdown list, so indent them by 2 spaces to relate them to the current list item - diff_text_indented = "\n".join( - [f" {line}" for line in diff_text.splitlines()] - ) - self._print(diff_text_indented) + self._print_diff(diff_text, indent=" ") else: if indirectly_modified_children: self._print("\n") @@ -3573,7 +3587,7 @@ def _show_categorized_snapshots(self, plan: Plan, default_catalog: t.Optional[st else: continue - self._print(f"```diff\n{context_diff.text_diff(snapshot.name)}\n```\n") + self._print_diff(context_diff.text_diff(snapshot.name)) self._print("```\n") self._print(tree) self._print("\n```") @@ -3697,6 +3711,15 @@ def _print(self, value: t.Any, **kwargs: t.Any) -> None: self.console.print(value, **kwargs) self._captured_outputs.append(capture.get()) + def _print_diff(self, diff: str, indent: str = "") -> None: + longest_backticks = max((len(run) for run in re.findall(r"`+", diff)), default=0) + fence = "`" * max(3, longest_backticks + 1) + indented_diff = diff.replace("\n", f"\n{indent}") + block = f"{indent}\n{indent}{fence}diff\n{indent}{indented_diff}\n{indent}{fence}\n" + # Capture the Markdown source, since even literal Rich output expands tabs. + self._captured_outputs.append(block) + self.console.print(block, markup=False, emoji=False, soft_wrap=True, end="") + class DatabricksMagicConsole(CaptureTerminalConsole): """ diff --git a/sqlmesh/core/context.py b/sqlmesh/core/context.py index b70ccae141..fd7f8ad071 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 @@ -107,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 @@ -119,7 +121,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 ( @@ -418,6 +420,7 @@ def __init__( self._engine_adapter: t.Optional[EngineAdapter] = None self._linters: t.Dict[str, Linter] = {} self._loaded: bool = False + self._materializations_loaded: bool = False self._load_state: bool = load_state self._uncached_model_names: t.Set[str] = set() self._selector_cls = selector or NativeSelector @@ -746,7 +749,25 @@ def load( prod = self.state_reader.get_environment(c.PROD) if prod: - for snapshot in self.state_reader.get_snapshots(prod.snapshots).values(): + # Environment snapshot infos already contain the names we need to distinguish + # local nodes from nodes owned by another project. Hydrating local snapshots + # here is wasteful: their payloads are not used, and a large remote state can + # spend most of Context.load() decoding those model object graphs. + # + # Only hydrate names which are absent locally. These can be deleted nodes from + # this project or nodes from another project which must be merged into the + # context. The project field on the hydrated node disambiguates the two cases. + remote_snapshot_infos = [] + for snapshot_info in prod.snapshots: + local_store = ( + self._standalone_audits if snapshot_info.is_audit else self._models + ) + if snapshot_info.name in local_store: + uncached.add(snapshot_info.name) + else: + remote_snapshot_infos.append(snapshot_info) + + for snapshot in self.state_reader.get_snapshots(remote_snapshot_infos).values(): if snapshot.node.project in self._projects: uncached.add(snapshot.name) else: @@ -787,6 +808,7 @@ def load( ) self._loaded = True + self._materializations_loaded = True return self def _update_model_schemas_and_validate(self, model_fqns: t.Optional[t.Set[str]] = None) -> None: @@ -997,6 +1019,10 @@ def run_janitor( @python_api_analytics def destroy(self) -> bool: + # Load first so snapshot unpickling cannot import a custom-kind module that this load then reimports. + # If loading fails, abort before invalidating any environments. + self._load_materializations() + success = False # Collect resources to be deleted @@ -2407,6 +2433,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 +2441,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: @@ -2600,8 +2635,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: @@ -2609,6 +2646,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 @@ -2617,7 +2655,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: @@ -2691,6 +2732,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.""" @@ -3141,6 +3188,8 @@ def _run_janitor( current_ts = now_timestamp() failures: t.List[str] = [] + self._load_materializations() + # Clean up expired environments by removing their views and schemas failures.extend( self._cleanup_environments( @@ -3280,6 +3329,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) @@ -3313,9 +3381,10 @@ def _register_notification_targets(self) -> None: ) def _load_materializations(self) -> None: - if not self._loaded: + if not self._materializations_loaded: for loader in self._loaders: loader.load_materializations() + self._materializations_loaded = True def _select_models_for_run( self, @@ -3611,30 +3680,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/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/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/base.py b/sqlmesh/core/engine_adapter/base.py index 930cdf7cd4..4242e1ebb0 100644 --- a/sqlmesh/core/engine_adapter/base.py +++ b/sqlmesh/core/engine_adapter/base.py @@ -457,6 +457,14 @@ def get_current_catalog(self) -> t.Optional[str]: """Returns the catalog name of the current connection.""" raise NotImplementedError() + def _get_current_catalog_for_set_catalog(self) -> t.Optional[str]: + """Catalog token @set_catalog saves and restores. + + Override when get_current_catalog() reports a default catalog name but + the restore must keep an internal sentinel so the connection is not reopened. + """ + return self.get_current_catalog() + def set_current_catalog(self, catalog: str) -> None: """Sets the catalog name of the current connection.""" raise NotImplementedError() @@ -833,7 +841,9 @@ def _create_table_from_columns( and self.COMMENT_CREATION_TABLE.is_comment_command_only and self.comments_enabled ): - self._create_column_comments(table_name, column_descriptions) + self._create_column_comments( + table_name, column_descriptions, table_format=kwargs.get("table_format") + ) def _build_schema_exp( self, @@ -990,7 +1000,11 @@ def _create_table_from_source_queries( ): self._create_table_comment(table_name, table_description) if column_descriptions and schema is None and self.comments_enabled: - self._create_column_comments(table_name, column_descriptions) + self._create_column_comments( + table_name, + column_descriptions, + table_format=None if table_kind else kwargs.get("table_format"), + ) def _create_table( self, @@ -1043,12 +1057,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 +1074,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 +1384,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: @@ -2636,12 +2658,17 @@ def execute( sql = self._attach_correlation_id(sql) - self._log_sql( - sql, - expression=e if isinstance(e, exp.Expr) else None, - quote_identifiers=quote_identifiers, - ) - self._execute(sql, track_rows_processed, **kwargs) + # The rendered statement and correlation comment are finalized + # here; observe the exact invocation, including driver errors. + from sqlmesh.core.execution_observation import action + + with action("query", "execute", engine=self.dialect): + self._log_sql( + sql, + expression=e if isinstance(e, exp.Expr) else None, + quote_identifiers=quote_identifiers, + ) + self._execute(sql, track_rows_processed, **kwargs) def _attach_correlation_id(self, sql: str) -> str: if self.ATTACH_CORRELATION_ID and self.correlation_id: @@ -3070,7 +3097,18 @@ def _create_column_comments( column_comments: t.Dict[str, str], table_kind: str = "TABLE", materialized_view: bool = False, + table_format: t.Optional[str] = None, ) -> None: + """Registers column comments with a post-creation command. + + Args: + table_name: The name of the table or view. + column_comments: Mapping between the column name and its comment. + table_kind: The kind of object being commented on, `TABLE` or `VIEW`. + materialized_view: Whether the view is materialized. + table_format: The table format of the table, if any. Engines that require + format-specific DDL to alter a table use it to derive `table_kind`. + """ table = exp.to_table(table_name) for col, comment in column_comments.items(): diff --git a/sqlmesh/core/engine_adapter/bigquery.py b/sqlmesh/core/engine_adapter/bigquery.py index 7917aaa149..e87a768f2d 100644 --- a/sqlmesh/core/engine_adapter/bigquery.py +++ b/sqlmesh/core/engine_adapter/bigquery.py @@ -819,6 +819,7 @@ def _create_column_comments( column_comments: t.Dict[str, str], table_kind: str = "TABLE", materialized_view: bool = False, + table_format: t.Optional[str] = None, ) -> None: if not (table_kind == "VIEW" and materialized_view): table = self._get_table(table_name) diff --git a/sqlmesh/core/engine_adapter/clickhouse.py b/sqlmesh/core/engine_adapter/clickhouse.py index 16ae5b5b51..27b35ee00c 100644 --- a/sqlmesh/core/engine_adapter/clickhouse.py +++ b/sqlmesh/core/engine_adapter/clickhouse.py @@ -3,7 +3,9 @@ import typing as t import logging import re +from functools import cached_property from sqlglot import exp, maybe_parse +from sqlglot.optimizer.scope import Scope, find_all_in_scope, traverse_scope from sqlmesh.core.dialect import to_schema from sqlmesh.core.engine_adapter.mixins import LogicalMergeMixin from sqlmesh.core.engine_adapter.base import EngineAdapterWithIndexSupport @@ -19,6 +21,7 @@ ) from sqlmesh.core.schema_diff import TableAlterOperation from sqlmesh.utils import get_source_columns_to_types +from sqlmesh.utils.errors import SQLMeshError if t.TYPE_CHECKING: import pandas as pd @@ -31,6 +34,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" @@ -61,6 +71,168 @@ 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.""" + virtual_catalog = self._default_catalog or self._extra_config.get("virtual_catalog") + if virtual_catalog and any(self._virtual_catalog_references(expression)): + expression = expression.copy() + for reference in list(self._virtual_catalog_references(expression)): + reference.set("catalog", None) + if isinstance(expression, exp.Query): + expression = self._map_catalog_references(expression, preserve_unmapped=True) + elif isinstance(expression, exp.Delete): + where = expression.args.get("where") + if where and any(where.find_all(exp.Query)): + expression = expression.copy() + where = expression.args["where"] + expression.set( + "where", + where.transform( + lambda node: self._map_catalog_references(node) + if isinstance(node, exp.Query) + else node, + copy=False, + ), + ) + elif isinstance(expression, exp.Insert) and isinstance(expression.expression, exp.Query): + expression = expression.copy() + expression.set("expression", self._map_catalog_references(expression.expression)) + return super()._to_sql(expression, quote=quote, **kwargs) + + def _virtual_catalog_references( + self, expression: exp.Expr + ) -> t.Iterator[t.Union[exp.Table, exp.Column]]: + virtual_catalog = self._default_catalog or self._extra_config.get("virtual_catalog") + return ( + reference + for reference in self._catalog_references(expression) + if virtual_catalog and reference.text("catalog") == virtual_catalog + ) + + def _get_source_queries( + self, + query_or_df: QueryOrDF, + target_columns_to_types: t.Optional[t.Dict[str, exp.DataType]], + target_table: TableName, + *, + batch_size: t.Optional[int] = None, + source_columns: t.Optional[t.List[str]] = None, + ) -> t.List[SourceQuery]: + if isinstance(query_or_df, exp.Query): + query_or_df = self._map_catalog_references(query_or_df) + return super()._get_source_queries( + query_or_df, + target_columns_to_types, + target_table, + batch_size=batch_size, + source_columns=source_columns, + ) + + def _map_catalog_references(self, query: Query, *, preserve_unmapped: bool = False) -> Query: + mapping = self._extra_config.get("datalake_catalog_mapping") or {} + if not self._default_catalog and not mapping: + return query + + mapped_catalogs = {self._default_catalog, *mapping} + query = query.copy() + for reference in self._catalog_references(query): + if not reference.catalog or ( + preserve_unmapped and reference.catalog not in mapped_catalogs + ): + continue + if isinstance(reference, exp.Table): + self._map_catalog_reference(reference) + continue + + table = self._map_catalog_reference( + exp.Table( + this=reference.args["table"].copy(), + db=reference.args["db"].copy(), + catalog=reference.args["catalog"].copy(), + ) + ) + for column_key, table_key in (("table", "this"), ("db", "db"), ("catalog", "catalog")): + value = table.args.get(table_key) + reference.set(column_key, value.copy() if value is not None else None) + return query + + def _catalog_references(self, expression: exp.Expr) -> t.List[t.Union[exp.Table, exp.Column]]: + """Use query scopes to distinguish qualified columns from nested-field paths.""" + tables = list(expression.find_all(exp.Table)) + references: t.List[t.Union[exp.Table, exp.Column]] = list(tables) + root_tables = list(find_all_in_scope(expression, exp.Table)) + scoped_columns = set() + virtual_catalog = self._default_catalog or self._extra_config.get("virtual_catalog") + + def matches_source_table(column: exp.Column, table: exp.Table) -> bool: + if (column.catalog, column.db, column.table) == (table.catalog, table.db, table.name): + return True + # ClickHouse strips the virtual catalog from DML targets before SQL rendering. + return ( + column.catalog == virtual_catalog + and not table.catalog + and (column.db, column.table) == (table.db, table.name) + ) + + def add_column_reference(column: exp.Column, scope: t.Optional[Scope]) -> None: + if not column.catalog: + return + current_scope = scope + while current_scope is not None: + # The nearest alias or CTE name takes precedence as a nested-field path. + if column.catalog in current_scope.sources: + return + if any( + isinstance(source, exp.Table) and matches_source_table(column, source) + for source in current_scope.sources.values() + ): + references.append(column) + return + current_scope = current_scope.parent + + if column.catalog in {table.alias_or_name for table in root_tables}: + return + if any(matches_source_table(column, table) for table in root_tables): + references.append(column) + + for scope in traverse_scope(expression): + for column in scope.find_all(exp.Column): + scoped_columns.add(id(column)) + add_column_reference(column, scope) + + for column in find_all_in_scope(expression, exp.Column): + if id(column) not in scoped_columns: + add_column_reference(column, None) + return references + + def _map_catalog_reference(self, table: exp.Table) -> exp.Table: + """Map catalog.schema.table to a ClickHouse DataLakeCatalog database.table reference.""" + catalog = table.catalog + if not catalog: + return table + if catalog == self._default_catalog: + table.set("catalog", None) + return table + + target_database = (self._extra_config.get("datalake_catalog_mapping") or {}).get(catalog) + if target_database: + if not table.db: + raise SQLMeshError( + f"ClickHouse DataLakeCatalog mapping for '{catalog}' requires a " + "three-level catalog.schema.table reference" + ) + source_table = f"{table.db}.{table.name}" + table.set("catalog", None) + table.set("db", exp.to_identifier(target_database)) + table.set("this", exp.to_identifier(source_table, quoted=True)) + return table + + raise SQLMeshError( + f"{self.dialect} requires that all catalog operations be against the virtual " + f"catalog {self._default_catalog!r} or a configured DataLakeCatalog mapping. " + f"Provided catalog: {catalog}" + ) + @property def engine_run_mode(self) -> EngineRunMode: if self._extra_config.get("cloud_mode"): @@ -194,9 +366,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 @@ -417,7 +595,7 @@ def _build_alter_partition_exp( ) -> exp.Alter: alter_expr = exp.Alter(this=target_table, kind="TABLE") - for partition in partitions_to_replace: + for partition in sorted(partitions_to_replace): alter_expr.append( "actions", exp.ReplacePartition( @@ -428,7 +606,7 @@ def _build_alter_partition_exp( ), ) - for partition in partitions_to_drop: + for partition in sorted(partitions_to_drop): alter_expr.append( "actions", exp.DropPartition( @@ -502,8 +680,15 @@ 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}" + f"{self._on_cluster_sql(target_table_name)} AS {source_table_sql}" ) def _get_partition_ids( @@ -648,7 +833,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,13 +845,21 @@ 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 + ) + + 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, @@ -685,14 +878,25 @@ 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()}") + 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) @@ -711,7 +915,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)) ) @@ -735,14 +953,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, ) @@ -844,6 +1072,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] = [] @@ -922,7 +1151,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: @@ -947,6 +1176,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""" @@ -954,7 +1184,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: @@ -974,12 +1204,12 @@ 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) - 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, @@ -989,16 +1219,175 @@ 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) 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/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/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/sqlmesh/core/engine_adapter/fabric.py b/sqlmesh/core/engine_adapter/fabric.py index 427a04d087..b4856a4ac5 100644 --- a/sqlmesh/core/engine_adapter/fabric.py +++ b/sqlmesh/core/engine_adapter/fabric.py @@ -8,9 +8,11 @@ from sqlglot import exp from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_result from sqlmesh.core.engine_adapter.mssql import MSSQLEngineAdapter +from sqlmesh.core.dialect import to_schema from sqlmesh.core.engine_adapter.shared import ( CommentCreationTable, CommentCreationView, + DataObject, InsertOverwriteStrategy, ) from sqlmesh.utils.errors import SQLMeshError @@ -18,7 +20,6 @@ from sqlmesh.core.schema_diff import TableAlterOperation from sqlmesh.utils import random_id - logger = logging.getLogger(__name__) @@ -85,6 +86,15 @@ def _catalog_state_label(self, catalog_name: t.Optional[str]) -> str: or "" ) + def _resolved_catalog(self) -> t.Optional[str]: + # A lazy restore sets the logical target back to the default but leaves + # the open connection on the previous warehouse. Name that connection, + # because that is the warehouse the query hits. + connected_catalog = self._normalize_catalog(self._connected_catalog) + if self._normalize_catalog(self._target_catalog) is None and connected_catalog: + return connected_catalog + return self.get_current_catalog() + @property def api_client(self) -> FabricHttpClient: # the requests Session is not guaranteed to be threadsafe @@ -145,10 +155,29 @@ def _drop_catalog(self, catalog_name: exp.Identifier) -> None: if warehouse_name in in_use: self.close() - def get_current_catalog(self) -> t.Optional[str]: - """Return the explicit Fabric catalog target for the current thread.""" + def _get_current_catalog_for_set_catalog(self) -> t.Optional[str]: + """Override of EngineAdapter._get_current_catalog_for_set_catalog. + + The base method returns get_current_catalog(). @set_catalog saves that + value and writes it back with set_current_catalog. Fabric's public method + returns the configured warehouse name, so restoring it would reconnect. + This returns the normalized internal target instead. None is that default, + and restoring None skips the reconnect. + """ return self._normalize_catalog(self._target_catalog) + def get_current_catalog(self) -> t.Optional[str]: + """Return the warehouse name for the current thread. + + The configured default stays None internally so set_current_catalog can + skip a reconnect. Callers still receive that warehouse's name. None is + returned only when no warehouse is configured. + """ + explicit_catalog = self._normalize_catalog(self._target_catalog) + if explicit_catalog: + return explicit_catalog + return self._default_catalog or self._extra_config.get("database") + def set_current_catalog(self, catalog_name: t.Optional[str]) -> None: """ Set the current catalog for Microsoft Fabric connections. @@ -173,10 +202,12 @@ def set_current_catalog(self, catalog_name: t.Optional[str]) -> None: explicit_default_catalog = catalog_name is not None and target_catalog is None connected_catalog = self._normalize_catalog(self._connected_catalog) + # Compare the internal sentinel, not get_current_catalog(). That method + # returns the configured warehouse name when this sentinel is None. # An explicit request for the default catalog must also match the catalog # used by the open connection. A lazy restore with None only updates the # logical target and intentionally leaves that connection in place. - if self.get_current_catalog() == target_catalog and ( + if self._normalize_catalog(self._target_catalog) == target_catalog and ( not explicit_default_catalog or connected_catalog is None ): logger.debug("Already using requested Fabric catalog state, no action needed") @@ -224,6 +255,55 @@ def set_current_catalog(self, catalog_name: t.Optional[str]) -> None: self._target_catalog = target_catalog + def _get_data_objects( + self, schema_name: t.Union[str, exp.Table], object_names: t.Optional[t.Set[str]] = None + ) -> t.List[DataObject]: + objects = super()._get_data_objects(schema_name, object_names) + # Runs before EngineAdapter.get_data_objects writes the cache. @set_catalog + # has already stripped the catalog, so the lookup key is schema.table. + # MSSQL stamps get_current_catalog() here, which is now the default warehouse + # name, and that would store catalog.schema.table instead. Blank that name so the + # stored key matches. get_data_objects puts it back on the objects it returns. + default_catalog = self._default_catalog or self._extra_config.get("database") + if not default_catalog: + return objects + return [ + DataObject( + catalog=None if obj.catalog == default_catalog else obj.catalog, + schema=obj.schema_name, + name=obj.name, + type=obj.type, + clustering_key=obj.clustering_key, + ) + for obj in objects + ] + + def get_data_objects( + self, + schema_name: t.Union[str, exp.Table], + object_names: t.Optional[t.Set[str]] = None, + safe_to_cache: bool = False, + ) -> t.List[DataObject]: + catalog = to_schema(schema_name).catalog or self._resolved_catalog() + default_catalog = self._default_catalog or self._extra_config.get("database") + if catalog and catalog != default_catalog: + objects = self._get_data_objects(schema_name, object_names) + else: + # Cache key is schema.table, so only the default warehouse may use it. + objects = super().get_data_objects(schema_name, object_names, safe_to_cache) + if not catalog: + return objects + return [ + DataObject( + catalog=obj.catalog or catalog, + schema=obj.schema_name, + name=obj.name, + type=obj.type, + clustering_key=obj.clustering_key, + ) + for obj in objects + ] + def alter_table( self, alter_expressions: t.Union[t.List[exp.Alter], t.List[TableAlterOperation]], @@ -363,7 +443,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/sqlmesh/core/engine_adapter/mixins.py b/sqlmesh/core/engine_adapter/mixins.py index bf4bb970a2..50b8b8752b 100644 --- a/sqlmesh/core/engine_adapter/mixins.py +++ b/sqlmesh/core/engine_adapter/mixins.py @@ -18,6 +18,7 @@ if t.TYPE_CHECKING: from sqlmesh.core._typing import TableName + from sqlmesh.core.engine_adapter.shared import DataObject from sqlmesh.core.engine_adapter._typing import ( DCL, DF, @@ -383,23 +384,53 @@ def get_alter_operations( self.get_data_objects(target_table_schema, {target_table.name}), 0 ) + clustering_operation: t.Optional[TableAlterClusterByOperation] = None if current_table_info and target_table_info: - if target_table_info.is_clustered: - if target_table_info.clustering_key and ( - current_table_info.clustering_key != target_table_info.clustering_key - ): - operations.append( - TableAlterChangeClusterKeyOperation( - target_table=current_table, - clustering_key=target_table_info.clustering_key, - dialect=self.dialect, - ) - ) + if target_table_info.is_clustered and target_table_info.clustering_key: + # Include an unchanged key. Snowflake may have to drop it and set it + # again when a key column is dropped and re-added. Other engines ignore + # that operation in _apply_clustering_operation. + clustering_operation = TableAlterChangeClusterKeyOperation( + target_table=current_table, + clustering_key=target_table_info.clustering_key, + dialect=self.dialect, + ) elif current_table_info.is_clustered: - operations.append(TableAlterDropClusterKeyOperation(target_table=current_table)) + clustering_operation = TableAlterDropClusterKeyOperation(target_table=current_table) + + if clustering_operation: + self._apply_clustering_operation(operations, clustering_operation, current_table_info) return operations + def _clustering_key_is_unchanged( + self, + clustering_operation: "TableAlterClusterByOperation", + current_table_info: t.Optional["DataObject"], + ) -> bool: + return ( + isinstance(clustering_operation, TableAlterChangeClusterKeyOperation) + and current_table_info is not None + and current_table_info.clustering_key == clustering_operation.clustering_key + ) + + def _apply_clustering_operation( + self, + operations: t.List[TableAlterOperation], + clustering_operation: "TableAlterClusterByOperation", + current_table_info: t.Optional["DataObject"], + ) -> None: + """Insert the clustering operation into the alter operations list. + + The default implementation appends a real clustering change after all column + changes. An unchanged key is ignored here. Snowflake overrides this so it can + drop that key before removing a column the key names, then set the same key + after the column comes back. + """ + if self._clustering_key_is_unchanged(clustering_operation, current_table_info): + return + operations.append(clustering_operation) + def logical_merge( engine_adapter: EngineAdapter, 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/sqlmesh/core/engine_adapter/mysql.py b/sqlmesh/core/engine_adapter/mysql.py index 6918cdec49..a20ba2af26 100644 --- a/sqlmesh/core/engine_adapter/mysql.py +++ b/sqlmesh/core/engine_adapter/mysql.py @@ -131,6 +131,7 @@ def _create_column_comments( column_comments: t.Dict[str, str], table_kind: str = "TABLE", materialized_view: bool = False, + table_format: t.Optional[str] = None, ) -> None: table = exp.to_table(table_name) table_sql = table.sql(dialect=self.dialect, identify=True) 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/sqlmesh/core/engine_adapter/shared.py b/sqlmesh/core/engine_adapter/shared.py index ba0e1fa619..04c56dae0b 100644 --- a/sqlmesh/core/engine_adapter/shared.py +++ b/sqlmesh/core/engine_adapter/shared.py @@ -348,8 +348,11 @@ def internal_wrapper(*args: t.Any, **kwargs: t.Any) -> t.Any: f"{engine_adapter.dialect} requires that all catalog operations be against a single catalog: {engine_adapter._default_catalog}. Provided catalog: {catalog_name}" ) return func(*list_args, **kwargs) - # Set the catalog name on the engine adapter if needed - current_catalog = engine_adapter.get_current_catalog() + # Set the catalog name on the engine adapter if needed. + # See EngineAdapter._get_current_catalog_for_set_catalog. Fabric reports + # the configured warehouse name from get_current_catalog() and keeps None + # internally, so a restore of the default warehouse can skip a reconnect. + current_catalog = engine_adapter._get_current_catalog_for_set_catalog() if catalog_name != current_catalog: engine_adapter.set_current_catalog(catalog_name) resp = func(*list_args, **kwargs) diff --git a/sqlmesh/core/engine_adapter/snowflake.py b/sqlmesh/core/engine_adapter/snowflake.py index 37ca6eee22..46bc56903d 100644 --- a/sqlmesh/core/engine_adapter/snowflake.py +++ b/sqlmesh/core/engine_adapter/snowflake.py @@ -1,6 +1,7 @@ from __future__ import annotations import contextlib +import itertools import logging import typing as t @@ -16,7 +17,11 @@ ClusteredByMixin, RowDiffMixin, GrantsFromInfoSchemaMixin, + TableAlterChangeClusterKeyOperation, + TableAlterClusterByOperation, + TableAlterDropClusterKeyOperation, ) +from sqlmesh.core.schema_diff import TableAlterDropColumnOperation, TableAlterOperation from sqlmesh.core.engine_adapter.shared import ( CatalogSupport, DataObject, @@ -24,7 +29,6 @@ SourceQuery, set_catalog, ) -from sqlmesh.core.schema_diff import TableAlterOperation from sqlmesh.utils import optional_import, get_source_columns_to_types from sqlmesh.utils.errors import SQLMeshError from sqlmesh.utils.pandas import columns_to_types_from_dtypes @@ -174,7 +178,7 @@ def _drop_catalog(self, catalog_name: exp.Identifier) -> None: .from_(exp.to_table("information_schema.databases")) .where( exp.and_( - exp.column("database_name").eq(exp.Literal.string(catalog_name)), + exp.column("database_name").eq(exp.Literal.string(catalog_name.name)), exp.column("comment").eq(exp.Literal.string(c.SQLMESH_MANAGED)), ) ) @@ -633,13 +637,20 @@ def _create_column_comments( column_comments: t.Dict[str, str], table_kind: str = "TABLE", materialized_view: bool = False, + table_format: t.Optional[str] = None, ) -> None: """ Reference: https://docs.snowflake.com/en/sql-reference/sql/alter-table-column#syntax + Reference: https://docs.snowflake.com/en/sql-reference/sql/alter-iceberg-table#syntax """ if not column_comments: return + # Snowflake rejects `ALTER TABLE` for Iceberg tables, it requires + # `ALTER ICEBERG TABLE` instead + if table_format and table_kind == "TABLE": + table_kind = f"{table_format.upper()} TABLE" + table = exp.to_table(table_name) table_sql = self._to_sql(table) @@ -692,6 +703,62 @@ def clone_table( **kwargs, ) + def _apply_clustering_operation( + self, + operations: t.List[TableAlterOperation], + clustering_operation: TableAlterClusterByOperation, + current_table_info: t.Optional[DataObject], + ) -> None: + """Apply clustering DDL in the order Snowflake requires. + + DROP COLUMN fails while the column is still in the clustering key, including + inside an expression. CLUSTER BY fails on a column that does not exist yet. A + type change that becomes DROP plus ADD still needs the key dropped first even + when the key text is unchanged. An unchanged key with no matching column drop + emits nothing. DESCRIBE names are compared as stored. + """ + clustering_key = current_table_info.clustering_key if current_table_info else None + operations_include_drop_column = any( + isinstance(op, TableAlterDropColumnOperation) for op in operations + ) + + if clustering_key and operations_include_drop_column: + referenced = self._clustering_key_column_names(clustering_key) + drop_index = next( + ( + i + for i, op in enumerate(operations) + if isinstance(op, TableAlterDropColumnOperation) + and op.column_parts + and op.column_parts[0].name in referenced + ), + None, + ) + if drop_index is not None: + drop_key_op = TableAlterDropClusterKeyOperation( + target_table=clustering_operation.target_table + ) + operations.insert(drop_index, drop_key_op) + if isinstance(clustering_operation, TableAlterChangeClusterKeyOperation): + operations.append(clustering_operation) + return + if self._clustering_key_is_unchanged(clustering_operation, current_table_info): + return + operations.append(clustering_operation) + + def _clustering_key_column_names(self, clustering_key: str) -> t.Set[str]: + expressions = TableAlterChangeClusterKeyOperation( + target_table=exp.to_table("_"), + clustering_key=clustering_key, + dialect=self.dialect, + ).cluster_key_expressions + cluster_columns = itertools.chain.from_iterable( + expression.find_all(exp.Column) for expression in expressions + ) + return { + normalize_identifiers(column, dialect=self.dialect).name for column in cluster_columns + } + def alter_table( self, alter_expressions: t.Union[t.List[exp.Alter], t.List[TableAlterOperation]], @@ -757,14 +824,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/sqlmesh/core/execution_observation.py b/sqlmesh/core/execution_observation.py new file mode 100644 index 0000000000..36f426c90e --- /dev/null +++ b/sqlmesh/core/execution_observation.py @@ -0,0 +1,132 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Optional native lifecycle hooks, independent of telemetry storage or policy. + +Call sites report start before native work and finish in finally, including the +original error. Consumers must return promptly. Ordinary observer exceptions never +replace workload results. The scope only routes hooks and late native metadata; +execution IDs, timing, parent correlation and status mapping belong to consumers. +""" + +from __future__ import annotations + +import contextlib +import contextvars +import functools +import typing as t +from types import MappingProxyType + +Observer = t.Callable[ + [t.Literal["start", "finish"], t.Mapping[str, t.Any], t.Optional[BaseException]], None +] +_dispatching: contextvars.ContextVar[bool] = contextvars.ContextVar( + "execution_observer_dispatch", default=False +) +_scoped: contextvars.ContextVar[bool] = contextvars.ContextVar( + "execution_observer_scoped", default=False +) +_observer: contextvars.ContextVar[t.Optional[Observer]] = contextvars.ContextVar( + "execution_observer", default=None +) +_metadata: contextvars.ContextVar[t.Optional[t.Dict[str, t.Any]]] = contextvars.ContextVar( + "execution_observation_metadata", default=None +) + + +def update_execution(**metadata: t.Any) -> None: + """Supply native facts discovered inside the current hook boundary.""" + current = _metadata.get() + if current is not None and not _dispatching.get(): + current.update(metadata) + + +@contextlib.contextmanager +def observer_scope(observer: t.Optional[Observer]) -> t.Iterator[None]: + token = _observer.set(observer) + scope_token = _scoped.set(True) + metadata_token = _metadata.set(None) + try: + yield + finally: + _metadata.reset(metadata_token) + _scoped.reset(scope_token) + _observer.reset(token) + + +def _notify( + observer: Observer, + phase: t.Literal["start", "finish"], + metadata: t.Mapping[str, t.Any], + error: t.Optional[BaseException] = None, +) -> None: + token = _dispatching.set(True) + try: + observer(phase, metadata, error) + except Exception: + # Hooks are observational: do not alter execution or recursively log a + # telemetry failure. Consumers own their capture-loss reporting. + pass + finally: + _dispatching.reset(token) + + +@contextlib.contextmanager +def action(kind: str, name: str, **metadata: t.Any) -> t.Iterator[t.Optional[t.Dict[str, t.Any]]]: + observer = _observer.get() + if observer is None or _dispatching.get(): + yield None + return + data = {**metadata, "kind": kind, "action": name} + view = MappingProxyType(data) + token = _metadata.set(data) + try: + _notify(observer, "start", view) + error: t.Optional[BaseException] = None + try: + yield data + except BaseException as ex: + error = ex + raise + finally: + _notify(observer, "finish", view, error) + finally: + _metadata.reset(token) + + +def observe_snapshot(kind: str, name: str) -> t.Callable: + """Hook evaluator methods whose first argument after self is snapshot. + + Verified callers pass Snapshot as that argument (positional or keyword). + Pass the native object unchanged; no reflection, identity formatting, skip + classification or snapshot interpretation is performed by this hook. + """ + + def decorate(function: t.Callable) -> t.Callable: + @functools.wraps(function) + def wrapped(self: t.Any, snapshot: t.Any, *args: t.Any, **kwargs: t.Any) -> t.Any: + with action(kind, name, snapshot=snapshot): + return function(self, snapshot, *args, **kwargs) + + return wrapped + + return decorate + + +def execution_context_factory() -> t.Optional[t.Callable[[], contextvars.Context]]: + """Opt in to worker context propagation only during active observation.""" + return ( + contextvars.copy_context if _observer.get() is not None and not _dispatching.get() else None + ) + + +@contextlib.contextmanager +def console_observer_scope(console: t.Any) -> t.Iterator[None]: + """Resolve once at the outer boundary; an explicit None scope disables hooks.""" + if _scoped.get(): + yield + return + try: + observer = console.get_execution_observer() + except Exception: + observer = None + with observer_scope(observer): + yield 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/sqlmesh/core/metric/definition.py b/sqlmesh/core/metric/definition.py index 6119a883ed..fc523298c8 100644 --- a/sqlmesh/core/metric/definition.py +++ b/sqlmesh/core/metric/definition.py @@ -199,6 +199,10 @@ def is_measure(node: exp.Expr) -> bool: return is_measure(parent) if isinstance(parent, (exp.Binary, exp.Paren, exp.Distinct)): return is_measure(parent) + # AGG(x ORDER BY y) is parsed as AGG(Order(this=x, expressions=[Ordered(y)])). + # Only the Order's `this` can be the measure, not the ORDER BY expressions. + if isinstance(parent, exp.Order) and node.arg_key == "this": + return is_measure(parent) return False for node in expression.walk(): diff --git a/sqlmesh/core/model/cache.py b/sqlmesh/core/model/cache.py index 1f038c5d79..573f456459 100644 --- a/sqlmesh/core/model/cache.py +++ b/sqlmesh/core/model/cache.py @@ -112,15 +112,7 @@ def with_optimized_query(self, model: Model, name: t.Optional[str] = None) -> bo cache_entry = self._file_cache.get(name) if cache_entry: try: - # If the optimized rendered query is None, then there are likely adapter calls in the query - # that prevent us from rendering it at load time. This means that we can safely set the - # unoptimized cache to None as well to prevent attempts to render it downstream. - optimized = cache_entry.optimized_rendered_query is not None - model._query_renderer.update_cache( - cache_entry.optimized_rendered_query, - cache_entry.renderer_violations, - optimized=optimized, - ) + self.with_optimized_query_entry(model, cache_entry) return True except Exception as ex: logger.warning("Failed to load a cache entry '%s': %s", name, ex) @@ -128,6 +120,40 @@ def with_optimized_query(self, model: Model, name: t.Optional[str] = None) -> bo self._put(name, model) return False + @staticmethod + def with_optimized_query_entry(model: Model, cache_entry: OptimizedQueryCacheEntry) -> None: + """Adds an already-decoded optimized query cache entry to a model.""" + if not isinstance(model, SqlModel): + return + + # If the optimized rendered query is None, then there are likely adapter calls in the + # query that prevent us from rendering it at load time. This means that we can safely + # set the unoptimized cache to None as well to prevent attempts to render it downstream. + optimized = cache_entry.optimized_rendered_query is not None + model._query_renderer.update_cache( + cache_entry.optimized_rendered_query, + cache_entry.renderer_violations, + optimized=optimized, + ) + + def get_or_create_entry( + self, model: Model, name: t.Optional[str] = None + ) -> t.Optional[OptimizedQueryCacheEntry]: + """Returns one decoded cache entry, creating it when necessary.""" + if not isinstance(model, SqlModel): + return None + + name = self._entry_name(model) if name is None else name + cache_entry = self._file_cache.get(name) + if cache_entry: + try: + self.with_optimized_query_entry(model, cache_entry) + return cache_entry + except Exception as ex: + logger.warning("Failed to load a cache entry '%s': %s", name, ex) + + return self._put(name, model) + def put(self, model: Model) -> t.Optional[str]: if not isinstance(model, SqlModel): return None @@ -140,7 +166,7 @@ def put(self, model: Model) -> t.Optional[str]: self._put(name, model) return name - def _put(self, name: str, model: SqlModel) -> None: + def _put(self, name: str, model: SqlModel) -> OptimizedQueryCacheEntry: optimized_query = model.render_query() new_entry = OptimizedQueryCacheEntry( @@ -148,6 +174,7 @@ def _put(self, name: str, model: SqlModel) -> None: renderer_violations=model.violated_rules_for_query, ) self._file_cache.put(name, value=new_entry) + return new_entry @staticmethod def _entry_name(model: SqlModel) -> str: @@ -197,7 +224,13 @@ def load_optimized_query( def load_optimized_query_and_mapping( model: Model, mapping: t.Dict -) -> t.Tuple[str, t.Optional[str], str, str, t.Dict]: +) -> t.Tuple[ + str, + t.Optional[OptimizedQueryCacheEntry], + str, + str, + t.Dict, +]: assert _optimized_query_cache schema = MappingSchema(normalize=False) @@ -207,13 +240,13 @@ def load_optimized_query_and_mapping( if isinstance(model, SqlModel): entry_name = _optimized_query_cache._entry_name(model) - _optimized_query_cache.with_optimized_query(model, entry_name) + cache_entry = _optimized_query_cache.get_or_create_entry(model, entry_name) else: - entry_name = None + cache_entry = None return ( model.fqn, - entry_name, + cache_entry, model.data_hash, model.metadata_hash, model.mapping_schema, diff --git a/sqlmesh/core/model/schema.py b/sqlmesh/core/model/schema.py index e29cacade0..0d55859fbf 100644 --- a/sqlmesh/core/model/schema.py +++ b/sqlmesh/core/model/schema.py @@ -87,13 +87,16 @@ def process_models(completed_model: t.Optional[Model] = None) -> None: for future in as_completed(futures): try: futures.remove(future) - fqn, entry_name, data_hash, metadata_hash, mapping_schema = future.result() + fqn, cache_entry, data_hash, metadata_hash, mapping_schema = future.result() model = models[fqn] model._data_hash = data_hash model._metadata_hash = metadata_hash if model.mapping_schema != mapping_schema: model.set_mapping_schema(mapping_schema) - optimized_query_cache.with_optimized_query(model, entry_name) + if cache_entry is not None: + # The worker has already decompressed and decoded this entry. Passing + # it back avoids a second gzip/pickle read in the parent process. + optimized_query_cache.with_optimized_query_entry(model, cache_entry) _update_schema_with_model(schema, model) process_models(completed_model=model) except Exception as ex: diff --git a/sqlmesh/core/plan/evaluator.py b/sqlmesh/core/plan/evaluator.py index f2f432a97e..71e5285d63 100644 --- a/sqlmesh/core/plan/evaluator.py +++ b/sqlmesh/core/plan/evaluator.py @@ -18,6 +18,7 @@ import logging import typing as t from sqlmesh.core import analytics +from sqlmesh.core.execution_observation import action, console_observer_scope from sqlmesh.core import constants as c from sqlmesh.core.console import Console, get_console from sqlmesh.core.environment import EnvironmentNamingInfo, execute_environment_statements @@ -102,7 +103,8 @@ def evaluate( try: plan_stages = stages.build_plan_stages(plan, self.state_sync, self.default_catalog) - self._evaluate_stages(plan_stages, plan) + with console_observer_scope(self.console): + self._evaluate_stages(plan_stages, plan) except Exception as e: analytics.collector.on_plan_apply_end(plan_id=plan.plan_id, error=e) raise @@ -122,7 +124,8 @@ def _evaluate_stages( raise SQLMeshError(f"Unexpected plan stage: {stage_name}") logger.info("Evaluating plan stage %s", stage_name) handler = getattr(self, handler_name) - handler(stage, plan) + with action("stage", stage_name, native_plan_id=plan.plan_id): + handler(stage, plan) def visit_before_all_stage(self, stage: stages.BeforeAllStage, plan: EvaluatablePlan) -> None: execute_environment_statements( diff --git a/sqlmesh/core/plan/explainer.py b/sqlmesh/core/plan/explainer.py index f0a1e44aff..6e3fb8f9c3 100644 --- a/sqlmesh/core/plan/explainer.py +++ b/sqlmesh/core/plan/explainer.py @@ -8,9 +8,11 @@ from rich.console import Console as RichConsole from rich.tree import Tree +from sqlglot import exp from sqlglot.dialects.dialect import DialectType from sqlmesh.core import constants as c from sqlmesh.core.console import Console, TerminalConsole, get_console +from sqlmesh.core.dialect import schema_ from sqlmesh.core.environment import EnvironmentNamingInfo from sqlmesh.core.plan.common import ( SnapshotIntervalClearRequest, @@ -145,6 +147,29 @@ def visit_before_all_stage(self, stage: stages.BeforeAllStage) -> Tree: def visit_after_all_stage(self, stage: stages.AfterAllStage) -> Tree: return Tree("[bold]Execute after all statements[/bold]") + def visit_physical_layer_schema_creation_stage( + self, stage: stages.PhysicalLayerSchemaCreationStage + ) -> t.Optional[Tree]: + tables = [ + exp.to_table( + snapshot.table_name(is_deployable=stage.deployability_index.is_deployable(snapshot)) + ) + for snapshot in stage.snapshots + if snapshot.is_model and not snapshot.is_symbolic + ] + schemas = { + schema_(table.args["db"], table.args.get("catalog")).sql(dialect=self.dialect) + for table in tables + if table.db + } + if not schemas: + return None + + tree = Tree("[bold]Create physical schemas if they do not exist[/bold]") + for schema in sorted(schemas): + tree.add(schema) + return tree + def visit_physical_layer_update_stage(self, stage: stages.PhysicalLayerUpdateStage) -> Tree: snapshots = [ s for s in stage.snapshots if s.snapshot_id in stage.snapshots_with_missing_intervals 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/scheduler.py b/sqlmesh/core/scheduler.py index 5eb0ff40ff..7345d92888 100644 --- a/sqlmesh/core/scheduler.py +++ b/sqlmesh/core/scheduler.py @@ -8,6 +8,11 @@ from sqlglot import exp from sqlmesh.core import constants as c from sqlmesh.core.console import Console, get_console +from sqlmesh.core.execution_observation import ( + action, + console_observer_scope, + execution_context_factory, +) from sqlmesh.core.environment import EnvironmentNamingInfo, execute_environment_statements from sqlmesh.core.macros import RuntimeStage from sqlmesh.core.model.definition import AuditResult @@ -454,178 +459,43 @@ def run_merged_intervals( Returns: A tuple of errors and skipped intervals. """ - execution_time = execution_time or now_timestamp() + with console_observer_scope(self.console): + execution_time = execution_time or now_timestamp() - selected_snapshots = [self.snapshots[sid] for sid in (selected_snapshot_ids or set())] - if not selected_snapshots: - selected_snapshots = list(merged_intervals) + selected_snapshots = [self.snapshots[sid] for sid in (selected_snapshot_ids or set())] + if not selected_snapshots: + selected_snapshots = list(merged_intervals) - # Build the full DAG from all snapshots to preserve transitive dependencies - full_dag = snapshots_to_dag(self.snapshots.values()) + # Build the full DAG from all snapshots to preserve transitive dependencies + full_dag = snapshots_to_dag(self.snapshots.values()) - # Create a subdag that includes the selected snapshots and all their upstream dependencies - # This ensures that transitive dependencies are preserved even when intermediate nodes are not selected - selected_snapshot_ids_set = {s.snapshot_id for s in selected_snapshots} - snapshot_dag = full_dag.subdag(*selected_snapshot_ids_set) - - batched_intervals = self.batch_intervals( - merged_intervals, - deployability_index, - environment_naming_info, - dag=snapshot_dag, - is_restatement=is_restatement, - ) - self.console.start_evaluation_progress( - batched_intervals, - environment_naming_info, - self.default_catalog, - audit_only=audit_only, - ) + # Create a subdag that includes the selected snapshots and all their upstream dependencies + # This ensures that transitive dependencies are preserved even when intermediate nodes are not selected + selected_snapshot_ids_set = {s.snapshot_id for s in selected_snapshots} + snapshot_dag = full_dag.subdag(*selected_snapshot_ids_set) - if run_environment_statements: - environment_statements = self.state_sync.get_environment_statements( - environment_naming_info.name - ) - execute_environment_statements( - adapter=self.snapshot_evaluator.adapter, - environment_statements=environment_statements, - runtime_stage=RuntimeStage.BEFORE_ALL, - environment_naming_info=environment_naming_info, - default_catalog=self.default_catalog, - snapshots=self.snapshots_by_name, - start=start, - end=end, - execution_time=execution_time, - selected_models=selected_models, + batched_intervals = self.batch_intervals( + merged_intervals, + deployability_index, + environment_naming_info, + dag=snapshot_dag, + is_restatement=is_restatement, ) - - # We only need to create physical tables if the snapshot is not representative or if it - # needs backfill - snapshots_to_create_candidates = [ - s - for s in selected_snapshots - if not deployability_index.is_representative(s) or s in batched_intervals - ] - snapshots_to_create = { - s.snapshot_id - for s in self.snapshot_evaluator.get_snapshots_to_create( - snapshots_to_create_candidates, deployability_index + self.console.start_evaluation_progress( + batched_intervals, + environment_naming_info, + self.default_catalog, + audit_only=audit_only, ) - } - - dag = self._dag( - batched_intervals, snapshot_dag=snapshot_dag, snapshots_to_create=snapshots_to_create - ) - def run_node(node: SchedulingUnit) -> None: - if circuit_breaker and circuit_breaker(): - raise CircuitBreakerError() - if isinstance(node, DummyNode): - return - - snapshot = self.snapshots_by_name[node.snapshot_name] - - if isinstance(node, EvaluateNode): - self.console.start_snapshot_evaluation_progress(snapshot) - execution_start_ts = now_timestamp() - evaluation_duration_ms: t.Optional[int] = None - start, end = node.interval - - audit_results: t.List[AuditResult] = [] - try: - assert execution_time # mypy - assert deployability_index # mypy - - if audit_only: - audit_results = self._audit_snapshot( - snapshot=snapshot, - environment_naming_info=environment_naming_info, - deployability_index=deployability_index, - snapshots=self.snapshots_by_name, - start=start, - end=end, - execution_time=execution_time, - ) - else: - # If batch_index > 0, then the target table must exist since the first batch would have created it - target_table_exists = ( - snapshot.snapshot_id not in snapshots_to_create or node.batch_index > 0 - ) - audit_results = self.evaluate( - snapshot=snapshot, - environment_naming_info=environment_naming_info, - start=start, - end=end, - execution_time=execution_time, - deployability_index=deployability_index, - batch_index=node.batch_index, - allow_destructive_snapshots=allow_destructive_snapshots, - allow_additive_snapshots=allow_additive_snapshots, - target_table_exists=target_table_exists, - selected_models=selected_models, - ) - - evaluation_duration_ms = now_timestamp() - execution_start_ts - finally: - num_audits = len(audit_results) - num_audits_failed = sum(1 for result in audit_results if result.count) - - execution_stats = self.snapshot_evaluator.execution_tracker.get_execution_stats( - SnapshotIdBatch(snapshot_id=snapshot.snapshot_id, batch_id=node.batch_index) - ) - - self.console.update_snapshot_evaluation_progress( - snapshot, - batched_intervals[snapshot][node.batch_index], - node.batch_index, - evaluation_duration_ms, - num_audits - num_audits_failed, - num_audits_failed, - execution_stats=execution_stats, - auto_restatement_triggers=auto_restatement_triggers.get( - snapshot.snapshot_id - ), - ) - elif isinstance(node, CreateNode): - self.snapshot_evaluator.create_snapshot( - snapshot=snapshot, - snapshots=self.snapshots_by_name, - deployability_index=deployability_index, - allow_destructive_snapshots=allow_destructive_snapshots or set(), - allow_additive_snapshots=allow_additive_snapshots or set(), - ) - - try: - with self.snapshot_evaluator.concurrent_context(): - errors, skipped_intervals = concurrent_apply_to_dag( - dag, - run_node, - self.max_workers, - raise_on_error=False, - ) - self.console.stop_evaluation_progress(success=not errors) - - skipped_snapshots = { - i.snapshot_name for i in skipped_intervals if isinstance(i, EvaluateNode) - } - self.console.log_skipped_models(skipped_snapshots) - for skipped in skipped_snapshots: - logger.info(f"SKIPPED snapshot {skipped}\n") - - for error in errors: - if isinstance(error.__cause__, CircuitBreakerError): - raise error.__cause__ - logger.info(str(error), exc_info=error) - - self.console.log_failed_models(errors) - - return errors, skipped_intervals - finally: if run_environment_statements: + environment_statements = self.state_sync.get_environment_statements( + environment_naming_info.name + ) execute_environment_statements( adapter=self.snapshot_evaluator.adapter, environment_statements=environment_statements, - runtime_stage=RuntimeStage.AFTER_ALL, + runtime_stage=RuntimeStage.BEFORE_ALL, environment_naming_info=environment_naming_info, default_catalog=self.default_catalog, snapshots=self.snapshots_by_name, @@ -635,7 +505,166 @@ def run_node(node: SchedulingUnit) -> None: selected_models=selected_models, ) - self.state_sync.recycle() + # We only need to create physical tables if the snapshot is not representative or if it + # needs backfill + snapshots_to_create_candidates = [ + s + for s in selected_snapshots + if not deployability_index.is_representative(s) or s in batched_intervals + ] + snapshots_to_create = { + s.snapshot_id + for s in self.snapshot_evaluator.get_snapshots_to_create( + snapshots_to_create_candidates, deployability_index + ) + } + + dag = self._dag( + batched_intervals, + snapshot_dag=snapshot_dag, + snapshots_to_create=snapshots_to_create, + ) + + def run_node(node: SchedulingUnit) -> None: + if isinstance(node, EvaluateNode): + with action( + "model", + "audit_only" if audit_only else "evaluate", + snapshot=self.snapshots_by_name[node.snapshot_name], + interval=node.interval, + batch_index=node.batch_index, + execution_time=execution_time, + audit_only=audit_only, + ): + execute_node(node) + else: + execute_node(node) + + def execute_node(node: SchedulingUnit) -> None: + if circuit_breaker and circuit_breaker(): + raise CircuitBreakerError() + if isinstance(node, DummyNode): + return + + snapshot = self.snapshots_by_name[node.snapshot_name] + + if isinstance(node, EvaluateNode): + self.console.start_snapshot_evaluation_progress(snapshot) + execution_start_ts = now_timestamp() + evaluation_duration_ms: t.Optional[int] = None + start, end = node.interval + + audit_results: t.List[AuditResult] = [] + try: + assert execution_time # mypy + assert deployability_index # mypy + + if audit_only: + audit_results = self._audit_snapshot( + snapshot=snapshot, + environment_naming_info=environment_naming_info, + deployability_index=deployability_index, + snapshots=self.snapshots_by_name, + start=start, + end=end, + execution_time=execution_time, + ) + else: + # If batch_index > 0, then the target table must exist since the first batch would have created it + target_table_exists = ( + snapshot.snapshot_id not in snapshots_to_create + or node.batch_index > 0 + ) + audit_results = self.evaluate( + snapshot=snapshot, + environment_naming_info=environment_naming_info, + start=start, + end=end, + execution_time=execution_time, + deployability_index=deployability_index, + batch_index=node.batch_index, + allow_destructive_snapshots=allow_destructive_snapshots, + allow_additive_snapshots=allow_additive_snapshots, + target_table_exists=target_table_exists, + selected_models=selected_models, + ) + + evaluation_duration_ms = now_timestamp() - execution_start_ts + finally: + num_audits = len(audit_results) + num_audits_failed = sum(1 for result in audit_results if result.count) + + execution_stats = ( + self.snapshot_evaluator.execution_tracker.get_execution_stats( + SnapshotIdBatch( + snapshot_id=snapshot.snapshot_id, batch_id=node.batch_index + ) + ) + ) + + self.console.update_snapshot_evaluation_progress( + snapshot, + batched_intervals[snapshot][node.batch_index], + node.batch_index, + evaluation_duration_ms, + num_audits - num_audits_failed, + num_audits_failed, + execution_stats=execution_stats, + auto_restatement_triggers=auto_restatement_triggers.get( + snapshot.snapshot_id + ), + ) + elif isinstance(node, CreateNode): + self.snapshot_evaluator.create_snapshot( + snapshot=snapshot, + snapshots=self.snapshots_by_name, + deployability_index=deployability_index, + allow_destructive_snapshots=allow_destructive_snapshots or set(), + allow_additive_snapshots=allow_additive_snapshots or set(), + ) + + try: + with self.snapshot_evaluator.concurrent_context(): + errors, skipped_intervals = concurrent_apply_to_dag( + dag, + run_node, + self.max_workers, + raise_on_error=False, + context_factory=execution_context_factory(), + ) + self.console.stop_evaluation_progress(success=not errors) + + skipped_snapshots = { + i.snapshot_name for i in skipped_intervals if isinstance(i, EvaluateNode) + } + self.console.log_skipped_models(skipped_snapshots) + for skipped in skipped_snapshots: + logger.info(f"SKIPPED snapshot {skipped}\n") + + for error in errors: + if isinstance(error.__cause__, CircuitBreakerError): + raise error.__cause__ + logger.info(str(error), exc_info=error) + + self.console.log_failed_models(errors) + + return errors, skipped_intervals + finally: + if run_environment_statements: + execute_environment_statements( + adapter=self.snapshot_evaluator.adapter, + environment_statements=environment_statements, + runtime_stage=RuntimeStage.AFTER_ALL, + environment_naming_info=environment_naming_info, + default_catalog=self.default_catalog, + snapshots=self.snapshots_by_name, + start=start, + end=end, + execution_time=execution_time, + selected_models=selected_models, + ) + + self.state_sync.recycle() def _dag( self, 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..345f8816e6 100644 --- a/sqlmesh/core/snapshot/evaluator.py +++ b/sqlmesh/core/snapshot/evaluator.py @@ -29,6 +29,12 @@ from collections import defaultdict from contextlib import contextmanager from functools import reduce +from sqlmesh.core.execution_observation import ( + action, + observe_snapshot, + update_execution, + execution_context_factory, +) from sqlglot import exp, select from sqlglot.executor import execute @@ -312,6 +318,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,13 +328,14 @@ 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 on_complete=on_complete, ), self.ddl_concurrent_tasks, + context_factory=execution_context_factory(), ) def demote( @@ -355,6 +364,7 @@ def demote( table_mapping=table_mapping, ), self.ddl_concurrent_tasks, + context_factory=execution_context_factory(), ) def create( @@ -465,6 +475,7 @@ def _create_snapshots( on_complete=on_complete, ), self.ddl_concurrent_tasks, + context_factory=execution_context_factory(), raise_on_error=False, ) if errors: @@ -512,6 +523,7 @@ def migrate( deployability_index, ), self.ddl_concurrent_tasks, + context_factory=execution_context_factory(), ) def cleanup( @@ -556,6 +568,7 @@ def cleanup( on_complete, ), self.ddl_concurrent_tasks, + context_factory=execution_context_factory(), reverse_order=True, raise_on_error=False, ) @@ -634,8 +647,11 @@ def audit( # so that we can fall back to the audit's setting, which we override to blocking: False audit = audit.model_copy(update={"blocking": False}) - results.append( - self._audit( + # Observe before calling _audit: query exceptions need a terminal + # event even when no AuditResult exists. Preserve completed audits + # before later aggregate handling or WAP publication can fail. + with action("audit", "audit", audit_name=audit.name) as observation: + audit_result = self._audit( audit=audit, audit_args=audit_args, snapshot=snapshot, @@ -646,7 +662,9 @@ def audit( deployability_index=deployability_index, **kwargs, ) - ) + if observation is not None: + observation["audit_result"] = audit_result + results.append(audit_result) if wap_id is not None: logger.info( @@ -776,6 +794,16 @@ def _evaluate_snapshot( ) with ( + # The first batch may create via CTAS instead of create_snapshot. + # Observe the materialization, including its transaction exit, so + # lazy creation is not missing from physical-layer history. + action( + "physical", + "materialize", + target=target_table_name, + creating=not target_table_exists, + snapshot=snapshot, + ), adapter.transaction(), adapter.session(snapshot.model.render_session_properties(**render_statements_kwargs)), ): @@ -864,6 +892,7 @@ def _evaluate_snapshot( return wap_id + @observe_snapshot("physical", "create") def create_snapshot( self, snapshot: Snapshot, @@ -887,6 +916,9 @@ def create_snapshot( return logger.info("Creating a physical table for snapshot %s", snapshot.snapshot_id) + update_execution( + target=snapshot.table_name(is_deployable=deployability_index.is_deployable(snapshot)), + ) adapter = self.get_adapter(snapshot.model.gateway) create_render_kwargs: t.Dict[str, t.Any] = dict( @@ -1122,6 +1154,7 @@ def _clone_snapshot_in_dev( adapter.drop_table(target_table_name) raise + @observe_snapshot("physical", "schema_migration") def _migrate_snapshot( self, snapshot: Snapshot, @@ -1143,6 +1176,7 @@ def _migrate_snapshot( deployability_index=deployability_index, ) target_table_name = snapshot.table_name() + update_execution(target=target_table_name, existed=target_data_object is not None) evaluation_strategy = _evaluation_strategy(snapshot, adapter) evaluation_strategy.run_pre_statements( @@ -1251,6 +1285,7 @@ def _migrate_target_table( if snapshot.is_materialized: adapter.drop_table(tmp_table_name) + @observe_snapshot("virtual", "promote") def _promote_snapshot( self, snapshot: Snapshot, @@ -1260,7 +1295,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: @@ -1275,6 +1310,7 @@ def _promote_snapshot( view_name = snapshot.qualified_view_name.for_environment( environment_naming_info, dialect=adapter.dialect ) + update_execution(target=view_name, source_table=table_name) render_kwargs: t.Dict[str, t.Any] = dict( start=start, end=end, @@ -1299,13 +1335,14 @@ 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) + @observe_snapshot("virtual", "demote") def _demote_snapshot( self, snapshot: Snapshot, @@ -1325,6 +1362,7 @@ def _demote_snapshot( view_name = snapshot.qualified_view_name.for_environment( environment_naming_info, dialect=adapter.dialect ) + update_execution(target=view_name) with ( adapter.transaction(), adapter.session( @@ -1475,6 +1513,7 @@ def _create_schema( list(unique_schemas), lambda item: _create_schema(item[0], item[1], item[2]), self.ddl_concurrent_tasks, + context_factory=execution_context_factory(), ) def get_adapter(self, gateway: t.Optional[str] = None) -> EngineAdapter: @@ -1649,6 +1688,7 @@ def _get_data_objects_in_schema( schema=s, object_names=tables_by_schema.get(s), gateway=gateway ), self.ddl_concurrent_tasks, + context_factory=execution_context_factory(), ) for schema, objs in zip(schema_list, results): 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/sqlmesh/core/test/definition.py b/sqlmesh/core/test/definition.py index ee6ce26b71..e81d18548b 100644 --- a/sqlmesh/core/test/definition.py +++ b/sqlmesh/core/test/definition.py @@ -34,6 +34,7 @@ import pandas as pd from sqlglot.dialects.dialect import DialectType + from sqlglot.generator import Generator Row = t.Dict[str, t.Any] @@ -48,6 +49,54 @@ } +_FROZEN_TIME_GENERATORS: t.Dict[ + t.Tuple[t.Type[Generator], str, t.Optional[str]], t.Type[Generator] +] = {} +_FROZEN_TIME_GENERATORS_LOCK = threading.Lock() + + +def _frozen_time_generator_class( + generator_class: t.Type[Generator], execution_time: str, dialect: t.Optional[str] +) -> t.Type[Generator]: + """Returns a subclass of `generator_class` whose CURRENT_* transforms render `execution_time`. + + SQLGlot caches one dispatch table per generator class, so a subclass gets its own table and + the dialect's shared generator class is never modified. Subclasses are cached per + (generator, execution time, dialect) so tests that share an execution time share a table. + """ + key = (generator_class, execution_time, dialect) + with _FROZEN_TIME_GENERATORS_LOCK: + klass = _FROZEN_TIME_GENERATORS.get(key) + if klass is None: + exec_time = exp.Literal.string(execution_time) + klass = t.cast( + t.Type["Generator"], + type( + f"{generator_class.__name__}FrozenTime", + (generator_class,), + { + "TRANSFORMS": { + **generator_class.TRANSFORMS, + exp.CurrentDate: lambda self, _: self.sql( + exp.cast(exec_time, "date", dialect=dialect) + ), + exp.CurrentDatetime: lambda self, _: self.sql( + exp.cast(exec_time, "datetime", dialect=dialect) + ), + exp.CurrentTime: lambda self, _: self.sql( + exp.cast(exec_time, "time", dialect=dialect) + ), + exp.CurrentTimestamp: lambda self, _: self.sql( + exp.cast(exec_time, "timestamp", dialect=dialect) + ), + } + }, + ), + ) + _FROZEN_TIME_GENERATORS[key] = klass + return klass + + class ModelTest(unittest.TestCase): __test__ = False @@ -116,31 +165,22 @@ def __init__( ) self._qualified_fixture_schema = schema_(self._fixture_schema, self._fixture_catalog) - self._transforms = self._test_adapter_dialect.generator_class.TRANSFORMS self._execution_time = str(self.body.get("vars", {}).get("execution_time") or "") if self._execution_time: # Normalizes the execution time by converting it into UTC timezone self._execution_time = str(to_datetime(self._execution_time)) - # When execution_time is set, we mock the CURRENT_* SQL expressions so they always return it + # When execution_time is set, the CURRENT_* SQL expressions must render as that time. The + # overrides live on a per-test generator subclass rather than on the dialect's shared + # generator class: SQLGlot caches one dispatch table per generator class, so patching the + # shared one is visible to every other thread that renders SQL (e.g. a concurrent test + # creating its fixture views) and races with the patch's restoration. + self._generator_class = self._test_adapter_dialect.generator_class if self._execution_time: - exec_time = exp.Literal.string(self._execution_time) - self._transforms = { - **self._transforms, - exp.CurrentDate: lambda self, _: self.sql( - exp.cast(exec_time, "date", dialect=dialect) - ), - exp.CurrentDatetime: lambda self, _: self.sql( - exp.cast(exec_time, "datetime", dialect=dialect) - ), - exp.CurrentTime: lambda self, _: self.sql( - exp.cast(exec_time, "time", dialect=dialect) - ), - exp.CurrentTimestamp: lambda self, _: self.sql( - exp.cast(exec_time, "timestamp", dialect=dialect) - ), - } + self._generator_class = _frozen_time_generator_class( + self._generator_class, self._execution_time, dialect + ) super().__init__() @@ -600,15 +640,18 @@ def _normalize_column_name(self, name: str) -> str: return normalized_name @contextmanager - def _concurrent_render_context(self) -> t.Iterator[None]: + def _concurrent_render_context(self, patch_shared_dialect: bool = False) -> t.Iterator[None]: """ Context manager that ensures that the tests are executed safely in a concurrent environment. - This is needed in case `execution_time` is set, as we'd then have to: - - Freeze time through `time_machine` (not thread safe) - - Globally patch the SQLGlot dialect so that any date/time nodes are evaluated at the `execution_time` during generation + This is needed in case `execution_time` is set, as we'd then have to freeze time through + `time_machine`, which is not thread safe. + + SQL model tests render through `self._generator_class`, so the shared dialect is never + modified. Python model tests may run arbitrary SQL through the engine adapter, whose + generator cannot be swapped per test, so they additionally patch the shared generator's + transforms (`patch_shared_dialect=True`) while holding the lock. """ import time_machine - from sqlglot.generator import _DISPATCH_CACHE lock_ctx: AbstractContextManager = ( self.CONCURRENT_RENDER_LOCK if self.concurrency else nullcontext() @@ -618,19 +661,30 @@ def _concurrent_render_context(self) -> t.Iterator[None]: dispatch_patch_ctx: AbstractContextManager = nullcontext() if self._execution_time: - generator_class = self._test_adapter_dialect.generator_class time_ctx = time_machine.travel(self._execution_time, tick=False) - dialect_patch_ctx = patch.dict(generator_class.TRANSFORMS, self._transforms) + + if self._execution_time and patch_shared_dialect: + from sqlglot.generator import _DISPATCH_CACHE + + generator_class = self._test_adapter_dialect.generator_class + transforms = self._generator_class.TRANSFORMS + dialect_patch_ctx = patch.dict(generator_class.TRANSFORMS, transforms) # sqlglot caches a dispatch table per generator class, so we need to patch # it as well to ensure the overridden transforms are actually used dispatch = _DISPATCH_CACHE.get(generator_class) if dispatch is not None: - dispatch_patch_ctx = patch.dict(dispatch, self._transforms) + dispatch_patch_ctx = patch.dict(dispatch, transforms) with lock_ctx, time_ctx, dialect_patch_ctx, dispatch_patch_ctx: yield + def _generate_sql(self, expression: exp.Expr) -> str: + """Generates SQL for the testing engine, rendering CURRENT_* at `execution_time` when set.""" + return self._generator_class( + dialect=self._test_adapter_dialect, pretty=self.engine_adapter._pretty_sql + ).generate(expression) + def _execute(self, query: exp.Query | str) -> pd.DataFrame: """Executes the given query using the testing engine adapter and returns a DataFrame.""" return self.engine_adapter.fetchdf(query) @@ -698,9 +752,7 @@ def test_ctes(self, ctes: t.Dict[str, exp.Expr], recursive: bool = False) -> Non with self._concurrent_render_context(): # Similar to the model's query, we render the CTE query under the locked context # so that the execution (fetchdf) can continue concurrently between the threads - sql = cte_query.sql( - self._test_adapter_dialect, pretty=self.engine_adapter._pretty_sql - ) + sql = self._generate_sql(cte_query) actual = self._execute(sql) expected = self._create_df(values, columns=cte_query.named_selects, partial=partial) @@ -712,7 +764,7 @@ def runTest(self) -> None: # Render the model's query and generate the SQL under the locked context so that # execution (fetchdf) can continue concurrently between the threads query = self._render_model_query() - sql = query.sql(self._test_adapter_dialect, pretty=self.engine_adapter._pretty_sql) + sql = self._generate_sql(query) with_clause = query.args.get("with_") @@ -817,7 +869,7 @@ def _execute_model(self) -> pd.DataFrame: """Executes the python model and returns a DataFrame.""" import pandas as pd - with self._concurrent_render_context(): + with self._concurrent_render_context(patch_shared_dialect=True): variables = self.body.get("vars", {}).copy() time_kwargs = {key: variables.pop(key) for key in TIME_KWARG_KEYS if key in variables} df = next(self.model.render(context=self.context, variables=variables, **time_kwargs)) diff --git a/sqlmesh/dbt/builtin.py b/sqlmesh/dbt/builtin.py index fa05e3d7f9..3b06ec985a 100644 --- a/sqlmesh/dbt/builtin.py +++ b/sqlmesh/dbt/builtin.py @@ -369,7 +369,7 @@ def to_yaml(value: t.Any, default: t.Optional[t.Any] = None) -> t.Optional[t.Any def from_yaml(value: t.Any, default: t.Optional[t.Any] = None) -> t.Optional[t.Any]: try: - return dict(yaml.load(value, raise_if_empty=False, render_jinja=False)) + return yaml.load(value, raise_if_empty=False, render_jinja=False) except (TypeError, YAMLError): return default diff --git a/sqlmesh/migrations/v0071_add_dev_version_to_intervals.py b/sqlmesh/migrations/v0071_add_dev_version_to_intervals.py index 61a49dc0b9..d5f1e4d105 100644 --- a/sqlmesh/migrations/v0071_add_dev_version_to_intervals.py +++ b/sqlmesh/migrations/v0071_add_dev_version_to_intervals.py @@ -106,7 +106,7 @@ def _migrate_intervals( continue dev_version = snapshot_ids_to_dev_versions.get((name, identifier)) - if dev_version not in used_dev_versions and is_dev: + if (name, dev_version) not in used_dev_versions and is_dev: # If the interval's dev version is no longer used and this is a dev interval, we can safely delete it continue diff --git a/sqlmesh/utils/concurrency.py b/sqlmesh/utils/concurrency.py index c5f78645f6..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,36 +62,54 @@ 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: + 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 @@ -98,9 +123,17 @@ 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(): + return + if not self._unprocessed_nodes_num: self._finished_future.set_result(None) return @@ -139,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. @@ -151,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. @@ -172,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, ) @@ -180,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. @@ -191,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. @@ -202,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() @@ -216,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]] = [] @@ -231,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 @@ -249,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. @@ -256,23 +305,35 @@ 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] 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): - 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/sqlmesh/utils/databricks.py b/sqlmesh/utils/databricks.py new file mode 100644 index 0000000000..251511b9ca --- /dev/null +++ b/sqlmesh/utils/databricks.py @@ -0,0 +1,168 @@ +from __future__ import annotations + +import inspect +import logging +import re +import typing as t +from functools import lru_cache +from threading import Lock + +logger = logging.getLogger(__name__) + +HeaderFactory = t.Callable[[], t.Dict[str, str]] + + +class SharedU2MCredentialsProvider: + """A Databricks SQL connector `credentials_provider` that shares one U2M OAuth login across connections. + + Without this, every `databricks.sql.connect()` call builds its own OAuth provider. For U2M OAuth that means + each thread runs its own browser flow, and these race on the CSRF `state` parameter + (https://github.com/tobymao/sqlmesh/issues/5646). Even if the browser flow is only run once, each connection + would still hold its own copy of the refresh token. Databricks can issue single-use refresh tokens, so the + first connection to refresh would invalidate the token held by every other connection. + + Instead, a single connector OAuth provider is created lazily (behind a lock, so the browser flow only runs once) + and every connection reads its headers from it. Reads are also serialized so only one thread can refresh the + token at a time. This lets each thread have its own connection while sharing a single login. + + If reading the token fails (for example because the refresh token expired or was revoked) the login is + discarded, so the next connection or request logs in again rather than failing for the rest of the process. + Network failures while refreshing keep the login, so the next request retries the refresh without a browser flow. + """ + + def __init__(self, server_hostname: str, auth_type: str): + self._server_hostname = server_hostname + self._auth_type = auth_type + self._auth_provider: t.Optional[t.Any] = None + self._lock = Lock() + # Incremented when a login attempt finishes, so threads that waited on a failed attempt can tell it happened + self._login_attempts_finished = 0 + self._login_error: t.Optional[Exception] = None + + def auth_type(self) -> str: + return self._auth_type + + def __call__(self, *args: t.Any, **kwargs: t.Any) -> HeaderFactory: + """Called by the connector once per connection. Logs in if needed and returns that connection's header factory.""" + login_attempts_seen = self._login_attempts_finished + with self._lock: + self._ensure_logged_in(login_attempts_seen) + return self._headers + + def _headers(self) -> t.Dict[str, str]: + """Returns the auth headers for one request, refreshing the token if it has expired.""" + from databricks.sql.exc import RequestError + + headers: t.Dict[str, str] = {} + login_attempts_seen = self._login_attempts_finished + with self._lock: + auth_provider = self._ensure_logged_in(login_attempts_seen) + try: + auth_provider.add_headers(headers) + except RequestError: + # A network failure while refreshing leaves the login intact, since the connector only replaces its + # tokens after a successful refresh, so the next request retries the refresh rather than logging in + raise + except Exception: + self._auth_provider = None + raise + return headers + + def _ensure_logged_in(self, login_attempts_seen: int) -> t.Any: + """Returns the shared connector auth provider, logging in if needed. Must be called with the lock held.""" + if self._auth_provider is not None: + return self._auth_provider + + # A login attempt failed while this thread was waiting on the lock. Re-raise its error rather than opening + # another browser window for every waiting thread; callers that arrive afterwards will try again. + if self._login_attempts_finished != login_attempts_seen and self._login_error is not None: + raise self._login_error + + try: + self._auth_provider = self._create_auth_provider() + self._login_error = None + except Exception as e: + self._login_error = e + raise + finally: + self._login_attempts_finished += 1 + return self._auth_provider + + def _create_auth_provider(self) -> t.Any: + # These are internal to the connector, but using them means the OAuth flow is identical to the one the + # connector runs when `auth_type` is passed to `connect()` (same client ID, redirect ports, and scopes) + from databricks.sql import __version__ + from databricks.sql.auth.auth import get_python_sql_connector_auth_provider + from databricks.sql.common.unified_http_client import UnifiedHttpClient + from databricks.sql.utils import build_client_context + + # The provider outlives any single connection, so it gets its own HTTP client rather than borrowing one + # that would be closed along with its connection + http_client = UnifiedHttpClient( + build_client_context(self._server_hostname, __version__, user_agent_entry="sqlmesh") + ) + return get_python_sql_connector_auth_provider( + self._server_hostname, http_client=http_client, auth_type=self._auth_type + ) + + +@lru_cache(maxsize=1) +def supports_shared_u2m_login() -> bool: + """Whether the connector internals `SharedU2MCredentialsProvider` builds on accept the arguments it passes them. + + These internals aren't public, so a connector upgrade could change them. If one has, U2M OAuth falls back to + sharing a single connection rather than failing to connect. + """ + try: + from databricks.sql import __version__ + except ImportError: + # The connector isn't installed, so there are no connections to share a login across + return False + + try: + from databricks.sql.auth.auth import get_python_sql_connector_auth_provider + from databricks.sql.common.unified_http_client import UnifiedHttpClient + from databricks.sql.exc import RequestError # noqa: F401 + from databricks.sql.utils import build_client_context + + inspect.signature(build_client_context).bind( + "hostname", __version__, user_agent_entry="sqlmesh" + ) + inspect.signature(UnifiedHttpClient).bind(None) + inspect.signature(get_python_sql_connector_auth_provider).bind( + "hostname", http_client=None, auth_type="databricks-oauth" + ) + except Exception as e: + logger.warning( + "Databricks SQL connector %s is not compatible with SQLMesh's shared U2M OAuth login (%s). U2M OAuth " + "connections will share a single connection, so queries will run one at a time.", + __version__, + e, + ) + return False + return True + + +_shared_u2m_credentials_providers: t.Dict[t.Tuple[str, str], SharedU2MCredentialsProvider] = {} +_shared_u2m_credentials_providers_lock = Lock() + + +def get_shared_u2m_credentials_provider( + server_hostname: str, auth_type: str +) -> SharedU2MCredentialsProvider: + """Returns the process-wide U2M credentials provider for the given workspace and auth type. + + Engine adapters and config copies are created several times per process, so the provider is kept at module + level to avoid prompting the user to log in more than once. U2M OAuth is an interactive, single-user login, so + every connection to a workspace in this process uses the identity of whoever completed the browser flow. + """ + # The same workspace can be written with or without a scheme or trailing slash + normalized_hostname = re.sub(r"^https?://", "", server_hostname.strip(), flags=re.I) + normalized_hostname = normalized_hostname.rstrip("/").lower() + key = (normalized_hostname, auth_type) + with _shared_u2m_credentials_providers_lock: + if key not in _shared_u2m_credentials_providers: + _shared_u2m_credentials_providers[key] = SharedU2MCredentialsProvider( + normalized_hostname, auth_type + ) + return _shared_u2m_credentials_providers[key] diff --git a/tests/cli/test_cli.py b/tests/cli/test_cli.py index b52df5394a..1602dc3b11 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"]) @@ -2164,7 +2269,7 @@ def test_init_project_engine_configs(tmp_path): "redshift": "# concurrent_tasks: 4\n # register_comments: True\n # pre_ping: False\n # pretty_sql: False\n # schema_differ_overrides: \n # catalog_type_overrides: \n # user: \n # password: \n # database: \n # host: \n # port: \n # source_address: \n # unix_sock: \n # ssl: \n # sslmode: \n # timeout: \n # tcp_keepalive: \n # application_name: \n # preferred_role: \n # principal_arn: \n # credentials_provider: \n # region: \n # cluster_identifier: \n # iam: \n # db_user: \n # is_serverless: \n # serverless_acct_id: \n # serverless_work_group: \n # enable_merge: ", "bigquery": "# concurrent_tasks: 1\n # register_comments: True\n # pre_ping: False\n # pretty_sql: False\n # schema_differ_overrides: \n # catalog_type_overrides: \n # method: oauth\n # project: \n # execution_project: \n # quota_project: \n # location: \n # keyfile: \n # keyfile_json: \n # token: \n # refresh_token: \n # client_id: \n # client_secret: \n # token_uri: \n # scopes: \n # impersonated_service_account: \n # job_creation_timeout_seconds: \n # job_execution_timeout_seconds: \n # job_retries: 1\n # job_retry_deadline_seconds: \n # priority: \n # maximum_bytes_billed: \n # reservation: ", "snowflake": "account: \n # concurrent_tasks: 4\n # register_comments: True\n # pre_ping: False\n # pretty_sql: False\n # schema_differ_overrides: \n # catalog_type_overrides: \n # user: \n # password: \n # warehouse: \n # database: \n # role: \n # authenticator: \n # token: \n # host: \n # port: \n # application: Tobiko_SQLMesh\n # private_key: \n # private_key_path: \n # private_key_passphrase: \n # session_parameters: ", - "databricks": "# concurrent_tasks: 1\n # register_comments: True\n # pre_ping: False\n # pretty_sql: False\n # schema_differ_overrides: \n # catalog_type_overrides: \n # server_hostname: \n # http_path: \n # access_token: \n # auth_type: \n # oauth_client_id: \n # oauth_client_secret: \n # catalog: \n # http_headers: \n # session_configuration: \n # databricks_connect_server_hostname: \n # databricks_connect_access_token: \n # databricks_connect_cluster_id: \n # databricks_connect_use_serverless: False\n # force_databricks_connect: False\n # disable_databricks_connect: False\n # disable_spark_session: False", + "databricks": "# concurrent_tasks: 1\n # register_comments: True\n # pre_ping: False\n # pretty_sql: False\n # schema_differ_overrides: \n # catalog_type_overrides: \n # server_hostname: \n # http_path: \n # access_token: \n # auth_type: \n # oauth_client_id: \n # oauth_client_secret: \n # catalog: \n # http_headers: \n # session_configuration: \n # databricks_connect_server_hostname: \n # databricks_connect_access_token: \n # databricks_connect_cluster_id: \n # databricks_connect_use_serverless: False\n # force_databricks_connect: False\n # disable_databricks_connect: False\n # disable_spark_session: False\n # force_shared_connection: False", "postgres": "host: \n user: \n password: \n port: \n database: \n # concurrent_tasks: 4\n # register_comments: True\n # pre_ping: True\n # pretty_sql: False\n # schema_differ_overrides: \n # catalog_type_overrides: \n # keepalives_idle: \n # connect_timeout: 10\n # role: \n # sslmode: \n # application_name: ", } @@ -2666,6 +2771,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 +2902,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/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/clickhouse-datalake/Dockerfile b/tests/core/engine_adapter/integration/docker/clickhouse-datalake/Dockerfile new file mode 100644 index 0000000000..5b98992d0f --- /dev/null +++ b/tests/core/engine_adapter/integration/docker/clickhouse-datalake/Dockerfile @@ -0,0 +1,12 @@ +# SPDX-License-Identifier: Apache-2.0 + +FROM python:3.12.13-slim-bookworm@sha256:4766d8b510c428e595d74b9cc5bbb2fae8e26316fffb4adc89908d79aacd58a2 + +WORKDIR /fixture + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY seed.py . + +CMD ["python", "seed.py"] diff --git a/tests/core/engine_adapter/integration/docker/clickhouse-datalake/README.md b/tests/core/engine_adapter/integration/docker/clickhouse-datalake/README.md new file mode 100644 index 0000000000..fc2be35f3f --- /dev/null +++ b/tests/core/engine_adapter/integration/docker/clickhouse-datalake/README.md @@ -0,0 +1,88 @@ + + +# Run the ClickHouse DataLake integration tests + +This fixture tests ClickHouse `DataLakeCatalog` with a local Iceberg REST catalog and MinIO. Run it from the repository root with a recent Docker Compose v2 release that supports `up --wait --wait-timeout`. + +## Run the tests + +Run the complete fixture and test module: + +```bash +make clickhouse-datalake-test +``` + +The PR CI Docker matrix runs this target as `clickhouse-datalake`. It uploads the JUnit +report at `test-results/junit-clickhouse-datalake.xml` and stops the services after the run. + +If Docker runs under a named context, set `DOCKER_CONTEXT` for each Make command. For example, with a context named `colima`: + +```bash +DOCKER_CONTEXT=colima make clickhouse-datalake-test +``` + +Replace `colima` with the name of your context. This setting applies only to the command and leaves Docker's global context unchanged. Use it with the `up` and `down` targets too. + +The test target checks the Docker daemon, installs the ClickHouse test dependencies, and starts the dedicated Compose project. + +Compose waits up to 120 seconds for these checks: + +- MinIO can list `local/warehouse-rest` with `mc ls`. +- The REST catalog accepts a TCP connection on port `8181`. +- ClickHouse returns a result for `SELECT 1`. + +Before MinIO creates the bucket, its init service retries `mc ready` up to 30 times. The target seeds the Iceberg table, then runs [the integration tests](../../test_integration_clickhouse_datalake.py) with `SQLMESH_RUN_CLICKHOUSE_DATALAKE=1`. + +To start and seed the services without running pytest, use: + +```bash +make clickhouse-datalake-up +``` + +To run pytest directly after startup, install the ClickHouse test dependencies and set the opt-in flag: + +```bash +make engine-clickhouse-install +SQLMESH_RUN_CLICKHOUSE_DATALAKE=1 pytest -n 0 -m "docker and clickhouse_datalake" tests/core/engine_adapter/integration/test_integration_clickhouse_datalake.py +``` + +Pytest skips the module if you omit the flag. The test target checks Docker with `docker info`. The startup target fails if Compose cannot reach the daemon. + +## Fixture behavior + +The Compose project is named `sqlmesh-clickhouse-datalake`. It publishes ClickHouse HTTP only on `127.0.0.1:18123`. The REST catalog and MinIO have no host ports. The fixture bucket has no public policy. The services use local fixture credentials, and the tests do not read shared integration profiles or production credentials. + +The Tabulario REST service uses `CATALOG_S3_PATH__STYLE__ACCESS=true` for path-style S3 access. + +The [seed script](seed.py) connects to the REST catalog at `http://rest:8181`. PyIceberg adds `/v1`. ClickHouse connects to `http://rest:8181/v1`. + +The script creates `analytics.events` at `s3://warehouse-rest/data/sqlmesh/events`. It appends two rows, then one row, and verifies three rows across two snapshots. On rerun, it drops the table, deletes objects under that location, and creates the table again. + +The tests check the ClickHouse version and read the seeded table. They also cover: + +- Mapped reads with qualified tables, aliases, qualified columns, and CTEs, with and without virtual catalog injection. +- Preserving the original query AST. +- CTAS, append, and replace materializations. +- Rejection of an unknown source before CTAS creates its target. +- Stripping the injected virtual catalog from local reads. + +View creation accepts a mapped source without virtual catalog injection. With injection, it still raises the single-catalog error. + +Run `make clickhouse-datalake-down` to stop the services. The target removes their containers, the project network, attached volumes, and orphan containers. + +The next `make clickhouse-datalake-test` starts a clean project and reseeds the table. + +## Pinned versions and source + +The DataLakeCatalog setup and Iceberg seed flow follow ClickHouse's [`v25.8.16.34-lts` integration test](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/tests/integration/test_database_iceberg/test.py) and [REST catalog Compose file](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/tests/integration/compose/docker_compose_iceberg_rest_catalog.yml). + +ClickHouse pins PyIceberg `0.8.1` and PyArrow `17.0.0` in its [integration runner requirements](https://github.com/ClickHouse/ClickHouse/blob/v25.8.16.34-lts/ci/docker/integration/runner/requirements.txt). This fixture also pins MinIO's Python client to `7.2.3` for cleanup. + +The [fixture Compose file](../compose.clickhouse-datalake.yaml) pins these images by digest: + +- `clickhouse/clickhouse-server:25.8.16.34` (`sha256:86e6acceeacb49202fd694b77b4f7fcd6e022b52a29b0568fbfb4b05e8f6b2e7`). This version matches the upstream test tag `v25.8.16.34-lts`. +- `tabulario/iceberg-rest:1.6.0` (`sha256:3b7d31bdfec626b68e97531c9778a1b9119659e456fe28545a49f6aa6a9ce472`). +- `cgr.dev/chainguard/minio` (`sha256:039800e64ec7247d2fde7cff3697e964f6fe20b6d7d2c46aa7d82cc63355d512`) and `cgr.dev/chainguard/minio-client:latest-dev` (`sha256:fb635b967f5f32424391150dac4985cc1aea78fb0a1ce031c01952cf661a13ec`). +- Seeder base image `python:3.12.13-slim-bookworm` (`sha256:4766d8b510c428e595d74b9cc5bbb2fae8e26316fffb4adc89908d79aacd58a2`). Its package pins are in [requirements.txt](requirements.txt). + +The upstream Compose MinIO image references were unavailable during version verification, so this fixture uses pinned Chainguard images. diff --git a/tests/core/engine_adapter/integration/docker/clickhouse-datalake/requirements.txt b/tests/core/engine_adapter/integration/docker/clickhouse-datalake/requirements.txt new file mode 100644 index 0000000000..3470a1fb13 --- /dev/null +++ b/tests/core/engine_adapter/integration/docker/clickhouse-datalake/requirements.txt @@ -0,0 +1,5 @@ +# SPDX-License-Identifier: Apache-2.0 + +pyiceberg==0.8.1 +pyarrow==17.0.0 +minio==7.2.3 diff --git a/tests/core/engine_adapter/integration/docker/clickhouse-datalake/seed.py b/tests/core/engine_adapter/integration/docker/clickhouse-datalake/seed.py new file mode 100644 index 0000000000..874de046f4 --- /dev/null +++ b/tests/core/engine_adapter/integration/docker/clickhouse-datalake/seed.py @@ -0,0 +1,122 @@ +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import os +import time +from typing import Any + +import pyarrow as pa # type: ignore[import-untyped] +from minio import Minio # type: ignore[import-not-found] +from pyiceberg.catalog import load_catalog # type: ignore[import-not-found] +from pyiceberg.schema import Schema # type: ignore[import-not-found] +from pyiceberg.types import LongType, NestedField, StringType # type: ignore[import-not-found] + + +CATALOG_NAME = "demo" +NAMESPACE = "analytics" +TABLE_NAME = "events" +TABLE_IDENTIFIER = f"{NAMESPACE}.{TABLE_NAME}" +BUCKET = "warehouse-rest" +OBJECT_PREFIX = "data/sqlmesh/events/" +TABLE_LOCATION = "s3://warehouse-rest/data/sqlmesh/events" +ROWS = [ + {"id": 1, "value": "alpha"}, + {"id": 2, "value": "beta"}, + {"id": 3, "value": "gamma"}, +] + +SCHEMA = Schema( + NestedField(field_id=1, name="id", field_type=LongType(), required=True), + NestedField(field_id=2, name="value", field_type=StringType(), required=True), +) +ARROW_SCHEMA = pa.schema( + [ + pa.field("id", pa.int64(), nullable=False), + pa.field("value", pa.string(), nullable=False), + ] +) + + +def _load_catalog() -> Any: + last_error: Exception | None = None + for attempt in range(30): + try: + catalog = load_catalog( + CATALOG_NAME, + **{ + "uri": os.environ["ICEBERG_REST_URL"], + "type": "rest", + "s3.endpoint": os.environ["S3_ENDPOINT"], + "s3.access-key-id": os.environ["S3_ACCESS_KEY_ID"], + "s3.secret-access-key": os.environ["S3_SECRET_ACCESS_KEY"], + "s3.region": "us-east-1", + # PyArrow's pinned S3FileSystem defaults to path-style addressing. + }, + ) + catalog.list_namespaces() + return catalog + except Exception as ex: + last_error = ex + if attempt == 29: + break + time.sleep(1) + + raise RuntimeError( + "Iceberg REST catalog did not become ready after 30 attempts" + ) from last_error + + +def _clear_table_location() -> None: + client = Minio( + "minio:9000", + access_key=os.environ["S3_ACCESS_KEY_ID"], + secret_key=os.environ["S3_SECRET_ACCESS_KEY"], + secure=False, + ) + for attempt in range(30): + try: + if client.bucket_exists(BUCKET): + break + except Exception: + if attempt == 29: + raise + time.sleep(1) + else: + raise RuntimeError(f"MinIO bucket {BUCKET!r} was not created") + + for item in client.list_objects(BUCKET, prefix=OBJECT_PREFIX, recursive=True): + if item.object_name: + client.remove_object(BUCKET, item.object_name) + + +def main() -> None: + catalog = _load_catalog() + namespaces = catalog.list_namespaces() + if (NAMESPACE,) not in namespaces: + catalog.create_namespace(NAMESPACE) + + if (NAMESPACE, TABLE_NAME) in catalog.list_tables(NAMESPACE): + catalog.drop_table(TABLE_IDENTIFIER) + _clear_table_location() + + table = catalog.create_table( + identifier=TABLE_IDENTIFIER, + schema=SCHEMA, + location=TABLE_LOCATION, + ) + table.append(pa.Table.from_pylist(ROWS[:2], schema=ARROW_SCHEMA)) + table.append(pa.Table.from_pylist(ROWS[2:], schema=ARROW_SCHEMA)) + + actual_rows = sorted(table.scan().to_arrow().to_pylist(), key=lambda row: row["id"]) + snapshot_count = len(table.metadata.snapshots) + if actual_rows != ROWS or snapshot_count != 2: + raise RuntimeError( + f"Expected 3 rows in 2 snapshots; got rows={actual_rows!r}, snapshots={snapshot_count}" + ) + + print(f"Seeded {TABLE_IDENTIFIER} at {TABLE_LOCATION}: 3 rows, 2 snapshots") + + +if __name__ == "__main__": + main() diff --git a/tests/core/engine_adapter/integration/docker/compose.clickhouse-datalake.yaml b/tests/core/engine_adapter/integration/docker/compose.clickhouse-datalake.yaml new file mode 100644 index 0000000000..afeca3e86b --- /dev/null +++ b/tests/core/engine_adapter/integration/docker/compose.clickhouse-datalake.yaml @@ -0,0 +1,105 @@ +# SPDX-License-Identifier: Apache-2.0 + +services: + minio: + image: cgr.dev/chainguard/minio@sha256:039800e64ec7247d2fde7cff3697e964f6fe20b6d7d2c46aa7d82cc63355d512 + command: ["server", "/data", "--console-address", ":9001"] + environment: + MINIO_ROOT_USER: minio + MINIO_ROOT_PASSWORD: localpwd + + minio-init: + image: cgr.dev/chainguard/minio-client:latest-dev@sha256:fb635b967f5f32424391150dac4985cc1aea78fb0a1ce031c01952cf661a13ec + depends_on: + minio: + condition: service_started + environment: + MINIO_ROOT_USER: minio + MINIO_ROOT_PASSWORD: localpwd + entrypoint: ["/bin/sh", "-c"] + command: + - | + set -eu + attempt=0 + until mc alias set local http://minio:9000 "$${MINIO_ROOT_USER}" "$${MINIO_ROOT_PASSWORD}" >/dev/null 2>&1 && mc ready local >/dev/null 2>&1; do + attempt=$$((attempt + 1)) + if [ "$$attempt" -ge 30 ]; then + echo 'MinIO did not become ready after 30 attempts' >&2 + exit 1 + fi + sleep 1 + done + mc mb --ignore-existing local/warehouse-rest + exec sleep infinity + healthcheck: + test: ["CMD-SHELL", "mc ls local/warehouse-rest >/dev/null"] + interval: 2s + timeout: 2s + retries: 30 + start_period: 1s + + rest: + image: tabulario/iceberg-rest:1.6.0@sha256:3b7d31bdfec626b68e97531c9778a1b9119659e456fe28545a49f6aa6a9ce472 + depends_on: + minio-init: + condition: service_healthy + environment: + AWS_ACCESS_KEY_ID: minio + AWS_SECRET_ACCESS_KEY: localpwd + AWS_REGION: us-east-1 + CATALOG_WAREHOUSE: s3://warehouse-rest/ + CATALOG_IO__IMPL: org.apache.iceberg.aws.s3.S3FileIO + CATALOG_S3_ENDPOINT: http://minio:9000 + CATALOG_S3_PATH__STYLE__ACCESS: "true" + healthcheck: + test: ["CMD", "bash", "-c", "echo > /dev/tcp/localhost/8181"] + interval: 2s + timeout: 2s + retries: 30 + start_period: 15s + + clickhouse: + image: clickhouse/clickhouse-server:25.8.16.34@sha256:86e6acceeacb49202fd694b77b4f7fcd6e022b52a29b0568fbfb4b05e8f6b2e7 + depends_on: + rest: + condition: service_healthy + minio-init: + condition: service_healthy + environment: + CLICKHOUSE_DEFAULT_ACCESS_MANAGEMENT: "1" + CLICKHOUSE_USER: clickhouse + CLICKHOUSE_PASSWORD: clickhouse + CLICKHOUSE_DB: default + ports: + - "127.0.0.1:18123:8123" + healthcheck: + test: + [ + "CMD", + "clickhouse-client", + "--user", + "clickhouse", + "--password", + "clickhouse", + "--query", + "SELECT 1", + ] + interval: 2s + timeout: 2s + retries: 30 + start_period: 15s + + seed: + build: + context: ./clickhouse-datalake + dockerfile: Dockerfile + depends_on: + rest: + condition: service_healthy + minio-init: + condition: service_healthy + environment: + ICEBERG_REST_URL: http://rest:8181 + S3_ENDPOINT: http://minio:9000 + S3_ACCESS_KEY_ID: minio + S3_SECRET_ACCESS_KEY: localpwd 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/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 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_clickhouse_datalake.py b/tests/core/engine_adapter/integration/test_integration_clickhouse_datalake.py new file mode 100644 index 0000000000..0da91bb71b --- /dev/null +++ b/tests/core/engine_adapter/integration/test_integration_clickhouse_datalake.py @@ -0,0 +1,320 @@ +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import os +import typing as t + +import pytest +from sqlglot import exp, parse_one + +from sqlmesh.core.config.connection import ClickhouseConnectionConfig +from sqlmesh.core.engine_adapter.clickhouse import ClickhouseEngineAdapter +from sqlmesh.utils.errors import SQLMeshError + + +pytestmark = [pytest.mark.docker, pytest.mark.clickhouse_datalake] + +_RUN_FLAG = "SQLMESH_RUN_CLICKHOUSE_DATALAKE" +_CLICKHOUSE_VERSION = "25.8.16.34" +_REST_PASSWORD = "localpwd" +_EXPECTED_ROWS = [(1, "alpha"), (2, "beta"), (3, "gamma")] +_COLUMN_TYPES = { + "id": exp.DataType.build("Int64", dialect="clickhouse"), + "value": exp.DataType.build("String", dialect="clickhouse"), +} +_SOURCE_QUERY = "SELECT id, value FROM lake.analytics.events ORDER BY id" + + +def _new_adapter() -> ClickhouseEngineAdapter: + connection_config = ClickhouseConnectionConfig( + host="127.0.0.1", + port=18123, + username="clickhouse", + password="clickhouse", + connection_settings={"allow_database_iceberg": True}, + datalake_catalog_mapping={"lake": "iceberg"}, + concurrent_tasks=1, + register_comments=False, + ) + adapter = connection_config.create_engine_adapter() + assert isinstance(adapter, ClickhouseEngineAdapter) + return adapter + + +@pytest.fixture(scope="module") +def engine_adapter() -> t.Iterator[ClickhouseEngineAdapter]: + if os.environ.get(_RUN_FLAG) != "1": + pytest.skip(f"Set {_RUN_FLAG}=1 after starting the dedicated DataLake Compose stack") + + adapter = _new_adapter() + try: + version = adapter.fetchone("SELECT version()") + assert version is not None and version[0] == _CLICKHOUSE_VERSION + + # Keep the official ClickHouse test's setting and DDL sequence. The mapped database is + # local to this Compose project and points at its private MinIO bucket. + adapter.execute("SET allow_database_iceberg=true") + adapter.execute( + "CREATE DATABASE IF NOT EXISTS iceberg " + "ENGINE = DataLakeCatalog('http://rest:8181/v1', 'minio', " + f"'{_REST_PASSWORD}') " + "SETTINGS catalog_type = 'rest', warehouse = 'demo', " + "storage_endpoint = 'http://minio:9000/warehouse-rest'" + ) + physical_query = parse_one( + 'SELECT id, value FROM iceberg."analytics.events" ORDER BY id', + dialect="clickhouse", + ) + assert adapter.fetchall(physical_query) == _EXPECTED_ROWS + + yield adapter + finally: + adapter.close() + + +@pytest.fixture(scope="module") +def injected_engine_adapter( + engine_adapter: ClickhouseEngineAdapter, +) -> t.Iterator[ClickhouseEngineAdapter]: + adapter = _new_adapter() + adapter.inject_virtual_catalog("clickhouse_datalake") + try: + yield adapter + finally: + adapter.close() + + +@pytest.mark.parametrize( + ("adapter_fixture", "query_sql"), + [ + pytest.param("engine_adapter", _SOURCE_QUERY, id="uninjected-qualified-table"), + pytest.param( + "injected_engine_adapter", + _SOURCE_QUERY, + id="injected-qualified-table", + ), + pytest.param( + "engine_adapter", + "SELECT source.id, source.value " + "FROM lake.analytics.events AS source ORDER BY source.id", + id="uninjected-table-alias", + ), + pytest.param( + "injected_engine_adapter", + "SELECT source.id, source.value " + "FROM lake.analytics.events AS source ORDER BY source.id", + id="injected-table-alias", + ), + pytest.param( + "engine_adapter", + "SELECT lake.analytics.events.id, lake.analytics.events.value " + "FROM lake.analytics.events ORDER BY lake.analytics.events.id", + id="uninjected-qualified-columns", + ), + pytest.param( + "injected_engine_adapter", + "SELECT lake.analytics.events.id, lake.analytics.events.value " + "FROM lake.analytics.events ORDER BY lake.analytics.events.id", + id="injected-qualified-columns", + ), + pytest.param( + "engine_adapter", + "WITH source AS (SELECT id, value FROM lake.analytics.events) " + "SELECT id, value FROM source ORDER BY id", + id="uninjected-cte", + ), + pytest.param( + "injected_engine_adapter", + "WITH source AS (SELECT id, value FROM lake.analytics.events) " + "SELECT id, value FROM source ORDER BY id", + id="injected-cte", + ), + ], +) +def test_reads_mapped_source_queries_without_mutating_ast( + request: pytest.FixtureRequest, adapter_fixture: str, query_sql: str +) -> None: + adapter = request.getfixturevalue(adapter_fixture) + query = parse_one(query_sql, dialect="clickhouse") + original_query = query.copy() + + assert adapter.fetchall(query) == _EXPECTED_ROWS + assert query == original_query + + +@pytest.mark.parametrize("adapter_fixture", ["engine_adapter", "injected_engine_adapter"]) +def test_ctas_reads_mapped_source(request: pytest.FixtureRequest, adapter_fixture: str) -> None: + adapter = request.getfixturevalue(adapter_fixture) + target = "default.sqlmesh_datalake_ctas" + adapter.drop_table(target, exists=True) + try: + adapter.ctas( + target, + parse_one(_SOURCE_QUERY, dialect="clickhouse"), + target_columns_to_types=_COLUMN_TYPES, + ) + + assert ( + adapter.fetchall( + parse_one(f"SELECT id, value FROM {target} ORDER BY id", dialect="clickhouse") + ) + == _EXPECTED_ROWS + ) + finally: + adapter.drop_table(target, exists=True) + + +@pytest.mark.parametrize("alias", ["t", "lake", "__clickhouse_datalake__"]) +def test_insert_append_preserves_nested_fields( + injected_engine_adapter: ClickhouseEngineAdapter, alias: str +) -> None: + adapter = injected_engine_adapter + source = "default.sqlmesh_datalake_nested_source" + target = "default.sqlmesh_datalake_nested_target" + columns = {"id": _COLUMN_TYPES["id"]} + adapter.drop_table(source, exists=True) + adapter.drop_table(target, exists=True) + try: + adapter.execute( + f"CREATE TABLE {source} (payload Tuple(user Tuple(id Int64))) ENGINE = Memory" + ) + adapter.execute(f"INSERT INTO {source} SELECT tuple(tuple(7))") + adapter.create_table(target, columns, exists=False) + query = parse_one( + f"SELECT {alias}.payload.user.id AS id FROM {source} AS {alias}", + dialect="clickhouse", + ) + original = query.copy() + + adapter.insert_append(target, query, target_columns_to_types=columns) + + assert adapter.fetchall(f"SELECT id FROM {target}") == [(7,)] + assert query == original + finally: + adapter.drop_table(target, exists=True) + adapter.drop_table(source, exists=True) + + +@pytest.mark.parametrize("adapter_fixture", ["engine_adapter", "injected_engine_adapter"]) +def test_insert_append_reads_mapped_source( + request: pytest.FixtureRequest, adapter_fixture: str +) -> None: + adapter = request.getfixturevalue(adapter_fixture) + target = "default.sqlmesh_datalake_insert" + adapter.drop_table(target, exists=True) + try: + adapter.create_table(target, _COLUMN_TYPES, exists=False) + adapter.insert_append( + target, + parse_one(_SOURCE_QUERY, dialect="clickhouse"), + target_columns_to_types=_COLUMN_TYPES, + ) + + assert ( + adapter.fetchall( + parse_one(f"SELECT id, value FROM {target} ORDER BY id", dialect="clickhouse") + ) + == _EXPECTED_ROWS + ) + finally: + adapter.drop_table(target, exists=True) + + +@pytest.mark.parametrize("adapter_fixture", ["engine_adapter", "injected_engine_adapter"]) +def test_replace_query_reads_mapped_source( + request: pytest.FixtureRequest, adapter_fixture: str +) -> None: + adapter = request.getfixturevalue(adapter_fixture) + target = "default.sqlmesh_datalake_replace" + adapter.drop_table(target, exists=True) + try: + adapter.ctas( + target, + parse_one("SELECT 99 AS id, 'stale' AS value", dialect="clickhouse"), + target_columns_to_types=_COLUMN_TYPES, + ) + adapter.replace_query( + target, + parse_one(_SOURCE_QUERY, dialect="clickhouse"), + target_columns_to_types=_COLUMN_TYPES, + ) + + assert ( + adapter.fetchall( + parse_one(f"SELECT id, value FROM {target} ORDER BY id", dialect="clickhouse") + ) + == _EXPECTED_ROWS + ) + finally: + adapter.drop_table(target, exists=True) + + +def test_unknown_materialization_source_fails_before_target_creation( + engine_adapter: ClickhouseEngineAdapter, +) -> None: + target = "default.sqlmesh_datalake_unknown_source" + engine_adapter.drop_table(target, exists=True) + + try: + with pytest.raises(SQLMeshError, match="Provided catalog: foreign"): + engine_adapter.ctas( + target, + parse_one("SELECT id, value FROM foreign.analytics.events", dialect="clickhouse"), + target_columns_to_types=_COLUMN_TYPES, + ) + + assert not engine_adapter.table_exists(target) + finally: + engine_adapter.drop_table(target, exists=True) + + +def test_uninjected_view_maps_source(engine_adapter: ClickhouseEngineAdapter) -> None: + view = "default.sqlmesh_datalake_view" + engine_adapter.drop_view(view, ignore_if_not_exists=True) + try: + engine_adapter.create_view(view, parse_one(_SOURCE_QUERY, dialect="clickhouse")) + + assert ( + engine_adapter.fetchall( + parse_one(f"SELECT id, value FROM {view} ORDER BY id", dialect="clickhouse") + ) + == _EXPECTED_ROWS + ) + finally: + engine_adapter.drop_view(view, ignore_if_not_exists=True) + + +def test_injected_view_rejects_mapped_source( + injected_engine_adapter: ClickhouseEngineAdapter, +) -> None: + adapter = injected_engine_adapter + view = "default.sqlmesh_datalake_injected_view" + adapter.drop_view(view, ignore_if_not_exists=True) + try: + with pytest.raises(SQLMeshError, match="all catalog operations"): + adapter.create_view(view, parse_one(_SOURCE_QUERY, dialect="clickhouse")) + assert not adapter.table_exists(view) + finally: + adapter.drop_view(view, ignore_if_not_exists=True) + + +def test_injected_virtual_catalog_is_stripped_from_reads( + injected_engine_adapter: ClickhouseEngineAdapter, +) -> None: + target = "default.sqlmesh_datalake_virtual_catalog" + injected_engine_adapter.drop_table(target, exists=True) + try: + injected_engine_adapter.ctas( + target, + parse_one("SELECT 1 AS id, 'local' AS value", dialect="clickhouse"), + target_columns_to_types=_COLUMN_TYPES, + ) + virtual_query = parse_one( + "SELECT id, value FROM __clickhouse_datalake__.default.sqlmesh_datalake_virtual_catalog", + dialect="clickhouse", + ) + + assert injected_engine_adapter.fetchall(virtual_query) == [(1, "local")] + finally: + injected_engine_adapter.drop_table(target, exists=True) 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/integration/test_integration_snowflake.py b/tests/core/engine_adapter/integration/test_integration_snowflake.py index 7f3c38be46..c9ce95654c 100644 --- a/tests/core/engine_adapter/integration/test_integration_snowflake.py +++ b/tests/core/engine_adapter/integration/test_integration_snowflake.py @@ -315,6 +315,33 @@ def fetch_database_names() -> t.Set[str]: assert fetch_database_names() == {non_sqlmesh_managed_catalog} +def test_create_drop_catalog_quoted_name(ctx: TestContext, engine_adapter: SnowflakeEngineAdapter): + # a name with a hyphen has to be quoted, so it only matches the existence check in + # drop_catalog if the check compares against the bare name + sqlmesh_managed_catalog = ctx.add_test_suffix("env-dev") + + initial_catalog = engine_adapter.get_current_catalog() + assert initial_catalog + + ctx._catalogs.append(sqlmesh_managed_catalog) # so it still gets cleaned up if the test fails + engine_adapter.create_catalog(sqlmesh_managed_catalog) + + def fetch_database_names() -> t.Set[str]: + engine_adapter.set_current_catalog(initial_catalog) + return { + str(r[0]) + for r in engine_adapter.fetchall( + f"select database_name from information_schema.databases where database_name like '%{ctx.test_id}'" + ) + } + + # the database is stored under the bare name, without identifier quotes + assert fetch_database_names() == {sqlmesh_managed_catalog} + + engine_adapter.drop_catalog(sqlmesh_managed_catalog) + assert fetch_database_names() == set() + + def test_rows_tracker( ctx: TestContext, engine_adapter: SnowflakeEngineAdapter, mocker: MockerFixture ): diff --git a/tests/core/engine_adapter/test_bigquery.py b/tests/core/engine_adapter/test_bigquery.py index 134f144df1..783bd48f91 100644 --- a/tests/core/engine_adapter/test_bigquery.py +++ b/tests/core/engine_adapter/test_bigquery.py @@ -13,7 +13,12 @@ import sqlmesh.core.dialect as d from sqlmesh.core.engine_adapter import BigQueryEngineAdapter from sqlmesh.core.engine_adapter.bigquery import select_partitions_expr -from sqlmesh.core.engine_adapter.shared import DataObjectType +from sqlmesh.core.engine_adapter.mixins import ( + TableAlterClusterByOperation, + TableAlterDropClusterKeyOperation, +) +from sqlmesh.core.engine_adapter.shared import DataObject, DataObjectType +from sqlmesh.core.schema_diff import TableAlterDropColumnOperation from sqlmesh.core.node import IntervalUnit from sqlmesh.utils import AttributeDict from sqlmesh.utils.errors import SQLMeshError @@ -1380,3 +1385,158 @@ def test_sync_grants_config_no_schema( with pytest.raises(ValueError, match="Table test_table does not have a schema \\(dataset\\)"): adapter.sync_grants_config(relation, new_grants_config) + + +def _mock_bq_data_objects( + mocker: MockerFixture, + adapter: BigQueryEngineAdapter, + current_obj: DataObject, + target_obj: DataObject, +) -> None: + """Patch _get_data_objects on *adapter* to return the supplied DataObjects.""" + + def _side_effect( + schema_name: t.Any, object_names: t.Optional[t.Set[str]] = None + ) -> t.List[DataObject]: + results = [] + for obj in [current_obj, target_obj]: + if object_names is None or obj.name in object_names: + results.append(obj) + return results + + mocker.patch.object(adapter, "_get_data_objects", side_effect=_side_effect) + + +def test_bigquery_clustering_column_drop_before_clustering_change( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """BigQuery keeps the historical order: DROP COLUMN before clustering key change. + + Dropping a column that belongs to the current clustering key must NOT trigger + a reorder. BigQuery must emit DROP COLUMN first, then DROP CLUSTERING KEY. + """ + adapter = make_mocked_engine_adapter(BigQueryEngineAdapter, patch_get_data_objects=False) + + current_columns = {"tenant_id": "INT64", "partition_month": "INT64"} + target_columns = {"tenant_id": "INT64"} + adapter.columns = lambda table_name, **kwargs: { + k: exp.DataType.build(v, dialect="bigquery") + for k, v in ( + current_columns if table_name == "project.dataset.current_table" else target_columns + ).items() + } + + _mock_bq_data_objects( + mocker, + adapter, + current_obj=DataObject( + catalog="project", + schema="dataset", + name="current_table", + type=DataObjectType.TABLE, + clustering_key="(partition_month)", + ), + target_obj=DataObject( + catalog="project", + schema="dataset", + name="target_table", + type=DataObjectType.TABLE, + clustering_key=None, + ), + ) + + operations = adapter.get_alter_operations( + "project.dataset.current_table", "project.dataset.target_table" + ) + + assert len(operations) == 2 + assert isinstance(operations[0], TableAlterDropColumnOperation) + assert isinstance(operations[1], TableAlterDropClusterKeyOperation) + + +def test_bigquery_no_column_change_clustering_drop_only( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """BigQuery: same columns, only clustering key removed — one DROP CLUSTERING KEY.""" + adapter = make_mocked_engine_adapter(BigQueryEngineAdapter, patch_get_data_objects=False) + + columns = {"tenant_id": "INT64", "partition_month": "INT64"} + adapter.columns = lambda table_name, **kwargs: { + k: exp.DataType.build(v, dialect="bigquery") for k, v in columns.items() + } + + _mock_bq_data_objects( + mocker, + adapter, + current_obj=DataObject( + catalog="project", + schema="dataset", + name="current_table", + type=DataObjectType.TABLE, + clustering_key="(partition_month)", + ), + target_obj=DataObject( + catalog="project", + schema="dataset", + name="target_table", + type=DataObjectType.TABLE, + clustering_key=None, + ), + ) + + operations = adapter.get_alter_operations( + "project.dataset.current_table", "project.dataset.target_table" + ) + + assert len(operations) == 1 + assert isinstance(operations[0], TableAlterDropClusterKeyOperation) + + +def test_unchanged_clustering_key_is_not_altered_when_column_added( + adapter: BigQueryEngineAdapter, mocker: MockerFixture +): + # Adding a column to a clustered table must not emit a clustering change when the key + # itself is unchanged. BigQuery applies a new key by rewriting the clustered columns. + current_columns = {"c1": exp.DataType.build("INT64", dialect="bigquery")} + target_columns = { + **current_columns, + "c2": exp.DataType.build("INT64", dialect="bigquery"), + } + + def columns(table_name: str, include_pseudo_columns: bool = False) -> t.Dict[str, exp.DataType]: + if exp.to_table(table_name).name == "current_table": + return current_columns + return target_columns + + mocker.patch.object(adapter, "columns", side_effect=columns) + + def get_data_objects( + schema_name: exp.Table, + object_names: t.Optional[t.Set[str]] = None, + safe_to_cache: bool = False, + ) -> t.List[DataObject]: + assert object_names is not None + return [ + DataObject( + schema=schema_name.db, + name=next(iter(object_names)), + type=DataObjectType.TABLE, + clustering_key="(c1)", + ) + ] + + mocker.patch.object(adapter, "get_data_objects", side_effect=get_data_objects) + # Let a wrongly emitted clustering change surface as the column-rewrite UPDATE. + mocker.patch.object(adapter, "_get_table", return_value=mocker.Mock()) + mocker.patch.object(adapter, "_db_call") + + operations = adapter.get_alter_operations( + "test_schema.current_table", "test_schema.target_table" + ) + assert not any(isinstance(operation, TableAlterClusterByOperation) for operation in operations) + + adapter.alter_table(operations) + + assert _to_sql_calls(adapter) == [ + "ALTER TABLE `test_schema`.`current_table` ADD COLUMN `c2` INT64" + ] diff --git a/tests/core/engine_adapter/test_clickhouse.py b/tests/core/engine_adapter/test_clickhouse.py index a3dfe0fdda..d457b0f877 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: @@ -1066,7 +1081,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"', @@ -1103,8 +1118,8 @@ def test_insert_overwrite_by_condition_replace( columns_to_types, ) - to_sql_calls(adapter) == [ - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + assert to_sql_calls(adapter) == [ + '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"', @@ -1118,7 +1133,10 @@ def test_insert_overwrite_by_condition_where_partitioned( temp_table_mock = mocker.patch("sqlmesh.core.engine_adapter.EngineAdapter._get_temp_table") table_name = "target" - temp_table_mock.return_value = make_temp_table_name(table_name, "abcd") + temp_table_mock.side_effect = lambda table, *args, **kwargs: make_temp_table_name( + "affected_partitions" if exp.to_table(table).name == "_affected_partitions" else table_name, + "abcd", + ) fetchone_mock = mocker.patch("sqlmesh.core.engine_adapter.ClickhouseEngineAdapter.fetchone") fetchone_mock.return_value = "dateTrunc('WEEK', ds)" @@ -1126,7 +1144,7 @@ def test_insert_overwrite_by_condition_where_partitioned( fetchall_mock = mocker.patch("sqlmesh.core.engine_adapter.ClickhouseEngineAdapter.fetchall") fetchall_mock.side_effect = [ [("1",), ("2",), ("3",), ("4",)], - ["1", "2", "4"], + [("1",), ("2",), ("4",)], ] insert_table_name = make_temp_table_name("new_records", "abcd") @@ -1152,11 +1170,12 @@ def test_insert_overwrite_by_condition_where_partitioned( ), ) - to_sql_calls(adapter) == [ - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + assert to_sql_calls(adapter) == [ + '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")""", + '''CREATE TABLE IF NOT EXISTS "__temp_affected_partitions_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_affected_partitions_abcd")""", + 'DROP TABLE IF EXISTS "__temp_affected_partitions_abcd"', """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 PARTITION ID '3'""", 'DROP TABLE IF EXISTS "__temp_target_abcd"', ] @@ -1203,15 +1222,15 @@ def test_insert_overwrite_by_condition_by_key( dynamic_key_unique=False, ) - to_sql_calls(adapter) == [ - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + assert to_sql_calls(adapter) == [ + '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"))', + 'INSERT INTO "__temp_target_abcd" SELECT "id", "ds" FROM "__temp_existing_records_abcd" WHERE NOT ("id" IN (SELECT DISTINCT "id" FROM "__temp_target_abcd"))', 'EXCHANGE TABLES "__temp_existing_records_abcd" AND "__temp_target_abcd"', 'DROP TABLE IF EXISTS "__temp_target_abcd"', ] @@ -1224,7 +1243,10 @@ def test_insert_overwrite_by_condition_by_key_partitioned( temp_table_mock = mocker.patch("sqlmesh.core.engine_adapter.EngineAdapter._get_temp_table") table_name = "target" - temp_table_mock.return_value = make_temp_table_name(table_name, "abcd") + temp_table_mock.side_effect = lambda table, *args, **kwargs: make_temp_table_name( + "affected_partitions" if exp.to_table(table).name == "_affected_partitions" else table_name, + "abcd", + ) fetchone_mock = mocker.patch("sqlmesh.core.engine_adapter.ClickhouseEngineAdapter.fetchone") fetchone_mock.side_effect = ["dateTrunc('WEEK', ds)", "dateTrunc('WEEK', ds)"] @@ -1232,9 +1254,9 @@ def test_insert_overwrite_by_condition_by_key_partitioned( fetchall_mock = mocker.patch("sqlmesh.core.engine_adapter.ClickhouseEngineAdapter.fetchall") fetchall_mock.side_effect = [ [("1",), ("2",), ("3",), ("4",)], - ["1", "2", "4"], + [("1",), ("2",), ("4",)], [("1",), ("2",), ("3",), ("4",)], - ["1", "2", "4"], + [("1",), ("2",), ("4",)], ] insert_table_name = make_temp_table_name("new_records", "abcd") @@ -1266,18 +1288,20 @@ def test_insert_overwrite_by_condition_by_key_partitioned( dynamic_key_unique=False, ) - to_sql_calls(adapter) == [ - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + assert to_sql_calls(adapter) == [ + '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'""", + 'CREATE TABLE IF NOT EXISTS "__temp_affected_partitions_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_affected_partitions_abcd")', + 'DROP TABLE IF EXISTS "__temp_affected_partitions_abcd"', + """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 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")', - """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'""", + 'CREATE TABLE IF NOT EXISTS "__temp_affected_partitions_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 DISTINCT "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 DISTINCT "id" FROM "__temp_target_abcd")) AND "_partition_id" IN (SELECT "partition_id" FROM "__temp_affected_partitions_abcd")', + 'DROP TABLE IF EXISTS "__temp_affected_partitions_abcd"', + """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 PARTITION ID '3'""", 'DROP TABLE IF EXISTS "__temp_target_abcd"', ] @@ -1315,8 +1339,8 @@ def test_insert_overwrite_by_condition_inc_by_partition( keep_existing_partition_rows=False, ) - to_sql_calls(adapter) == [ - "CREATE TABLE __temp_target_abcd AS __temp_existing_records_abcd", + assert to_sql_calls(adapter) == [ + '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 +1620,131 @@ 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)", + ) + adapter.delete_from( + "__ch_gw__.mydb.target", + "EXISTS (SELECT 1 FROM __ch_gw__.mydb.source " + "WHERE __ch_gw__.mydb.target.id = __ch_gw__.mydb.source.id)", + ) + + 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")', + 'DELETE FROM "mydb"."target" WHERE EXISTS(SELECT 1 FROM "mydb"."source" WHERE ' + '"mydb"."target"."id" = "mydb"."source"."id")', + ] + + +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, ): @@ -1637,3 +1786,867 @@ 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__ + + +def test_clickhouse_datalake_catalog_mapping_config_is_forwarded(): + from sqlmesh.core.config.connection import ClickhouseConnectionConfig + + mapping = {"lake": "iceberg"} + config = ClickhouseConnectionConfig( + host="localhost", username="user", datalake_catalog_mapping=mapping + ) + + assert config._extra_engine_config["datalake_catalog_mapping"] == mapping + + +@pytest.mark.parametrize( + "mapping", + [ + {"": "iceberg"}, + {"lake.schema": "iceberg"}, + {"lake": ""}, + {"lake": "iceberg.db"}, + ], +) +def test_clickhouse_datalake_catalog_mapping_rejects_invalid_identifiers( + mapping: t.Dict[str, str], +): + from sqlmesh.core.config.connection import ClickhouseConnectionConfig + from sqlmesh.utils.errors import ConfigError + + with pytest.raises(ConfigError, match="datalake_catalog_mapping"): + ClickhouseConnectionConfig( + host="localhost", username="user", datalake_catalog_mapping=mapping + ) + + +@pytest.mark.parametrize("inject_catalog", [False, True]) +@pytest.mark.parametrize( + "query_sql, expected_sql", + [ + ( + "SELECT e.id FROM lake.source.events AS e", + 'SELECT "e"."id" FROM "iceberg"."source.events" AS "e"', + ), + ( + "SELECT lake.source.events.id FROM lake.source.events", + 'SELECT "iceberg"."source.events"."id" FROM "iceberg"."source.events"', + ), + ( + "WITH events AS (SELECT id FROM lake.source.events) " + "SELECT id FROM events UNION ALL SELECT id FROM lake.source.other", + 'WITH "events" AS (SELECT "id" FROM "iceberg"."source.events") ' + 'SELECT "id" FROM "events" UNION ALL SELECT "id" FROM ' + '"iceberg"."source.other"', + ), + ( + "SELECT nested.id FROM (SELECT id FROM lake.source.events) AS nested", + 'SELECT "nested"."id" FROM (SELECT "id" FROM "iceberg"."source.events") AS "nested"', + ), + ( + "SELECT lake.source.events.* FROM lake.source.events", + 'SELECT "iceberg"."source.events".* FROM "iceberg"."source.events"', + ), + ], +) +def test_clickhouse_datalake_mapping_rewrites_direct_query_sources( + make_mocked_engine_adapter: t.Callable, + inject_catalog: bool, + query_sql: str, + expected_sql: str, +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, datalake_catalog_mapping={"lake": "iceberg"} + ) + if inject_catalog: + adapter.inject_virtual_catalog("clickhouse_gw") + + query = parse_one(query_sql, dialect="clickhouse") + original = query.copy() + adapter.fetchall(query, quote_identifiers=True) + + assert to_sql_calls(adapter) == [expected_sql] + assert query == original + + +@pytest.mark.parametrize( + ("target", "target_alias", "predicate_sql", "expected_sql"), + [ + ( + "db.target", + None, + "id IN (SELECT id FROM lake.analytics.events)", + 'DELETE FROM "db"."target" WHERE "id" IN ' + '(SELECT "id" FROM "iceberg"."analytics.events")', + ), + ( + "lake.analytics.target", + None, + "id IN (SELECT id FROM lake.analytics.events)", + 'DELETE FROM "lake"."analytics"."target" WHERE "id" IN ' + '(SELECT "id" FROM "iceberg"."analytics.events")', + ), + ( + "db.target", + None, + "id IN (SELECT id FROM lake.analytics.events " + "UNION ALL SELECT id FROM lake.analytics.archive)", + 'DELETE FROM "db"."target" WHERE "id" IN ' + '(SELECT "id" FROM "iceberg"."analytics.events" UNION ALL ' + 'SELECT "id" FROM "iceberg"."analytics.archive")', + ), + ( + "db.target", + None, + "id IN (SELECT nested.id FROM (SELECT id FROM lake.analytics.events) AS nested)", + 'DELETE FROM "db"."target" WHERE "id" IN ' + '(SELECT "nested"."id" FROM (SELECT "id" FROM ' + '"iceberg"."analytics.events") AS "nested")', + ), + ( + "db.target", + "lake", + "EXISTS (SELECT lake.analytics.events.id FROM lake.analytics.events)", + 'DELETE FROM "db"."target" AS "lake" WHERE EXISTS(SELECT ' + '"iceberg"."analytics.events"."id" FROM "iceberg"."analytics.events")', + ), + ( + "db.target", + "lake", + "EXISTS (SELECT lake.payload.user.id FROM lake.analytics.events AS lake)", + 'DELETE FROM "db"."target" AS "lake" WHERE EXISTS(SELECT ' + '"lake"."payload"."user"."id" FROM "iceberg"."analytics.events" AS "lake")', + ), + ], +) +def test_clickhouse_datalake_mapping_rewrites_delete_subquery_sources( + make_mocked_engine_adapter: t.Callable, + target: str, + target_alias: t.Optional[str], + predicate_sql: str, + expected_sql: str, +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, datalake_catalog_mapping={"lake": "iceberg"} + ) + predicate = parse_one(predicate_sql, dialect="clickhouse") + original_predicate = predicate.copy() + delete_target = exp.to_table(target) + if target_alias: + delete_target.set("alias", exp.TableAlias(this=exp.to_identifier(target_alias))) + + adapter.delete_from(delete_target, predicate) + + assert to_sql_calls(adapter) == [expected_sql] + assert predicate == original_predicate + + +def test_clickhouse_datalake_mapping_leaves_raw_delete_sql_unchanged( + make_mocked_engine_adapter: t.Callable, +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, datalake_catalog_mapping={"lake": "iceberg"} + ) + statement = "DELETE FROM db.target WHERE id IN (SELECT id FROM lake.analytics.events)" + + adapter.execute(statement) + + assert to_sql_calls(adapter) == [statement] + + +@pytest.mark.parametrize("mapping", [{}, {"lake": "iceberg"}]) +def test_clickhouse_datalake_mapping_preserves_unmapped_foreign_read_catalogs( + make_mocked_engine_adapter: t.Callable, mapping: t.Dict[str, str] +): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter, datalake_catalog_mapping=mapping) + adapter.inject_virtual_catalog("clickhouse_gw") + query = parse_one( + "SELECT foreign_catalog.source.events.id FROM foreign_catalog.source.events", + dialect="clickhouse", + ) + original = query.copy() + + adapter.fetchall(query, quote_identifiers=True) + + assert to_sql_calls(adapter) == [ + 'SELECT "foreign_catalog"."source"."events"."id" FROM "foreign_catalog"."source"."events"' + ] + assert query == original + + +@pytest.mark.parametrize("fetch_method", ["fetchall", "fetchdf"]) +def test_clickhouse_datalake_mapping_leaves_raw_sql_strings_unchanged( + make_mocked_engine_adapter: t.Callable, fetch_method: str +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, datalake_catalog_mapping={"lake": "iceberg"} + ) + query = "SELECT id, value FROM lake.analytics.events ORDER BY id" + + if fetch_method == "fetchall": + adapter.fetchall(query) + adapter.cursor.execute.assert_called_once_with(query) + else: + import pandas as pd + + adapter.cursor.client.query_df.return_value = pd.DataFrame() + adapter.fetchdf(query) + adapter.cursor.client.query_df.assert_called_once_with(query, use_extended_dtypes=True) + + +@pytest.mark.parametrize("inject_catalog", [False, True]) +def test_clickhouse_datalake_mapping_rewrites_insert_select_source( + make_mocked_engine_adapter: t.Callable, inject_catalog: bool +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, datalake_catalog_mapping={"lake": "iceberg"} + ) + if inject_catalog: + adapter.inject_virtual_catalog("clickhouse_gw") + target = "lake.analytics.target" + statement = parse_one( + f"INSERT INTO {target} (id) SELECT lake.source.events.id FROM lake.source.events", + dialect="clickhouse", + ) + original = statement.copy() + + adapter.execute(statement) + + assert to_sql_calls(adapter) == [ + 'INSERT INTO "lake"."analytics"."target" ("id") ' + 'SELECT "iceberg"."source.events"."id" FROM "iceberg"."source.events"' + ] + assert statement == original + + +def test_clickhouse_insert_values_keeps_generic_virtual_catalog_rendering( + make_mocked_engine_adapter: t.Callable, +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, datalake_catalog_mapping={"lake": "iceberg"} + ) + adapter.inject_virtual_catalog("clickhouse_gw") + statement = parse_one( + "INSERT INTO __clickhouse_gw__.analytics.target (id) VALUES (1)", + dialect="clickhouse", + ) + original = statement.copy() + + adapter.execute(statement) + + assert to_sql_calls(adapter) == ['INSERT INTO "analytics"."target" ("id") VALUES ((1))'] + assert statement == original + + +@pytest.mark.parametrize("inject_catalog", [False, True]) +@pytest.mark.parametrize("operation", ["ctas", "insert", "replace"]) +def test_clickhouse_datalake_mapping_rewrites_materialized_query_sources( + make_mocked_engine_adapter: t.Callable, inject_catalog: bool, operation: str +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, datalake_catalog_mapping={"lake": "iceberg"} + ) + if inject_catalog: + adapter.inject_virtual_catalog("clickhouse_gw") + target = "__clickhouse_gw__.analytics.target" if inject_catalog else "analytics.target" + query = parse_one("SELECT lake.source.events.id FROM lake.source.events", dialect="clickhouse") + original = query.copy() + columns_to_types = {"id": exp.DataType.build("Int64", dialect="clickhouse")} + + if operation == "ctas": + adapter.ctas(target, query, columns_to_types) + elif operation == "insert": + adapter.insert_append(target, query, columns_to_types, track_rows_processed=False) + else: + adapter.get_data_object = lambda *args, **kwargs: None # type: ignore[method-assign] + adapter.replace_query(target, query, columns_to_types) + + rendered = "\n".join(to_sql_calls(adapter)) + assert '"iceberg"."source.events"' in rendered + assert '"lake"."source"."events"' not in rendered + assert query == original + + +@pytest.mark.parametrize( + "alias,virtual_catalog", + [ + ("t", None), + ("lake", None), + ("t", "t"), + ("__clickhouse_gw__", None), + ], +) +def test_clickhouse_datalake_mapping_preserves_nested_fields_qualified_by_alias( + make_mocked_engine_adapter: t.Callable, + alias: str, + virtual_catalog: t.Optional[str], +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, + virtual_catalog=virtual_catalog, + datalake_catalog_mapping={"lake": "iceberg"}, + ) + adapter.inject_virtual_catalog("clickhouse_gw") + query = parse_one( + f"SELECT {alias}.payload.user.id FROM db.src AS {alias}", dialect="clickhouse" + ) + original = query.copy() + + adapter.insert_append( + "analytics.target", + query, + {"id": exp.DataType.build("Int64", dialect="clickhouse")}, + track_rows_processed=False, + ) + + assert any( + f'SELECT "{alias}"."payload"."user"."id" FROM "db"."src" AS "{alias}"' in call + for call in to_sql_calls(adapter) + ) + assert query == original + + +@pytest.mark.parametrize( + "virtual_catalog,alias", + [ + ("t", "t"), + ("__clickhouse_gw__", "__clickhouse_gw__"), + ], +) +def test_clickhouse_virtual_catalog_keeps_direct_read_alias_nested_fields( + make_mocked_engine_adapter: t.Callable, + virtual_catalog: str, + alias: str, +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, + virtual_catalog=virtual_catalog, + datalake_catalog_mapping={"lake": "iceberg"}, + ) + query = parse_one( + f"SELECT {alias}.payload.user.id FROM db.src AS {alias}", dialect="clickhouse" + ) + original = query.copy() + + adapter.fetchall(query, quote_identifiers=True) + + assert to_sql_calls(adapter) == [ + f'SELECT "{alias}"."payload"."user"."id" FROM "db"."src" AS "{alias}"' + ] + assert query == original + + +@pytest.mark.parametrize( + "query_sql,expected_sql", + [ + ( + "WITH t AS (SELECT payload FROM db.src) SELECT t.payload.user.id FROM t", + 'INSERT INTO "analytics"."target" ("id") WITH "t" AS ' + '(SELECT "payload" FROM "db"."src") SELECT ' + '"t"."payload"."user"."id" FROM "t"', + ), + ( + "SELECT sub.payload.user.id FROM (SELECT payload FROM db.src) AS sub", + 'INSERT INTO "analytics"."target" ("id") SELECT ' + '"sub"."payload"."user"."id" FROM ' + '(SELECT "payload" FROM "db"."src") AS "sub"', + ), + ( + "SELECT t.payload.user.id FROM db.src AS t WHERE EXISTS (" + "SELECT 1 FROM db.other WHERE t.payload.user.id = 1)", + 'INSERT INTO "analytics"."target" ("id") SELECT ' + '"t"."payload"."user"."id" FROM "db"."src" AS "t" ' + 'WHERE EXISTS(SELECT 1 FROM "db"."other" WHERE ' + '"t"."payload"."user"."id" = 1)', + ), + ( + "SELECT lake.source.events.id FROM lake.source.events WHERE EXISTS (" + "SELECT 1 FROM db.src AS lake WHERE lake.payload.user.id = 1)", + 'INSERT INTO "analytics"."target" ("id") SELECT ' + '"iceberg"."source.events"."id" FROM "iceberg"."source.events" ' + 'WHERE EXISTS(SELECT 1 FROM "db"."src" AS "lake" WHERE ' + '"lake"."payload"."user"."id" = 1)', + ), + ( + "SELECT lake.id FROM db.src AS lake WHERE EXISTS (" + "SELECT lake.source.events.id FROM lake.source.events)", + 'INSERT INTO "analytics"."target" ("id") SELECT "lake"."id" ' + 'FROM "db"."src" AS "lake" WHERE EXISTS(SELECT ' + '"iceberg"."source.events"."id" FROM "iceberg"."source.events")', + ), + ( + "SELECT payload.user.event.id FROM db.src", + 'INSERT INTO "analytics"."target" ("id") SELECT ' + '"payload"."user"."event"."id" FROM "db"."src"', + ), + ], +) +def test_clickhouse_datalake_mapping_resolves_nested_paths_in_query_scope( + make_mocked_engine_adapter: t.Callable, query_sql: str, expected_sql: str +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, datalake_catalog_mapping={"lake": "iceberg"} + ) + query = parse_one(query_sql, dialect="clickhouse") + original = query.copy() + + adapter.insert_append( + "analytics.target", + query, + {"id": exp.DataType.build("Int64", dialect="clickhouse")}, + track_rows_processed=False, + ) + + assert to_sql_calls(adapter) == [expected_sql] + assert query == original + + +@pytest.mark.parametrize("operation", ["insert", "ctas", "replace", "view"]) +def test_clickhouse_datalake_mapping_rejects_unconfigured_write_sources( + make_mocked_engine_adapter: t.Callable, operation: str +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, datalake_catalog_mapping={"lake": "iceberg"} + ) + query = parse_one("SELECT id FROM foreign_catalog.source.events", dialect="clickhouse") + columns_to_types = {"id": exp.DataType.build("Int64", dialect="clickhouse")} + + with pytest.raises(SQLMeshError, match="Provided catalog: foreign_catalog"): + if operation == "insert": + adapter.insert_append( + "analytics.target", query, columns_to_types, track_rows_processed=False + ) + elif operation == "ctas": + adapter.ctas("analytics.target", query, columns_to_types) + elif operation == "replace": + adapter.get_data_object = lambda *args, **kwargs: None # type: ignore[method-assign] + adapter.replace_query("analytics.target", query, columns_to_types) + else: + adapter.create_view("analytics.target", query) + + +def test_clickhouse_datalake_mapping_rejects_foreign_write_source_when_virtual_catalog_exists( + make_mocked_engine_adapter: t.Callable, +): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter) + adapter.inject_virtual_catalog("clickhouse_gw") + query = parse_one("SELECT id FROM foreign_catalog.source.events", dialect="clickhouse") + + with pytest.raises(SQLMeshError, match="Provided catalog: foreign_catalog"): + adapter._get_source_queries(query, None, "analytics.target") + + +def test_clickhouse_without_mapping_or_virtual_catalog_preserves_query_source( + make_mocked_engine_adapter: t.Callable, +): + adapter = make_mocked_engine_adapter(ClickhouseEngineAdapter) + query = parse_one("SELECT id FROM foreign_catalog.source.events", dialect="clickhouse") + original = query.copy() + + source_queries = adapter._get_source_queries(query, None, "analytics.target") + + assert source_queries[0].query_factory() == original + assert query == original + + +def test_clickhouse_datalake_mapping_gives_virtual_catalog_precedence_over_mapping_key( + make_mocked_engine_adapter: t.Callable, +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, + virtual_catalog="css_data", + datalake_catalog_mapping={"css_data": "iceberg"}, + ) + adapter.inject_virtual_catalog("clickhouse_gw") + query = parse_one("SELECT id FROM css_data.source.events", dialect="clickhouse") + + source_queries = adapter._get_source_queries(query, None, "analytics.target") + rendered = adapter._to_sql(source_queries[0].query_factory()) + + assert rendered == 'SELECT "id" FROM "source"."events"' + + +def test_clickhouse_datalake_mapping_rewrites_create_view_query_source( + make_mocked_engine_adapter: t.Callable, +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, datalake_catalog_mapping={"lake": "iceberg"} + ) + query = parse_one("SELECT id FROM lake.source.events", dialect="clickhouse") + original = query.copy() + + adapter.create_view("analytics.events_view", query) + + assert any('"iceberg"."source.events"' in call for call in to_sql_calls(adapter)) + assert query == original + + +def test_clickhouse_datalake_mapping_does_not_bypass_injected_create_view_catalog_validation( + make_mocked_engine_adapter: t.Callable, +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, datalake_catalog_mapping={"lake": "iceberg"} + ) + adapter.inject_virtual_catalog("clickhouse_gw") + query = parse_one("SELECT id FROM lake.source.events", dialect="clickhouse") + original = query.copy() + + with pytest.raises( + SQLMeshError, + match="requires that all catalog operations be against a single catalog: __clickhouse_gw__", + ): + adapter.create_view("analytics.events_view", query) + + assert to_sql_calls(adapter) == [] + assert query == original + + +@pytest.mark.parametrize("mapping", [{}, {"configured_catalog": "iceberg"}]) +def test_virtual_catalog_execute_uses_configured_catalog_fallback( + make_mocked_engine_adapter: t.Callable, mapping: t.Dict[str, str] +): + adapter = make_mocked_engine_adapter( + ClickhouseEngineAdapter, + virtual_catalog="configured_catalog", + datalake_catalog_mapping=mapping, + ) + query = parse_one( + "SELECT configured_catalog.mydb.source.id, other_catalog.otherdb.source.id, " + "'configured_catalog.literal' FROM configured_catalog.mydb.source " + "JOIN other_catalog.otherdb.source ON configured_catalog.mydb.source.id = " + "other_catalog.otherdb.source.id", + dialect="clickhouse", + ) + original = query.copy() + + adapter.execute(query) + + assert to_sql_calls(adapter) == [ + 'SELECT "mydb"."source"."id", "other_catalog"."otherdb"."source"."id", ' + '\'configured_catalog.literal\' FROM "mydb"."source" JOIN ' + '"other_catalog"."otherdb"."source" ON "mydb"."source"."id" = ' + '"other_catalog"."otherdb"."source"."id"' + ] + assert query == original 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/engine_adapter/test_duckdb.py b/tests/core/engine_adapter/test_duckdb.py index 9fd65a6e66..6e8097d7eb 100644 --- a/tests/core/engine_adapter/test_duckdb.py +++ b/tests/core/engine_adapter/test_duckdb.py @@ -126,17 +126,25 @@ def test_drop_catalog_motherduck(make_mocked_engine_adapter: t.Callable) -> None assert to_sql_calls(adapter) == ['DROP DATABASE IF EXISTS "foo" CASCADE'] -def test_ducklake_partitioning(adapter: EngineAdapter, duck_conn, tmp_path): +@pytest.fixture +def ducklake_conn(duck_conn): + # Don't call install_extension here: on Windows it fails with "Access is denied" + # once an earlier test in this process has loaded DuckLake. LOAD auto-installs it + # when missing, and Windows CI pre-installs it before pytest. + duck_conn.load_extension("ducklake") + return duck_conn + + +@pytest.mark.xdist_group("ducklake_extension") +def test_ducklake_partitioning(adapter: EngineAdapter, ducklake_conn, tmp_path): catalog = "a_ducklake_db" - duck_conn.install_extension("ducklake") - duck_conn.load_extension("ducklake") - duck_conn.execute( + ducklake_conn.execute( f"ATTACH 'ducklake:{tmp_path}/{catalog}.ducklake' AS {catalog} (DATA_PATH '{tmp_path}');" ) # no partitions on catalog creation - partition_info = duck_conn.execute( + partition_info = ducklake_conn.execute( f"SELECT * FROM __ducklake_metadata_{catalog}.main.ducklake_partition_info" ).fetchdf() assert partition_info.empty @@ -150,7 +158,77 @@ def test_ducklake_partitioning(adapter: EngineAdapter, duck_conn, tmp_path): ) # 1 partition after table creation - partition_info = duck_conn.execute( + partition_info = ducklake_conn.execute( f"SELECT * FROM __ducklake_metadata_{catalog}.main.ducklake_partition_info" ).fetchdf() assert partition_info.shape[0] == 1 + + +@pytest.mark.xdist_group("ducklake_extension") +def test_drop_table_ducklake_no_cascade(adapter: EngineAdapter, ducklake_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" + + ducklake_conn.execute( + f"ATTACH 'ducklake:{tmp_path}/{catalog}.ducklake' AS {catalog} (DATA_PATH '{tmp_path}');" + ) + + ducklake_conn.execute(f"CREATE SCHEMA {catalog}.phys") + ducklake_conn.execute(f"CREATE SCHEMA {catalog}.virt") + ducklake_conn.execute(f"CREATE TABLE {catalog}.phys.t (i INTEGER)") + ducklake_conn.execute(f"CREATE VIEW {catalog}.virt.v AS SELECT * FROM {catalog}.phys.t") + + # native catalog, cascade is passed through + ducklake_conn.execute("CREATE TABLE memory.main.native_t (i INTEGER)") + ducklake_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") + + +@pytest.mark.xdist_group("ducklake_extension") +def test_drop_table_ducklake_no_cascade_mixed_case_alias( + adapter: EngineAdapter, ducklake_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. + ducklake_conn.execute( + f"ATTACH 'ducklake:{tmp_path}/my_lake.ducklake' AS \"MyLake\" (DATA_PATH '{tmp_path}');" + ) + ducklake_conn.execute("CREATE SCHEMA MyLake.phys") + ducklake_conn.execute("CREATE TABLE MyLake.phys.t (i INTEGER)") + ducklake_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', + ] diff --git a/tests/core/engine_adapter/test_fabric.py b/tests/core/engine_adapter/test_fabric.py index d16e973e8a..5c44b795b1 100644 --- a/tests/core/engine_adapter/test_fabric.py +++ b/tests/core/engine_adapter/test_fabric.py @@ -4,12 +4,14 @@ 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 +from sqlmesh.core.engine_adapter.shared import DataObject, DataObjectType pytestmark = [pytest.mark.engine, pytest.mark.fabric] @@ -19,7 +21,39 @@ def adapter(make_mocked_engine_adapter: t.Callable) -> FabricEngineAdapter: return make_mocked_engine_adapter(FabricEngineAdapter) -def test_get_current_catalog_uses_only_explicit_target_catalog( +@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 _record_catalogs_at_execute(adapter: FabricEngineAdapter) -> t.List[t.Optional[str]]: + catalogs: t.List[t.Optional[str]] = [] + real_execute = adapter.execute + + def execute(*args: t.Any, **kwargs: t.Any) -> None: + catalogs.append(adapter._resolved_catalog()) + return real_execute(*args, **kwargs) + + adapter.execute = execute # type: ignore[method-assign] + return catalogs + + +def test_get_current_catalog_returns_configured_database_when_target_is_default( make_mocked_engine_adapter: t.Callable, ): adapter = make_mocked_engine_adapter( @@ -27,7 +61,10 @@ def test_get_current_catalog_uses_only_explicit_target_catalog( database="default_catalog", ) - assert adapter.get_current_catalog() is None + current_catalog = adapter.get_current_catalog() + assert current_catalog is not None + assert current_catalog.lower() == "default_catalog" + assert adapter._target_catalog is None adapter._target_catalog = "switched_catalog" @@ -36,10 +73,31 @@ def test_get_current_catalog_uses_only_explicit_target_catalog( adapter._connection_pool.close() assert adapter._connection_pool.get_attribute("target_catalog") is None - assert adapter.get_current_catalog() is None + assert adapter.get_current_catalog() == "default_catalog" adapter.cursor.execute.assert_not_called() +def test_shared_catalog_operations_can_lowercase_the_default_warehouse( + make_mocked_engine_adapter: t.Callable, +): + """test_catalog_operations lowercases the current catalog, then restores it.""" + adapter = make_mocked_engine_adapter( + FabricEngineAdapter, + database="ci_abc", + ) + + current_catalog = adapter.get_current_catalog().lower() + assert current_catalog == "ci_abc" + assert adapter._target_catalog is None + + adapter.set_current_catalog("testing") + assert adapter.get_current_catalog().lower() == "testing" + + adapter.set_current_catalog(current_catalog) + assert adapter.get_current_catalog().lower() == current_catalog + assert adapter._target_catalog is None + + def test_get_current_catalog_returns_none_without_target_or_database( make_mocked_engine_adapter: t.Callable, ): @@ -75,7 +133,8 @@ def test_set_current_catalog_to_default_clears_explicit_target( adapter.set_current_catalog("planning") adapter.set_current_catalog("core") - assert adapter.get_current_catalog() is None + assert adapter._target_catalog is None + assert adapter.get_current_catalog() == "core" adapter.cursor.execute.assert_not_called() @@ -97,8 +156,9 @@ def test_catalog_scoped_call_restores_to_neutral_without_close( # Decorator calls set_current_catalog("planning") then set_current_catalog(None). # Only the first call (None→planning) should trigger a connection close. assert close_spy.call_count == 1 + assert adapter._target_catalog is None assert adapter._connected_catalog == "planning" - assert adapter.get_current_catalog() is None + assert adapter.get_current_catalog() == "core" def test_default_catalog_after_non_default_catalog_reconnects( @@ -117,8 +177,9 @@ def test_default_catalog_after_non_default_catalog_reconnects( adapter.table_exists("core.db.table") assert close_spy.call_count == 2 + assert adapter._target_catalog is None assert adapter._connected_catalog is None - assert adapter.get_current_catalog() is None + assert adapter.get_current_catalog() == "core" def test_repeated_same_catalog_reuses_connection( @@ -451,3 +512,210 @@ 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") + + +def test_get_data_objects_uses_configured_default_catalog( + make_mocked_engine_adapter: t.Callable, + mocker: MockerFixture, +) -> None: + adapter = make_mocked_engine_adapter( + FabricEngineAdapter, + default_catalog="ci_abc", + database="ci_abc", + patch_get_data_objects=False, + ) + assert adapter._target_catalog is None + assert adapter.get_current_catalog() == "ci_abc" + + mocker.patch.object( + adapter, + "fetchdf", + return_value=pd.DataFrame([{"name": "test_table", "schema_name": "dbo", "type": "TABLE"}]), + ) + + assert adapter.get_data_objects("ci_abc.dbo") == [ + DataObject( + catalog="ci_abc", + schema="dbo", + name="test_table", + type=DataObjectType.TABLE, + ) + ] + + +def test_get_data_objects_cache_hits_for_default_catalog( + make_mocked_engine_adapter: t.Callable, + mocker: MockerFixture, +) -> None: + """Listing fills catalog on the return value. Cache must still hit.""" + adapter = make_mocked_engine_adapter( + FabricEngineAdapter, + default_catalog="ci_abc", + database="ci_abc", + patch_get_data_objects=False, + ) + fetchdf = mocker.patch.object( + adapter, + "fetchdf", + return_value=pd.DataFrame([{"name": "t", "schema_name": "dbo", "type": "TABLE"}]), + ) + + first = adapter.get_data_objects("ci_abc.dbo", {"t"}, safe_to_cache=True) + second = adapter.get_data_objects("ci_abc.dbo", {"t"}, safe_to_cache=True) + + assert first[0].catalog == "ci_abc" + assert second[0].catalog == "ci_abc" + assert fetchdf.call_count == 1 + + +def test_get_data_objects_labels_connected_warehouse_after_lazy_restore( + make_mocked_engine_adapter: t.Callable, + mocker: MockerFixture, +) -> None: + """Logical target is the default; the connection is still on planning. + + The public catalog is the configured warehouse. The unqualified list must + still be planning, because that is the warehouse the query hits. + ci_abc.dbo must still switch. + """ + adapter = make_mocked_engine_adapter( + FabricEngineAdapter, + default_catalog="ci_abc", + database="ci_abc", + patch_get_data_objects=False, + ) + adapter.set_current_catalog("planning") + adapter.set_current_catalog(None) + assert adapter._target_catalog is None + assert adapter._connected_catalog == "planning" + assert adapter.get_current_catalog() == "ci_abc" + + fetchdf = mocker.patch.object( + adapter, + "fetchdf", + return_value=pd.DataFrame([{"name": "t", "schema_name": "dbo", "type": "TABLE"}]), + ) + + objects = adapter.get_data_objects("dbo") + + assert objects == [ + DataObject( + catalog="planning", + schema="dbo", + name="t", + type=DataObjectType.TABLE, + ) + ] + + assert adapter.get_data_objects("ci_abc.dbo") == [ + DataObject( + catalog="ci_abc", + schema="dbo", + name="t", + type=DataObjectType.TABLE, + ) + ] + assert fetchdf.call_count == 2 + + +def test_get_data_objects_non_default_warehouse_skips_default_cache( + make_mocked_engine_adapter: t.Callable, + mocker: MockerFixture, +) -> None: + """dbo and ci_abc.dbo share the base cache key. planning must not use that entry.""" + adapter = make_mocked_engine_adapter( + FabricEngineAdapter, + default_catalog="ci_abc", + database="ci_abc", + patch_get_data_objects=False, + ) + frames = { + "default": pd.DataFrame([{"name": "t", "schema_name": "dbo", "type": "TABLE"}]), + "planning": pd.DataFrame([{"name": "t", "schema_name": "dbo", "type": "VIEW"}]), + } + current = {"warehouse": "default"} + mocker.patch.object( + adapter, "fetchdf", side_effect=lambda *_args, **_kwargs: frames[current["warehouse"]] + ) + + cached = adapter.get_data_objects("ci_abc.dbo", {"t"}, safe_to_cache=True) + assert cached[0].type == DataObjectType.TABLE + + adapter.set_current_catalog("planning") + adapter.set_current_catalog(None) + current["warehouse"] = "planning" + listed = adapter.get_data_objects("dbo", {"t"}, safe_to_cache=True) + assert listed[0].catalog == "planning" + assert listed[0].type == DataObjectType.VIEW + + again = adapter.get_data_objects("ci_abc.dbo", {"t"}, safe_to_cache=True) + assert again[0].catalog == "ci_abc" + assert again[0].type == DataObjectType.TABLE + + +def test_drop_data_object_default_catalog_drops_without_requalifying( + make_mocked_engine_adapter: t.Callable, + mocker: MockerFixture, +) -> None: + """DROP SQL has no warehouse. Prove it ran on ci_abc, without reconnecting.""" + adapter = make_mocked_engine_adapter( + FabricEngineAdapter, + default_catalog="ci_abc", + database="ci_abc", + ) + close = mocker.spy(adapter._connection_pool, "close") + catalogs_at_execute = _record_catalogs_at_execute(adapter) + + adapter.drop_data_object( + DataObject(catalog="ci_abc", schema="dbo", name="v", type=DataObjectType.VIEW) + ) + + close.assert_not_called() + assert catalogs_at_execute == ["ci_abc"] + assert to_sql_calls(adapter) == ["DROP VIEW IF EXISTS [dbo].[v];"] + + +def test_drop_data_object_default_catalog_reconnects_when_connected_elsewhere( + make_mocked_engine_adapter: t.Callable, + mocker: MockerFixture, +) -> None: + """DROP SQL has no warehouse. Prove it ran on ci_abc, then restored planning.""" + adapter = make_mocked_engine_adapter( + FabricEngineAdapter, + default_catalog="ci_abc", + database="ci_abc", + ) + adapter.set_current_catalog("planning") + assert adapter.get_current_catalog() == "planning" + close = mocker.spy(adapter._connection_pool, "close") + catalogs_at_execute = _record_catalogs_at_execute(adapter) + + adapter.drop_data_object( + DataObject(catalog="ci_abc", schema="dbo", name="v", type=DataObjectType.VIEW) + ) + + assert catalogs_at_execute == ["ci_abc"] + assert adapter.get_current_catalog() == "planning" + assert close.call_count == 2 + assert "DROP VIEW IF EXISTS [dbo].[v];" in to_sql_calls(adapter) 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) diff --git a/tests/core/engine_adapter/test_redshift.py b/tests/core/engine_adapter/test_redshift.py index ddd2c7c2c8..a3260ed4cd 100644 --- a/tests/core/engine_adapter/test_redshift.py +++ b/tests/core/engine_adapter/test_redshift.py @@ -11,6 +11,7 @@ import sqlmesh.core.dialect as d from sqlmesh.core.engine_adapter import RedshiftEngineAdapter from sqlmesh.core.engine_adapter.shared import DataObject, DataObjectType +from sqlmesh.core.schema_diff import TableAlterDropColumnOperation from sqlmesh.core.model import load_sql_based_model from sqlmesh.core.model.definition import SqlModel from sqlmesh.utils.errors import SQLMeshError @@ -152,22 +153,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 +195,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")', ] @@ -863,3 +913,46 @@ def test_merge_logical( 'INSERT INTO "target" ("ID", "ts") SELECT "ID", "ts" FROM (SELECT "ID" AS "ID", "ts" AS "ts", ROW_NUMBER() OVER (PARTITION BY "ID" ORDER BY "ID") AS _row_number FROM "__temp_test_abcdefgh") AS _t WHERE _row_number = 1', 'DROP TABLE IF EXISTS "__temp_test_abcdefgh"', ] + + +def test_redshift_no_clustering_operations_on_column_drop( + make_mocked_engine_adapter: t.Callable, +) -> None: + """Dropping a column on Redshift never emits clustering statements.""" + adapter = make_mocked_engine_adapter(RedshiftEngineAdapter) + adapter.cursor.fetchall.return_value = [] + + current_columns = {"TENANT_ID": "INT", "PARTITION_MONTH": "INT"} + target_columns = {"TENANT_ID": "INT"} + adapter.columns = lambda table_name, **kwargs: { + k: exp.DataType.build(v) + for k, v in (current_columns if "current" in str(table_name) else target_columns).items() + } + + operations = adapter.get_alter_operations("current_table", "target_table") + + assert len(operations) == 1 + assert all(isinstance(op, TableAlterDropColumnOperation) for op in operations) + + +def test_redshift_multiple_column_drops_no_clustering_operations( + make_mocked_engine_adapter: t.Callable, +) -> None: + """Dropping multiple columns on Redshift preserves the schema-diff order. + + No clustering operations must be injected between or after the column drops. + """ + adapter = make_mocked_engine_adapter(RedshiftEngineAdapter) + adapter.cursor.fetchall.return_value = [] + + current_columns = {"EXTRA": "INT", "PARTITION_MONTH": "INT", "TENANT_ID": "INT"} + target_columns = {"TENANT_ID": "INT"} + adapter.columns = lambda table_name, **kwargs: { + k: exp.DataType.build(v) + for k, v in (current_columns if "current" in str(table_name) else target_columns).items() + } + + operations = adapter.get_alter_operations("current_table", "target_table") + + assert len(operations) == 2 + assert all(isinstance(op, TableAlterDropColumnOperation) for op in operations) diff --git a/tests/core/engine_adapter/test_snowflake.py b/tests/core/engine_adapter/test_snowflake.py index 05f0133ec8..3557d536a8 100644 --- a/tests/core/engine_adapter/test_snowflake.py +++ b/tests/core/engine_adapter/test_snowflake.py @@ -1,19 +1,27 @@ import typing as t +from datetime import datetime, timezone import pandas as pd # noqa: TID253 import pytest from pytest_mock.plugin import MockerFixture from sqlglot import exp, parse_one +from sqlglot.errors import ParseError from sqlglot.optimizer.normalize_identifiers import normalize_identifiers import sqlmesh.core.dialect as d from sqlmesh.core.dialect import normalize_model_name from sqlmesh.core.engine_adapter import SnowflakeEngineAdapter from sqlmesh.core.engine_adapter.base import EngineAdapter -from sqlmesh.core.engine_adapter.shared import DataObjectType +from sqlmesh.core.engine_adapter.mixins import ( + TableAlterChangeClusterKeyOperation, + TableAlterDropClusterKeyOperation, +) +from sqlmesh.core.engine_adapter.shared import DataObject, DataObjectType +from sqlmesh.core.schema_diff import TableAlterAddColumnOperation, TableAlterDropColumnOperation 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 +81,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 +211,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) @@ -246,6 +309,38 @@ def test_multiple_column_comments(make_mocked_engine_adapter: t.Callable, mocker ] +def test_column_comments_iceberg(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter) + + adapter._create_column_comments( + "test_table", + {"a": "a column description", "b": "b column description"}, + table_format="iceberg", + ) + + assert to_sql_calls(adapter) == [ + """ALTER ICEBERG TABLE "test_table" ALTER COLUMN "a" COMMENT 'a column description', COLUMN "b" COMMENT 'b column description'""", + ] + + +def test_ctas_column_comments_iceberg(make_mocked_engine_adapter: t.Callable): + adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter) + + # The column types are unknown, so the comments can't be inlined into the CTAS + # schema definition and are registered with a post-creation ALTER instead + adapter.ctas( + "test_table", + parse_one("SELECT a, b FROM source_table"), + table_format="iceberg", + column_descriptions={"a": "a column description"}, + ) + + assert to_sql_calls(adapter) == [ + """CREATE ICEBERG TABLE IF NOT EXISTS "test_table" AS SELECT "a", "b" FROM "source_table\"""", + """ALTER ICEBERG TABLE "test_table" ALTER COLUMN "a" COMMENT 'a column description'""", + ] + + def test_sync_grants_config(make_mocked_engine_adapter: t.Callable, mocker: MockerFixture): adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter) relation = normalize_identifiers( @@ -574,6 +669,31 @@ def test_create_managed_table(make_mocked_engine_adapter: t.Callable, mocker: Mo ] +@pytest.mark.parametrize("table_format", [None, "iceberg"]) +def test_create_managed_table_column_comments( + make_mocked_engine_adapter: t.Callable, table_format: t.Optional[str] +): + adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter) + + # Unknown column types require a post-creation comment command. + adapter.create_managed_table( + table_name="test_table", + query=parse_one("SELECT a, b FROM source_table"), + table_format=table_format, + table_properties={ + "target_lag": exp.Literal.string("20 minutes"), + "warehouse": exp.to_identifier("test_warehouse"), + }, + column_descriptions={"a": "a column description", "b": "b column description"}, + ) + + table_kind = "DYNAMIC ICEBERG TABLE" if table_format else "DYNAMIC TABLE" + assert to_sql_calls(adapter) == [ + f'CREATE OR REPLACE {table_kind} "test_table" TARGET_LAG=\'20 minutes\' WAREHOUSE="test_warehouse" AS SELECT "a", "b" FROM "source_table"', + """ALTER TABLE "test_table" ALTER COLUMN "a" COMMENT 'a column description', COLUMN "b" COMMENT 'b column description'""", + ] + + def test_drop_managed_table(make_mocked_engine_adapter: t.Callable, mocker: MockerFixture): adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter) @@ -1130,3 +1250,718 @@ def test_drop_catalog(snowflake_mocked_engine_adapter: SnowflakeEngineAdapter) - """SELECT 1 FROM "INFORMATION_SCHEMA"."DATABASES" WHERE "DATABASE_NAME" = 'foo' AND "COMMENT" = 'sqlmesh_managed'""", 'DROP DATABASE IF EXISTS "foo"', ] + + +@pytest.mark.parametrize( + "catalog_name, expected_name", + [ + # names that need quoting are parsed into quoted identifiers + ("my-db__dev", "my-db__dev"), + (exp.to_identifier("my db", quoted=True), "my db"), + (exp.to_identifier("MyDb", quoted=True), "MyDb"), + ], +) +def test_drop_catalog_quoted_name( + snowflake_mocked_engine_adapter: SnowflakeEngineAdapter, + catalog_name: t.Union[str, exp.Identifier], + expected_name: str, +) -> None: + adapter = snowflake_mocked_engine_adapter + exists_check = f"""SELECT 1 FROM "INFORMATION_SCHEMA"."DATABASES" WHERE "DATABASE_NAME" = '{expected_name}' AND "COMMENT" = 'sqlmesh_managed'""" + + # the existence check finds the sqlmesh_managed database, so it is dropped + adapter.cursor.fetchone.return_value = (1,) + adapter.drop_catalog(catalog_name) + + # the existence check must compare against the bare database name, without identifier quotes + assert to_sql_calls(adapter) == [ + exists_check, + f'DROP DATABASE IF EXISTS "{expected_name}"', + ] + + # the existence check finds nothing, so the database is left alone + adapter.cursor.execute.reset_mock() + adapter.cursor.fetchone.return_value = None + adapter.drop_catalog(catalog_name) + + assert to_sql_calls(adapter) == [exists_check] + + +def _make_snowflake_clustering_adapter( + make_mocked_engine_adapter: t.Callable, + mocker: MockerFixture, + current_columns: t.Dict[str, str], + target_columns: t.Dict[str, str], + current_clustering_key: t.Optional[str] = None, + target_clustering_key: t.Optional[str] = None, +) -> SnowflakeEngineAdapter: + """Create a mocked SnowflakeEngineAdapter wired for clustering-key tests.""" + adapter = make_mocked_engine_adapter( + SnowflakeEngineAdapter, default_catalog="catalog", patch_get_data_objects=False + ) + mocker.patch("sqlmesh.core.engine_adapter.snowflake.SnowflakeEngineAdapter.set_current_catalog") + + adapter.columns = lambda table_name, **kwargs: { + k: exp.DataType.build(v) + for k, v in ( + current_columns if table_name == "catalog.db.current_table" else target_columns + ).items() + } + + current_obj = DataObject( + catalog="catalog", + schema="db", + name="current_table", + type=DataObjectType.TABLE, + clustering_key=current_clustering_key, + ) + target_obj = DataObject( + catalog="catalog", + schema="db", + name="target_table", + type=DataObjectType.TABLE, + clustering_key=target_clustering_key, + ) + + def _mock_get_data_objects( + schema_name: t.Any, object_names: t.Optional[t.Set[str]] = None + ) -> t.List[DataObject]: + results = [] + for obj in [current_obj, target_obj]: + if object_names is None or obj.name in object_names: + results.append(obj) + return results + + mocker.patch.object(adapter, "_get_data_objects", side_effect=_mock_get_data_objects) + return adapter + + +def _cluster_alter(action: str) -> str: + return f'ALTER TABLE "CATALOG"."db"."current_table" {action}' + + +def test_clustering_key_drop_before_column_drop( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """Case 1: Both clustered columns dropped; clustering key removed. + + Current: TENANT_ID, PARTITION_MONTH — clustered on LINEAR("TENANT_ID", "PARTITION_MONTH"). + Target: TENANT_ID only, no clustering. + Expected order: DROP CLUSTERING KEY, then DROP COLUMN PARTITION_MONTH. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"TENANT_ID": "INT", "PARTITION_MONTH": "INT"}, + target_columns={"TENANT_ID": "INT"}, + current_clustering_key='LINEAR("TENANT_ID", "PARTITION_MONTH")', + target_clustering_key=None, + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert len(operations) == 2 + assert isinstance(operations[0], TableAlterDropClusterKeyOperation) + assert isinstance(operations[1], TableAlterDropColumnOperation) + + sql_calls = to_sql_calls(adapter) + assert sql_calls == [ + _cluster_alter("DROP CLUSTERING KEY"), + _cluster_alter('DROP COLUMN "PARTITION_MONTH"'), + ] + + +def test_clustering_key_cluster_by_before_column_drop( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """Case 2: Shrink clustering key from (ID, PARTITION_MONTH) to (ID); drop PARTITION_MONTH. + + Current: ID, PARTITION_MONTH — clustered on LINEAR("ID", "PARTITION_MONTH"). + Target: ID only, clustered on LINEAR("ID"). + Expected order: DROP CLUSTERING KEY, DROP COLUMN PARTITION_MONTH, CLUSTER BY ("ID"). + Setting the new key before dropping the column that was in the old key fails on + Snowflake, so the old key must come off first. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"ID": "INT", "PARTITION_MONTH": "INT"}, + target_columns={"ID": "INT"}, + current_clustering_key='LINEAR("ID", "PARTITION_MONTH")', + target_clustering_key='LINEAR("ID")', + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert len(operations) == 3 + assert isinstance(operations[0], TableAlterDropClusterKeyOperation) + assert isinstance(operations[1], TableAlterDropColumnOperation) + assert isinstance(operations[2], TableAlterChangeClusterKeyOperation) + + sql_calls = to_sql_calls(adapter) + assert sql_calls == [ + _cluster_alter("DROP CLUSTERING KEY"), + _cluster_alter('DROP COLUMN "PARTITION_MONTH"'), + _cluster_alter('CLUSTER BY ("ID")'), + ] + + +def test_clustering_key_unchanged_when_dropped_column_not_in_key( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """Case 3: Dropped column is not referenced by the clustering key. + + Current: TENANT_ID, EXTRA — clustered on LINEAR("TENANT_ID"). + Target: TENANT_ID, clustered on LINEAR("TENANT_ID"). + Expected: only DROP COLUMN EXTRA; no clustering statements emitted. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"TENANT_ID": "INT", "EXTRA": "INT"}, + target_columns={"TENANT_ID": "INT"}, + current_clustering_key='LINEAR("TENANT_ID")', + target_clustering_key='LINEAR("TENANT_ID")', + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + + assert len(operations) == 1 + assert isinstance(operations[0], TableAlterDropColumnOperation) + assert not any( + isinstance(op, (TableAlterChangeClusterKeyOperation, TableAlterDropClusterKeyOperation)) + for op in operations + ) + + +def test_clustering_key_add_column_before_cluster_by( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """Case 4: New clustering key references a column being added. + + Current: ID, not clustered. + Target: ID, C — clustered on LINEAR("C"). + Expected order: ADD COLUMN C, then CLUSTER BY ("C"). + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"ID": "INT"}, + target_columns={"ID": "INT", "C": "INT"}, + current_clustering_key=None, + target_clustering_key='LINEAR("C")', + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert len(operations) == 2 + assert isinstance(operations[0], TableAlterAddColumnOperation) + assert isinstance(operations[1], TableAlterChangeClusterKeyOperation) + + sql_calls = to_sql_calls(adapter) + assert sql_calls == [ + _cluster_alter('ADD "C" INT'), + _cluster_alter('CLUSTER BY ("C")'), + ] + + +def test_clustering_key_drop_column_add_column_change_key( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """Case 4b: Drop b, add c, and change the clustering key from b to c. + + Current: A, B — clustered on LINEAR("B"). + Target: A, C — clustered on LINEAR("C"). + Expected order: DROP CLUSTERING KEY, DROP COLUMN B, ADD COLUMN C, CLUSTER BY ("C"). + Snowflake rejects DROP COLUMN while the column is still in the key, and also + rejects CLUSTER BY on a column that has not yet been added. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"A": "INT", "B": "INT"}, + target_columns={"A": "INT", "C": "INT"}, + current_clustering_key='LINEAR("B")', + target_clustering_key='LINEAR("C")', + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert len(operations) == 4 + assert isinstance(operations[0], TableAlterDropClusterKeyOperation) + assert isinstance(operations[1], TableAlterDropColumnOperation) + assert isinstance(operations[2], TableAlterAddColumnOperation) + assert isinstance(operations[3], TableAlterChangeClusterKeyOperation) + + sql_calls = to_sql_calls(adapter) + assert sql_calls == [ + _cluster_alter("DROP CLUSTERING KEY"), + _cluster_alter('DROP COLUMN "B"'), + _cluster_alter('ADD "C" INT'), + _cluster_alter('CLUSTER BY ("C")'), + ] + + +def test_clustering_key_drop_only_when_same_columns( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """Case 5: No column changes, clustering key removed. + + Current: ID, C — clustered on LINEAR("ID"). + Target: ID, C — not clustered. + Expected: exactly one DROP CLUSTERING KEY, nothing else. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"ID": "INT", "C": "INT"}, + target_columns={"ID": "INT", "C": "INT"}, + current_clustering_key='LINEAR("ID")', + target_clustering_key=None, + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert len(operations) == 1 + assert isinstance(operations[0], TableAlterDropClusterKeyOperation) + + sql_calls = to_sql_calls(adapter) + assert sql_calls == [_cluster_alter("DROP CLUSTERING KEY")] + + +def test_clustering_key_inserted_between_multiple_drops( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """Case 6: Multiple columns dropped; only one belongs to the clustering key. + + Current: EXTRA, PARTITION_MONTH, TENANT_ID — clustered on LINEAR("PARTITION_MONTH"). + Target: TENANT_ID, not clustered. + Schema diff proposes: DROP EXTRA, DROP PARTITION_MONTH. + Expected order: DROP COLUMN EXTRA, DROP CLUSTERING KEY, DROP COLUMN PARTITION_MONTH. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"EXTRA": "INT", "PARTITION_MONTH": "INT", "TENANT_ID": "INT"}, + target_columns={"TENANT_ID": "INT"}, + current_clustering_key='LINEAR("PARTITION_MONTH")', + target_clustering_key=None, + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert len(operations) == 3 + assert isinstance(operations[0], TableAlterDropColumnOperation) + assert isinstance(operations[1], TableAlterDropClusterKeyOperation) + assert isinstance(operations[2], TableAlterDropColumnOperation) + + sql_calls = to_sql_calls(adapter) + assert sql_calls == [ + _cluster_alter('DROP COLUMN "EXTRA"'), + _cluster_alter("DROP CLUSTERING KEY"), + _cluster_alter('DROP COLUMN "PARTITION_MONTH"'), + ] + + +def test_clustering_key_cluster_by_change_inserted_between_drops( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """Clustering key changes (not just dropped) with multiple column drops. + + Current: EXTRA, PARTITION_MONTH, ID — clustered on LINEAR("PARTITION_MONTH"). + Target: ID, clustered on LINEAR("ID"). + Expected: DROP COLUMN EXTRA, DROP CLUSTERING KEY, DROP COLUMN PARTITION_MONTH, CLUSTER BY ("ID"). + The old key comes off before the drop of the column it names; the new key is set last. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"EXTRA": "INT", "PARTITION_MONTH": "INT", "ID": "INT"}, + target_columns={"ID": "INT"}, + current_clustering_key='LINEAR("PARTITION_MONTH")', + target_clustering_key='LINEAR("ID")', + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert len(operations) == 4 + assert isinstance(operations[0], TableAlterDropColumnOperation) + assert operations[0].column_parts[0].name == "EXTRA" + assert isinstance(operations[1], TableAlterDropClusterKeyOperation) + assert isinstance(operations[2], TableAlterDropColumnOperation) + assert isinstance(operations[3], TableAlterChangeClusterKeyOperation) + + sql_calls = to_sql_calls(adapter) + assert sql_calls == [ + _cluster_alter('DROP COLUMN "EXTRA"'), + _cluster_alter("DROP CLUSTERING KEY"), + _cluster_alter('DROP COLUMN "PARTITION_MONTH"'), + _cluster_alter('CLUSTER BY ("ID")'), + ] + + +def test_clustering_key_reorder_targets_current_table( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """All operations must target the current (source) table, not the target table.""" + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"TENANT_ID": "INT", "PARTITION_MONTH": "INT"}, + target_columns={"TENANT_ID": "INT"}, + current_clustering_key='LINEAR("TENANT_ID", "PARTITION_MONTH")', + target_clustering_key=None, + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + + for op in operations: + assert "current_table" in op.target_table.sql(dialect="snowflake").lower() + + +def test_clustering_key_normalization_quoted_upper_matches_upper_column( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """LINEAR("PARTITION_MONTH") references the column string PARTITION_MONTH. + + Both the quoted key identifier and the column name normalize to PARTITION_MONTH + in Snowflake, so the reorder must fire. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"TENANT_ID": "INT", "PARTITION_MONTH": "INT"}, + target_columns={"TENANT_ID": "INT"}, + current_clustering_key='LINEAR("PARTITION_MONTH")', + target_clustering_key=None, + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + + assert isinstance(operations[0], TableAlterDropClusterKeyOperation) + assert isinstance(operations[1], TableAlterDropColumnOperation) + + +def test_clustering_key_quoted_upper_does_not_match_stored_lower_column( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """LINEAR("PARTITION_MONTH") does not reference a column stored as partition_month. + + DESCRIBE returns the stored name. A lowercase name was created with quotes, so it + is a different column from PARTITION_MONTH and the key stays in place. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"TENANT_ID": "INT", "partition_month": "INT"}, + target_columns={"TENANT_ID": "INT"}, + current_clustering_key='LINEAR("PARTITION_MONTH")', + target_clustering_key=None, + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert len(operations) == 2 + assert isinstance(operations[0], TableAlterDropColumnOperation) + assert isinstance(operations[1], TableAlterDropClusterKeyOperation) + assert to_sql_calls(adapter) == [ + _cluster_alter('DROP COLUMN "partition_month"'), + _cluster_alter("DROP CLUSTERING KEY"), + ] + + +def test_clustering_key_normalization_quoted_lower_no_match_upper_column( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """LINEAR("partition_month") does NOT reference the column PARTITION_MONTH. + + The quoted-lowercase identifier stays lowercase, while the column string + PARTITION_MONTH normalizes to PARTITION_MONTH. No match → no reorder. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"TENANT_ID": "INT", "PARTITION_MONTH": "INT"}, + target_columns={"TENANT_ID": "INT"}, + current_clustering_key='LINEAR("partition_month")', + target_clustering_key='LINEAR("partition_month")', + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + + assert len(operations) == 1 + assert isinstance(operations[0], TableAlterDropColumnOperation) + assert not any( + isinstance(op, (TableAlterChangeClusterKeyOperation, TableAlterDropClusterKeyOperation)) + for op in operations + ) + + +def test_clustering_key_quoted_lower_matches_stored_lower_column( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """LINEAR("b") references the column stored as b. + + The stored name is already case-resolved, so it matches the quoted key and the + key comes off before the drop. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"id": "INT", "b": "INT"}, + target_columns={"id": "INT"}, + current_clustering_key='LINEAR("id", "b")', + target_clustering_key='LINEAR("id")', + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert [type(op) for op in operations] == [ + TableAlterDropClusterKeyOperation, + TableAlterDropColumnOperation, + TableAlterChangeClusterKeyOperation, + ] + assert to_sql_calls(adapter) == [ + _cluster_alter("DROP CLUSTERING KEY"), + _cluster_alter('DROP COLUMN "b"'), + _cluster_alter('CLUSTER BY ("id")'), + ] + + +def test_clustering_key_expression_column_dropped( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """A column inside a key expression is still part of the key. + + Current: TS, ID clustered on LINEAR(TO_DATE("TS"), "ID"). + Target: ID clustered on LINEAR("ID"). + Expected: DROP CLUSTERING KEY, DROP COLUMN TS, CLUSTER BY ("ID"). + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"TS": "DATE", "ID": "INT"}, + target_columns={"ID": "INT"}, + current_clustering_key='LINEAR(TO_DATE("TS"), "ID")', + target_clustering_key='LINEAR("ID")', + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert to_sql_calls(adapter) == [ + _cluster_alter("DROP CLUSTERING KEY"), + _cluster_alter('DROP COLUMN "TS"'), + _cluster_alter('CLUSTER BY ("ID")'), + ] + + +def test_clustering_key_expression_keeps_expression_column( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """Inverse of dropping the column inside the key expression. + + Current: TS DATE, ID INT clustered on LINEAR(TO_DATE("TS"), "ID"). + Target: TS DATE only, clustered on LINEAR(TO_DATE("TS")). + The plain column ID is dropped. TS stays, because the remaining key still uses it. + Expected: DROP CLUSTERING KEY, DROP COLUMN ID, CLUSTER BY (TO_DATE("TS")). + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"TS": "DATE", "ID": "INT"}, + target_columns={"TS": "DATE"}, + current_clustering_key='LINEAR(TO_DATE("TS"), "ID")', + target_clustering_key='LINEAR(TO_DATE("TS"))', + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + sql_calls = to_sql_calls(adapter) + assert sql_calls == [ + _cluster_alter("DROP CLUSTERING KEY"), + _cluster_alter('DROP COLUMN "ID"'), + _cluster_alter('CLUSTER BY (TO_DATE("TS"))'), + ] + assert not any('DROP COLUMN "TS"' in sql for sql in sql_calls) + + +def test_clustering_key_substring_expression_column_dropped( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """SUBSTRING(NAME, 1, 3) still names NAME, so NAME cannot be dropped first.""" + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"NAME": "VARCHAR", "ID": "INT"}, + target_columns={"ID": "INT"}, + current_clustering_key="LINEAR(SUBSTRING(NAME, 1, 3), ID)", + target_clustering_key="LINEAR(ID)", + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert to_sql_calls(adapter) == [ + _cluster_alter("DROP CLUSTERING KEY"), + _cluster_alter('DROP COLUMN "NAME"'), + _cluster_alter('CLUSTER BY ("ID")'), + ] + + +def test_clustering_key_type_change_on_key_column( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """VARCHAR to INT on a key column is a drop and an add, and the key stays the same. + + Snowflake still rejects the drop while the column is in the key, so the key comes + off first and is set again after the new column exists. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"A": "INT", "B": "VARCHAR"}, + target_columns={"A": "INT", "B": "INT"}, + current_clustering_key="LINEAR(B)", + target_clustering_key="LINEAR(B)", + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + assert to_sql_calls(adapter) == [ + _cluster_alter("DROP CLUSTERING KEY"), + _cluster_alter('DROP COLUMN "B"'), + _cluster_alter('ADD "B" INT'), + _cluster_alter('CLUSTER BY ("B")'), + ] + + +def test_clustering_key_issue_5813_clone_inherited_column_drop( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """Issue 5813: a cloned FULL snapshot still has the source clustering key. + + The issue's model is ANALYTICS.SESSION_FACTS. The deployed query projects + tenant_id, user_id, session_start_ts, and date_trunc('month', session_start_ts) + AS partition_month, with clustered_by (TENANT_ID, PARTITION_MONTH). A later edit + removes clustered_by and stops projecting partition_month. + + SQLMesh creates the new physical table with CREATE TABLE ... CLONE. Snowflake + copies the clustering key onto that clone. clone_table only emits the CLONE + statement, so this test is the alter that follows: the current table is the + clone and still has the inherited key. The issue does not state column types. + TENANT_ID and USER_ID are INT here; SESSION_START_TS is TIMESTAMP and + PARTITION_MONTH is DATE because the issue derives the latter with date_trunc. + + Snowflake rejects DROP COLUMN PARTITION_MONTH while it is still in the key + (error 003203). Expected: DROP CLUSTERING KEY, then DROP COLUMN PARTITION_MONTH. + The columns the model still projects are not dropped, and no CLUSTER BY is + emitted because the target has no clustering key. + """ + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={ + "TENANT_ID": "INT", + "USER_ID": "INT", + "SESSION_START_TS": "TIMESTAMP", + "PARTITION_MONTH": "DATE", + }, + target_columns={ + "TENANT_ID": "INT", + "USER_ID": "INT", + "SESSION_START_TS": "TIMESTAMP", + }, + current_clustering_key='LINEAR("TENANT_ID", "PARTITION_MONTH")', + target_clustering_key=None, + ) + + operations = adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") + adapter.alter_table(operations) + + sql_calls = to_sql_calls(adapter) + assert sql_calls == [ + _cluster_alter("DROP CLUSTERING KEY"), + _cluster_alter('DROP COLUMN "PARTITION_MONTH"'), + ] + for kept in ('"TENANT_ID"', '"USER_ID"', '"SESSION_START_TS"'): + assert not any(f"DROP COLUMN {kept}" in sql for sql in sql_calls) + + +def test_clustering_key_unparseable_without_column_drop_skips_parse( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """A key string that cannot be parsed is ignored unless a column is dropped. + + LINEAR( is not valid Snowflake SQL. With no column drop, the current key is not + parsed: an unchanged key emits nothing, and a removed or replaced key is appended. + """ + unchanged = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"ID": "INT"}, + target_columns={"ID": "INT"}, + current_clustering_key="LINEAR(", + target_clustering_key="LINEAR(", + ) + assert ( + unchanged.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") == [] + ) + + removed = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"ID": "INT"}, + target_columns={"ID": "INT"}, + current_clustering_key="LINEAR(", + target_clustering_key=None, + ) + removed_operations = removed.get_alter_operations( + "catalog.db.current_table", "catalog.db.target_table" + ) + removed.alter_table(removed_operations) + assert [type(op) for op in removed_operations] == [TableAlterDropClusterKeyOperation] + assert to_sql_calls(removed) == [_cluster_alter("DROP CLUSTERING KEY")] + + replaced = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"ID": "INT"}, + target_columns={"ID": "INT"}, + current_clustering_key="LINEAR(", + target_clustering_key='LINEAR("ID")', + ) + replaced_operations = replaced.get_alter_operations( + "catalog.db.current_table", "catalog.db.target_table" + ) + replaced.alter_table(replaced_operations) + assert [type(op) for op in replaced_operations] == [TableAlterChangeClusterKeyOperation] + assert to_sql_calls(replaced) == [_cluster_alter('CLUSTER BY ("ID")')] + + +def test_clustering_key_unparseable_column_drop_still_raises( + make_mocked_engine_adapter: t.Callable, mocker: MockerFixture +) -> None: + """Dropping a column still parses the current key, so a bad key still fails.""" + adapter = _make_snowflake_clustering_adapter( + make_mocked_engine_adapter, + mocker, + current_columns={"ID": "INT", "EXTRA": "INT"}, + target_columns={"ID": "INT"}, + current_clustering_key="LINEAR(", + target_clustering_key=None, + ) + + with pytest.raises(ParseError): + adapter.get_alter_operations("catalog.db.current_table", "catalog.db.target_table") diff --git a/tests/core/engine_adapter/test_starrocks.py b/tests/core/engine_adapter/test_starrocks.py index db0b1cc4ae..76f7a8b695 100644 --- a/tests/core/engine_adapter/test_starrocks.py +++ b/tests/core/engine_adapter/test_starrocks.py @@ -23,7 +23,9 @@ from sqlglot import expressions as exp from sqlglot import parse_one from pytest_mock.plugin import MockerFixture -from sqlmesh.core.engine_adapter.shared import DataObjectType +from sqlmesh.core.engine_adapter.mixins import TableAlterDropClusterKeyOperation +from sqlmesh.core.engine_adapter.shared import DataObject, DataObjectType +from sqlmesh.core.schema_diff import TableAlterDropColumnOperation from sqlmesh.utils.errors import SQLMeshError from tests.core.engine_adapter import to_sql_calls @@ -2486,3 +2488,60 @@ def test_non_starrocks_engine_is_not_affected(self) -> None: "excluded_refresh_tables" in StarRocksEngineAdapter.RESOLVE_TABLE_REFS_IN_PHYSICAL_PROPERTIES ) + + +class TestClusteringKeyOrdering: + """StarRocks uses ClusteredByMixin but must KEEP the historical alter order. + + Dropping a column that belongs to the current clustering key must NOT trigger + a reorder. StarRocks must emit DROP COLUMN first, then the clustering change. + """ + + def test_column_drop_before_clustering_key_change( + self, + make_mocked_engine_adapter: t.Callable[..., StarRocksEngineAdapter], + mocker: MockerFixture, + ) -> None: + """DROP COLUMN is emitted before DROP CLUSTERING KEY (historical order).""" + adapter = make_mocked_engine_adapter(StarRocksEngineAdapter, patch_get_data_objects=False) + + current_columns = {"id": "INT", "partition_month": "INT"} + target_columns = {"id": "INT"} + + def _columns(table_name: t.Any, **kwargs: t.Any) -> t.Dict[str, exp.DataType]: + mapping = current_columns if table_name == "db.current_table" else target_columns + return {k: exp.DataType.build(v) for k, v in mapping.items()} + + mocker.patch.object(adapter, "columns", side_effect=_columns) + + current_obj = DataObject( + catalog=None, + schema="db", + name="current_table", + type=DataObjectType.TABLE, + clustering_key='LINEAR("partition_month")', + ) + target_obj = DataObject( + catalog=None, + schema="db", + name="target_table", + type=DataObjectType.TABLE, + clustering_key=None, + ) + + def _mock_get_data_objects( + schema_name: t.Any, object_names: t.Optional[t.Set[str]] = None + ) -> t.List[DataObject]: + results = [] + for obj in [current_obj, target_obj]: + if object_names is None or obj.name in object_names: + results.append(obj) + return results + + mocker.patch.object(adapter, "_get_data_objects", side_effect=_mock_get_data_objects) + + operations = adapter.get_alter_operations("db.current_table", "db.target_table") + + assert len(operations) == 2 + assert isinstance(operations[0], TableAlterDropColumnOperation) + assert isinstance(operations[1], TableAlterDropClusterKeyOperation) diff --git a/tests/core/integration/test_aux_commands.py b/tests/core/integration/test_aux_commands.py index 7de585576d..070f38d780 100644 --- a/tests/core/integration/test_aux_commands.py +++ b/tests/core/integration/test_aux_commands.py @@ -1,6 +1,8 @@ from __future__ import annotations import typing as t +import subprocess +import sys from unittest.mock import patch import pytest from pathlib import Path @@ -86,6 +88,121 @@ def test_table_name(init_and_plan_context: t.Callable): ) +@time_machine.travel("2023-01-08 15:00:00 UTC") +def test_run_loads_materializations_once(init_and_plan_context: t.Callable, mocker: MockerFixture): + """Verify janitor and run dispatch loading while loaders execute only once.""" + context, plan = init_and_plan_context("examples/sushi") + context.apply(plan) + load_dispatch_spy = mocker.spy(context, "_load_materializations") + loader_spies = [mocker.spy(loader, "load_materializations") for loader in context._loaders] + assert loader_spies + assert context._materializations_loaded is True + + # Reset the guard to exercise lazy loading through run's janitor and scheduler paths. + context._materializations_loaded = False + context.run(skip_janitor=False) + + # The janitor and run each call the context wrapper; the second call is guarded. + assert load_dispatch_spy.call_count == 2 + + # Only the janitor's first dispatch reaches the loaders. + for loader_spy in loader_spies: + assert loader_spy.call_count == 1 + + +@time_machine.travel("2023-01-08 15:00:00 UTC") +def test_destroy_fails_before_invalidating_environments_on_materialization_error( + init_and_plan_context: t.Callable, mocker: MockerFixture +): + context, plan = init_and_plan_context("examples/sushi") + context.apply(plan) + assert context.state_reader.get_environment("prod").expiration_ts is None + + for loader in context._loaders: + mocker.patch.object( + loader, "load_materializations", side_effect=SQLMeshError("broken materialization") + ) + context._materializations_loaded = False + + with pytest.raises(SQLMeshError, match="broken materialization"): + context.destroy() + + assert context.state_reader.get_environment("prod").expiration_ts is None + + +def test_janitor_loads_materialization(tmp_path: Path): + config_file_path = Path("config.yaml") + database = tmp_path / "janitor_test.duckdb" + materialization_name = "dummy_materialization" + materialization_file_path = Path(f"materializations/{materialization_name}.py") + schema_name = "test" + model_name = "dummy_model" + model_file_path = Path(f"models/{model_name}.sql") + config_yaml = f"""\ +gateways: + local: + connection: + type: duckdb + database: {database} +default_gateway: local +model_defaults: + dialect: duckdb +""" + materialization_code = f"""from sqlmesh.core.snapshot.evaluator import CustomMaterialization +class DummyMaterialization(CustomMaterialization): + NAME = "{materialization_name}" + def insert(self, table_name, query_or_df, model, is_first_insert, render_kwargs, **kwargs): + self._replace_query_for_model(model, table_name, query_or_df, render_kwargs) +""" + model_code = f"""MODEL(name {schema_name}.{model_name}, kind CUSTOM (materialization '{materialization_name}')); +SELECT 1 AS col""" + + create_temp_file(tmp_path, config_file_path, config_yaml) + create_temp_file(tmp_path, materialization_file_path, materialization_code) + create_temp_file(tmp_path, model_file_path, model_code) + + ctx = Context(paths=[tmp_path]) + ctx.plan("dev", no_prompts=True, auto_apply=True) + + snapshot = ctx.get_snapshot(f"{schema_name}.{model_name}") + assert snapshot + table_name = snapshot.table_name() + assert ctx.engine_adapter.table_exists(table_name) + assert ctx.state_sync.get_snapshots([snapshot.snapshot_id]) + assert ctx._loaded + assert ctx._materializations_loaded + ctx.invalidate_environment("dev") + ctx.close() + + # A fresh interpreter cannot reuse materialization classes loaded during setup. + program = """\ +import sys +from sqlmesh.core.context import Context + +ctx = Context(paths=[sys.argv[1]], load=False) +table_name = sys.argv[2] +assert not ctx._loaded +assert not ctx._materializations_loaded +assert ctx.engine_adapter.table_exists(table_name) + +assert ctx.run_janitor(ignore_ttl=True) + +assert not ctx.engine_adapter.table_exists(table_name) +assert not ctx._loaded +assert ctx._materializations_loaded +ctx.close() +""" + result = subprocess.run( + [sys.executable, "-c", program, str(tmp_path), table_name], + cwd=tmp_path, + capture_output=True, + text=True, + timeout=120, + ) + + assert result.returncode == 0, result.stdout + result.stderr + + def test_janitor_cleanup_order(mocker: MockerFixture, tmp_path: Path): def setup_scenario(): models_dir = tmp_path / "models" diff --git a/tests/core/integration/test_plan_options.py b/tests/core/integration/test_plan_options.py index a50dc145cd..25bb03fc94 100644 --- a/tests/core/integration/test_plan_options.py +++ b/tests/core/integration/test_plan_options.py @@ -1,5 +1,6 @@ from __future__ import annotations +import logging import typing as t import pytest from sqlmesh.core.console import ( @@ -112,9 +113,10 @@ def test_empty_backfill_new_model(init_and_plan_context: t.Callable): @time_machine.travel("2023-01-08 15:00:00 UTC") -def test_plan_explain(init_and_plan_context: t.Callable): +def test_plan_explain(init_and_plan_context: t.Callable, caplog): old_console = get_console() - set_console(TerminalConsole()) + console = TerminalConsole() + set_console(console) context, plan = init_and_plan_context("examples/sushi") context.apply(plan) @@ -130,17 +132,25 @@ def test_plan_explain(init_and_plan_context: t.Callable): common_kwargs = dict(skip_tests=True, no_prompts=True, explain=True) - # For now just making sure the plan doesn't error - context.plan("dev", **common_kwargs) - context.plan("dev", **common_kwargs, skip_backfill=True) - context.plan("dev", **common_kwargs, empty_backfill=True) - context.plan("dev", **common_kwargs, forward_only=True, enable_preview=True) - context.plan("prod", **common_kwargs) - context.plan("prod", **common_kwargs, forward_only=True) - context.plan("prod", **common_kwargs, restate_models=[waiter_revenue_by_day_model.name]) + # Verify the schema creation stage is rendered, not only that dispatch succeeds. + with caplog.at_level(logging.ERROR, logger="sqlmesh.core.plan.explainer"): + with console.console.capture() as output: + context.plan("dev", **common_kwargs) + explanation = output.get() + assert "Create physical schemas if they do not exist" in explanation + assert "memory.sqlmesh__sushi" in explanation + context.plan("dev", **common_kwargs, skip_backfill=True) + context.plan("dev", **common_kwargs, empty_backfill=True) + context.plan("dev", **common_kwargs, forward_only=True, enable_preview=True) + context.plan("prod", **common_kwargs) + context.plan("prod", **common_kwargs, forward_only=True) + context.plan("prod", **common_kwargs, restate_models=[waiter_revenue_by_day_model.name]) set_console(old_console) + # Every stage produced by the plan must have a corresponding visit method on the explainer + assert "Unexpected stage" not in caplog.text + # Make sure that the now changes were actually applied for target_env in ("dev", "prod"): plan = context.plan_builder(target_env, skip_tests=True).build() 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) diff --git a/tests/core/linter/test_helpers.py b/tests/core/linter/test_helpers.py index c3ba46f304..7e0c7027ae 100644 --- a/tests/core/linter/test_helpers.py +++ b/tests/core/linter/test_helpers.py @@ -7,8 +7,8 @@ from sqlmesh.core.model import SqlModel -def test_get_position_of_model_block(): - context = Context(paths=["examples/sushi"]) +def test_get_position_of_model_block(copy_to_temp_path): + context = Context(paths=copy_to_temp_path("examples/sushi")) sql_models = [ model @@ -40,8 +40,8 @@ def test_get_position_of_model_block(): assert read_range.endswith(";") -def test_get_range_of_a_key_in_model_block_testing_on_sushi(): - context = Context(paths=["examples/sushi"]) +def test_get_range_of_a_key_in_model_block_testing_on_sushi(copy_to_temp_path): + context = Context(paths=copy_to_temp_path("examples/sushi")) sql_models = [ model diff --git a/tests/core/metric/test_metric.py b/tests/core/metric/test_metric.py index 51c97fbe3d..f15c4c8032 100644 --- a/tests/core/metric/test_metric.py +++ b/tests/core/metric/test_metric.py @@ -154,3 +154,11 @@ def test_get_measure_and_dim_tables(): "a", ("b",), ) + assert _get_measure_and_dim_tables(d.parse_one("ARRAY_AGG(a.x ORDER BY a.x)")) == ("a", ()) + assert _get_measure_and_dim_tables(d.parse_one("ARRAY_AGG(a.x ORDER BY b.y)")) == ("a", ("b",)) + assert _get_measure_and_dim_tables( + d.parse_one("ARRAY_AGG(IF(c.z = 'dim', a.x, NULL) ORDER BY b.y)") + ) == ("a", ("b", "c")) + # A column that only appears in the ORDER BY clause cannot be the measure. + with pytest.raises(ConfigError, match="Could not infer a measures table"): + _get_measure_and_dim_tables(d.parse_one("ARRAY_AGG(1 ORDER BY b.y)")) diff --git a/tests/core/metric/test_rewriter.py b/tests/core/metric/test_rewriter.py index 9fe8169508..d2ce821c2d 100644 --- a/tests/core/metric/test_rewriter.py +++ b/tests/core/metric/test_rewriter.py @@ -1,7 +1,9 @@ from sqlglot import parse_one -from sqlmesh.core.metric import rewrite +from sqlmesh.core import dialect as d +from sqlmesh.core.metric import expand_metrics, load_metric_ddl, rewrite from sqlmesh.core.reference import ReferenceGraph +from sqlmesh.utils import UniqueKeyDict def test_rewrite(sushi_context_pre_scheduling, assert_exp_eq): @@ -222,3 +224,27 @@ def test_rewrite(sushi_context_pre_scheduling, assert_exp_eq): # dialect=context.config.dialect, # ), # ) + + +def test_rewrite_order_by_metric(sushi_context_pre_scheduling): + context = sushi_context_pre_scheduling + graph = ReferenceGraph(context.models.values()) + meta = load_metric_ddl( + d.parse_one( + "METRIC (name sorted_amounts, expression ARRAY_AGG(sushi.orders.amount ORDER BY sushi.orders.amount))", + dialect=context.config.dialect, + ), + dialect=context.config.dialect, + ) + metrics = expand_metrics(UniqueKeyDict("metas", {meta.name: meta})) + + query = rewrite( + "SELECT c.customer_id, METRIC(sorted_amounts) FROM sushi.customers AS c GROUP BY c.customer_id", + graph=graph, + metrics=metrics, + ) + sql = query.sql() + # Stop before the generated NULLS LAST so the assertion doesn't depend on null ordering. + assert "ARRAY_AGG(sushi__orders.amount ORDER BY sushi__orders.amount" in sql + assert "sushi.orders AS sushi__orders" in sql + parse_one(sql, dialect=context.config.dialect) diff --git a/tests/core/state_sync/test_state_sync.py b/tests/core/state_sync/test_state_sync.py index 562afc6ac7..503f89296e 100644 --- a/tests/core/state_sync/test_state_sync.py +++ b/tests/core/state_sync/test_state_sync.py @@ -2971,6 +2971,141 @@ def test_migrate_rows(state_sync: EngineAdapterStateSync, mocker: MockerFixture) ) +def test_migrate_v0071_keeps_still_live_dev_intervals() -> None: + from sqlmesh.migrations import v0071_add_dev_version_to_intervals as migration + + engine_adapter = create_engine_adapter(duckdb.connect, "duckdb") + engine_adapter.create_schema(c.SQLMESH) + + engine_adapter.create_table( + "sqlmesh._snapshots", + { + "name": exp.DataType.build("text"), + "identifier": exp.DataType.build("text"), + "version": exp.DataType.build("text"), + "snapshot": exp.DataType.build("text"), + "kind_name": exp.DataType.build("text"), + "updated_ts": exp.DataType.build("bigint"), + "unpaused_ts": exp.DataType.build("bigint"), + "ttl_ms": exp.DataType.build("bigint"), + "unrestorable": exp.DataType.build("boolean"), + }, + ) + # The intervals table at schema version 70, before v0071 adds the dev_version column. + engine_adapter.create_table( + "sqlmesh._intervals", + { + "id": exp.DataType.build("text"), + "created_ts": exp.DataType.build("bigint"), + "name": exp.DataType.build("text"), + "identifier": exp.DataType.build("text"), + "version": exp.DataType.build("text"), + "start_ts": exp.DataType.build("bigint"), + "end_ts": exp.DataType.build("bigint"), + "is_dev": exp.DataType.build("boolean"), + "is_removed": exp.DataType.build("boolean"), + "is_compacted": exp.DataType.build("boolean"), + "is_pending_restatement": exp.DataType.build("boolean"), + }, + ) + + def snapshot_blob(name: str, identifier: str, version: str, dev_version: str) -> str: + return json.dumps( + { + "name": name, + "identifier": identifier, + "version": version, + "dev_version": dev_version, + "fingerprint": { + "data_hash": "data", + "metadata_hash": "metadata", + "parent_data_hash": "parent_data", + "parent_metadata_hash": "parent_metadata", + }, + "previous_versions": [], + } + ) + + engine_adapter.insert_append( + "sqlmesh._snapshots", + pd.DataFrame( + [ + { + "name": '"db"."prod_model"', + "identifier": "prod_ident", + "version": "prod_ver", + "snapshot": snapshot_blob( + '"db"."prod_model"', "prod_ident", "prod_ver", "prod_dev" + ), + "kind_name": "FULL", + "updated_ts": 1, + "unpaused_ts": None, + "ttl_ms": None, + "unrestorable": False, + }, + { + "name": '"db"."dev_model"', + "identifier": "dev_ident", + "version": "dev_ver", + "snapshot": snapshot_blob( + '"db"."dev_model"', "dev_ident", "dev_ver", "dev_dev" + ), + "kind_name": "FULL", + "updated_ts": 1, + "unpaused_ts": None, + "ttl_ms": None, + "unrestorable": False, + }, + ] + ), + ) + + engine_adapter.insert_append( + "sqlmesh._intervals", + pd.DataFrame( + [ + # A non-dev interval that is always kept; it forces the migration to + # rewrite the intervals table so a wrongly-dropped dev interval is + # actually deleted rather than left behind by the empty-result guard. + { + "id": "prod_int", + "created_ts": 1, + "name": '"db"."prod_model"', + "identifier": "prod_ident", + "version": "prod_ver", + "start_ts": 100, + "end_ts": 200, + "is_dev": False, + "is_removed": False, + "is_compacted": False, + "is_pending_restatement": False, + }, + # A dev interval whose version and dev version are both still live. + # It must be preserved by the migration. + { + "id": "dev_int", + "created_ts": 1, + "name": '"db"."dev_model"', + "identifier": "dev_ident", + "version": "dev_ver", + "start_ts": 100, + "end_ts": 200, + "is_dev": True, + "is_removed": False, + "is_compacted": False, + "is_pending_restatement": False, + }, + ] + ), + ) + + migration.migrate_schemas(engine_adapter, c.SQLMESH) + migration.migrate_rows(engine_adapter, c.SQLMESH) + + surviving_ids = {row[0] for row in engine_adapter.fetchall("SELECT id FROM sqlmesh._intervals")} + assert surviving_ids == {"prod_int", "dev_int"} + + def test_backup_state(state_sync: EngineAdapterStateSync, mocker: MockerFixture) -> None: state_sync.engine_adapter.replace_query( "sqlmesh._snapshots", @@ -4254,3 +4389,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/core/test_audit.py b/tests/core/test_audit.py index b5226563b5..d579064a07 100644 --- a/tests/core/test_audit.py +++ b/tests/core/test_audit.py @@ -221,6 +221,103 @@ def test_load_standalone_with_macros(assert_exp_eq): assert "extra_macro" not in audit.python_env +def test_load_multiple_single_standalone_with_macros(): + # Regression test for https://github.com/SQLMesh/sqlmesh/issues/6119 + # A standalone audit that is the *last* (and in this case only) AUDIT in its + # file must still have access to project python macros passed into + # `load_multiple_audits`. + expressions = parse( + """ + AUDIT ( + name only_allowed, + standalone true, + ); + + SELECT 1 FROM some_table WHERE name NOT IN @allowed() + """ + ) + + macros = { + "allowed": Executable(payload="def allowed(evaluator):\n return ['a']"), + } + + (audit,) = load_multiple_audits(expressions, path="/path/to/audit", macros=macros) + + assert "allowed" in audit.python_env + + +def test_load_multiple_last_standalone_with_macros(): + # Same as above, but for the last audit of a *multi*-audit file, to make sure + # the fix doesn't just special-case single-audit files. + expressions = parse( + """ + AUDIT ( + name first_audit, + standalone true, + ); + + SELECT 1 FROM some_table WHERE col1 IS NULL; + + AUDIT ( + name second_audit, + standalone true, + ); + + SELECT 1 FROM some_table WHERE name NOT IN @allowed() + """ + ) + + macros = { + "allowed": Executable(payload="def allowed(evaluator):\n return ['a']"), + } + + first_audit, second_audit = load_multiple_audits( + expressions, path="/path/to/audit", macros=macros + ) + + assert "allowed" not in first_audit.python_env + assert "allowed" in second_audit.python_env + + +def test_load_multiple_last_standalone_with_jinja_macros(): + # Regression test for https://github.com/SQLMesh/sqlmesh/issues/6119 + # Same as test_load_multiple_single_standalone_with_macros, but for jinja macros: + # a standalone audit that is the last (and in this case only) AUDIT in its file + # must still have access to project jinja macros passed into `load_multiple_audits`. + expressions = parse( + """ + AUDIT ( + name only_allowed, + standalone true, + ); + + JINJA_QUERY_BEGIN; + SELECT + *, + {{ test_macro(1) }}, + FROM + db.table t1 + WHERE + col IS NULL + JINJA_QUERY_END; + """ + ) + + macros = """ + {% macro test_macro(v) %}{{ v }}{% endmacro %} + + {% macro extra_macro(v) %}{{ v + 1 }}{% endmacro %} + """ + + jinja_macros = JinjaMacroRegistry() + jinja_macros.add_macros(MacroExtractor().extract(macros)) + + (audit,) = load_multiple_audits(expressions, path="/path/to/audit", jinja_macros=jinja_macros) + + assert "test_macro" in audit.jinja_macros.root_macros + assert "extra_macro" not in audit.jinja_macros.root_macros + + def test_load_standalone_with_jinja_macros(assert_exp_eq): expressions = parse( """ @@ -697,6 +794,89 @@ def test_pattern_audits(model: Model): ) +def test_z_score_audit(model: Model): + rendered_query = model.render_audit_query( + builtin.z_score_audit, + column=exp.to_column("a"), + threshold=exp.convert(3), + ) + assert ( + rendered_query.sql() + == """WITH "stats" AS (SELECT AVG("a") AS "mean_a", STDDEV("a") AS "stddev_a" FROM (SELECT * FROM "db"."test_model" AS "test_model" WHERE "ds" BETWEEN '1970-01-01' AND '1970-01-01') AS "_0" WHERE TRUE) SELECT "a" AS "a", ("a" - "mean_a") / NULLIF("stddev_a", 0) AS "z_score" FROM (SELECT * FROM "db"."test_model" AS "test_model" WHERE "ds" BETWEEN '1970-01-01' AND '1970-01-01') AS "_1", "stats" AS "stats" WHERE ABS(("a" - "mean_a") / NULLIF("stddev_a", 0)) > 3 AND TRUE""" + ) + + # The condition must filter the rows being checked, not just the rows used to compute the stats + rendered_query = model.render_audit_query( + builtin.z_score_audit, + column=exp.to_column("a"), + threshold=exp.convert(3), + condition=parse_one("b > 0"), + ) + assert ( + rendered_query.sql() + == """WITH "stats" AS (SELECT AVG("a") AS "mean_a", STDDEV("a") AS "stddev_a" FROM (SELECT * FROM "db"."test_model" AS "test_model" WHERE "ds" BETWEEN '1970-01-01' AND '1970-01-01') AS "_0" WHERE "b" > 0) SELECT "a" AS "a", ("a" - "mean_a") / NULLIF("stddev_a", 0) AS "z_score" FROM (SELECT * FROM "db"."test_model" AS "test_model" WHERE "ds" BETWEEN '1970-01-01' AND '1970-01-01') AS "_1", "stats" AS "stats" WHERE ABS(("a" - "mean_a") / NULLIF("stddev_a", 0)) > 3 AND "b" > 0""" + ) + + +def test_valid_http_method_audit(model: Model): + rendered_query = model.render_audit_query( + builtin.valid_http_method_audit, + column=exp.to_column("a"), + ) + assert ( + rendered_query.sql() + == """SELECT * FROM (SELECT * FROM "db"."test_model" AS "test_model" WHERE "ds" BETWEEN '1970-01-01' AND '1970-01-01') AS "_0" WHERE NOT "a" IN ('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'TRACE', 'CONNECT') AND TRUE""" + ) + + rendered_query = model.render_audit_query( + builtin.valid_http_method_audit, + column=exp.to_column("a"), + condition=parse_one("b > 0"), + ) + assert ( + rendered_query.sql() + == """SELECT * FROM (SELECT * FROM "db"."test_model" AS "test_model" WHERE "ds" BETWEEN '1970-01-01' AND '1970-01-01') AS "_0" WHERE NOT "a" IN ('GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS', 'TRACE', 'CONNECT') AND "b" > 0""" + ) + + +def test_builtin_audits_condition_filters_audited_rows(): + import duckdb + + model = create_sql_model( + "db.test_model", + parse_one("SELECT region, v, method FROM db.src"), + kind=FullKind(), + dialect="duckdb", + ) + connection = duckdb.connect() + connection.execute( + "CREATE SCHEMA db; CREATE TABLE db.test_model AS " + "SELECT * FROM (VALUES ('us', 10, 'GET'), ('us', 10, 'POST'), ('us', 11, 'PUT'), " + "('eu', 1000, 'get'), ('eu', 1000, 'post')) AS t(region, v, method)" + ) + condition = parse_one("region = 'us'", dialect="duckdb") + + z_score_query = model.render_audit_query( + builtin.z_score_audit, + column=exp.to_column("v"), + threshold=exp.convert(1), + condition=condition, + ) + # Only the rows matching the condition are compared against the stats computed for them + assert connection.execute(z_score_query.sql("duckdb")).fetchall() == [ + (11, pytest.approx(1.1547005)) + ] + + valid_http_method_query = model.render_audit_query( + builtin.valid_http_method_audit, + column=exp.to_column("method"), + condition=condition, + ) + assert connection.execute(valid_http_method_query.sql("duckdb")).fetchall() == [] + + connection.close() + + def test_standalone_audit(model: Model, assert_exp_eq): audit = StandaloneAudit( name="test_audit", query=parse_one(f"SELECT * FROM {model.name} WHERE col IS NULL") @@ -852,6 +1032,44 @@ def test_not_constant_audit(model: Model): ) +def test_valid_uuid_audit(model: Model): + import duckdb + + rendered_query = model.render_audit_query(builtin.valid_uuid_audit, column=exp.column("a")) + assert ( + rendered_query.sql() + == """SELECT * FROM (SELECT * FROM "db"."test_model" AS "test_model" WHERE "ds" BETWEEN '1970-01-01' AND '1970-01-01') AS "_0" WHERE NOT REGEXP_LIKE(LOWER("a"), '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') AND TRUE""" + ) + + valid = [ + "6ba7b810-9dad-11d1-80b4-00c04fd430c8", # v1 + "000003e8-2363-21ef-b200-325096b39f47", # v2 + "5df41881-3aed-3515-88a7-2f4a814cf09e", # v3 + "919108F7-52D1-4320-9BAC-F847DB4148A8", # v4, upper case + "2ed6657d-e927-568b-95e1-2665a8aea6a2", # v5 + "1ec9414c-232a-6b00-b3c8-9f6bdeced846", # v6 + "017f22e2-79b0-7cc3-98c4-dc0c0c07398f", # v7 + "2489e9ad-2ee2-8e00-8ec9-32d5f69181c0", # v8 + ] + invalid = [ + "017f22e2-79b0-9cc3-98c4-dc0c0c07398f", # unknown version + "017f22e2-79b0-7cc3-c8c4-dc0c0c07398f", # non-RFC variant + "017f22e279b07cc398c4dc0c0c07398f", # no hyphens + "not-a-uuid", + ] + + connection = duckdb.connect() + connection.execute("CREATE SCHEMA db") + connection.execute("CREATE TABLE db.test_model (a TEXT, b INT, ds TEXT)") + connection.executemany( + "INSERT INTO db.test_model VALUES (?, 1, '1970-01-01')", + [[value] for value in valid + invalid + [None]], + ) + + failing_rows = connection.execute(rendered_query.sql(dialect="duckdb")).fetchall() + assert sorted(row[0] for row in failing_rows) == sorted(invalid) + + def test_condition_with_macro_var(model: Model): rendered_query = model.render_audit_query( builtin.not_null_audit, 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, diff --git a/tests/core/test_connection_config.py b/tests/core/test_connection_config.py index c506d401d9..e331da2587 100644 --- a/tests/core/test_connection_config.py +++ b/tests/core/test_connection_config.py @@ -1,4 +1,5 @@ import base64 +import logging import re import typing as t from unittest.mock import MagicMock, patch @@ -1426,21 +1427,20 @@ def test_databricks(make_config): ) -def test_databricks__u2m_oauth__shared_connection_pool(make_config): - """Databricks should use a shared connection pool when using OAuth to prevent CSRF races. +def test_databricks__u2m_oauth__connection_pool(make_config): + """Databricks should use a connection per thread with U2M OAuth, sharing a single login. - When concurrent_tasks > 1, ThreadLocalConnectionPool creates one connection per - thread. For U2M OAuth, each thread triggers its own browser-based OAuth flow; - these race on the CSRF state parameter and cause MismatchingStateError. - - For non-U2M OAuth authentication types (e.g. access_token and M2M OAuth) then - ThreadLocalConnectionPool should still be used. + If each connection ran its own U2M OAuth flow then the browser flows would race on the + CSRF state parameter and cause MismatchingStateError. Sharing a single connection avoids + that but forces all queries to run sequentially. Instead, every connection is given the + same credentials provider so the browser flow only runs once. See: https://github.com/tobymao/sqlmesh/issues/5646 https://github.com/SQLMesh/sqlmesh/issues/5858 """ - from sqlmesh.utils.connection_pool import ThreadLocalSharedConnectionPool + from sqlmesh.utils.connection_pool import ThreadLocalConnectionPool + from sqlmesh.utils.databricks import SharedU2MCredentialsProvider config = make_config( type="databricks", @@ -1450,10 +1450,89 @@ def test_databricks__u2m_oauth__shared_connection_pool(make_config): concurrent_tasks=4, ) assert isinstance(config, DatabricksConnectionConfig) + assert config.shared_connection is False + + adapter = config.create_engine_adapter() + assert isinstance(adapter._connection_pool, ThreadLocalConnectionPool) + + connection_kwargs = config._connection_factory_with_kwargs.keywords + assert connection_kwargs["auth_type"] == "databricks-oauth" + credentials_provider = connection_kwargs["credentials_provider"] + assert isinstance(credentials_provider, SharedU2MCredentialsProvider) + + # Separate engine adapters (and copies of the config) must reuse the same login + other_config = make_config( + type="databricks", + server_hostname="dbc-test.cloud.databricks.com", + http_path="sql/test/bar", + auth_type="databricks-oauth", + ) + assert ( + other_config._connection_factory_with_kwargs.keywords["credentials_provider"] + is credentials_provider + ) + + +def test_databricks__u2m_oauth__incompatible_connector_shares_connection(make_config, caplog): + """If a connector upgrade changes the internals the shared login builds on, U2M OAuth falls back to one shared + connection and logs a warning rather than failing to connect.""" + from sqlmesh.utils import databricks + from sqlmesh.utils.connection_pool import ThreadLocalSharedConnectionPool + + databricks.supports_shared_u2m_login.cache_clear() + try: + with ( + patch("databricks.sql.utils.build_client_context", lambda server_hostname: None), + caplog.at_level(logging.WARNING, logger="sqlmesh.utils.databricks"), + ): + config = make_config( + type="databricks", + server_hostname="dbc-test.cloud.databricks.com", + http_path="sql/test/foo", + auth_type="databricks-oauth", + concurrent_tasks=4, + ) + assert isinstance(config, DatabricksConnectionConfig) + assert config.shared_connection is True + + adapter = config.create_engine_adapter() + assert isinstance(adapter._connection_pool, ThreadLocalSharedConnectionPool) + + connection_kwargs = config._connection_factory_with_kwargs.keywords + assert connection_kwargs["auth_type"] == "databricks-oauth" + assert "credentials_provider" not in connection_kwargs + + assert "not compatible with SQLMesh's shared U2M OAuth login" in caplog.text + finally: + databricks.supports_shared_u2m_login.cache_clear() + + +@pytest.mark.parametrize( + "auth_kwargs", + [ + {"auth_type": "databricks-oauth"}, + {"access_token": "foo"}, + ], +) +def test_databricks__force_shared_connection(make_config, auth_kwargs): + """`force_shared_connection` runs every query over one connection, for connector backends that can't share a + U2M OAuth login (the kernel backend runs its own browser flow for each connection).""" + from sqlmesh.utils.connection_pool import ThreadLocalSharedConnectionPool + + config = make_config( + type="databricks", + server_hostname="dbc-test.cloud.databricks.com", + http_path="sql/test/foo", + concurrent_tasks=4, + force_shared_connection=True, + **auth_kwargs, + ) + assert isinstance(config, DatabricksConnectionConfig) assert config.shared_connection is True adapter = config.create_engine_adapter() assert isinstance(adapter._connection_pool, ThreadLocalSharedConnectionPool) + assert "credentials_provider" not in config._connection_factory_with_kwargs.keywords @patch.object(DatabricksConnectionConfig, "_connection_factory_with_kwargs") diff --git a/tests/core/test_console.py b/tests/core/test_console.py index f899713235..12e68b990e 100644 --- a/tests/core/test_console.py +++ b/tests/core/test_console.py @@ -1,4 +1,229 @@ +import pytest + from sqlmesh.core.console import MarkdownConsole +from sqlmesh.core.context_diff import ContextDiff +from sqlmesh.core.dialect import parse +from sqlmesh.core.environment import EnvironmentNamingInfo, EnvironmentStatements +from sqlmesh.core.model import load_sql_based_model +from sqlmesh.core.snapshot import SnapshotChangeCategory +from sqlmesh.utils.metaprogramming import Executable + + +@pytest.fixture +def markdown_context_diff(make_snapshot): + def make_diff(old_query, new_query, dialect="tsql"): + old, new = [ + make_snapshot( + load_sql_based_model(parse(f"MODEL (name test.model, dialect {dialect}); {query}")) + ) + for query in (old_query, new_query) + ] + new.categorize_as(SnapshotChangeCategory.NON_BREAKING) + return ContextDiff( + environment="prod", + is_new_environment=False, + is_unfinalized_environment=False, + normalize_environment_name=True, + create_from="prod", + create_from_env_exists=True, + added=set(), + removed_snapshots={}, + modified_snapshots={new.name: (new, old)}, + snapshots={new.snapshot_id: new}, + new_snapshots={new.snapshot_id: new}, + previous_plan_id=None, + previously_promoted_snapshot_ids=set(), + previous_finalized_snapshots=None, + previous_gateway_managed_virtual_layer=False, + gateway_managed_virtual_layer=False, + environment_statements=[], + ) + + return make_diff + + +@pytest.mark.parametrize( + "dialect,old_column,new_column,table", + [ + ("tsql", "[old_col]", "[new_col]", "[schema].[table]"), + ("tsql", "[old column]", "[new]]column]", "[my schema].[my]]table]"), + ("duckdb", "old_col", "new_col", "schema_name.table_name"), + ], +) +def test_markdown_console_model_diff_identifiers( + markdown_context_diff, dialect, old_column, new_column, table +): + context_diff = markdown_context_diff( + f"SELECT {old_column} FROM {table}", + f"SELECT {new_column} FROM {table}", + dialect, + ) + snapshot = next(iter(context_diff.snapshots.values())) + diff = context_diff.text_diff(snapshot.name) + assert old_column in diff and new_column in diff and table in diff + + console = MarkdownConsole() + console.show_model_difference_summary( + context_diff, EnvironmentNamingInfo(), None, no_diff=False + ) + + output = console.consume_captured_output() + assert ( + " ```diff\n" + "\n".join(f" {line}" for line in diff.split("\n")) + "\n ```\n" in output + ) + assert "**Directly Modified:**" in output + assert "(Non-breaking)" in output + assert console.consume_captured_output() == "" + + +@pytest.mark.parametrize("categorized", [False, True]) +@pytest.mark.parametrize("backticks", ["", "```", "`````"]) +def test_markdown_console_literal_model_diffs( + markdown_context_diff, mocker, capsys, categorized, backticks +): + literal = f"[bold] [/invalid] :smile: \\path\t{'long text ' * 20}\n{backticks}\nend" + context_diff = markdown_context_diff("SELECT 1 AS [old]", f"SELECT '{literal}' AS [new]") + snapshot = next(iter(context_diff.snapshots.values())) + diff = context_diff.text_diff(snapshot.name) + assert all(line in diff for line in literal.split("\n")) + console = MarkdownConsole(width=30) + console.log_success("before diff") + if categorized: + plan = mocker.Mock( + context_diff=context_diff, + categorized=[snapshot], + indirectly_modified={}, + environment_naming_info=EnvironmentNamingInfo(), + ) + console._show_categorized_snapshots(plan, None) + else: + console.show_model_difference_summary( + context_diff, EnvironmentNamingInfo(), None, no_diff=False + ) + console.log_success("after diff") + + output = console.consume_captured_output() + fence = "`" * max(3, len(backticks) + 1) + indent = "" if categorized else " " + block = ( + f"{indent}{fence}diff\n" + + "\n".join(f"{indent}{line}" for line in diff.split("\n")) + + f"\n{indent}{fence}\n" + ) + assert block in output + assert output.count(block) == 1 + assert output.index("before diff") < output.index(block) < output.index("after diff") + assert console.consume_captured_output() == "" + visible = capsys.readouterr().out + assert visible.count(f"{fence}diff") == 1 + assert "[bold] [/invalid] :smile:" in visible + if categorized: + assert "Directly Modified:" in output + assert "[bold]" not in output.split(block, 1)[1] + + +@pytest.mark.parametrize("no_diff,empty_diff", [(True, False), (False, True)]) +def test_markdown_console_omitted_model_diffs(markdown_context_diff, mocker, no_diff, empty_diff): + context_diff = markdown_context_diff("SELECT 1 AS [old]", "SELECT 2 AS [new]") + text_diff = mocker.patch.object(ContextDiff, "text_diff", return_value="") + console = MarkdownConsole() + console.show_model_difference_summary( + context_diff, EnvironmentNamingInfo(), None, no_diff=no_diff + ) + output = console.consume_captured_output() + assert "```" not in output + assert "**Directly Modified:**" in output + if empty_diff: + text_diff.assert_called_once() + else: + text_diff.assert_not_called() + + +@pytest.mark.parametrize("no_diff", [False, True]) +def test_markdown_console_environment_sql_diffs(markdown_context_diff, no_diff): + context_diff = markdown_context_diff("SELECT 1", "SELECT 2") + context_diff.previous_environment_statements = [ + EnvironmentStatements( + before_all=["SELECT [old] FROM [schema].[table]"], + after_all=["SELECT [old]"], + python_env={"version": Executable.value(1)}, + ) + ] + context_diff.environment_statements = [ + EnvironmentStatements( + before_all=["SELECT [new], ':smile: [/invalid]\\path\t' FROM [schema].[table]"], + after_all=[f"SELECT '```\n{'long text ' * 20}\n```' AS [new]"], + python_env={"version": Executable.value(2)}, + ) + ] + console = MarkdownConsole(width=35) + console.show_environment_difference_summary(context_diff, no_diff=no_diff) + output = console.consume_captured_output() + assert "**Summary of differences from" in output and "`prod`:**" in output + if no_diff: + assert "Environment statements:" not in output + assert "```" not in output + return + + assert "Environment statements:" in output + for language, diff in context_diff.environment_statements_diff(include_python_env=True): + if language == "sql": + fence = "````" if "```" in diff else "```" + assert f"{fence}diff\n{diff}\n{fence}\n" in output + else: + assert diff in output + assert output.index("before_all:") < output.index("after_all:") < output.index("dependencies:") + + +@pytest.mark.parametrize("indirect_only", [False, True]) +def test_markdown_console_model_change_categories( + markdown_context_diff, make_snapshot, indirect_only +): + context_diff = markdown_context_diff("SELECT 1 AS [old]", "SELECT 2 AS [new]") + current, previous = next(iter(context_diff.modified_snapshots.values())) + child_model = load_sql_based_model( + parse("MODEL (name test.child, dialect tsql); SELECT * FROM test.model") + ) + old_child, new_child = [ + make_snapshot(child_model, nodes={parent.name: parent.model}) + for parent in (previous, current) + ] + new_child.categorize_as(SnapshotChangeCategory.INDIRECT_NON_BREAKING) + old_metadata, new_metadata = [ + make_snapshot( + load_sql_based_model( + parse(f"MODEL (name test.metadata, owner {owner}); SELECT 1 AS value") + ) + ) + for owner in ("old_owner", "new_owner") + ] + context_diff.modified_snapshots.update( + { + new_child.name: (new_child, old_child), + new_metadata.name: (new_metadata, old_metadata), + } + ) + context_diff.snapshots.update( + {new_child.snapshot_id: new_child, new_metadata.snapshot_id: new_metadata} + ) + assert context_diff.indirectly_modified(new_child.name) + assert context_diff.metadata_updated(new_metadata.name) + if indirect_only: + del context_diff.modified_snapshots[current.name] + + console = MarkdownConsole() + console.show_model_difference_summary( + context_diff, EnvironmentNamingInfo(), None, no_diff=False + ) + output = console.consume_captured_output() + assert "**Indirectly Modified:**\n- `test.child` (Indirect Non-breaking)" in output + assert "**Metadata Updated:**\n- `test.metadata`" in output + if indirect_only: + assert "**Directly Modified:**" not in output + assert "```" not in output + else: + assert " Indirectly Modified Children:\n - `test.child`" in output + assert output.index(" ```diff") < output.index(" Indirectly Modified Children:") def test_markdown_console_warning_block(): diff --git a/tests/core/test_context.py b/tests/core/test_context.py index 1d87e1db18..71276b7396 100644 --- a/tests/core/test_context.py +++ b/tests/core/test_context.py @@ -17,6 +17,7 @@ import sqlmesh.core.constants from sqlmesh.cli.project_init import init_example_project +from sqlmesh.core.audit import StandaloneAudit from sqlmesh.core.console import TerminalConsole from sqlmesh.core import dialect as d, constants as c from sqlmesh.core.config import ( @@ -276,6 +277,78 @@ def test_render_seed_model(sushi_context, assert_exp_eq): ) +@pytest.mark.slow +def test_load_only_hydrates_remote_snapshots_missing_locally(sushi_context: Context) -> None: + prod = sushi_context.state_reader.get_environment("prod") + assert prod is not None + sushi_context._projects = {"local_project"} + + local_node_names = {*sushi_context.models, *sushi_context.standalone_audits} + expected_remote_names = { + snapshot_info.name + for snapshot_info in prod.snapshots + if snapshot_info.name not in local_node_names + } + assert len(expected_remote_names) < len(prod.snapshots) + + with patch.object( + sushi_context.state_reader, + "get_snapshots", + wraps=sushi_context.state_reader.get_snapshots, + ) as get_snapshots_mock: + sushi_context.load(update_schemas=False) + + load_snapshot_names = { + snapshot_info.name + for call_args in get_snapshots_mock.call_args_list + for snapshot_info in call_args.args[0] + } + assert load_snapshot_names == expected_remote_names + + +@pytest.mark.slow +def test_load_hydrates_opposite_type_snapshot_name_collision( + sushi_context: Context, make_snapshot: t.Callable +) -> None: + prod = sushi_context.state_reader.get_environment("prod") + assert prod is not None + sushi_context._projects = {"local_project"} + + local_model = next(iter(sushi_context.models.values())) + remote_audit_snapshot = make_snapshot( + StandaloneAudit( + name=local_model.fqn, + query=parse_one("SELECT NULL LIMIT 0"), + project="remote_project", + ) + ) + remote_audit_snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + prod_with_collision = prod.copy( + update={"snapshots_": [*prod.snapshots, remote_audit_snapshot.table_info]} + ) + + with ( + patch.object( + sushi_context.state_reader, + "get_environment", + return_value=prod_with_collision, + ), + patch.object( + sushi_context.state_reader, + "get_snapshots", + wraps=sushi_context.state_reader.get_snapshots, + ) as get_snapshots_mock, + ): + sushi_context.load(update_schemas=False) + + requested_snapshot_names = { + snapshot_info.name + for call_args in get_snapshots_mock.call_args_list + for snapshot_info in call_args.args[0] + } + assert remote_audit_snapshot.name in requested_snapshot_names + + @pytest.mark.slow def test_diff(sushi_context: Context, mocker: MockerFixture): mock_console = mocker.Mock() @@ -2609,8 +2682,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 +2689,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): diff --git a/tests/core/test_dialect.py b/tests/core/test_dialect.py index 142b40b31f..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 @@ -342,6 +344,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. @@ -1050,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) diff --git a/tests/core/test_execution_observation.py b/tests/core/test_execution_observation.py new file mode 100644 index 0000000000..626eae3d98 --- /dev/null +++ b/tests/core/test_execution_observation.py @@ -0,0 +1,482 @@ +# SPDX-License-Identifier: Apache-2.0 +import logging +from dataclasses import dataclass, field +from contextvars import ContextVar + +import pytest + +from sqlmesh.core.execution_observation import ( + action, + observer_scope, + update_execution, + execution_context_factory, +) + + +@dataclass +class Observer: + events: list = field(default_factory=list) + + def __call__(self, phase, facts, error): + self.events.append((phase, dict(facts), error)) + + +def test_native_facts_have_no_telemetry_policy(): + observer = Observer() + error = ValueError("view failed") + with observer_scope(observer), pytest.raises(ValueError) as raised: + with action("virtual", "promote", target="view"): + update_execution(source_table="table") + raise error + assert raised.value is error + assert observer.events == [ + ("start", {"kind": "virtual", "action": "promote", "target": "view"}, None), + ( + "finish", + {"kind": "virtual", "action": "promote", "target": "view", "source_table": "table"}, + error, + ), + ] + + +@pytest.mark.parametrize("phase", ["start", "finish"]) +@pytest.mark.parametrize("failure", [None, ValueError("native failure"), KeyboardInterrupt()]) +def test_observer_errors_cannot_change_workload_outcome(phase, failure): + calls = [] + + def observer(event, facts, error): + calls.append(event) + if event == phase: + raise RuntimeError("observer failure") + + def workload(): + with observer_scope(observer), action("query", "execute"): + if failure is not None: + raise failure + return 42 + + if failure is None: + assert workload() == 42 + else: + with pytest.raises(type(failure)) as raised: + workload() + assert raised.value is failure + assert calls == ["start", "finish"] + + +def test_disabled_observer_does_not_create_metadata(): + from sqlmesh.core.console import TerminalConsole + + assert TerminalConsole().get_execution_observer() is None + with action("query", "execute") as metadata: + assert metadata is None + + +def test_real_adapter_preserves_sql_and_errors(duck_conn, caplog): + from sqlmesh.core.engine_adapter import DuckDBEngineAdapter + + adapter = DuckDBEngineAdapter(lambda: duck_conn) + observer = Observer() + sql = "SELECT\n 1 AS observed_value" + with caplog.at_level(logging.DEBUG), observer_scope(observer): + adapter.execute(sql) + with pytest.raises(Exception): + adapter.execute("SELECT * FROM missing_observed_table") + queries = [event for event in observer.events if event[0] == "finish"] + assert len(queries) == 2 + assert queries[0][2] is None + assert queries[1][2] is not None + assert all( + event[1] == {"kind": "query", "action": "execute", "engine": "duckdb"} for event in queries + ) + assert f"Executing SQL: {sql}" in [record.getMessage() for record in caplog.records] + assert "Executing SQL: SELECT * FROM missing_observed_table" in [ + record.getMessage() for record in caplog.records + ] + + +def test_native_dag_copies_consumer_context_not_predecessor_context(): + from sqlmesh.utils.concurrency import ConcurrentDAGExecutor + from sqlmesh.utils.dag import DAG + + consumer_context = ContextVar("consumer_context", default=None) + observer = Observer() + dag = DAG() + dag.add("second", {"first"}) + + def execute(name): + assert consumer_context.get() == "stage" + consumer_context.set(name) + with action("physical", "create", target=name): + pass + + with observer_scope(observer): + token = consumer_context.set("stage") + try: + errors, skipped = ConcurrentDAGExecutor( + dag, execute, 2, False, execution_context_factory() + ).run() + finally: + consumer_context.reset(token) + assert not errors and not skipped + assert len(observer.events) == 4 + + +def test_concurrent_model_hooks_keep_batch_context_and_original_failures(): + """Real DAG workers retain independent batch scopes even when one fails.""" + from threading import Barrier, Lock, get_ident + + from sqlmesh.utils.concurrency import ConcurrentDAGExecutor + from sqlmesh.utils.dag import DAG + + consumer_context = ContextVar("batch_context", default="plan") + barrier = Barrier(2) + lock = Lock() + events = [] + failure = RuntimeError("model evaluation failed") + dag = DAG() + dag.add(0) + dag.add(1) + + def observer(phase, facts, error): + with lock: + events.append((phase, dict(facts), error, get_ident(), consumer_context.get())) + + def execute(batch): + assert consumer_context.get() == "plan" + token = consumer_context.set(batch) + try: + with action("model", "evaluate", batch_index=batch, interval=(batch, batch + 1)): + barrier.wait(timeout=5) + if batch == 1: + raise failure + finally: + consumer_context.reset(token) + + with observer_scope(observer): + errors, skipped = ConcurrentDAGExecutor( + dag, execute, 2, False, execution_context_factory() + ).run() + assert len(errors) == 1 and errors[0].__cause__ is failure + assert not skipped + assert len({event[3] for event in events}) == 2 + for batch in (0, 1): + batch_events = [event for event in events if event[1]["batch_index"] == batch] + assert [event[0] for event in batch_events] == ["start", "finish"] + assert all(event[4] == batch for event in batch_events) + assert batch_events[-1][2] is (failure if batch == 1 else None) + assert consumer_context.get() == "plan" + + +def test_read_only_identity_and_callback_reentry(): + events = [] + native = object() + + def observer(phase, facts, error): + events.append((phase, facts, error)) + with pytest.raises(TypeError): + facts["kind"] = "corrupt" + update_execution(corrupt=True) + with action("query", "observer-query"): + update_execution(corrupt=True) + + with observer_scope(observer), action("model", "evaluate", snapshot=native): + with action("query", "execute"): + update_execution(late=True) + update_execution(target="late table") + assert [event[0] for event in events] == ["start", "start", "finish", "finish"] + assert events[0][1] is events[-1][1] + assert events[1][1] is events[2][1] + assert events[-1][1]["snapshot"] is native + assert events[-1][1]["target"] == "late table" + assert "late" not in events[-1][1] + assert all("corrupt" not in event[1] for event in events) + + +def test_explicit_disabled_scope_isolates_parent_metadata(): + observer = Observer() + with observer_scope(observer), action("model", "evaluate"): + with observer_scope(None), action("query", "execute"): + update_execution(corrupt=True) + update_execution(target="parent") + assert len(observer.events) == 2 + assert observer.events[-1][1] == {"kind": "model", "action": "evaluate", "target": "parent"} + + +def test_console_scope_getter_failure_and_nested_reuse(): + from sqlmesh.core.execution_observation import console_observer_scope + from unittest.mock import Mock + + console = Mock() + console.get_execution_observer.side_effect = ValueError("getter failed") + with console_observer_scope(console), action("query", "execute") as facts: + assert facts is None + observer = Observer() + console.reset_mock(side_effect=True) + console.get_execution_observer.return_value = observer + with console_observer_scope(console): + with console_observer_scope(console), action("model", "evaluate"): + pass + console.get_execution_observer.assert_called_once_with() + assert len(observer.events) == 2 + console.reset_mock() + with observer_scope(None), console_observer_scope(console): + with action("query", "execute") as facts: + assert facts is None + console.get_execution_observer.assert_not_called() + + +def test_unobserved_context_factory_is_disabled(): + assert execution_context_factory() is None + with observer_scope(None): + assert execution_context_factory() is None + + +@pytest.mark.parametrize("phase", ["start", "finish"]) +def test_callback_base_exception_propagates_and_scope_is_restored(phase): + interrupt = KeyboardInterrupt() + events = [] + + def observer(event, facts, error): + events.append(event) + if event == phase: + raise interrupt + + with pytest.raises(KeyboardInterrupt) as raised: + with observer_scope(observer), action("query", "execute"): + pass + assert raised.value is interrupt + assert events == (["start"] if phase == "start" else ["start", "finish"]) + with action("query", "execute") as facts: + assert facts is None + observed = Observer() + with observer_scope(observed), action("model", "evaluate"): + update_execution(target="clean") + assert len(observed.events) == 2 + assert observed.events[-1][1]["target"] == "clean" + + +def test_disabled_and_observed_adapter_sql_and_side_effects_match(duck_conn, mocker): + from sqlmesh.core.engine_adapter import DuckDBEngineAdapter + + adapter = DuckDBEngineAdapter(lambda: duck_conn) + execute = mocker.spy(adapter, "_execute") + sql_log = mocker.spy(adapter, "_log_sql") + sql = "CREATE OR REPLACE TABLE observed_effect AS SELECT 42 AS value" + calls = [] + for observer in (None, Observer()): + execute.reset_mock() + sql_log.reset_mock() + with observer_scope(observer): + adapter.execute(sql) + calls.append((execute.call_args_list, sql_log.call_args_list)) + assert duck_conn.execute("SELECT value FROM observed_effect").fetchall() == [(42,)] + assert calls[0] == calls[1] + assert len(calls[0][0]) == 1 + + +def test_default_dag_does_not_capture_context(mocker): + from sqlmesh.utils.concurrency import ConcurrentDAGExecutor, concurrent_apply_to_dag + from sqlmesh.utils.dag import DAG + + copy = mocker.patch("contextvars.copy_context", side_effect=AssertionError("unexpected copy")) + dag = DAG() + dag.add("node") + for workers in (1, 2): + concurrent_apply_to_dag(dag, lambda _: None, workers) + executor = ConcurrentDAGExecutor(dag, lambda _: None, workers, False) + executor.run() + assert executor._context is None + copy.assert_not_called() + + +@pytest.mark.parametrize("workers", [1, 2]) +@pytest.mark.parametrize("registration", ["console", "explicit", "disabled", "broken"]) +def test_plan_and_scheduler_registration(mocker, make_snapshot, workers, registration): + from contextlib import nullcontext + from sqlglot import parse_one + from sqlmesh.core.console import TerminalConsole + from sqlmesh.core.environment import EnvironmentNamingInfo + from sqlmesh.core.model import SqlModel, FullKind + from sqlmesh.core.plan.evaluator import BuiltInPlanEvaluator + from sqlmesh.core.plan import stages + from sqlmesh.core.scheduler import Scheduler + from sqlmesh.core.snapshot import DeployabilityIndex, SnapshotChangeCategory + from sqlmesh.utils.date import to_timestamp + + snapshot = make_snapshot( + SqlModel(name="test.model", kind=FullKind(), query=parse_one("SELECT 1 AS a")) + ) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + console = TerminalConsole() + observer = Observer() + getter = mocker.patch.object(console, "get_execution_observer", return_value=observer) + if registration == "broken": + getter.side_effect = RuntimeError("getter failure") + native = mocker.MagicMock() + native.execution_tracker.get_execution_stats.return_value = None + native.get_snapshots_to_create.return_value = [] + native.set_correlation_id.return_value = native + scheduler = Scheduler( + [snapshot], native, mocker.MagicMock(), None, max_workers=workers, console=console + ) + workload = [] + consumer = ContextVar("plan_consumer", default=None) + + def evaluate(*args, **kwargs): + if registration in ("console", "explicit"): + assert consumer.get() == "stage" + with action("query", "execute"): + workload.append(True) + return [] + + mocker.patch.object(scheduler, "evaluate", side_effect=evaluate) + evaluator = BuiltInPlanEvaluator( + mocker.MagicMock(), native, mocker.Mock(), None, console=console + ) + stage = stages.BeforeAllStage(statements=[], all_snapshots=[]) + mocker.patch("sqlmesh.core.plan.evaluator.stages.build_plan_stages", return_value=[stage]) + mocker.patch("sqlmesh.core.plan.evaluator.analytics.collector") + + def run_scheduler(*args): + token = consumer.set("stage") + try: + errors, skipped = scheduler.run_merged_intervals( + merged_intervals={ + snapshot: [(to_timestamp("2024-01-01"), to_timestamp("2024-01-02"))] + }, + deployability_index=DeployabilityIndex.all_deployable(), + environment_naming_info=EnvironmentNamingInfo(), + ) + assert not errors and not skipped + finally: + consumer.reset(token) + + mocker.patch.object(evaluator, "visit_before_all_stage", side_effect=run_scheduler) + scope = ( + observer_scope(observer if registration == "explicit" else None) + if registration in ("explicit", "disabled") + else nullcontext() + ) + with scope: + evaluator.evaluate(mocker.Mock(plan_id="observed-plan")) + assert workload == [True] + assert getter.call_count == (1 if registration in ("console", "broken") else 0) + if registration in ("console", "explicit"): + assert [(phase, facts["kind"]) for phase, facts, _ in observer.events] == [ + ("start", "stage"), + ("start", "model"), + ("start", "query"), + ("finish", "query"), + ("finish", "model"), + ("finish", "stage"), + ] + else: + assert observer.events == [] + + +@pytest.mark.parametrize("registration", ["console", "disabled"]) +def test_standalone_scheduler_observes_environment_statement_queries( + duck_conn, mocker, registration +): + from contextlib import nullcontext + + from sqlmesh.core.engine_adapter import DuckDBEngineAdapter + from sqlmesh.core.environment import EnvironmentNamingInfo, EnvironmentStatements + from sqlmesh.core.scheduler import Scheduler + from sqlmesh.core.snapshot import DeployabilityIndex, SnapshotEvaluator + + observer = Observer() + console = mocker.MagicMock() + getter = mocker.patch.object(console, "get_execution_observer", return_value=observer) + state_sync = mocker.MagicMock() + state_sync.get_environment_statements.return_value = [ + EnvironmentStatements( + before_all=["CREATE TABLE observed_environment (stage VARCHAR)"], + after_all=["INSERT INTO observed_environment VALUES ('after')"], + python_env={}, + ) + ] + scheduler = Scheduler( + snapshots=[], + snapshot_evaluator=SnapshotEvaluator(DuckDBEngineAdapter(lambda: duck_conn)), + state_sync=state_sync, + default_catalog=None, + console=console, + ) + + scope = observer_scope(None) if registration == "disabled" else nullcontext() + with scope: + errors, skipped = scheduler.run_merged_intervals( + merged_intervals={}, + deployability_index=DeployabilityIndex.all_deployable(), + environment_naming_info=EnvironmentNamingInfo(name="observed"), + run_environment_statements=True, + ) + + assert not errors and not skipped + assert duck_conn.execute("SELECT stage FROM observed_environment").fetchall() == [("after",)] + if registration == "console": + assert [(phase, facts["kind"], facts["action"]) for phase, facts, _ in observer.events] == [ + ("start", "query", "execute"), + ("finish", "query", "execute"), + ("start", "query", "execute"), + ("finish", "query", "execute"), + ] + assert all(error is None for phase, _, error in observer.events if phase == "finish") + getter.assert_called_once_with() + else: + assert observer.events == [] + getter.assert_not_called() + + +@pytest.mark.parametrize("failing_stage", ["before_all", "after_all"]) +def test_standalone_scheduler_restores_observer_scope_after_environment_query_error( + duck_conn, mocker, failing_stage +): + from sqlmesh.core.engine_adapter import DuckDBEngineAdapter + from sqlmesh.core.environment import EnvironmentNamingInfo, EnvironmentStatements + from sqlmesh.core.scheduler import Scheduler + from sqlmesh.core.snapshot import DeployabilityIndex, SnapshotEvaluator + from sqlmesh.utils.errors import SQLMeshError + + observer = Observer() + console = mocker.MagicMock() + getter = mocker.patch.object(console, "get_execution_observer", return_value=observer) + state_sync = mocker.MagicMock() + state_sync.get_environment_statements.return_value = [ + EnvironmentStatements( + before_all=( + ["SELECT * FROM missing_before_all"] + if failing_stage == "before_all" + else ["SELECT 1"] + ), + after_all=(["SELECT * FROM missing_after_all"] if failing_stage == "after_all" else []), + python_env={}, + ) + ] + scheduler = Scheduler( + snapshots=[], + snapshot_evaluator=SnapshotEvaluator(DuckDBEngineAdapter(lambda: duck_conn)), + state_sync=state_sync, + default_catalog=None, + console=console, + ) + + with pytest.raises(SQLMeshError): + scheduler.run_merged_intervals( + merged_intervals={}, + deployability_index=DeployabilityIndex.all_deployable(), + environment_naming_info=EnvironmentNamingInfo(name="observed"), + run_environment_statements=True, + ) + + query_events = [event for event in observer.events if event[1]["kind"] == "query"] + assert len(query_events) == (2 if failing_stage == "before_all" else 4) + assert query_events[-1][0] == "finish" + assert query_events[-1][2] is not None + getter.assert_called_once_with() + state_sync.recycle.assert_not_called() + + with action("query", "outside") as facts: + assert facts is None 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)"] 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"' 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..0955af331d 100644 --- a/tests/core/test_snapshot_evaluator.py +++ b/tests/core/test_snapshot_evaluator.py @@ -28,6 +28,7 @@ from sqlmesh.core.environment import EnvironmentNamingInfo from sqlmesh.core.macros import RuntimeStage, macro, MacroEvaluator, MacroFunc from sqlmesh.core.model import ( + AuditResult, Model, FullKind, IncrementalByTimeRangeKind, @@ -247,6 +248,122 @@ def x(evaluator, y=None) -> None: ) +def test_evaluate_reports_materialization_through_transaction_exit( + duck_conn, mocker: MockerFixture, make_snapshot +): + from sqlmesh.core.engine_adapter import DuckDBEngineAdapter + from sqlmesh.core.execution_observation import observer_scope + + model = SqlModel( + name="test_schema.test_model", + kind=FullKind(), + query=parse_one("SELECT 1 AS value"), + ) + snapshot = make_snapshot(model) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + duck_conn.execute("CREATE SCHEMA sqlmesh__test_schema") + evaluator = SnapshotEvaluator(DuckDBEngineAdapter(lambda: duck_conn)) + observations: t.List[t.Tuple[str, t.Dict[str, t.Any], t.Optional[BaseException]]] = [] + materialize_active = False + + def observer(phase, facts, error): + nonlocal materialize_active + observations.append((phase, dict(facts), error)) + if facts["action"] == "materialize": + materialize_active = phase == "start" + + target = snapshot.table_name() + transaction_failure = RuntimeError("transaction exit failed") + transaction_depth = 0 + transaction = evaluator.adapter.transaction + + @contextlib.contextmanager + def fail_outer_transaction(*args: t.Any, **kwargs: t.Any) -> t.Iterator[None]: + nonlocal transaction_depth + outermost = transaction_depth == 0 + fail_on_exit = outermost and materialize_active + transaction_depth += 1 + try: + with transaction(*args, **kwargs): + yield + if fail_on_exit: + raise transaction_failure + finally: + transaction_depth -= 1 + + mocker.patch.object(evaluator.adapter, "transaction", new=fail_outer_transaction) + with observer_scope(observer), pytest.raises(RuntimeError) as raised: + evaluator.evaluate( + snapshot, + start="2020-01-01", + end="2020-01-02", + execution_time="2020-01-02", + snapshots={}, + target_table_exists=False, + ) + + assert raised.value is transaction_failure + assert evaluator.adapter.table_exists(target) + materialize_events = [event for event in observations if event[1]["action"] == "materialize"] + assert [phase for phase, _, _ in materialize_events] == ["start", "finish"] + assert all(facts["kind"] == "physical" for _, facts, _ in materialize_events) + assert all(facts["target"] == target for _, facts, _ in materialize_events) + assert all(facts["creating"] is True for _, facts, _ in materialize_events) + assert materialize_events[0][2] is None + assert materialize_events[1][2] is transaction_failure + + +@pytest.mark.parametrize("workers", [1, 2]) +def test_create_physical_schemas_preserves_observation_context(duck_conn, make_snapshot, workers): + from contextvars import ContextVar + + from sqlmesh.core.engine_adapter import DuckDBEngineAdapter + from sqlmesh.core.execution_observation import observer_scope + + snapshots = [] + for index in ("one", "two"): + snapshot = make_snapshot( + SqlModel( + name=f"schema_{index}.model", + kind=FullKind(), + query=parse_one("SELECT 1 AS value"), + ) + ) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + snapshots.append(snapshot) + evaluator = SnapshotEvaluator( + DuckDBEngineAdapter(lambda: duck_conn), ddl_concurrent_tasks=workers + ) + consumer = ContextVar("schema_consumer", default=None) + observed = [] + + def observer(phase, facts, error): + observed.append((phase, dict(facts), error, consumer.get())) + + token = consumer.set("parent") + try: + with observer_scope(observer): + evaluator.create_physical_schemas(snapshots, DeployabilityIndex.all_deployable()) + finally: + consumer.reset(token) + + query_events = [event for event in observed if event[1]["kind"] == "query"] + assert len(query_events) == 4 + assert sum(phase == "start" for phase, _, _, _ in query_events) == 2 + assert sum(phase == "finish" for phase, _, _, _ in query_events) == 2 + assert all(facts["action"] == "execute" for _, facts, _, _ in query_events) + assert all(context == "parent" for _, _, _, context in query_events) + assert all(error is None for phase, _, error, _ in query_events if phase == "finish") + + created_schemas = { + row[0] + for row in duck_conn.execute( + "SELECT schema_name FROM information_schema.schemata" + ).fetchall() + } + assert {"sqlmesh__schema_one", "sqlmesh__schema_two"} <= created_schemas + + def test_runtime_stages(capsys, mocker, adapter_mock, make_snapshot): evaluator = SnapshotEvaluator(adapter_mock) @@ -3285,6 +3402,26 @@ def test_standalone_audit(mocker: MockerFixture, adapter_mock, make_snapshot): adapter_mock.session.assert_not_called() +def _audit_observed( + evaluator: SnapshotEvaluator, + snapshot: Snapshot, + *, + observe_result: t.Callable[[AuditResult], None], + **kwargs: t.Any, +) -> t.List[AuditResult]: + """Exercise the generic hook at the real per-audit evaluator boundary.""" + from sqlmesh.core.execution_observation import observer_scope + + def observer( + phase: str, facts: t.Mapping[str, t.Any], error: t.Optional[BaseException] + ) -> None: + if phase == "finish" and facts["kind"] == "audit" and "audit_result" in facts: + observe_result(facts["audit_result"]) + + with observer_scope(observer): + return evaluator.audit(snapshot, **kwargs) + + def test_audit_wap(adapter_mock: Mock, make_snapshot: t.Callable[..., Snapshot]) -> None: evaluator = SnapshotEvaluator(adapter_mock) @@ -3310,8 +3447,15 @@ def test_audit_wap(adapter_mock: Mock, make_snapshot: t.Callable[..., Snapshot]) expected_table_name = f"spark_catalog.test_schema.test_table.branch_wap_{wap_id}" adapter_mock.wap_table_name.return_value = expected_table_name adapter_mock.fetchone.return_value = (0,) + observed_results: t.List[AuditResult] = [] - evaluator.audit(snapshot, snapshots={}, wap_id=wap_id) + _audit_observed( + evaluator, + snapshot, + snapshots={}, + wap_id=wap_id, + observe_result=observed_results.append, + ) call_args = adapter_mock.fetchone.call_args_list assert len(call_args) == 2 @@ -3330,6 +3474,123 @@ def test_audit_wap(adapter_mock: Mock, make_snapshot: t.Callable[..., Snapshot]) adapter_mock.wap_table_name.assert_called_once_with(snapshot.table_name(), wap_id) adapter_mock.wap_publish.assert_called_once_with(snapshot.table_name(), wap_id) + assert [result.audit.name for result in observed_results] == ["not_null", "test_audit"] + + +def test_audit_observer_preserves_completed_results_when_a_later_audit_fails( + adapter_mock: Mock, make_snapshot: t.Callable[..., Snapshot] +) -> None: + evaluator = SnapshotEvaluator(adapter_mock) + model = SqlModel( + name="test_schema.test_table", + kind=FullKind(), + query=parse_one("SELECT a::int FROM tbl"), + audits=[ + ("not_null", {"columns": exp.to_column("a")}), + ("unique_values", {"columns": exp.convert(["a"])}), + ], + ) + snapshot = make_snapshot(model) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + observed_results: t.List[AuditResult] = [] + fetch_count = 0 + + def fetch_audit_result(*args: t.Any, **kwargs: t.Any) -> t.Tuple[int]: + nonlocal fetch_count + fetch_count += 1 + if fetch_count == 2: + assert [result.audit.name for result in observed_results] == ["not_null"] + raise RuntimeError("second audit failed") + return (0,) + + adapter_mock.fetchone.side_effect = fetch_audit_result + + with pytest.raises(RuntimeError, match="second audit failed"): + _audit_observed( + evaluator, + snapshot, + snapshots={}, + observe_result=observed_results.append, + ) + + assert [result.audit.name for result in observed_results] == ["not_null"] + + +def test_audit_observer_failure_does_not_abort_remaining_audits( + adapter_mock: Mock, make_snapshot: t.Callable[..., Snapshot] +) -> None: + evaluator = SnapshotEvaluator(adapter_mock) + model = SqlModel( + name="test_schema.test_table", + kind=FullKind(), + query=parse_one("SELECT a::int, b::int FROM tbl"), + audits=[ + ("not_null", {"columns": exp.to_column("a")}), + ("not_null", {"columns": exp.to_column("b")}), + ], + ) + snapshot = make_snapshot(model) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + adapter_mock.fetchone.return_value = (0,) + + def fail_observer(_result: AuditResult) -> None: + raise RuntimeError("observer unavailable") + + results = _audit_observed( + evaluator, + snapshot, + snapshots={}, + observe_result=fail_observer, + ) + + assert len(results) == adapter_mock.fetchone.call_count == 2 + + +def test_audit_observer_reports_failed_skipped_and_repeated_results_once_in_order( + adapter_mock: Mock, make_snapshot: t.Callable[..., Snapshot] +) -> None: + evaluator = SnapshotEvaluator(adapter_mock) + skipped_audit = ModelAudit( + name="skipped_audit", + query="SELECT * FROM test_schema.test_table", + skip=True, + ) + model = SqlModel( + name="test_schema.test_table", + kind=FullKind(), + query=parse_one("SELECT a::int, b::int FROM tbl"), + audits=[ + ("not_null", {"columns": exp.to_column("a")}), + ("skipped_audit", {}), + ("not_null", {"columns": exp.to_column("b")}), + ], + audit_definitions={skipped_audit.name: skipped_audit}, + ) + snapshot = make_snapshot(model) + snapshot.categorize_as(SnapshotChangeCategory.BREAKING) + adapter_mock.fetchone.side_effect = [(2,), (0,)] + observed_results: t.List[AuditResult] = [] + + returned_results = _audit_observed( + evaluator, + snapshot, + snapshots={}, + observe_result=observed_results.append, + ) + + assert observed_results == returned_results + assert [result.audit.name for result in observed_results] == [ + "not_null", + "skipped_audit", + "not_null", + ] + assert [result.count for result in observed_results] == [2, None, 0] + assert [result.skipped for result in observed_results] == [False, True, False] + assert [observed_results[index].audit_args["columns"].sql() for index in (0, 2)] == [ + "a", + "b", + ] + assert adapter_mock.fetchone.call_count == 2 def test_audit_with_datetime_macros(adapter_mock, make_snapshot): @@ -4810,9 +5071,15 @@ def test_multiple_engine_virtual_layer(snapshot: Snapshot, adapters, make_snapsh ) +@pytest.mark.parametrize("observer_enabled", [False, True]) def test_wap_basic( - adapter_mock: Mock, make_snapshot: t.Callable[..., Snapshot], mocker: MockerFixture + adapter_mock: Mock, + make_snapshot: t.Callable[..., Snapshot], + mocker: MockerFixture, + observer_enabled: bool, ) -> None: + from sqlmesh.core.execution_observation import observer_scope + evaluator = SnapshotEvaluator(adapter_mock) model = SqlModel( @@ -4828,19 +5095,25 @@ def test_wap_basic( expected_wap_table = "test_schema.test_table.branch_wap_12345678" adapter_mock.wap_prepare.return_value = expected_wap_table - wap_id = evaluator.evaluate( - snapshot, - start="2020-01-01", - end="2020-01-01", - execution_time="2020-01-01", - snapshots={}, - target_table_exists=True, # Use parameter to control table existence - ) + observations = [] + + def observer(phase, facts, error): + observations.append((phase, dict(facts), error)) + + expected_table_name = snapshot.table_name() + with observer_scope(observer if observer_enabled else None): + wap_id = evaluator.evaluate( + snapshot, + start="2020-01-01", + end="2020-01-01", + execution_time="2020-01-01", + snapshots={}, + target_table_exists=True, # Use parameter to control table existence + ) assert wap_id is not None assert len(wap_id) == 8 - expected_table_name = snapshot.table_name() adapter_mock.wap_prepare.assert_called_once_with(expected_table_name, wap_id) adapter_mock.replace_query.assert_called_once_with( expected_wap_table, @@ -4857,6 +5130,21 @@ def test_wap_basic( source_columns=mocker.ANY, ) + materialization_observations = [ + (phase, facts, error) + for phase, facts, error in observations + if facts.get("kind") == "physical" and facts.get("action") == "materialize" + ] + if observer_enabled: + assert [ + (phase, facts["target"], error) for phase, facts, error in materialization_observations + ] == [ + ("start", expected_table_name, None), + ("finish", expected_table_name, None), + ] + else: + assert observations == [] + def test_wap_model_wap_supported( adapter_mock: Mock, make_snapshot: t.Callable[..., Snapshot], mocker: MockerFixture @@ -5052,12 +5340,24 @@ def test_wap_publish_failure(adapter_mock: Mock, make_snapshot: t.Callable[..., adapter_mock.wap_table_name.return_value = expected_wap_table_name adapter_mock.fetchone.return_value = (0,) - # Mock WAP publish to raise an exception - adapter_mock.wap_publish.side_effect = Exception("WAP publish failed") + observed_results: t.List[AuditResult] = [] + + def fail_wap_publish(*args: t.Any, **kwargs: t.Any) -> None: + assert [result.audit.name for result in observed_results] == ["not_null"] + raise RuntimeError("WAP publish failed") + + adapter_mock.wap_publish.side_effect = fail_wap_publish + + with pytest.raises(RuntimeError, match="WAP publish failed"): + _audit_observed( + evaluator, + snapshot, + snapshots={}, + wap_id=wap_id, + observe_result=observed_results.append, + ) - # Execute audit with WAP ID and expect it to raise the exception - with pytest.raises(Exception, match="WAP publish failed"): - evaluator.audit(snapshot, snapshots={}, wap_id=wap_id) + assert [result.audit.name for result in observed_results] == ["not_null"] def test_properties_are_preserved_in_both_create_statements( @@ -5656,3 +5956,160 @@ 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 + + +@pytest.mark.parametrize("workers", [1, 2]) +@pytest.mark.parametrize("operation", ["create", "promote", "demote", "migrate"]) +def test_observation_propagates_through_snapshot_dispatch( + mocker, adapter_mock, snapshot, workers, operation +): + from contextvars import ContextVar + from sqlmesh.core.execution_observation import observer_scope + + evaluator = SnapshotEvaluator(adapter_mock, ddl_concurrent_tasks=workers) + consumer = ContextVar("snapshot_dispatch_consumer", default=None) + events = [] + + def observer(phase, facts, error): + assert consumer.get() == "admission" + assert facts["snapshot"] is snapshot + events.append((phase, facts["action"], error)) + + naming = EnvironmentNamingInfo(name="test") + mocker.patch.object(evaluator, "_get_virtual_data_objects", return_value={}) + mocker.patch.object( + evaluator, "_get_physical_data_objects", return_value={snapshot.snapshot_id: mocker.Mock()} + ) + mocker.patch.object(evaluator, "_create_schemas") + token = consumer.set("admission") + try: + with observer_scope(observer): + if operation == "create": + evaluator._create_snapshots( + [snapshot], + {snapshot.name: snapshot}, + DeployabilityIndex.all_deployable(), + None, + set(), + set(), + ) + elif operation == "promote": + evaluator.promote([snapshot], naming) + elif operation == "demote": + evaluator.demote([snapshot], naming) + else: + evaluator.migrate([snapshot], {snapshot.snapshot_id: snapshot}) + finally: + consumer.reset(token) + action = "schema_migration" if operation == "migrate" else operation + assert events == [("start", action, None), ("finish", action, None)] diff --git a/tests/core/test_test.py b/tests/core/test_test.py index 7c67192a14..9be1237b58 100644 --- a/tests/core/test_test.py +++ b/tests/core/test_test.py @@ -1,8 +1,10 @@ from __future__ import annotations import datetime +import re import typing as t import io +import threading from pathlib import Path import unittest from unittest.mock import call, patch @@ -1360,6 +1362,68 @@ def test_nested_data_types(sushi_context: Context) -> None: ) +def test_freeze_time_does_not_patch_shared_generator() -> None: + from sqlglot.dialects.dialect import Dialect + from sqlglot.generator import _DISPATCH_CACHE + + duckdb = Dialect.get_or_raise("duckdb") + exp.select("1").sql("duckdb") # make sure the shared dispatch table exists + shared_transforms = dict(duckdb.generator_class.TRANSFORMS) + shared_dispatch = dict(_DISPATCH_CACHE[duckdb.generator_class]) + + test = _create_test( + body=load_yaml( + """ +test_foo: + model: xyz + outputs: + query: + - cur_date: 2023-01-01 + vars: + execution_time: "2023-01-01 12:05:03+00:00" + """ + ), + test_name="test_foo", + model=_create_model("SELECT CURRENT_DATE AS cur_date"), + context=Context(config=Config(model_defaults=ModelDefaultsConfig(dialect="duckdb"))), + ) + test.concurrency = True + + rendered: t.List[str] = [] + errors: t.List[BaseException] = [] + + def render_ddl_through_shared_dialect() -> None: + # Mimics another test creating its fixture views while this test's frozen render + # context is active; both go through the dialect's shared generator class. + try: + for _ in range(200): + rendered.append( + exp.Create( + this=exp.to_table("s.v"), kind="VIEW", expression=exp.select("1") + ).sql("duckdb") + ) + rendered.append(exp.CurrentDate().sql("duckdb")) + except BaseException as e: # pragma: no cover + errors.append(e) + + with test._concurrent_render_context(): + other = threading.Thread(target=render_ddl_through_shared_dialect) + other.start() + other.join() + + # this test renders the frozen time... + assert test._generate_sql(exp.CurrentDate()) == "CAST('2023-01-01 12:05:03+00:00' AS DATE)" + # ...while the shared dialect is untouched, even inside the frozen context + assert exp.CurrentDate().sql("duckdb") == "CURRENT_DATE" + + assert not errors + assert set(rendered) == {"CREATE VIEW s.v AS SELECT 1", "CURRENT_DATE"} + assert duckdb.generator_class.TRANSFORMS == shared_transforms + assert _DISPATCH_CACHE[duckdb.generator_class] == shared_dispatch + + _check_successful_or_raise(test.run()) + + def test_freeze_time(mocker: MockerFixture) -> None: mocker.patch("sqlmesh.core.test.definition.random_id", return_value="jzngz56a") test = _create_test( @@ -2687,6 +2751,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() diff --git a/tests/dbt/test_transformation.py b/tests/dbt/test_transformation.py index fe6073dfad..32249cbef3 100644 --- a/tests/dbt/test_transformation.py +++ b/tests/dbt/test_transformation.py @@ -1792,6 +1792,12 @@ def test_yaml(sushi_test_project: Project): assert context.render("{{ toyaml(invalid) }}", invalid=lambda: "") == "None" assert context.render("""{{ fromyaml('key: value') }}""") == "{'key': 'value'}" + assert context.render("""{{ fromyaml('[1, 2]') }}""") == "[1, 2]" + assert ( + context.render("{% set my_yaml %}\n- good\n- bad\n{% endset %}{{ fromyaml(my_yaml) }}") + == "['good', 'bad']" + ) + assert context.render("""{{ fromyaml('42') }}""") == "42" @pytest.mark.xdist_group("dbt_manifest") diff --git a/tests/integrations/github/cicd/test_github_controller.py b/tests/integrations/github/cicd/test_github_controller.py index dbb09f4336..66c5999850 100644 --- a/tests/integrations/github/cicd/test_github_controller.py +++ b/tests/integrations/github/cicd/test_github_controller.py @@ -12,7 +12,9 @@ from sqlmesh.core import constants as c from sqlmesh.core.config import CategorizerConfig from sqlmesh.core.dialect import parse_one +from sqlmesh.core.environment import EnvironmentNamingInfo, EnvironmentStatements from sqlmesh.core.model import SqlModel +from sqlmesh.core.snapshot import SnapshotChangeCategory from sqlmesh.core.user import User, UserRole from sqlmesh.core.plan.definition import Plan from sqlmesh.core.linter.rule import RuleViolation @@ -800,6 +802,60 @@ def test_get_plan_summary_includes_warnings_and_errors( ) in summary +def test_get_plan_summary_preserves_literal_sql( + github_client, make_controller, make_snapshot, mocker +): + controller = make_controller( + "tests/fixtures/github/pull_request_synchronized.json", github_client + ) + context_diff = controller.prod_plan.context_diff + old, new = [ + make_snapshot( + SqlModel( + name="test.model", + dialect="tsql", + query=parse_one(f"SELECT [{column}] FROM [schema].[table]", dialect="tsql"), + ) + ) + for column in ("old_col", "new_col") + ] + new.categorize_as(SnapshotChangeCategory.NON_BREAKING) + context_diff.is_new_environment = False + context_diff.added = set() + context_diff.snapshots = {new.snapshot_id: new} + context_diff.modified_snapshots = {new.name: (new, old)} + context_diff.environment_statements = [ + EnvironmentStatements( + before_all=["SELECT [before] FROM [schema].[table]"], + after_all=["SELECT ':smile: [/invalid] ```' AS [after]"], + python_env={}, + ) + ] + plan = mocker.Mock( + spec=Plan, + context_diff=context_diff, + restatements={}, + missing_intervals=[], + user_provided_flags={}, + environment_naming_info=EnvironmentNamingInfo(), + ) + controller._console.log_success("stale output") + github_client.reset_mock() + + summary = controller.get_plan_summary(plan) + + diff = context_diff.text_diff(new.name) + assert ( + " ```diff\n" + "\n".join(f" {line}" for line in diff.split("\n")) + "\n ```\n" in summary + ) + for _, diff in context_diff.environment_statements_diff(): + fence = "````" if "```" in diff else "```" + assert f"{fence}diff\n{diff}\n{fence}\n" in summary + assert "stale output" not in summary + assert controller._console.consume_captured_output() == "" + assert not github_client.mock_calls + + def test_get_pr_environment_summary_includes_warnings_and_errors( github_client, make_controller: t.Callable[..., GithubController] ): 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 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): diff --git a/tests/utils/test_cache.py b/tests/utils/test_cache.py index aa11b6c846..cddee0d2ce 100644 --- a/tests/utils/test_cache.py +++ b/tests/utils/test_cache.py @@ -78,6 +78,29 @@ def test_optimized_query_cache(tmp_path: Path, mocker: MockerFixture): assert model._query_renderer._optimized_cache is not None +def test_optimized_query_cache_reuses_decoded_entry(tmp_path: Path, mocker: MockerFixture): + model = SqlModel( + name="test_model", + query=parse_one("SELECT a FROM tbl"), + mapping_schema={"tbl": {"a": "int"}}, + ) + cache = OptimizedQueryCache(tmp_path) + assert not cache.with_optimized_query(model) + + get_mock = mocker.spy(cache._file_cache, "get") + cache_entry = cache.get_or_create_entry(model) + assert cache_entry is not None + assert get_mock.call_count == 1 + + model._query_renderer._cache = [] + model._query_renderer._optimized_cache = None + cache.with_optimized_query_entry(model, cache_entry) + + # Applying the entry in the parent process must not read and decompress it again. + assert get_mock.call_count == 1 + assert model._query_renderer._optimized_cache is not None + + def test_optimized_query_cache_missing_rendered_query(tmp_path: Path, mocker: MockerFixture): model = SqlModel( name="test_model", diff --git a/tests/utils/test_concurrency.py b/tests/utils/test_concurrency.py index 5e1e4326f7..0d45a375f1 100644 --- a/tests/utils/test_concurrency.py +++ b/tests/utils/test_concurrency.py @@ -1,3 +1,10 @@ +import os +import subprocess +import sys +import textwrap +from contextvars import ContextVar, copy_context +from pathlib import Path + import pytest from pytest_mock.plugin import MockerFixture @@ -147,3 +154,338 @@ 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"} + """ + ) + + +@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 + + +@pytest.mark.parametrize("phase", ["start", "finish"]) +def test_concurrent_dag_propagates_observer_base_exception_and_can_be_reused(phase: str): + _run_bounded_python( + f""" + from threading import Event, Thread + + from sqlmesh.core.execution_observation import action, observer_scope + 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 = [] + failing_phase = {phase!r} + + def observe(current_phase, facts, callback_error): + if current_phase == failing_phase: + raise error + + def execute(node): + if node == "cancel": + assert sibling_started.wait(timeout=3) + with observer_scope(observe), action("query", "execute"): + pass + if node == "sibling": + sibling_started.set() + assert release_sibling.wait(timeout=6) + called.append(node) + + executor = ConcurrentDAGExecutor(dag, execute, 2, True) + run_errors = [] + + def run(): + try: + executor.run() + except BaseException as ex: + run_errors.append(ex) + + runner = Thread(target=run) + runner.start() + assert sibling_started.wait(timeout=3) + try: + try: + executor._finished_future.result(timeout=3) + except KeyboardInterrupt as raised: + assert raised is error + else: + raise AssertionError("the worker cancellation was not propagated") + finally: + release_sibling.set() + + runner.join(timeout=3) + assert not runner.is_alive() + assert run_errors == [error] + assert "dependent" not in called + + 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") + """ + ) diff --git a/tests/utils/test_databricks.py b/tests/utils/test_databricks.py new file mode 100644 index 0000000000..b0bd6a9eb7 --- /dev/null +++ b/tests/utils/test_databricks.py @@ -0,0 +1,265 @@ +import time +import typing as t +from concurrent.futures import ThreadPoolExecutor +from threading import Lock +from unittest.mock import patch + +import pytest + +from sqlmesh.utils import databricks +from sqlmesh.utils.databricks import ( + SharedU2MCredentialsProvider, + get_shared_u2m_credentials_provider, +) + +pytest.importorskip("databricks.sql") + + +@pytest.fixture(autouse=True) +def clear_shared_providers(): + databricks._shared_u2m_credentials_providers.clear() + yield + databricks._shared_u2m_credentials_providers.clear() + + +class FakeAuthProvider: + """Records how many threads are reading headers at the same time.""" + + def __init__(self) -> None: + self.active_readers = 0 + self.max_active_readers = 0 + self._counter_lock = Lock() + + def add_headers(self, request_headers: t.Dict[str, str]) -> None: + with self._counter_lock: + self.active_readers += 1 + self.max_active_readers = max(self.max_active_readers, self.active_readers) + # Give other threads a chance to enter if reads are not serialized + time.sleep(0.01) + request_headers["Authorization"] = "Bearer token" + with self._counter_lock: + self.active_readers -= 1 + + +def test_browser_flow_runs_once_across_threads(): + provider = SharedU2MCredentialsProvider("dbc-test.cloud.databricks.com", "databricks-oauth") + fake_auth_provider = FakeAuthProvider() + flow_count = 0 + + def slow_browser_flow() -> FakeAuthProvider: + nonlocal flow_count + flow_count += 1 + time.sleep(0.1) + return fake_auth_provider + + with patch.object(provider, "_create_auth_provider", side_effect=slow_browser_flow): + with ThreadPoolExecutor(max_workers=8) as executor: + header_factories = list(executor.map(lambda _: provider(), range(8))) + + assert flow_count == 1 + assert all(factory() == {"Authorization": "Bearer token"} for factory in header_factories) + + +def test_header_reads_are_serialized(): + provider = SharedU2MCredentialsProvider("dbc-test.cloud.databricks.com", "databricks-oauth") + fake_auth_provider = FakeAuthProvider() + + with patch.object(provider, "_create_auth_provider", return_value=fake_auth_provider): + header_factory = provider() + + with ThreadPoolExecutor(max_workers=8) as executor: + list(executor.map(lambda _: header_factory(), range(32))) + + # Only one thread may read (and so possibly refresh) the token at a time, since refresh tokens can be single-use + assert fake_auth_provider.max_active_readers == 1 + + +def test_failed_browser_flow_is_retried(): + provider = SharedU2MCredentialsProvider("dbc-test.cloud.databricks.com", "databricks-oauth") + fake_auth_provider = FakeAuthProvider() + + with patch.object( + provider, + "_create_auth_provider", + side_effect=[RuntimeError("login cancelled"), fake_auth_provider], + ): + with pytest.raises(RuntimeError, match="login cancelled"): + provider() + assert provider()() == {"Authorization": "Bearer token"} + + +def test_threads_waiting_on_a_failed_login_do_not_retry_it(): + provider = SharedU2MCredentialsProvider("dbc-test.cloud.databricks.com", "databricks-oauth") + fake_auth_provider = FakeAuthProvider() + flow_count = 0 + + def failing_browser_flow() -> FakeAuthProvider: + nonlocal flow_count + flow_count += 1 + time.sleep(0.1) + raise RuntimeError("login cancelled") + + def call_provider(_: int) -> t.Optional[Exception]: + try: + provider() + except Exception as e: + return e + return None + + with patch.object(provider, "_create_auth_provider", side_effect=failing_browser_flow): + with ThreadPoolExecutor(max_workers=8) as executor: + errors = list(executor.map(call_provider, range(8))) + + # Every waiting thread gets the error from the one browser flow instead of opening its own + assert flow_count == 1 + assert all(isinstance(error, RuntimeError) for error in errors) + + # A later caller still gets to try again + with patch.object(provider, "_create_auth_provider", return_value=fake_auth_provider): + assert provider()() == {"Authorization": "Bearer token"} + + +def test_failed_token_read_discards_login(): + provider = SharedU2MCredentialsProvider("dbc-test.cloud.databricks.com", "databricks-oauth") + fake_auth_provider = FakeAuthProvider() + + class RevokedAuthProvider: + def add_headers(self, request_headers: t.Dict[str, str]) -> None: + raise RuntimeError("refresh token revoked") + + with patch.object( + provider, + "_create_auth_provider", + side_effect=[RevokedAuthProvider(), fake_auth_provider], + ) as mock_create_auth_provider: + header_factory = provider() + with pytest.raises(RuntimeError, match="refresh token revoked"): + header_factory() + + # Both existing connections and new ones log in again instead of failing for the rest of the process + assert header_factory() == {"Authorization": "Bearer token"} + assert provider()() == {"Authorization": "Bearer token"} + + assert mock_create_auth_provider.call_count == 2 + + +def test_network_failure_during_token_read_keeps_login(): + from databricks.sql.exc import RequestError + + provider = SharedU2MCredentialsProvider("dbc-test.cloud.databricks.com", "databricks-oauth") + fake_auth_provider = FakeAuthProvider() + refresh_attempts = 0 + + class FlakyAuthProvider: + def add_headers(self, request_headers: t.Dict[str, str]) -> None: + nonlocal refresh_attempts + refresh_attempts += 1 + if refresh_attempts == 1: + raise RequestError("HTTP request failed: connection reset") + fake_auth_provider.add_headers(request_headers) + + with patch.object( + provider, "_create_auth_provider", return_value=FlakyAuthProvider() + ) as mock_create_auth_provider: + header_factory = provider() + with pytest.raises(RequestError): + header_factory() + + # The refresh is retried on the next request without another browser flow + assert header_factory() == {"Authorization": "Bearer token"} + + assert mock_create_auth_provider.call_count == 1 + + +def test_get_shared_u2m_credentials_provider(): + provider = get_shared_u2m_credentials_provider( + "dbc-test.cloud.databricks.com", "databricks-oauth" + ) + assert provider.auth_type() == "databricks-oauth" + assert ( + get_shared_u2m_credentials_provider("dbc-test.cloud.databricks.com", "databricks-oauth") + is provider + ) + assert ( + get_shared_u2m_credentials_provider("dbc-other.cloud.databricks.com", "databricks-oauth") + is not provider + ) + assert ( + get_shared_u2m_credentials_provider("dbc-test.cloud.databricks.com", "azure-oauth") + is not provider + ) + + # The same workspace written with a scheme, trailing slash, or different case shares the login + for hostname in ( + "https://dbc-test.cloud.databricks.com", + "dbc-test.cloud.databricks.com/", + "HTTPS://DBC-TEST.cloud.databricks.com/", + ): + assert get_shared_u2m_credentials_provider(hostname, "databricks-oauth") is provider + + +def test_uses_connector_oauth_provider(): + """Runs the real connector auth provider with only the browser flow mocked out. + + The provider relies on connector internals, so this fails if a connector upgrade changes them. + """ + import jwt + + server_hostname = "dbc-test.cloud.databricks.com" + access_token = jwt.encode( + {"exp": int(time.time()) + 3600, "iss": f"https://{server_hostname}/oidc"}, + "a-signing-key-that-is-at-least-32-bytes", + algorithm="HS256", + ) + provider = SharedU2MCredentialsProvider(server_hostname, "databricks-oauth") + + with patch( + "databricks.sql.auth.oauth.OAuthManager.get_tokens", + return_value=(access_token, "refresh-token"), + ) as mock_get_tokens: + header_factory = provider() + provider() + + mock_get_tokens.assert_called_once() + assert mock_get_tokens.call_args.kwargs["hostname"] == f"https://{server_hostname}/" + assert header_factory() == {"Authorization": f"Bearer {access_token}"} + + +def test_connector_prefers_shared_credentials_provider(): + """Builds per-connection auth providers the way `databricks.sql.connect()` does, passing both `auth_type` and + the shared `credentials_provider`, and checks the connector uses the shared login rather than its own.""" + import jwt + from databricks.sql import __version__ + from databricks.sql.auth.auth import get_python_sql_connector_auth_provider + from databricks.sql.common.unified_http_client import UnifiedHttpClient + from databricks.sql.utils import build_client_context + + server_hostname = "dbc-test.cloud.databricks.com" + access_token = jwt.encode( + {"exp": int(time.time()) + 3600, "iss": f"https://{server_hostname}/oidc"}, + "a-signing-key-that-is-at-least-32-bytes", + algorithm="HS256", + ) + provider = get_shared_u2m_credentials_provider(server_hostname, "databricks-oauth") + + def connection_auth_headers(_: int) -> t.Dict[str, str]: + http_client = UnifiedHttpClient(build_client_context(server_hostname, __version__)) + connection_auth_provider = get_python_sql_connector_auth_provider( + server_hostname, + http_client=http_client, + auth_type="databricks-oauth", + credentials_provider=provider, + ) + headers: t.Dict[str, str] = {} + connection_auth_provider.add_headers(headers) + return headers + + with patch( + "databricks.sql.auth.oauth.OAuthManager.get_tokens", + return_value=(access_token, "refresh-token"), + ) as mock_get_tokens: + with ThreadPoolExecutor(max_workers=8) as executor: + all_headers = list(executor.map(connection_auth_headers, range(8))) + + mock_get_tokens.assert_called_once() + assert all(headers["Authorization"] == f"Bearer {access_token}" for headers in all_headers) 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/src/commands/printEnvironment.ts b/vscode/extension/src/commands/printEnvironment.ts index 41e74e40d3..39fd171bd1 100644 --- a/vscode/extension/src/commands/printEnvironment.ts +++ b/vscode/extension/src/commands/printEnvironment.ts @@ -2,6 +2,7 @@ import * as vscode from 'vscode' import { getSqlmeshEnvironment } from '../utilities/sqlmesh/sqlmesh' import { isErr } from '@bus/result' import { IS_WINDOWS } from '../utilities/isWindows' +import { printEnvironmentCommand } from '../utilities/shellCommand' export function printEnvironment() { return async () => { @@ -23,14 +24,9 @@ export function printEnvironment() { // Show the terminal terminal.show() - // Run the appropriate command to display environment variables - if (IS_WINDOWS) { - // On Windows, use 'set' command - terminal.sendText('set') - } else { - // On Unix-like systems, use 'env' command - terminal.sendText('env | sort') - } + // Run the command the user's shell understands, since the terminal is + // opened with the default shell rather than a shell we pick + terminal.sendText(printEnvironmentCommand(vscode.env.shell, IS_WINDOWS)) // Show a notification vscode.window.showInformationMessage( 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), + ) +} diff --git a/vscode/extension/src/utilities/shellCommand.test.ts b/vscode/extension/src/utilities/shellCommand.test.ts new file mode 100644 index 0000000000..3c7984d4f8 --- /dev/null +++ b/vscode/extension/src/utilities/shellCommand.test.ts @@ -0,0 +1,106 @@ +// SPDX-License-Identifier: Apache-2.0 + +import { describe, it, expect } from 'vitest' +import { detectShellFamily, printEnvironmentCommand } from './shellCommand' + +const POWERSHELL_COMMAND = + "Get-ChildItem Env: | Sort-Object Name | ForEach-Object { '{0}={1}' -f $_.Name, $_.Value }" + +describe('detectShellFamily', () => { + it('should detect fish', () => { + expect(detectShellFamily('/usr/bin/fish', false)).toBe('fish') + expect(detectShellFamily('/opt/homebrew/bin/fish', false)).toBe('fish') + }) + + it('should detect POSIX shells', () => { + expect(detectShellFamily('/bin/bash', false)).toBe('posix') + expect(detectShellFamily('/bin/zsh', false)).toBe('posix') + expect(detectShellFamily('/bin/sh', false)).toBe('posix') + expect(detectShellFamily('/usr/bin/dash', false)).toBe('posix') + expect(detectShellFamily('/usr/bin/ksh', false)).toBe('posix') + }) + + it('should detect Windows shells, ignoring the executable extension', () => { + expect(detectShellFamily('C:\\Windows\\System32\\cmd.exe', true)).toBe( + 'cmd', + ) + expect( + detectShellFamily( + 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', + true, + ), + ).toBe('powershell') + expect( + detectShellFamily('C:\\Program Files\\PowerShell\\7\\pwsh.exe', true), + ).toBe('powershell') + }) + + it('should detect a POSIX shell installed on Windows', () => { + expect( + detectShellFamily('C:\\Program Files\\Git\\bin\\bash.exe', true), + ).toBe('posix') + }) + + it('should accept a bare shell name without a path', () => { + expect(detectShellFamily('fish', false)).toBe('fish') + expect(detectShellFamily('pwsh', false)).toBe('powershell') + }) + + it('should ignore the case of the shell name', () => { + expect(detectShellFamily('/usr/bin/FISH', false)).toBe('fish') + expect(detectShellFamily('C:\\WINDOWS\\SYSTEM32\\CMD.EXE', true)).toBe( + 'cmd', + ) + }) + + it('should fall back on the platform for an unknown shell', () => { + expect(detectShellFamily('/usr/bin/elvish', false)).toBe('posix') + expect(detectShellFamily('C:\\tools\\elvish.exe', true)).toBe('cmd') + }) + + it('should fall back on the platform when no shell is reported', () => { + expect(detectShellFamily('', false)).toBe('posix') + expect(detectShellFamily('', true)).toBe('cmd') + expect(detectShellFamily(undefined, false)).toBe('posix') + expect(detectShellFamily(undefined, true)).toBe('cmd') + }) +}) + +describe('printEnvironmentCommand', () => { + it('should use the exported-only set in fish', () => { + expect(printEnvironmentCommand('/usr/bin/fish', false)).toBe('set -x') + }) + + it('should use env | sort in POSIX shells', () => { + expect(printEnvironmentCommand('/bin/bash', false)).toBe('env | sort') + expect(printEnvironmentCommand('/bin/zsh', false)).toBe('env | sort') + expect(printEnvironmentCommand('/bin/sh', false)).toBe('env | sort') + }) + + it('should use set in cmd', () => { + expect( + printEnvironmentCommand('C:\\Windows\\System32\\cmd.exe', true), + ).toBe('set') + }) + + it('should not use set in PowerShell, where it prompts for a variable name', () => { + expect( + printEnvironmentCommand( + 'C:\\Program Files\\PowerShell\\7\\pwsh.exe', + true, + ), + ).toBe(POWERSHELL_COMMAND) + }) + + it('should use the PowerShell command for pwsh off Windows', () => { + expect(printEnvironmentCommand('/usr/local/bin/pwsh', false)).toBe( + POWERSHELL_COMMAND, + ) + expect(printEnvironmentCommand('pwsh', false)).toBe(POWERSHELL_COMMAND) + }) + + it('should keep the previous behaviour when the shell is unknown', () => { + expect(printEnvironmentCommand(undefined, false)).toBe('env | sort') + expect(printEnvironmentCommand(undefined, true)).toBe('set') + }) +}) diff --git a/vscode/extension/src/utilities/shellCommand.ts b/vscode/extension/src/utilities/shellCommand.ts new file mode 100644 index 0000000000..61ed04415f --- /dev/null +++ b/vscode/extension/src/utilities/shellCommand.ts @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: Apache-2.0 + +/** + * The shell families we know how to print environment variables in. + */ +export type ShellFamily = 'fish' | 'powershell' | 'cmd' | 'posix' + +/** + * Commands that list the environment variables of the current shell, one per + * shell family. + * + * `set -x` is fish's exported-only listing, which matches what the other + * families print; a bare `set` would also include shell-local variables. + * PowerShell formats each variable itself because the default table view + * truncates values at the console width. + */ +const PRINT_ENVIRONMENT_COMMANDS: Record = { + fish: 'set -x', + powershell: + "Get-ChildItem Env: | Sort-Object Name | ForEach-Object { '{0}={1}' -f $_.Name, $_.Value }", + cmd: 'set', + posix: 'env | sort', +} + +const SHELL_FAMILIES_BY_NAME: Record = { + fish: 'fish', + powershell: 'powershell', + pwsh: 'powershell', + cmd: 'cmd', + bash: 'posix', + zsh: 'posix', + sh: 'posix', + dash: 'posix', + ksh: 'posix', + ash: 'posix', +} + +/** + * Extracts the executable name from a shell path, which may use either + * separator and may carry a Windows executable extension. + */ +const shellName = (shellPath: string): string => { + const base = shellPath.split(/[\\/]/).pop() ?? '' + return base.toLowerCase().replace(/\.exe$/, '') +} + +/** + * Resolves a shell path to the family whose syntax it accepts. + * + * Unrecognized shells fall back on the platform default, which keeps POSIX + * shells we have not listed working. + * + * @param shellPath The path reported by `vscode.env.shell`, which is empty in + * environments without a shell + * @param isWindows Whether the extension host runs on Windows + */ +export const detectShellFamily = ( + shellPath: string | undefined, + isWindows: boolean, +): ShellFamily => { + const family = shellPath + ? SHELL_FAMILIES_BY_NAME[shellName(shellPath)] + : undefined + if (family) { + return family + } + return isWindows ? 'cmd' : 'posix' +} + +/** + * Returns the command that prints all environment variables in the given + * shell. + * + * @param shellPath The path reported by `vscode.env.shell`, which is empty in + * environments without a shell + * @param isWindows Whether the extension host runs on Windows + */ +export const printEnvironmentCommand = ( + shellPath: string | undefined, + isWindows: boolean, +): string => PRINT_ENVIRONMENT_COMMANDS[detectShellFamily(shellPath, isWindows)] 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 6ce92c3266..0c8e8026f7 100644 --- a/vscode/extension/tests/fixtures.ts +++ b/vscode/extension/tests/fixtures.ts @@ -7,12 +7,63 @@ 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] + +/** + * 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 {}, - { sharedCodeServer: CodeServerContext; tempDir: string } + { + sharedCodeServer: CodeServerContext + sharedPythonEnvironment: SharedPythonEnvironment + tempDir: string + } >({ sharedCodeServer: [ // eslint-disable-next-line no-empty-pattern @@ -40,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) => { @@ -52,7 +130,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 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 `