From 84eeb497c61fad939ea38c3ab45e61032662213b Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Sat, 28 Nov 2026 10:42:36 -0800 Subject: [PATCH 1/2] Add measure-preserving DuckDB views and streamline semantic catalog discovery --- .github/workflows/ci.yml | 35 +- .../workflows/duckdb-extension-release.yml | 3 +- docs/duckdb-extension.md | 32 +- scripts/duckdb_community_descriptor.py | 51 ++ sqlctx-duckdb/CMakeLists.txt | 18 +- sqlctx-duckdb/README.md | 81 +- sqlctx-duckdb/community/README.md | 50 ++ sqlctx-duckdb/community/description.yml.in | 51 ++ sqlctx-duckdb/scripts/benchmark_catalog.py | 165 ++++ sqlctx-duckdb/src/include/sqlctx_catalog.hpp | 16 +- .../src/include/sqlctx_compat.hpp.in | 2 + sqlctx-duckdb/src/include/sqlctx_compiler.hpp | 37 + sqlctx-duckdb/src/include/sqlctx_explain.hpp | 7 + sqlctx-duckdb/src/include/sqlctx_parser.hpp | 10 +- .../src/include/sqlctx_semantic_input.hpp | 7 + sqlctx-duckdb/src/sqlctx_api.cpp | 46 +- sqlctx-duckdb/src/sqlctx_catalog.cpp | 141 ++- sqlctx-duckdb/src/sqlctx_discovery.cpp | 220 ++++- sqlctx-duckdb/src/sqlctx_explain.cpp | 48 ++ sqlctx-duckdb/src/sqlctx_extension.cpp | 67 +- sqlctx-duckdb/src/sqlctx_grammar.cpp | 15 +- sqlctx-duckdb/src/sqlctx_parser.cpp | 582 ++++++++++--- sqlctx-duckdb/src/sqlctx_semantic_input.cpp | 102 +++ sqlctx-duckdb/test/README.md | 32 + sqlctx-duckdb/test/sql/sqlctx_native_peg.test | 29 + .../test/test_attached_catalog_host.py | 177 ++++ .../test/test_client_routing_host.py | 167 ++++ sqlctx-duckdb/test/test_discovery_host.py | 66 ++ sqlctx-duckdb/test/test_duckflight_host.py | 34 +- sqlctx-duckdb/test/test_explain_host.py | 52 ++ sqlctx-duckdb/test/test_release_workflow.py | 21 +- .../test/test_semantic_input_host.py | 81 +- .../test/test_semantic_views_host.py | 204 +++++ sqlctx-duckdb/test/test_yardstick_host.py | 79 ++ sqlctx-rs/include/sqlctx.h | 14 + sqlctx-rs/src/ffi/catalog.rs | 85 +- sqlctx-rs/src/ffi/catalog/api.rs | 51 +- sqlctx-rs/src/ffi/catalog/compiler.rs | 221 +++++ sqlctx-rs/src/ffi/catalog/explain.rs | 282 ++++++ sqlctx-rs/src/ffi/catalog/views.rs | 801 ++++++++++++++++++ sqlctx-rs/src/sql/explain.rs | 68 ++ sqlctx-rs/src/sql/generator.rs | 57 +- sqlctx-rs/src/sql/generator/aggregate_plan.rs | 10 + .../src/sql/generator/fanout_complete.rs | 6 + sqlctx-rs/src/sql/mod.rs | 1 + tests/test_duckdb_community_descriptor.py | 69 ++ 46 files changed, 4067 insertions(+), 326 deletions(-) create mode 100644 scripts/duckdb_community_descriptor.py create mode 100644 sqlctx-duckdb/community/README.md create mode 100644 sqlctx-duckdb/community/description.yml.in create mode 100644 sqlctx-duckdb/scripts/benchmark_catalog.py create mode 100644 sqlctx-duckdb/src/include/sqlctx_compiler.hpp create mode 100644 sqlctx-duckdb/src/include/sqlctx_explain.hpp create mode 100644 sqlctx-duckdb/src/include/sqlctx_semantic_input.hpp create mode 100644 sqlctx-duckdb/src/sqlctx_explain.cpp create mode 100644 sqlctx-duckdb/src/sqlctx_semantic_input.cpp create mode 100644 sqlctx-duckdb/test/test_attached_catalog_host.py create mode 100644 sqlctx-duckdb/test/test_client_routing_host.py create mode 100644 sqlctx-duckdb/test/test_discovery_host.py create mode 100644 sqlctx-duckdb/test/test_explain_host.py create mode 100644 sqlctx-duckdb/test/test_semantic_views_host.py create mode 100644 sqlctx-duckdb/test/test_yardstick_host.py create mode 100644 sqlctx-rs/src/ffi/catalog/compiler.rs create mode 100644 sqlctx-rs/src/ffi/catalog/explain.rs create mode 100644 sqlctx-rs/src/ffi/catalog/views.rs create mode 100644 sqlctx-rs/src/sql/explain.rs create mode 100644 tests/test_duckdb_community_descriptor.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc8d10be8..d7a19598c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -874,13 +874,42 @@ jobs: enable-cache: true suffix: ${{ github.workflow }}-${{ github.job }}-${{ strategy.job-index || 0 }} - - name: Execute SemanticInput in the loaded DuckDB extension + - name: Fetch pinned community Yardstick for parser coexistence + if: matrix.duckdb == 'v1.5.6' + run: | + uv run --no-project --python 3.12 --with duckdb==1.5.6 python -c \ + "import duckdb; assert duckdb.sql('pragma platform').fetchone()[0] == 'linux_amd64'" + # Signed community package: Yardstick 9efa623, DuckDB v1.5.6, linux_amd64. + YARDSTICK_ARCHIVE="$RUNNER_TEMP/yardstick.duckdb_extension.gz" + YARDSTICK_EXTENSION="$RUNNER_TEMP/yardstick.duckdb_extension" + curl --fail --location --retry 3 \ + https://community-extensions.duckdb.org/v1.5.6/linux_amd64/yardstick.duckdb_extension.gz \ + --output "$YARDSTICK_ARCHIVE" + echo "7ed50c9f5a0e6a5f6e34800f40d917ea6d85989bc887f15faac6f615a27784c3 $YARDSTICK_ARCHIVE" | sha256sum --check + gzip --decompress --stdout "$YARDSTICK_ARCHIVE" > "$YARDSTICK_EXTENSION" + echo "YARDSTICK_EXTENSION=$YARDSTICK_EXTENSION" >> "$GITHUB_ENV" + + - name: Exercise SQL and Python clients with the matching DuckDB extension + env: + SQLCTX_DUCKDB_BINARY: sqlctx-duckdb/build/release/duckdb + SQLCTX_DUCKDB_EXTENSION: sqlctx-duckdb/build/release/extension/sqlctx/sqlctx.duckdb_extension + run: | + uv run --no-project --python 3.12 --with pytest --with pyyaml --with "duckdb==${DUCKDB_VERSION#v}" \ + pytest -q -o addopts= sqlctx-duckdb/test --ignore=sqlctx-duckdb/test/test_duckflight_host.py + + - name: Exercise PostgreSQL BI discovery through released DuckFlight + if: matrix.duckdb == 'v2.0.1' env: SQLCTX_DUCKDB_BINARY: sqlctx-duckdb/build/release/duckdb SQLCTX_DUCKDB_EXTENSION: sqlctx-duckdb/build/release/extension/sqlctx/sqlctx.duckdb_extension run: | - uv run sqlctx-duckdb/test/test_semantic_input_host.py - uv run sqlctx-duckdb/test/test_catalog_host.py + DUCKFLIGHT_EXTENSION="$RUNNER_TEMP/duckflight.duckdb_extension" + export DUCKFLIGHT_EXTENSION + curl --fail --location --retry 3 \ + https://github.com/sidequery/duckflight-extension/releases/download/v0.2.1/duckflight-linux_amd64.duckdb_extension \ + --output "$DUCKFLIGHT_EXTENSION" + echo "7e0c3a624f795b6dc756483ebc8b7e7af85c13cf33c301f86bcecc626444dbf7 $DUCKFLIGHT_EXTENSION" | sha256sum --check + uv run sqlctx-duckdb/test/test_duckflight_host.py - name: Save completed build caches if: ${{ !cancelled() }} diff --git a/.github/workflows/duckdb-extension-release.yml b/.github/workflows/duckdb-extension-release.yml index 20592d295..8928a9dfc 100644 --- a/.github/workflows/duckdb-extension-release.yml +++ b/.github/workflows/duckdb-extension-release.yml @@ -213,6 +213,7 @@ jobs: done cat *.sha256 > SHA256SUMS cp ../LICENSE . + cp ../sqlctx-duckdb/LICENSE LICENSE.duckdb-extension # Creation fails if the tag already has a release; never overwrite published bytes. - gh release create "$TAG" *.duckdb_extension SHA256SUMS LICENSE \ + gh release create "$TAG" *.duckdb_extension SHA256SUMS LICENSE LICENSE.duckdb-extension \ --verify-tag --target "$RELEASE_COMMIT" --title "$TAG" --generate-notes diff --git a/docs/duckdb-extension.md b/docs/duckdb-extension.md index ea0531896..055062e8c 100644 --- a/docs/duckdb-extension.md +++ b/docs/duckdb-extension.md @@ -209,6 +209,36 @@ SELECT orders.revenue FROM orders; The legacy `SEMANTIC SELECT ...` form remains supported. +### Save a reusable selection of dimensions and measures + +With the `orders` model above, publish a selection and query it at two grains: + +```sql +create semantic view order_report as +select status, revenue as gross_revenue from orders; + +select status, gross_revenue from order_report order by status; +select gross_revenue from order_report; +``` + +A semantic view projects fields from one model or another semantic view. The consumer +chooses the grouping dimensions. Aliasing a ratio or filtered measure retains its +source definition. Replacing a source measure changes subsequent queries of the +semantic view. `CREATE OR REPLACE SEMANTIC VIEW`, `DROP SEMANTIC VIEW` and changes +to source definitions participate in the caller's transaction. An ordinary DuckDB +`CREATE VIEW ... AS SELECT ...` over a semantic query stores its compiled SQL. + +Use `sqlctx_explain('select orders.revenue from orders')` to inspect the semantic +compiler's decisions. DuckDB's own `EXPLAIN` shows the resulting database plan. +For applications with a SemanticInput v1 document, the +`sqlctx_query_semantic_input(input_json, query_json)` table function returns the +requested columns and rows directly in the caller's transaction. + +After attaching a database as `finance`, a query can explicitly select its model +with `from finance.semantic.orders`. Unqualified physical sources of a model in +another catalog resolve in that catalog's default schema. Explicitly qualified +sources retain their catalog. + ## Release Path Use `.github/workflows/duckdb-extension-release.yml`. @@ -219,7 +249,7 @@ The workflow: - builds the Rust-backed extension for `linux_amd64`, `linux_arm64`, `osx_amd64`, and `osx_arm64`, - runs the DuckDB sqllogictests, including native YAML load, native SQL definition file load, relationship rewrite, semantic select, persistence, and invalid-version coverage, - uploads a separate extension artifact for each DuckDB version and platform with its checksum, -- on a `sqlctx-duckdb-v*` tag push (or a manual run with `create_github_release`), creates the GitHub release with the artifacts, `SHA256SUMS`, and `LICENSE`. It never overwrites an existing release. +- on a `sqlctx-duckdb-v*` tag push (or a manual run with `create_github_release`), creates the GitHub release with the artifacts, `SHA256SUMS`, and both license notices. It never overwrites an existing release. It does not publish to the DuckDB community extension registry. diff --git a/scripts/duckdb_community_descriptor.py b/scripts/duckdb_community_descriptor.py new file mode 100644 index 000000000..189877586 --- /dev/null +++ b/scripts/duckdb_community_descriptor.py @@ -0,0 +1,51 @@ +"""Render the community registry descriptor from an immutable, complete commit.""" + +import argparse +import re +import subprocess +import sys +import tomllib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +TEMPLATE = "sqlctx-duckdb/community/description.yml.in" + + +def git(repo: Path, *args: str) -> str: + return subprocess.check_output(["git", "-C", str(repo), *args], text=True, stderr=subprocess.PIPE).strip() + + +def render_descriptor(repo: Path, ref: str) -> str: + commit = git(repo, "rev-parse", "--verify", "--end-of-options", f"{ref}^{{commit}}") + # Read all metadata from the selected commit, never from a newer worktree. + manifest = tomllib.loads(git(repo, "show", f"{commit}:sqlctx-rs/Cargo.toml")) + version = manifest["package"]["version"] + if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]+)?", version): + raise ValueError(f"Invalid extension version: {version!r}") + for path in ( + "sqlctx-duckdb/Makefile", + "sqlctx-duckdb/CMakeLists.txt", + "sqlctx-duckdb/extension_config.cmake", + "sqlctx-duckdb/LICENSE", + "sqlctx-rs/Cargo.lock", + "sqlctx-rs/include/sqlctx.h", + "LICENSE", + ): + git(repo, "cat-file", "-e", f"{commit}:{path}") + template = git(repo, "show", f"{commit}:{TEMPLATE}") + return template.replace("@VERSION@", version).replace("@COMMIT@", commit) + "\n" + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--ref", required=True, help="Final tested commit or immutable release tag to submit") + args = parser.parse_args() + try: + sys.stdout.write(render_descriptor(ROOT, args.ref)) + except (subprocess.CalledProcessError, ValueError) as error: + detail = error.stderr.strip() if isinstance(error, subprocess.CalledProcessError) else str(error) + parser.exit(1, f"Cannot prepare community descriptor: {detail}\n") + + +if __name__ == "__main__": + main() diff --git a/sqlctx-duckdb/CMakeLists.txt b/sqlctx-duckdb/CMakeLists.txt index 02e4e8a8d..43a5e0901 100644 --- a/sqlctx-duckdb/CMakeLists.txt +++ b/sqlctx-duckdb/CMakeLists.txt @@ -22,14 +22,15 @@ function(sqlctx_detect_apis) parser/parser_options.hpp parser/expression/constant_expression.hpp parser/statement/insert_statement.hpp parser/grammar_extension.hpp parser/peg/compiled_grammar.hpp parser/peg/transformer/peg_transformer.hpp - planner/operator/logical_get.hpp main/client_config.hpp) + planner/operator/logical_get.hpp planner/planner_extension.hpp main/client_config.hpp + common/types/data_chunk.hpp common/types/vector.hpp) if(EXISTS "${CMAKE_SOURCE_DIR}/src/include/duckdb/${header}") file(SHA256 "${CMAKE_SOURCE_DIR}/src/include/duckdb/${header}" header_hash) string(APPEND host_api ";${header_hash}") endif() endforeach() if(NOT SQLCTX_HOST_API STREQUAL host_api) - foreach(api TOKEN_PARSE_FN NEW_IDENTIFIER_API NEW_EXPRESSION_API QUALIFIED_TABLE_API BUILTIN_PARSER_OPTIONS LITERAL_API GRAMMAR_EXTENSION INSERT_QUERY_NODE BOUND_TABLE_FUNCTION GRAMMAR_EXTENSION_LIST ARENA_TRANSFORM SHELL_GRAMMAR_CONTEXT) + foreach(api TOKEN_PARSE_FN NEW_IDENTIFIER_API NEW_EXPRESSION_API QUALIFIED_TABLE_API BUILTIN_PARSER_OPTIONS LITERAL_API GRAMMAR_EXTENSION INSERT_QUERY_NODE BOUND_TABLE_FUNCTION GRAMMAR_EXTENSION_LIST ARENA_TRANSFORM SHELL_GRAMMAR_CONTEXT PRE_BIND VECTOR_APPEND) unset(SQLCTX_${api} CACHE) endforeach() set(SQLCTX_HOST_API "${host_api}" CACHE INTERNAL "DuckDB headers used for compatibility probes" FORCE) @@ -102,6 +103,17 @@ function(sqlctx_detect_apis) CompiledGrammar::Create(*options.context, vector{\"shell\", \"sqlctx\"}); } " SQLCTX_SHELL_GRAMMAR_CONTEXT) + check_cxx_source_compiles(" + #include + void probe(duckdb::PlannerExtension &extension) { extension.pre_bind_function = nullptr; } + " SQLCTX_PRE_BIND) + check_cxx_source_compiles(" + #include + void probe(duckdb::DataChunk &chunk, const duckdb::Value &value) { + chunk.data[0].Append(value); + chunk.CheckCardinality(1); + } + " SQLCTX_VECTOR_APPEND) configure_file(src/include/sqlctx_compat.hpp.in sqlctx_compat.hpp) cmake_pop_check_state() endfunction() @@ -173,7 +185,7 @@ add_custom_target(sqlctx_rust_staticlib DEPENDS "${SQLCTX_LIB}") # Include Rust library headers include_directories(${SQLCTX_INCLUDE}) -set(EXTENSION_SOURCES src/sqlctx_extension.cpp src/sqlctx_parser.cpp src/sqlctx_grammar.cpp src/sqlctx_catalog.cpp src/sqlctx_api.cpp src/sqlctx_discovery.cpp) +set(EXTENSION_SOURCES src/sqlctx_extension.cpp src/sqlctx_parser.cpp src/sqlctx_grammar.cpp src/sqlctx_catalog.cpp src/sqlctx_api.cpp src/sqlctx_discovery.cpp src/sqlctx_semantic_input.cpp src/sqlctx_explain.cpp) build_static_extension(${TARGET_NAME} ${EXTENSION_SOURCES}) build_loadable_extension(${TARGET_NAME} " " ${EXTENSION_SOURCES}) diff --git a/sqlctx-duckdb/README.md b/sqlctx-duckdb/README.md index 1397fc25f..2b047401d 100644 --- a/sqlctx-duckdb/README.md +++ b/sqlctx-duckdb/README.md @@ -27,6 +27,9 @@ SQLCTX_NATIVE_PEG=1 make test For embedded clients, set DuckDB's `allow_unsigned_extensions` database configuration before opening the connection. Community extension installation is planned, but this repository does not yet publish the signed multi-platform artifacts required for `INSTALL sqlctx FROM community`. +The [community registry submission guide](community/README.md) prepares an immutable +descriptor for both release lines and documents the registry's monorepo build contract. + The release workflow builds unsigned DuckDB 2.0.1 and 1.5.6 packages for Linux and macOS on AMD64 and ARM64. Linux builds use a glibc 2.28 baseline. When installing a release artifact, verify it against `SHA256SUMS` and give it the filename @@ -179,30 +182,61 @@ metadata. Import validates the complete candidate and merges it atomically into the selected database. A definition with the same name is replaced. Export and discovery work on read-only databases and observe the current transaction. +### Named semantic views + +Publish a selection of fields from a model or another semantic view. Each query +of the saved selection chooses its grouping dimensions: + +```sql +CREATE SEMANTIC VIEW order_report AS +SELECT status, revenue AS gross_revenue FROM orders_model; + +SELECT status, gross_revenue FROM order_report ORDER BY status; +SELECT gross_revenue FROM order_report; +``` + +The view retains measure definitions, including filters and ratio components. +`CREATE OR REPLACE SEMANTIC VIEW` and `DROP SEMANTIC VIEW` use the same +transaction and dependency rules as models. See the [extension guide](../docs/duckdb-extension.md) +for attached catalogs and ordinary DuckDB views. + ## Versioned SemanticInput -The stateless SQL functions `sqlctx_compile_semantic_input(input_json, query_json)` -and `sqlctx_rewrite_semantic_input(input_json, sql, context_json)` accept the -same SemanticInput v1 contract as the Python and WASM hosts. They return executable -SQL and do not change models loaded through the session APIs. +The table function `sqlctx_query_semantic_input(input_json, query_json)` accepts +the same SemanticInput v1 contract as the Python and WASM hosts and returns its +query result directly. Its columns and types follow the requested metrics and +dimensions, including retention's cohort table. It does not change models loaded +through the session APIs. ```sql -select sqlctx_compile_semantic_input( +select * from sqlctx_query_semantic_input( '{"version":1,"input_dialect":"duckdb","models":[{"name":"sales","table":"orders","primary_key":"order_id", "metrics":[{"name":"revenue","agg":"sum","sql":"amount"}]}]}', '{"metrics":["sales.revenue"]}' ); ``` -Pass `user_attributes` and `enforce_visibility` in query JSON for compilation, or -in the third argument for rewriting. Policies and invariant filters in the input -apply when generating SQL; missing policy attributes, visibility denials and -invalid contracts raise SQL errors. SQL NULL arguments return NULL; embedded NUL +Use this relation in joins, CTEs, views and outer filters. DuckDB binds the +generated query in the calling connection, so temporary tables, uncommitted writes +and rollback have their normal SQL behavior. Arguments must be available at bind +time: literals, constant expressions or bound prepared-statement parameters; +per-row request columns are not supported. Dimensions in the query JSON determine +the aggregation grain; an outer projection does not change that grain. + +The scalar functions `sqlctx_compile_semantic_input(input_json, query_json)` and +`sqlctx_rewrite_semantic_input(input_json, sql, context_json)` return generated SQL +for inspection or execution elsewhere. Pass `user_attributes` and +`enforce_visibility` in query JSON for compilation and direct queries, or in the +third argument for rewriting. Policies and invariant filters apply to all three +entrypoints; missing policy attributes, visibility denials and invalid contracts +raise SQL errors. The scalar functions return NULL for SQL NULL arguments; the +relation rejects NULL because it cannot determine a result schema. Embedded NUL bytes are rejected. Each call uses its own caller context. CI runs `test/test_semantic_input_host.py` against the freshly built DuckDB shell -and loaded extension, executes the returned SQL over real rows, and checks policy -isolation, invalid contracts and argument handling. To run it locally after a build: +and loaded extension. It checks direct relations and returned SQL over real rows, +policy isolation, prepared parameters, transactions, temporary tables, retention, +invalid contracts and argument handling. To run it locally after a build: ```bash SQLCTX_DUCKDB_BINARY=build/release/duckdb \ @@ -584,7 +618,7 @@ rows, including equal-valued metrics on distinct customers. - Native execution tests cover derived, ratio, cumulative, time-comparison, conversion, retention, and cohort metrics. Retention produces a table with cohort date, elapsed periods, active users, cohort size, and retention percentage; - use `sqlctx_compile_semantic_input` and execute its returned SQL. A scalar projection such as + use `select * from sqlctx_query_semantic_input(input_json, query_json)`. A scalar projection such as `SEMANTIC SELECT events.retention FROM events` is rejected. These contracts do not establish full parity with every Python adapter or API. - DuckDB 1.5.6 uses the compatibility frontend. Native PEG support targets @@ -595,6 +629,24 @@ rows, including equal-valued metrics on distinct customers. ## Utility Functions +`sqlctx_explain(sql)` returns a JSON report from the same Rust compiler and current +catalog snapshot used by `sqlctx_rewrite_sql`: + +```sql +select sqlctx_explain('select customers.country, orders.revenue from orders'); +``` + +The report includes compiled SQL, warnings, and ordered compiler observations: +effective grouping expressions, emitted relationship edges and join kinds, +population preservation, detected fanout risk and the guards actually emitted, +independent aggregate populations, and selected rollups where routing is enabled. +`rollup_candidates` lists declarations, not a claim that each candidate is eligible. +The catalog SQL rewrite route currently leaves materialized rollup routing disabled; +its query events expose that setting. Specialized compiler routes may expose fewer +events, as indicated by the report's `coverage` field. An absent guard event is not +a safety guarantee. Explanation compiles without executing the query or checking +physical table availability; ordinary DuckDB `explain` remains the physical plan. + ### sqlctx_models() List all loaded semantic models. @@ -680,4 +732,7 @@ version string and `source_id` the commit prefix. ## License -MIT +The DuckDB extension template carries the [MIT license](LICENSE). The embedded +`sqlctx-rs` compiler is licensed under [AGPL-3.0-only](../LICENSE), as declared in +its [Cargo manifest](../sqlctx-rs/Cargo.toml). Distributed binaries include that +compiler; the release workflow includes both license texts. diff --git a/sqlctx-duckdb/community/README.md b/sqlctx-duckdb/community/README.md new file mode 100644 index 000000000..b1cf5752a --- /dev/null +++ b/sqlctx-duckdb/community/README.md @@ -0,0 +1,50 @@ +# Community registry submission + +The descriptor is prepared here; signed installation becomes available only after +DuckDB's community registry merges the submission and deploys its builds. Local +release artifacts remain unsigned. Do not describe a prepared descriptor or a +green build as a published community extension. + +After the complete SQLCtx change has been committed, tested on both released hosts +and pushed to `sidequery/sqlctx`, render its descriptor from that exact commit: + +```bash +uv run scripts/duckdb_community_descriptor.py --ref > /path/to/community-extensions/extensions/sqlctx/description.yml +``` + +The destination directory must already exist. The generator reads the template, +version and required build files from the selected commit, rather than mixing a +new worktree with an old source pin. Submit only this descriptor to +[`duckdb/community-extensions`](https://github.com/duckdb/community-extensions). +Do not commit a generated descriptor back into SQLCtx: its source pin would then +necessarily precede the commit containing it. + +## Build contract + +- `repo.ref` targets DuckDB 2.0.1; `repo.variegata` targets DuckDB 1.5.6. Both pins + use the same SQLCtx commit, whose CMake probes select the host API. +- `repo.build_directory: sqlctx-duckdb` selects the extension Makefile without + extracting that directory from the repository. The registry checks out the full + repository. On Linux, its container mounts the repository root and changes its + working directory to `sqlctx-duckdb`; CMake can therefore read `../sqlctx-rs`, + its locked dependencies and public FFI header. +- `requires_toolchains: rust` installs the compiler used by the CMake static-library + build. Rust is linked into the extension; users do not install Rust or Python. +- The descriptor requests the four native release targets: Linux AMD64/ARM64 and + macOS AMD64/ARM64. macOS AMD64 is explicitly opted into reduced CI. Windows, + musl and WASM stay excluded until their artifacts are tested. +- Community CI checks out its own `extension-ci-tools` under the build directory. + SQLCtx's vendored copy is for local builds; changes there do not override the + community workflow. + +The owning upstream contracts are +[`scripts/build.py`](https://github.com/duckdb/community-extensions/blob/main/scripts/build.py), +[`build.yml`](https://github.com/duckdb/community-extensions/blob/main/.github/workflows/build.yml), +and [`ci_phase.py`](https://github.com/duckdb/extension-ci-tools/blob/v2.0-cyanoptera/scripts/ci_phase.py) +(`PhaseRunner.__init__`, `docker_workspace`, `docker_arguments`). + +Verify both registry build lines, including extension tests, before requesting +merge. After deployment, test `INSTALL sqlctx FROM community; LOAD sqlctx;` in a +clean signed-only DuckDB client for each release and execute the descriptor's +example. That final check establishes availability; the source descriptor alone +does not. diff --git a/sqlctx-duckdb/community/description.yml.in b/sqlctx-duckdb/community/description.yml.in new file mode 100644 index 000000000..be9a53407 --- /dev/null +++ b/sqlctx-duckdb/community/description.yml.in @@ -0,0 +1,51 @@ +extension: + name: sqlctx + description: SQL-first semantic models with reusable dimensions, metrics, relationships and automatic query rewriting + version: "@VERSION@" + language: C++ + build: cmake + license: AGPL-3.0-only AND MIT + requires_toolchains: rust + # Match the native platforms covered by the release workflow. + excluded_platforms: "wasm_mvp;wasm_eh;wasm_threads;windows_amd64;windows_amd64_rtools;windows_amd64_mingw;windows_arm64;linux_amd64_musl;linux_arm64_musl" + opt_in_platforms: osx_amd64 + maintainers: + - nicosuave + +repo: + github: sidequery/sqlctx + build_directory: sqlctx-duckdb + # The same source supports both released DuckDB C++ APIs. + ref: @COMMIT@ + variegata: @COMMIT@ + +docs: + hello_world: | + INSTALL sqlctx FROM community; + LOAD sqlctx; + + CREATE TABLE orders(id INTEGER, region VARCHAR, amount DECIMAL(10,2)); + INSERT INTO orders VALUES (1, 'US', 100), (2, 'US', 200), (3, 'EU', 150); + + MODEL (name sales, table orders, primary_key id); + DIMENSION (name region, type categorical); + METRIC revenue AS SUM(amount); + + SELECT sales.region, sales.revenue FROM sales ORDER BY 1; + SHOW METRICS FROM sales; + SELECT sqlctx_rewrite_sql('SELECT sales.region, sales.revenue FROM sales'); + extended_description: | + Define semantic models, dimensions, metrics and relationships in SQL, or load + definition files with sqlctx_load_file. Query model fields with ordinary SQL; + sqlctx compiles the requested dimensions and metrics into DuckDB SQL at bind time. + + Definitions participate in DuckDB transactions. SHOW MODELS, SHOW METRICS and + SHOW DIMENSIONS expose the model vocabulary, and sqlctx_rewrite_sql returns + generated SQL for inspection. Models are also discoverable under the semantic + schema through DuckDB's catalog interfaces. + + Native PEG grammar is used on DuckDB 2.0.1; DuckDB 1.5.6 uses the compatibility + frontend. The extension includes its Rust compiler in the binary and does not + require a Python environment or a separate server at runtime. + + Documentation: https://github.com/sidequery/sqlctx/tree/main/sqlctx-duckdb diff --git a/sqlctx-duckdb/scripts/benchmark_catalog.py b/sqlctx-duckdb/scripts/benchmark_catalog.py new file mode 100644 index 000000000..23cc00c96 --- /dev/null +++ b/sqlctx-duckdb/scripts/benchmark_catalog.py @@ -0,0 +1,165 @@ +# /// script +# requires-python = ">=3.11" +# /// +"""Reproduce catalog and routing costs with a matching DuckDB shell/extension. + +uv run --no-project sqlctx-duckdb/scripts/benchmark_catalog.py --binary /path/duckdb \ + --extension /path/sqlctx.duckdb_extension + +Times come from the shell, excluding process startup/model loading. CPU samples +retain sub-millisecond precision where the shell rounds wall time to milliseconds. +Run the same command with an earlier extension to compare identical workloads. +""" + +import argparse +import json +import re +import statistics +import subprocess +from decimal import Decimal +from pathlib import Path + + +def literal(value): + return "'" + str(value).replace("'", "''") + "'" + + +def setup(models, metrics): + declarations = [] + for model in range(models): + fields = "\n".join(f"sum(amount) AS metric_{metric}" for metric in range(metrics)) + declarations.append(f"MODEL model_{model} FROM facts (\nprimary key(id)\ncategory\n{fields}\n);") + return "\n".join(declarations) + + +def validate_results(results, models, metrics): + if results["ordinary_constant"] != [{"42": 42}]: + raise RuntimeError(f"Incorrect ordinary constant: {results['ordinary_constant']}") + for name in ("ordinary_aggregate", "one_metric"): + if name not in results: + continue + rows = results[name] + if len(rows) != 1 or Decimal(str(next(iter(rows[0].values())))) != Decimal(499500): + raise RuntimeError(f"Incorrect {name}: {rows}") + if "list_views" not in results: + return + expected_models = [{"table_name": name} for name in sorted(f"model_{i}" for i in range(models))] + expected_columns = [{"column_name": "category", "data_type": "VARCHAR"}] + [ + {"column_name": f"metric_{i}", "data_type": "DECIMAL(38,2)"} for i in range(metrics) + ] + expected_names = [{"column_name": row["column_name"]} for row in expected_columns] + for name, expected in ( + ("list_views", expected_models), + ("one_model_columns", expected_columns), + ("one_model_column_names", expected_names), + ): + if results[name] != expected: + raise RuntimeError(f"Incorrect {name}: expected {expected}, received {results[name]}") + expected_metrics = sorted((f"metric_{i}", "DECIMAL(38,2)", "sum") for i in range(metrics)) + actual_metrics = sorted((row["name"], row["data_type"], row["aggregation"]) for row in results["show_metrics"]) + if actual_metrics != expected_metrics: + raise RuntimeError(f"Incorrect show_metrics: expected {expected_metrics}, received {actual_metrics}") + + +def run(binary, extension, models, metrics, repeats, warmups): + queries = { + "ordinary_constant": "select 42;", + "ordinary_aggregate": "select sum(amount) from facts;", + } + if extension: + queries.update( + list_views="select table_name from information_schema.tables " + "where table_schema = 'semantic' order by table_name;", + one_model_columns="select column_name, data_type from information_schema.columns " + "where table_schema = 'semantic' and table_name = 'model_0' order by ordinal_position;", + one_model_column_names="select column_name from information_schema.columns " + "where table_schema = 'semantic' and table_name = 'model_0' order by ordinal_position;", + one_metric="select metric_0 from semantic.model_0;", + show_metrics="show metrics from model_0;", + ) + statements = [ + ".output /dev/null", + "set threads = 1;", + "create table facts as select i as id, (i % 4)::varchar as category, i::decimal(12,2) as amount " + "from range(1000) t(i);", + ] + if extension: + statements.extend([f"load {literal(extension)};", setup(models, metrics)]) + # Execute the exact timed queries with visible results in the same session. + # A truncated metadata scan must fail validation, not count as a speedup. + statements.extend([".mode json", ".output stdout", *queries.values(), ".output /dev/null"]) + # Round-robin samples reduce bias from CPU frequency/load drift. Warm every + # shape before recording; preserve every sample instead of only a headline. + statements.extend(query for _ in range(warmups) for query in queries.values()) + statements.append(".timer on") + statements.extend(query for _ in range(repeats) for query in queries.values()) + result = subprocess.run( + [str(binary), "-unsigned", "-no-init", "-batch", "-bail", ":memory:"], + input="\n".join(statements) + "\n", + capture_output=True, + text=True, + timeout=180, + ) + if result.returncode: + raise RuntimeError(result.stderr) + decoder = json.JSONDecoder() + remaining = result.stdout.lstrip() + results = {} + for name in queries: + rows, end = decoder.raw_decode(remaining) + results[name] = rows + remaining = remaining[end:].lstrip() + validate_results(results, models, metrics) + timings = re.findall(r"Run Time \(s\): real ([\d.]+) user ([\d.]+) sys ([\d.]+)", remaining) + if len(timings) != repeats * len(queries): + raise RuntimeError(f"Expected {repeats * len(queries)} timings, got {len(timings)}: {result.stdout}") + report = {} + for index, (name, query) in enumerate(queries.items()): + samples = timings[index :: len(queries)] + wall = [float(real) * 1000 for real, _, _ in samples] + cpu = [(float(user) + float(system)) * 1000 for _, user, system in samples] + report[name] = { + "sql": query, + "validated_row_count": len(results[name]), + "validated_result": results[name] + if name != "show_metrics" + else [{key: row[key] for key in ("name", "data_type", "aggregation")} for row in results[name]], + "wall_ms": wall, + "cpu_ms": cpu, + "median_wall_ms": statistics.median(wall), + "median_cpu_ms": statistics.median(cpu), + } + return report + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, required=True) + parser.add_argument("--extension", type=Path, required=True) + parser.add_argument("--models", type=int, default=25) + parser.add_argument("--metrics", type=int, default=8) + parser.add_argument("--repeats", type=int, default=7) + parser.add_argument("--warmups", type=int, default=2) + args = parser.parse_args() + version = subprocess.check_output([str(args.binary), "--version"], text=True).strip() + print( + json.dumps( + { + "host": version, + "extension": str(args.extension.resolve()), + "models": args.models, + "metrics_per_model": args.metrics, + "repeats": args.repeats, + "warmups": args.warmups, + "without_extension": run(args.binary, None, args.models, args.metrics, args.repeats, args.warmups), + "with_extension": run( + args.binary, args.extension, args.models, args.metrics, args.repeats, args.warmups + ), + }, + indent=2, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/sqlctx-duckdb/src/include/sqlctx_catalog.hpp b/sqlctx-duckdb/src/include/sqlctx_catalog.hpp index 1c1deeb4f..2462d469d 100644 --- a/sqlctx-duckdb/src/include/sqlctx_catalog.hpp +++ b/sqlctx-duckdb/src/include/sqlctx_catalog.hpp @@ -5,17 +5,25 @@ namespace duckdb { +class QueryNode; + struct SqlctxCatalogSnapshot { string payload; string active_model; + string catalog; }; // Resolve definitions against the caller's current catalog transaction. Legacy // sidecars are read only when no native snapshot exists and are never modified. -SqlctxCatalogSnapshot ReadSqlctxCatalog(ClientContext &context); +SqlctxCatalogSnapshot ReadSqlctxCatalog(ClientContext &context, const string &catalog = ""); +vector SqlctxCatalogNames(ClientContext &context); + +// Physical sources compiled from a model belong to its catalog, even when the +// caller selected it through an attachment from a different current database. +void QualifySqlctxSources(ClientContext &context, QueryNode &node, const string &catalog); // Virtual semantic relations are exposed through the host's standard catalogs. -bool SqlctxPhysicalRelationExists(ClientContext &context, const string &model); +bool SqlctxPhysicalRelationExists(ClientContext &context, const string &model, const string &catalog = ""); struct SqlctxPhysicalRelation { string catalog; @@ -32,13 +40,13 @@ string SqlctxErrorText(string error); // The result type of one semantic field, bound against the current database. LogicalType SqlctxFieldType(ClientContext &context, const string &snapshot, const string &model, - const string &field); + const string &field, const string &catalog = ""); // The table or view an unqualified name binds to natively, if any. bool SqlctxFindPhysicalRelation(ClientContext &context, const string &name, SqlctxPhysicalRelation &relation); void RegisterSqlctxDiscovery(DatabaseInstance &db); -void RegisterSqlctxCatalogRead(ClientContext &context, StatementProperties &properties); +void RegisterSqlctxCatalogRead(ClientContext &context, StatementProperties &properties, const string &catalog = ""); void RegisterSqlctxCatalogWrite(ClientContext &context, StatementProperties &properties); // Supported operations: model, item, use, yaml, file. Returns a summary of diff --git a/sqlctx-duckdb/src/include/sqlctx_compat.hpp.in b/sqlctx-duckdb/src/include/sqlctx_compat.hpp.in index cca7435ba..07f14fb15 100644 --- a/sqlctx-duckdb/src/include/sqlctx_compat.hpp.in +++ b/sqlctx-duckdb/src/include/sqlctx_compat.hpp.in @@ -12,6 +12,8 @@ #cmakedefine01 SQLCTX_GRAMMAR_EXTENSION_LIST #cmakedefine01 SQLCTX_ARENA_TRANSFORM #cmakedefine01 SQLCTX_SHELL_GRAMMAR_CONTEXT +#cmakedefine01 SQLCTX_PRE_BIND +#cmakedefine01 SQLCTX_VECTOR_APPEND #include "duckdb/parser/parser_options.hpp" #if SQLCTX_NEW_IDENTIFIER_API diff --git a/sqlctx-duckdb/src/include/sqlctx_compiler.hpp b/sqlctx-duckdb/src/include/sqlctx_compiler.hpp new file mode 100644 index 000000000..ba959cd82 --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_compiler.hpp @@ -0,0 +1,37 @@ +#pragma once + +#include "sqlctx.h" +#include "duckdb/common/exception.hpp" +#include "duckdb/common/types.hpp" + +namespace duckdb { + +// Only the semantic graph is retained. DuckDB source binding stays live in the +// caller's transaction. Input snapshot bytes are borrowed only during creation. +class SqlctxCompilerOwner { +public: + explicit SqlctxCompilerOwner(const string &snapshot) { + char *error = nullptr; + compiler = sqlctx_compiler_create(snapshot.c_str(), &error); + if (!compiler) { + string message = error ? error : "cannot create semantic compiler"; + sqlctx_free(error); + throw InvalidInputException("sqlctx: %s", message); + } + } + ~SqlctxCompilerOwner() { sqlctx_compiler_free(compiler); } + SqlctxCompilerOwner(const SqlctxCompilerOwner &) = delete; + SqlctxCompilerOwner &operator=(const SqlctxCompilerOwner &) = delete; + + SqlctxRewriteResult Rewrite(const string &sql) const { + return sqlctx_compiler_rewrite(compiler, sql.c_str()); + } + +private: + SqlctxCompiler *compiler = nullptr; +}; + +LogicalType SqlctxFieldType(ClientContext &context, const SqlctxCompilerOwner &compiler, + const string &model, const string &field, const string &catalog_name); + +} // namespace duckdb diff --git a/sqlctx-duckdb/src/include/sqlctx_explain.hpp b/sqlctx-duckdb/src/include/sqlctx_explain.hpp new file mode 100644 index 000000000..07e53fe98 --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_explain.hpp @@ -0,0 +1,7 @@ +#pragma once + +#include "duckdb/main/extension/extension_loader.hpp" + +namespace duckdb { +void RegisterSqlctxExplain(ExtensionLoader &loader); +} diff --git a/sqlctx-duckdb/src/include/sqlctx_parser.hpp b/sqlctx-duckdb/src/include/sqlctx_parser.hpp index ab0d760cb..be853aa73 100644 --- a/sqlctx-duckdb/src/include/sqlctx_parser.hpp +++ b/sqlctx-duckdb/src/include/sqlctx_parser.hpp @@ -7,6 +7,12 @@ #include "duckdb/planner/operator_extension.hpp" namespace duckdb { +class ExtensionLoader; + +struct SqlctxParserInfo : ParserExtensionInfo { + explicit SqlctxParserInfo(DatabaseInstance &database_p) : database(database_p) {} + DatabaseInstance &database; +}; struct SqlctxParseData : ParserExtensionParseData { // Definitions carry source only. Mutation is deferred until execution. @@ -22,7 +28,8 @@ struct SqlctxParseData : ParserExtensionParseData { unique_ptr SqlctxStatement(unique_ptr data); unique_ptr ParseSqlctxDefinition(const string &sql); -unique_ptr WrapSqlctxQuery(unique_ptr statement, bool explicit_semantic = false); +unique_ptr WrapSqlctxQuery(unique_ptr statement, bool explicit_semantic = false, + const string &source_override = "", const ParserOptions *parser_options = nullptr); ParserOverrideResult sqlctx_parser_override(ParserExtensionInfo *, const string &, ParserOptions &); #if SQLCTX_TOKEN_PARSE_FN @@ -34,6 +41,7 @@ ParserExtensionPlanResult sqlctx_plan(ParserExtensionInfo *, ClientContext &, unique_ptr); BoundStatement sqlctx_bind(ClientContext &, Binder &, OperatorExtensionInfo *, SQLStatement &); void RegisterSqlctxRouting(DatabaseInstance &db); +void RegisterSqlctxQueryCarrier(ExtensionLoader &loader); struct SqlctxParserExtension : ParserExtension { SqlctxParserExtension() { diff --git a/sqlctx-duckdb/src/include/sqlctx_semantic_input.hpp b/sqlctx-duckdb/src/include/sqlctx_semantic_input.hpp new file mode 100644 index 000000000..19c6a254b --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_semantic_input.hpp @@ -0,0 +1,7 @@ +#pragma once + +#include "duckdb/main/extension/extension_loader.hpp" + +namespace duckdb { +void RegisterSqlctxSemanticInput(ExtensionLoader &loader); +} // namespace duckdb diff --git a/sqlctx-duckdb/src/sqlctx_api.cpp b/sqlctx-duckdb/src/sqlctx_api.cpp index 3c554e552..70d28a1ce 100644 --- a/sqlctx-duckdb/src/sqlctx_api.cpp +++ b/sqlctx-duckdb/src/sqlctx_api.cpp @@ -1,5 +1,6 @@ #include "sqlctx_api.hpp" #include "sqlctx_catalog.hpp" +#include "sqlctx_compiler.hpp" #include "sqlctx_compat.hpp" #include "sqlctx.h" @@ -14,8 +15,6 @@ struct CatalogBindData : TableFunctionData { string kind; string model; string metric; - // Result types of fields without a declared data type, by qualified name. - case_insensitive_map_t result_types; }; struct CatalogState : GlobalTableFunctionState { @@ -23,32 +22,6 @@ struct CatalogState : GlobalTableFunctionState { idx_t offset = 0; }; -// Report the type a field produces, as information_schema does, when its -// definition declares none. Fields whose source cannot bind stay NULL. -static void BindResultTypes(ClientContext &context, CatalogBindData &data) { - auto snapshot = ReadSqlctxCatalog(context); - if (snapshot.payload.empty()) return; - struct CatalogResult { - SqlctxCatalogEntries result; - ~CatalogResult() { sqlctx_free_catalog_entries(result); } - } result {sqlctx_snapshot_catalog(snapshot.payload.c_str(), data.kind.c_str(), data.model.c_str(), - data.metric.empty() ? nullptr : data.metric.c_str())}; - if (result.result.error) return; - for (idx_t i = 0; i < result.result.count; ++i) { - auto &entry = result.result.entries[i]; - string kind(entry.kind); - if (entry.data_type || !entry.model_name || (kind != "dimension" && kind != "metric")) continue; - try { - data.result_types[entry.qualified_name] = - SqlctxFieldType(context, snapshot.payload, entry.model_name, entry.name).ToString(); - } catch (const std::exception &exception) { - auto error = ErrorData(exception); - if (error.Type() == ExceptionType::INTERRUPT || error.Type() == ExceptionType::INTERNAL || - error.Type() == ExceptionType::FATAL) throw; - } - } -} - static unique_ptr CatalogBind(ClientContext &context, TableFunctionBindInput &input, vector &types, vector &names) { if (input.binder) RegisterSqlctxCatalogRead(context, input.binder->GetStatementProperties()); @@ -70,7 +43,6 @@ static unique_ptr CatalogBind(ClientContext &context, TableFunctio types.emplace_back(LogicalType::BOOLEAN); names.emplace_back("definition"); types.emplace_back(LogicalType::VARCHAR); - BindResultTypes(context, *data); return std::move(data); } @@ -96,6 +68,7 @@ static unique_ptr CatalogInit(ClientContext &context, } result {sqlctx_snapshot_catalog(snapshot.payload.c_str(), data.kind.c_str(), data.model.c_str(), data.metric.empty() ? nullptr : data.metric.c_str())}; if (result.result.error) throw InvalidInputException("sqlctx: %s", SqlctxErrorText(result.result.error)); + unique_ptr compiler; for (idx_t i = 0; i < result.result.count; ++i) { auto &entry = result.result.entries[i]; vector row; @@ -104,8 +77,19 @@ static unique_ptr CatalogInit(ClientContext &context, entry.target_model, entry.relationship_type, entry.granularity}) { row.push_back(value ? Value(value) : Value(LogicalType::VARCHAR)); } - auto result_type = data.result_types.find(entry.qualified_name); - if (!entry.data_type && result_type != data.result_types.end()) row[7] = Value(result_type->second); + // Bind against the live caller transaction on every execution, after + // selecting the requested model/kind. Retain only the decoded graph. + string kind(entry.kind); + if (!entry.data_type && entry.model_name && (kind == "dimension" || kind == "metric")) { + if (!compiler) compiler = make_uniq(snapshot.payload); + try { + row[7] = Value(SqlctxFieldType(context, *compiler, entry.model_name, entry.name, snapshot.catalog).ToString()); + } catch (const std::exception &exception) { + auto error = ErrorData(exception); + if (error.Type() == ExceptionType::INTERRUPT || error.Type() == ExceptionType::INTERNAL || + error.Type() == ExceptionType::FATAL) throw; + } + } row.push_back(Value::BOOLEAN(entry.is_public)); row.push_back(Value(entry.definition)); state->rows.push_back(std::move(row)); diff --git a/sqlctx-duckdb/src/sqlctx_catalog.cpp b/sqlctx-duckdb/src/sqlctx_catalog.cpp index 708890ecc..960668369 100644 --- a/sqlctx-duckdb/src/sqlctx_catalog.cpp +++ b/sqlctx-duckdb/src/sqlctx_catalog.cpp @@ -10,7 +10,17 @@ #include "duckdb/main/client_context_state.hpp" #include "duckdb/main/database_manager.hpp" #include "duckdb/parser/expression/constant_expression.hpp" +#include "duckdb/parser/expression/subquery_expression.hpp" +#include "duckdb/parser/parsed_expression_iterator.hpp" #include "duckdb/parser/parsed_data/create_macro_info.hpp" +#include "duckdb/parser/query_node/select_node.hpp" +#include "duckdb/parser/query_node/set_operation_node.hpp" +#include "duckdb/parser/query_node/recursive_cte_node.hpp" +#include "duckdb/parser/query_node/cte_node.hpp" +#include "duckdb/parser/tableref/basetableref.hpp" +#include "duckdb/parser/tableref/joinref.hpp" +#include "duckdb/parser/tableref/subqueryref.hpp" +#include "duckdb/parser/tableref/table_function_ref.hpp" #include "duckdb/planner/binder.hpp" #include "duckdb/storage/storage_manager.hpp" #include @@ -59,8 +69,13 @@ class SqlctxCatalogSession : public ClientContextState { } }; -static Catalog &SemanticCatalog(ClientContext &context) { - return Catalog::GetCatalog(context, DatabaseManager::GetDefaultDatabase(context)); +static Catalog &SemanticCatalog(ClientContext &context, const string &name = "") { + if (name.empty()) return Catalog::GetCatalog(context, DatabaseManager::GetDefaultDatabase(context)); +#if SQLCTX_NEW_IDENTIFIER_API + return Catalog::GetCatalog(context, Identifier(name)); +#else + return Catalog::GetCatalog(context, name); +#endif } static shared_ptr Session(ClientContext &context) { @@ -150,7 +165,7 @@ static SqlctxSnapshotResult ImportDefinitionFiles(ClientContext &context, const static SqlctxCatalogSnapshot ReadLegacySnapshot(ClientContext &context, Catalog &catalog) { auto &database = catalog.GetAttached(); - if (catalog.InMemory() || !database.HasStorageManager()) { + if (!database.HasStorageManager() || catalog.InMemory()) { return {}; } auto path = database.GetStorageManager().GetDBPath(); @@ -190,8 +205,8 @@ static optional_ptr FindCatalogMacro(ClientContext &context, Catal #endif } -SqlctxCatalogSnapshot ReadSqlctxCatalog(ClientContext &context) { - auto &catalog = SemanticCatalog(context); +SqlctxCatalogSnapshot ReadSqlctxCatalog(ClientContext &context, const string &catalog_name) { + auto &catalog = SemanticCatalog(context, catalog_name); auto state = Session(context); auto entry = FindCatalogMacro(context, catalog, CATALOG_MACRO); if (!entry) { @@ -234,11 +249,123 @@ SqlctxCatalogSnapshot ReadSqlctxCatalog(ClientContext &context) { if (active != state->active_models.end()) { snapshot.active_model = active->second; } + snapshot.catalog = SqlctxName(catalog.GetName()); return snapshot; } -void RegisterSqlctxCatalogRead(ClientContext &context, StatementProperties &properties) { - properties.RegisterDBRead(SemanticCatalog(context), context); +vector SqlctxCatalogNames(ClientContext &context) { + vector names; + for (auto &database : DatabaseManager::Get(context).GetDatabases(context)) { + if (database->IsSystem()) continue; + names.push_back(SqlctxName(database->GetName())); + } + std::sort(names.begin(), names.end()); + return names; +} + +// Walk lexical CTE scopes rather than treating every base reference as a +// physical table. Compiled semantic SQL uses CTEs for aggregation and joins. +class SqlctxSourceQualifier { +public: + SqlctxSourceQualifier(const string &catalog, const string &schema) : catalog(catalog), default_schema(schema) {} + + void Query(QueryNode &node, case_insensitive_set_t ctes = {}) { + for (auto &cte : node.cte_map.map) { +#if SQLCTX_NEW_IDENTIFIER_API + Query(*cte.second->query_node, ctes); +#else + Query(*cte.second->query->node, ctes); +#endif + ctes.insert(SqlctxName(cte.first)); + } + if (node.type == QueryNodeType::SET_OPERATION_NODE) { + for (auto &child : node.Cast().children) Query(*child, ctes); + } else if (node.type == QueryNodeType::RECURSIVE_CTE_NODE) { + auto &recursive = node.Cast(); + ctes.insert(SqlctxName(recursive.ctename)); + Query(*recursive.left, ctes); + Query(*recursive.right, ctes); + } else if (node.type == QueryNodeType::CTE_NODE) { + auto &cte = node.Cast(); + Query(*cte.query, ctes); + ctes.insert(SqlctxName(cte.ctename)); + Query(*cte.child, ctes); + } else if (node.type == QueryNodeType::SELECT_NODE) { + auto &select = node.Cast(); + for (auto &expression : select.select_list) Expression(*expression, ctes); + for (auto &expression : select.groups.group_expressions) Expression(*expression, ctes); + if (select.where_clause) Expression(*select.where_clause, ctes); + if (select.having) Expression(*select.having, ctes); + if (select.qualify) Expression(*select.qualify, ctes); + if (select.from_table) Table(*select.from_table, ctes); + } + ParsedExpressionIterator::EnumerateQueryNodeModifiers(node, [&](unique_ptr &expression) { + Expression(*expression, ctes); + }); + } + +private: + const string &catalog; + const string &default_schema; + + void Expression(ParsedExpression &expression, const case_insensitive_set_t &ctes) { + if (expression.GetExpressionClass() == ExpressionClass::SUBQUERY) { +#if SQLCTX_NEW_EXPRESSION_API + Query(*expression.Cast().Subquery()->node, ctes); +#else + Query(*expression.Cast().subquery->node, ctes); +#endif + } + ParsedExpressionIterator::EnumerateChildren(expression, [&](ParsedExpression &child) { Expression(child, ctes); }); + } + + void Table(TableRef &ref, const case_insensitive_set_t &ctes) { + if (ref.type == TableReferenceType::BASE_TABLE) { + auto &table = ref.Cast(); +#if SQLCTX_QUALIFIED_TABLE_API + auto name = SqlctxName(table.Table()); + auto schema = SqlctxName(table.GetQualifiedName().Schema()); + if (!table.GetQualifiedName().Catalog().empty()) return; + if (schema.empty() && ctes.count(name)) return; + table.SetQualifiedName(Identifier(catalog), Identifier(schema.empty() ? default_schema : schema), Identifier(name)); +#else + if (!table.catalog_name.empty()) return; + if (table.schema_name.empty() && ctes.count(table.table_name)) return; + table.catalog_name = catalog; + if (table.schema_name.empty()) table.schema_name = default_schema; +#endif + } else if (ref.type == TableReferenceType::SUBQUERY) { + Query(*ref.Cast().subquery->node, ctes); + } else if (ref.type == TableReferenceType::JOIN) { + auto &join = ref.Cast(); + Table(*join.left, ctes); + Table(*join.right, ctes); + if (join.condition) Expression(*join.condition, ctes); + } else if (ref.type == TableReferenceType::TABLE_FUNCTION) { + auto &function = ref.Cast(); + if (function.subquery) Query(*function.subquery->node, ctes); + if (function.function) Expression(*function.function, ctes); + } else { + ParsedExpressionIterator::EnumerateTableRefChildren(ref, [&](unique_ptr &expression) { + Expression(*expression, ctes); + }); + } + } +}; + +void QualifySqlctxSources(ClientContext &context, QueryNode &node, const string &catalog) { + if (catalog.empty()) return; + auto schema = SemanticCatalog(context, catalog).GetDefaultSchema(); +#if SQLCTX_NEW_IDENTIFIER_API + auto default_schema = schema ? SqlctxName(*schema) : string(DEFAULT_SCHEMA); +#else + auto default_schema = schema.empty() ? string(DEFAULT_SCHEMA) : schema; +#endif + SqlctxSourceQualifier(catalog, default_schema).Query(node); +} + +void RegisterSqlctxCatalogRead(ClientContext &context, StatementProperties &properties, const string &catalog_name) { + properties.RegisterDBRead(SemanticCatalog(context, catalog_name), context); // A prepared semantic query must also observe connection-local MODEL changes. properties.always_require_rebind = true; } diff --git a/sqlctx-duckdb/src/sqlctx_discovery.cpp b/sqlctx-duckdb/src/sqlctx_discovery.cpp index c68adbd7d..d54f07654 100644 --- a/sqlctx-duckdb/src/sqlctx_discovery.cpp +++ b/sqlctx-duckdb/src/sqlctx_discovery.cpp @@ -1,4 +1,5 @@ #include "sqlctx_catalog.hpp" +#include "sqlctx_compiler.hpp" #include "sqlctx_compat.hpp" #include "sqlctx.h" @@ -10,7 +11,11 @@ #include "duckdb/main/config.hpp" #include "duckdb/main/database_manager.hpp" #include "duckdb/parser/parser.hpp" +#include "duckdb/parser/statement/select_statement.hpp" #include "duckdb/planner/binder.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression_iterator.hpp" #include "duckdb/planner/operator/logical_get.hpp" #include "duckdb/planner/operator/logical_set_operation.hpp" #include "duckdb/planner/planner_extension.hpp" @@ -61,7 +66,6 @@ struct SemanticColumn { string name; idx_t ordinal = 0; Value comment; - LogicalType type = LogicalTypeId::INVALID; }; struct SemanticRelation { @@ -73,6 +77,7 @@ struct SemanticRelation { struct SemanticMetadata { string database; + string snapshot; int64_t database_oid = 0; int64_t schema_oid = 0; bool physical_schema = false; @@ -82,9 +87,15 @@ struct SemanticMetadata { } // namespace LogicalType SqlctxFieldType(ClientContext &context, const string &snapshot, const string &model, - const string &field) { + const string &field, const string &catalog_name) { + SqlctxCompilerOwner compiler(snapshot); + return SqlctxFieldType(context, compiler, model, field, catalog_name); +} + +LogicalType SqlctxFieldType(ClientContext &context, const SqlctxCompilerOwner &compiler, const string &model, + const string &field, const string &catalog_name) { auto sql = "SELECT " + QuoteName(model) + "." + QuoteName(field) + " FROM " + QuoteName(model); - auto result = sqlctx_snapshot_rewrite(snapshot.c_str(), sql.c_str()); + auto result = compiler.Rewrite(sql); string compiled = result.sql ? result.sql : ""; string error = result.error ? result.error : ""; sqlctx_free_result(result); @@ -92,6 +103,9 @@ LogicalType SqlctxFieldType(ClientContext &context, const string &snapshot, cons Parser parser(SqlctxBuiltinParserOptions()); parser.ParseQuery(compiled); if (parser.statements.size() != 1) throw BinderException("Semantic field must compile to one query"); + if (!catalog_name.empty() && !StringUtil::CIEquals(catalog_name, SqlctxName(DatabaseManager::GetDefaultDatabase(context)))) { + QualifySqlctxSources(context, *parser.statements[0]->Cast().node, catalog_name); + } auto binder = Binder::CreateBinder(context); auto bound = binder->Bind(*parser.statements[0]); if (bound.types.size() != 1) throw BinderException("Semantic field must produce one column"); @@ -100,15 +114,15 @@ LogicalType SqlctxFieldType(ClientContext &context, const string &snapshot, cons namespace { -SemanticMetadata ReadMetadata(ClientContext &context) { +SemanticMetadata ReadMetadata(ClientContext &context, const string &catalog_name, unordered_set &used) { SemanticMetadata metadata; - auto &catalog = Catalog::GetCatalog(context, DatabaseManager::GetDefaultDatabase(context)); + auto &catalog = Catalog::GetCatalog(context, SqlctxIdentifier(catalog_name)); metadata.database = SqlctxName(catalog.GetName()); metadata.database_oid = NumericCast(catalog.GetOid()); - auto snapshot = ReadSqlctxCatalog(context); + auto snapshot = ReadSqlctxCatalog(context, catalog_name); if (snapshot.payload.empty()) return metadata; + metadata.snapshot = snapshot.payload; CatalogEntriesOwner entries(snapshot.payload); - unordered_set used; case_insensitive_set_t physical_relations; for (auto &schema_ref : Catalog::GetAllSchemas(context)) { auto &schema = schema_ref.get(); @@ -143,16 +157,6 @@ SemanticMetadata ReadMetadata(ClientContext &context) { column.name = field.name; column.ordinal = field.column_index; column.comment = field.description ? Value(field.description) : Value(); - try { - column.type = SqlctxFieldType(context, snapshot.payload, relation.name, column.name); - } catch (const std::exception &exception) { - // Like DuckDB's unbound views, keep the relation discoverable - // without inventing a physical type for an unavailable source. - // Do not hide cancellation or an engine invariant failure. - auto error = ErrorData(exception); - if (error.Type() == ExceptionType::INTERRUPT || error.Type() == ExceptionType::INTERNAL || - error.Type() == ExceptionType::FATAL) throw; - } relation.columns.push_back(std::move(column)); } std::sort(relation.columns.begin(), relation.columns.end(), @@ -164,27 +168,44 @@ SemanticMetadata ReadMetadata(ClientContext &context) { struct DiscoveryRows : public TableFunctionData { vector> rows; + vector names; + vector metadata; + string function; + // Equality hints are kept in the ordinary plan too. Only names, never + // deferred type values, can eliminate a row before physical binding. + vector> equalities; }; struct DiscoveryState : public GlobalTableFunctionState { + vector> rows; + vector column_ids; idx_t offset = 0; }; -unique_ptr InitDiscovery(ClientContext &, TableFunctionInitInput &) { - return make_uniq(); -} +unique_ptr InitDiscovery(ClientContext &, TableFunctionInitInput &); void ScanDiscovery(ClientContext &, TableFunctionInput &input, DataChunk &output) { - auto &data = input.bind_data->Cast(); auto &state = input.global_state->Cast(); - auto count = MinValue(STANDARD_VECTOR_SIZE, data.rows.size() - state.offset); + auto count = MinValue(STANDARD_VECTOR_SIZE, state.rows.size() - state.offset); for (idx_t row = 0; row < count; ++row) { for (idx_t column = 0; column < output.ColumnCount(); ++column) { - output.SetValue(column, row, data.rows[state.offset + row][column]); + auto id = state.column_ids[column]; + auto value = id == COLUMN_IDENTIFIER_ROW_ID ? Value::BIGINT(0) : state.rows[state.offset + row][id]; +#if SQLCTX_VECTOR_APPEND + // DuckDB 2 derives expression cardinality from each vector, not + // just the chunk. SetValue does not advance those vector sizes. + output.data[column].Append(value); +#else + output.SetValue(column, row, value); +#endif } } state.offset += count; +#if SQLCTX_VECTOR_APPEND + output.CheckCardinality(count); +#else output.SetCardinality(count); +#endif } void NumericMetadata(const LogicalType &type, Value &precision, Value &radix, Value &scale) { @@ -241,8 +262,8 @@ unique_ptr BuildRows(const SemanticMetadata &metadata, const stri values["comment"] = relation.comment; values["temporary"] = Value::BOOLEAN(false); values["column_count"] = Value::BIGINT(relation.columns.size()); - values["is_bound"] = Value::BOOLEAN(std::all_of(relation.columns.begin(), relation.columns.end(), - [](const SemanticColumn &column) { return column.type.id() != LogicalTypeId::INVALID; })); + // Populated in InitDiscovery only when requested by the plan. + values["is_bound"] = Value::BOOLEAN(false); append(values); } else { values["table_name"] = Value(relation.name); @@ -255,11 +276,6 @@ unique_ptr BuildRows(const SemanticMetadata &metadata, const stri row["column_name"] = Value(column.name); row["column_index"] = Value::INTEGER(i + 1); row["comment"] = column.comment; - if (column.type.id() != LogicalTypeId::INVALID) { - row["data_type"] = Value(column.type.ToString()); - row["data_type_id"] = Value::BIGINT(static_cast(column.type.id())); - NumericMetadata(column.type, row["numeric_precision"], row["numeric_precision_radix"], row["numeric_scale"]); - } append(row); } } @@ -267,8 +283,120 @@ unique_ptr BuildRows(const SemanticMetadata &metadata, const stri return result; } +void RestrictDiscovery(ClientContext &, LogicalGet &get, FunctionData *bind_data, + vector> &filters) { + auto &data = bind_data->Cast(); + for (auto &filter : filters) { + if (filter->GetExpressionType() != ExpressionType::COMPARE_EQUAL) continue; + const BoundColumnRefExpression *column = nullptr; + const BoundConstantExpression *constant = nullptr; + idx_t children = 0; + ExpressionIterator::EnumerateChildren(*filter, [&](const Expression &child) { + ++children; + if (child.GetExpressionClass() == ExpressionClass::BOUND_COLUMN_REF) { + column = &child.Cast(); + } else if (child.GetExpressionClass() == ExpressionClass::BOUND_CONSTANT) { + constant = &child.Cast(); + } + }); + if (children != 2 || !column || !constant) continue; +#if SQLCTX_NEW_EXPRESSION_API + auto &binding = column->Binding(); + auto column_index = binding.column_index.GetIndex(); + auto &value = constant->GetValue(); +#else + auto &binding = column->binding; + auto column_index = binding.column_index; + auto &value = constant->value; +#endif + if (binding.table_index != get.table_index || value.IsNull() || value.type() != LogicalType::VARCHAR) continue; + auto id = get.GetColumnIds()[column_index].GetPrimaryIndex(); + if (id >= data.names.size()) continue; + auto &name = SqlctxName(data.names[id]); + if (name == "database_name" || name == "schema_name" || name == "table_name" || + name == "view_name" || name == "column_name") { + data.equalities.emplace_back(id, value); + } + } +} + +LogicalType BindFieldType(ClientContext &context, const SemanticMetadata &metadata, + const SqlctxCompilerOwner &compiler, const string &model, const string &field) { + try { + return SqlctxFieldType(context, compiler, model, field, metadata.database); + } catch (const std::exception &exception) { + // Match unbound views: missing sources remain visible with NULL types. + // Cancellation and engine invariant failures must still reach the caller. + auto error = ErrorData(exception); + if (error.Type() == ExceptionType::INTERRUPT || error.Type() == ExceptionType::INTERNAL || + error.Type() == ExceptionType::FATAL) throw; + return LogicalTypeId::INVALID; + } +} + +unique_ptr InitDiscovery(ClientContext &context, TableFunctionInitInput &input) { + auto &data = input.bind_data->Cast(); + auto state = make_uniq(); + state->column_ids = input.column_ids; + unordered_map indexes; + for (idx_t i = 0; i < data.names.size(); ++i) indexes[SqlctxName(data.names[i])] = i; + unordered_set requested; + for (auto id : input.column_ids) { + if (id < data.names.size()) requested.insert(SqlctxName(data.names[id])); + } + bool bind_types = requested.count("is_bound") || requested.count("data_type") || requested.count("data_type_id") || + requested.count("numeric_precision") || requested.count("numeric_precision_radix") || requested.count("numeric_scale"); + unordered_map> compilers; + for (auto &original : data.rows) { + bool matches = true; + for (auto &equality : data.equalities) { + if (original[equality.first].IsNull() || + original[equality.first].GetValue() != equality.second.GetValue()) { + matches = false; + break; + } + } + if (!matches) continue; + auto row = original; + if (bind_types && data.function != "duckdb_schemas") { + auto database = row[indexes.at("database_name")].GetValue(); + auto model = row[indexes.at(data.function == "duckdb_views" ? "view_name" : "table_name")].GetValue(); + for (auto &metadata : data.metadata) { + if (metadata.database != database) continue; + auto &compiler = compilers[database]; + if (!compiler) compiler = make_uniq(metadata.snapshot); + if (data.function == "duckdb_views") { + for (auto &relation : metadata.relations) { + if (relation.name != model) continue; + bool bound = true; + for (auto &column : relation.columns) { + if (BindFieldType(context, metadata, *compiler, model, column.name).id() == LogicalTypeId::INVALID) { + bound = false; + break; + } + } + row[indexes.at("is_bound")] = Value::BOOLEAN(bound); + } + } else { + auto field = row[indexes.at("column_name")].GetValue(); + auto type = BindFieldType(context, metadata, *compiler, model, field); + if (type.id() != LogicalTypeId::INVALID) { + row[indexes.at("data_type")] = Value(type.ToString()); + row[indexes.at("data_type_id")] = Value::BIGINT(static_cast(type.id())); + NumericMetadata(type, row[indexes.at("numeric_precision")], + row[indexes.at("numeric_precision_radix")], row[indexes.at("numeric_scale")]); + } + } + break; + } + } + state->rows.push_back(std::move(row)); + } + return std::move(state); +} + void OverlayScans(PlannerExtensionInput &input, unique_ptr &plan, - unique_ptr &metadata) { + unique_ptr> &metadata) { // PREPARE has a nested planner. Its child can already contain this overlay. if (plan->type == LogicalOperatorType::LOGICAL_UNION) { for (auto &child : plan->children) { @@ -281,12 +409,27 @@ void OverlayScans(PlannerExtensionInput &input, unique_ptr &pla auto &get = plan->Cast(); auto name = ScanName(get); if (name != "duckdb_columns" && name != "duckdb_views" && name != "duckdb_schemas") return; - RegisterSqlctxCatalogRead(input.context, input.binder.GetStatementProperties()); - if (!metadata) metadata = make_uniq(ReadMetadata(input.context)); - if (metadata->relations.empty()) return; - auto rows = BuildRows(*metadata, name, get.names, get.returned_types); + if (!metadata) { + metadata = make_uniq>(); + unordered_set used; + for (auto &catalog : SqlctxCatalogNames(input.context)) { + RegisterSqlctxCatalogRead(input.context, input.binder.GetStatementProperties(), catalog); + auto entry = ReadMetadata(input.context, catalog, used); + if (!entry.relations.empty()) metadata->push_back(std::move(entry)); + } + } + auto rows = make_uniq(); + rows->names = get.names; + rows->metadata = *metadata; + rows->function = name; + for (auto &entry : *metadata) { + auto catalog_rows = BuildRows(entry, name, get.names, get.returned_types); + for (auto &row : catalog_rows->rows) rows->rows.push_back(std::move(row)); + } if (rows->rows.empty()) return; TableFunction function("sqlctx_catalog_scan", {}, ScanDiscovery, nullptr, InitDiscovery); + function.projection_pushdown = true; + function.pushdown_complex_filter = RestrictDiscovery; #if SQLCTX_BOUND_TABLE_FUNCTION auto extra = make_uniq(input.binder.GenerateTableIndex(), BoundTableFunction(function), std::move(rows), get.returned_types, get.names); @@ -305,14 +448,15 @@ void OverlayScans(PlannerExtensionInput &input, unique_ptr &pla void DiscoveryPostBind(PlannerExtensionInput &input, BoundStatement &statement) { if (!statement.plan) return; - unique_ptr metadata; + unique_ptr> metadata; OverlayScans(input, statement.plan, metadata); } } // namespace -bool SqlctxPhysicalRelationExists(ClientContext &context, const string &model) { - auto &catalog = Catalog::GetCatalog(context, DatabaseManager::GetDefaultDatabase(context)); +bool SqlctxPhysicalRelationExists(ClientContext &context, const string &model, const string &catalog_name) { + auto &catalog = Catalog::GetCatalog(context, catalog_name.empty() + ? DatabaseManager::GetDefaultDatabase(context) : SqlctxIdentifier(catalog_name)); #if SQLCTX_NEW_IDENTIFIER_API EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, QualifiedName(catalog.GetName(), Identifier(SEMANTIC_SCHEMA), Identifier(model))); diff --git a/sqlctx-duckdb/src/sqlctx_explain.cpp b/sqlctx-duckdb/src/sqlctx_explain.cpp new file mode 100644 index 000000000..5aebe0786 --- /dev/null +++ b/sqlctx-duckdb/src/sqlctx_explain.cpp @@ -0,0 +1,48 @@ +#include "sqlctx_explain.hpp" +#include "sqlctx_catalog.hpp" +#include "sqlctx.h" +#include "duckdb/common/vector_operations/unary_executor.hpp" +#include "duckdb/function/scalar_function.hpp" +#include "duckdb/execution/expression_executor_state.hpp" +#include + +namespace duckdb { + +static void ExplainFunction(DataChunk &args, ExpressionState &state, Vector &result) { + auto snapshot = ReadSqlctxCatalog(state.GetContext()); + char *error = nullptr; + std::unique_ptr compiler( + sqlctx_compiler_create(snapshot.payload.c_str(), &error), sqlctx_compiler_free); + if (error) { + string message(error); + sqlctx_free(error); + throw InvalidInputException("sqlctx: %s", SqlctxErrorText(message)); + } + if (!compiler) throw InternalException("sqlctx returned no compiler"); + UnaryExecutor::Execute(args.data[0], result, args.size(), [&](string_t input) { + auto sql = input.GetString(); + if (sql.find('\0') != string::npos) throw InvalidInputException("sqlctx SQL contains a NUL byte"); + auto report = sqlctx_compiler_explain(compiler.get(), sql.c_str()); + if (report.error) { + string error(report.error); + sqlctx_free_result(report); + throw InvalidInputException("sqlctx: %s", SqlctxErrorText(error)); + } + if (!report.sql) { + sqlctx_free_result(report); + throw InternalException("sqlctx returned no explanation"); + } + string json(report.sql); + sqlctx_free_result(report); + return StringVector::AddString(result, json); + }); +} + +void RegisterSqlctxExplain(ExtensionLoader &loader) { + auto explain = ScalarFunction("sqlctx_explain", {LogicalType::VARCHAR}, LogicalType::VARCHAR, ExplainFunction); + explain.SetStability(FunctionStability::VOLATILE); + explain.SetFallible(); + loader.RegisterFunction(explain); +} + +} // namespace duckdb diff --git a/sqlctx-duckdb/src/sqlctx_extension.cpp b/sqlctx-duckdb/src/sqlctx_extension.cpp index 5fb0a8860..d0b1bc014 100644 --- a/sqlctx-duckdb/src/sqlctx_extension.cpp +++ b/sqlctx-duckdb/src/sqlctx_extension.cpp @@ -1,12 +1,13 @@ #define DUCKDB_EXTENSION_MAIN #include "sqlctx_extension.hpp" +#include "sqlctx_explain.hpp" #include "sqlctx_parser.hpp" #include "sqlctx_catalog.hpp" +#include "sqlctx_semantic_input.hpp" #include "sqlctx.h" #include "duckdb/function/table_function.hpp" -#include "duckdb/common/vector_operations/binary_executor.hpp" -#include "duckdb/common/vector_operations/ternary_executor.hpp" +#include "duckdb/common/vector_operations/unary_executor.hpp" namespace duckdb { @@ -102,56 +103,6 @@ static void RewriteFunction(DataChunk &args, ExpressionState &state, Vector &res }); } -// Stateless SemanticInput entrypoints retain policies in the canonical input. -// Reject NULs before crossing the C string boundary instead of truncating input. -static string SemanticInputArgument(string_t value) { - auto text = value.GetString(); - if (text.find('\0') != string::npos) { - throw InvalidInputException("SemanticInput argument contains a NUL byte"); - } - return text; -} - -static string_t SemanticInputResult(Vector &result, SqlctxRewriteResult compiled) { - if (compiled.error) { - string message(compiled.error); - sqlctx_free_result(compiled); - throw InvalidInputException("SemanticInput failed: %s", message); - } - if (!compiled.sql) { - sqlctx_free_result(compiled); - throw InvalidInputException("SemanticInput returned no SQL"); - } - string sql(compiled.sql); - sqlctx_free_result(compiled); - return StringVector::AddString(result, sql); -} - -static void SqlctxCompileSemanticInputFunction(DataChunk &args, ExpressionState &state, - Vector &result) { - BinaryExecutor::Execute( - args.data[0], args.data[1], result, args.size(), [&](string_t input, string_t query) { - auto input_json = SemanticInputArgument(input); - auto query_json = SemanticInputArgument(query); - return SemanticInputResult(result, - sqlctx_compile_semantic_input(input_json.c_str(), query_json.c_str())); - }); -} - -static void SqlctxRewriteSemanticInputFunction(DataChunk &args, ExpressionState &state, - Vector &result) { - TernaryExecutor::Execute( - args.data[0], args.data[1], args.data[2], result, args.size(), - [&](string_t input, string_t sql, string_t context) { - auto input_json = SemanticInputArgument(input); - auto sql_text = SemanticInputArgument(sql); - auto context_json = SemanticInputArgument(context); - return SemanticInputResult(result, sqlctx_rewrite_semantic_input( - input_json.c_str(), sql_text.c_str(), context_json.c_str())); - }); -} - - static void LoadInternal(ExtensionLoader &loader) { auto &db = loader.GetDatabaseInstance(); auto &config = DBConfig::GetConfig(db); @@ -161,7 +112,9 @@ static void LoadInternal(ExtensionLoader &loader) { ParserExtension::Register(config, parser); OperatorExtension::Register(config, make_shared_ptr()); RegisterSqlctxRouting(db); + RegisterSqlctxQueryCarrier(loader); RegisterSqlctxDiscovery(db); + RegisterSqlctxExplain(loader); loader.RegisterFunction(TableFunction("sqlctx_load", {LogicalType::VARCHAR}, LoadFunction, LoadBind, LoadInit)); loader.RegisterFunction(TableFunction("sqlctx_load_file", {LogicalType::VARCHAR}, LoadFunction, LoadBind, LoadInit)); @@ -171,15 +124,7 @@ static void LoadInternal(ExtensionLoader &loader) { rewrite.SetStability(FunctionStability::VOLATILE); rewrite.SetFallible(); loader.RegisterFunction(rewrite); - auto compile_input = ScalarFunction("sqlctx_compile_semantic_input", - {LogicalType::VARCHAR, LogicalType::VARCHAR}, LogicalType::VARCHAR, SqlctxCompileSemanticInputFunction); - compile_input.SetFallible(); - loader.RegisterFunction(compile_input); - auto rewrite_input = ScalarFunction("sqlctx_rewrite_semantic_input", - {LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR}, LogicalType::VARCHAR, - SqlctxRewriteSemanticInputFunction); - rewrite_input.SetFallible(); - loader.RegisterFunction(rewrite_input); + RegisterSqlctxSemanticInput(loader); } void SqlctxExtension::Load(ExtensionLoader &loader) { LoadInternal(loader); } diff --git a/sqlctx-duckdb/src/sqlctx_grammar.cpp b/sqlctx-duckdb/src/sqlctx_grammar.cpp index 2f1c5f52b..c45765b85 100644 --- a/sqlctx-duckdb/src/sqlctx_grammar.cpp +++ b/sqlctx-duckdb/src/sqlctx_grammar.cpp @@ -147,16 +147,20 @@ class SqlctxGrammar final : public GrammarExtension { GrammarChange::AddRule("SqlctxModel <- 'MODEL' (SqlctxBlock / ColIdOrString ('FROM' (SqlctxSource / SqlctxBlock) SqlctxBlock / SqlctxBlock)?)"), GrammarChange::AddRule("SqlctxItem <- ('METRIC' / 'DIMENSION' / 'SEGMENT') (SqlctxBlock / SqlctxSource ('AS' Expression / SqlctxBlock))"), GrammarChange::AddRule("SqlctxDefinition <- 'SEMANTIC'? ('CREATE' ('OR' 'REPLACE')?)? (SqlctxModel / SqlctxItem)", StartDefinition), + GrammarChange::AddRule("SqlctxView <- 'CREATE' ('OR' 'REPLACE')? 'SEMANTIC' 'VIEW' ColIdOrString 'AS' SelectStatement", StartDefinition), + GrammarChange::AddRule("SqlctxDropView <- 'DROP' 'SEMANTIC' 'VIEW' ('IF' 'EXISTS')? ColIdOrString", StartDefinition), GrammarChange::AddRule("SqlctxDrop <- 'SEMANTIC'? 'DROP' ('MODEL' / 'METRIC' / 'DIMENSION' / 'SEGMENT') ('IF' 'EXISTS')? SqlctxSource", StartDefinition), GrammarChange::AddRule("SqlctxShow <- 'SHOW' 'SEMANTIC'? ('MODELS' / 'METRICS' / 'DIMENSIONS' / 'SEGMENTS' / 'RELATIONSHIPS') (('FROM' ColIdOrString) / ('FOR' SqlctxSource))?", StartDefinition), GrammarChange::AddRule("SqlctxDescribe <- ('DESCRIBE' / 'DESC') 'MODEL' ColIdOrString", StartDefinition), GrammarChange::AddRule("SqlctxExport <- 'EXPORT' 'SEMANTIC' 'CATALOG'", StartDefinition), GrammarChange::AddRule("SqlctxImport <- 'IMPORT' 'SEMANTIC' 'CATALOG' ColIdOrString", StartDefinition), GrammarChange::AddRule("SqlctxQuery <- 'SEMANTIC' (SelectStatement / CreateStatement / InsertStatement)", StartSemanticQuery), - GrammarChange::AddRule("SqlctxPreparable <- SqlctxShow / SqlctxDescribe / SqlctxExport / SqlctxImport / SqlctxDrop / SqlctxDefinition / SqlctxQuery"), + GrammarChange::AddRule("SqlctxPreparable <- SqlctxShow / SqlctxDescribe / SqlctxExport / SqlctxImport / SqlctxDropView / SqlctxDrop / SqlctxView / SqlctxDefinition / SqlctxQuery"), GrammarChange::AddRule("SqlctxPrepare <- 'PREPARE' ColIdOrString 'AS' SqlctxPreparable", StartPrepare), GrammarChange::AddRule("SqlctxExplain <- 'EXPLAIN' AnalyzeKeyword? ExplainOptionList? SqlctxPreparable", StartExplain), GrammarChange::PrependChoice("Statement", "SqlctxDefinition"), + GrammarChange::PrependChoice("Statement", "SqlctxView"), + GrammarChange::PrependChoice("Statement", "SqlctxDropView"), GrammarChange::PrependChoice("Statement", "SqlctxDrop"), GrammarChange::PrependChoice("Statement", "SqlctxShow"), GrammarChange::PrependChoice("Statement", "SqlctxDescribe"), @@ -169,7 +173,8 @@ class SqlctxGrammar final : public GrammarExtension { } }; -struct SqlctxGrammarInfo : public ParserExtensionInfo { +struct SqlctxGrammarInfo : public SqlctxParserInfo { + explicit SqlctxGrammarInfo(DatabaseInstance &database) : SqlctxParserInfo(database) {} shared_ptr default_grammar; shared_ptr grammar; }; @@ -179,7 +184,7 @@ struct SqlctxGrammarInfo : public ParserExtensionInfo { shared_ptr RegisterSqlctxGrammar(DatabaseInstance &db) { auto extension = make_shared_ptr(); GrammarExtension::Register(db, extension); - auto info = make_shared_ptr(); + auto info = make_shared_ptr(db); info->default_grammar = db.GetParserCache().GetMatcher(); #if SQLCTX_GRAMMAR_EXTENSION_LIST info->grammar = CompiledGrammar::Create(vector> {*extension}); @@ -224,7 +229,9 @@ bool ParseSqlctxGrammar(ParserExtensionInfo *info, const string &sql, const Pars } // namespace duckdb #else namespace duckdb { -shared_ptr RegisterSqlctxGrammar(DatabaseInstance &) { return nullptr; } +shared_ptr RegisterSqlctxGrammar(DatabaseInstance &db) { + return make_shared_ptr(db); +} bool ParseSqlctxGrammar(ParserExtensionInfo *, const string &, const ParserOptions &, vector> &) { return false; } } // namespace duckdb diff --git a/sqlctx-duckdb/src/sqlctx_parser.cpp b/sqlctx-duckdb/src/sqlctx_parser.cpp index 7322f9d76..f4768aae0 100644 --- a/sqlctx-duckdb/src/sqlctx_parser.cpp +++ b/sqlctx-duckdb/src/sqlctx_parser.cpp @@ -7,9 +7,11 @@ #include "duckdb/main/config.hpp" #include "duckdb/main/connection_manager.hpp" #include "duckdb/main/database_manager.hpp" +#include "duckdb/main/extension_manager.hpp" #include "duckdb/main/prepared_statement_data.hpp" #include "duckdb/main/valid_checker.hpp" #include "duckdb/parser/expression/columnref_expression.hpp" +#include "duckdb/parser/expression/constant_expression.hpp" #include "duckdb/parser/expression/function_expression.hpp" #include "duckdb/parser/expression/conjunction_expression.hpp" #include "duckdb/parser/expression/subquery_expression.hpp" @@ -30,10 +32,16 @@ #include "duckdb/parser/tableref/joinref.hpp" #include "duckdb/parser/tableref/subqueryref.hpp" #include "duckdb/parser/tableref/showref.hpp" +#include "duckdb/parser/tableref/table_function_ref.hpp" +#include "duckdb/main/extension/extension_loader.hpp" +#include "duckdb/function/table_function.hpp" +#include "duckdb/function/function_set.hpp" #include "duckdb/planner/extension_callback.hpp" #include "duckdb/planner/bound_parameter_map.hpp" #include "duckdb/planner/planner_extension.hpp" #include "duckdb/planner/operator/logical_extension_operator.hpp" +#include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/expression/bound_columnref_expression.hpp" namespace duckdb { namespace { @@ -87,7 +95,7 @@ string IdentifierText(const string &text) { return text; } -string Literal(const string &text) { +string SqlctxLiteral(const string &text) { return "'" + StringUtil::Replace(text, "'", "''") + "'"; } @@ -196,7 +204,7 @@ unique_ptr ParseCompatibilityStatement(const string &sql, const Pa } else { statement->Cast().statement = std::move(child); } - return WrapSqlctxQuery(std::move(statement)); + return WrapSqlctxQuery(std::move(statement), false, "", &options); } } } @@ -205,7 +213,7 @@ unique_ptr ParseCompatibilityStatement(const string &sql, const Pa if (parser.statements.size() != 1) { throw ParserException("Expected one sqlctx statement"); } - return WrapSqlctxQuery(std::move(parser.statements[0]), explicit_semantic); + return WrapSqlctxQuery(std::move(parser.statements[0]), explicit_semantic, "", &options); } void ParseCompatibility(const string &sql, const ParserOptions &options, @@ -665,12 +673,20 @@ string QuoteName(const string &name) { class SemanticRelations { public: SemanticRelations(ClientContext &context, const SqlctxModelList &list, const string &snapshot) - : context(context), snapshot(snapshot) { - for (idx_t i = 0; i < list.count; ++i) models[list.models[i].name] = &list.models[i]; + : context(context) { + auto current = SqlctxName(DatabaseManager::GetDefaultDatabase(context)); + auto catalog = make_uniq(); + catalog->snapshot = {snapshot, "", current}; + for (idx_t i = 0; i < list.count; ++i) catalog->models[list.models[i].name] = &list.models[i]; + catalogs[current] = std::move(catalog); } // Derived tables created for semantic relations, in creation order. - vector> relations; + struct CompiledRelation { + reference relation; + const SqlctxCatalogSnapshot &snapshot; + }; + vector relations; void Query(QueryNode &node) { for (auto &cte : node.cte_map.map) { @@ -701,9 +717,18 @@ class SemanticRelations { } private: + struct RelationCatalog { + SqlctxCatalogSnapshot snapshot; + unique_ptr list; + case_insensitive_map_t models; + unique_ptr catalog; + case_insensitive_map_t> fields; + }; + struct Relation { unique_ptr *slot; const SqlctxModelInfo *model; + RelationCatalog *catalog; string alias; bool nullable; bool star = false; @@ -712,16 +737,29 @@ class SemanticRelations { }; ClientContext &context; - const string &snapshot; - case_insensitive_map_t models; - unique_ptr catalog; - case_insensitive_map_t> fields; + case_insensitive_map_t> catalogs; + + RelationCatalog &GetCatalog(string name) { + if (name.empty()) name = SqlctxName(DatabaseManager::GetDefaultDatabase(context)); + auto entry = catalogs.find(name); + if (entry != catalogs.end()) return *entry->second; + auto catalog = make_uniq(); + catalog->snapshot = ReadSqlctxCatalog(context, name); + catalog->list = make_uniq(catalog->snapshot.payload); + for (idx_t i = 0; i < catalog->list->list.count; ++i) { + auto &model = catalog->list->list.models[i]; + catalog->models[model.name] = &model; + } + auto &result = *catalog; + catalogs[name] = std::move(catalog); + return result; + } // Selectable fields (dimensions and metrics), in SELECT * order. vector Columns(const Relation &relation) { Info(relation, relation.model->name); vector> ordered; - for (auto &field : fields[relation.model->name]) { + for (auto &field : relation.catalog->fields[relation.model->name]) { if (field.second.position) ordered.emplace_back(field.second.position, field.first); } std::sort(ordered.begin(), ordered.end()); @@ -731,8 +769,10 @@ class SemanticRelations { } const FieldInfo &Info(const Relation &relation, const string &field) { + auto &catalog = relation.catalog->catalog; + auto &fields = relation.catalog->fields; if (!catalog) { - catalog = make_uniq(snapshot); + catalog = make_uniq(relation.catalog->snapshot.payload); for (idx_t i = 0; i < catalog->result.count; ++i) { auto &entry = catalog->result.entries[i]; string kind(entry.kind); @@ -860,12 +900,10 @@ class SemanticRelations { auto catalog_name = table.catalog_name; #endif if (!StringUtil::CIEquals(schema, "semantic")) return; - if (!catalog_name.empty() && - !StringUtil::CIEquals(catalog_name, SqlctxName(DatabaseManager::GetDefaultDatabase(context)))) { - return; - } // A user-created semantic schema keeps its physical relations. - if (SqlctxPhysicalRelationExists(context, name)) return; + if (SqlctxPhysicalRelationExists(context, name, catalog_name)) return; + auto &catalog = GetCatalog(catalog_name); + auto &models = catalog.models; auto entry = models.find(name); if (entry == models.end()) { vector names; @@ -877,6 +915,7 @@ class SemanticRelations { Relation relation; relation.slot = &slot; relation.model = entry->second; + relation.catalog = &catalog; relation.alias = ref.alias.empty() ? string(entry->second->name) : SqlctxName(ref.alias); relation.nullable = nullable; found.push_back(std::move(relation)); @@ -901,9 +940,9 @@ class SemanticRelations { if (!relation) return nullptr; bool current_catalog = names.size() == 3 || (names.size() == 4 && StringUtil::CIEquals(SqlctxName(names[0]), - SqlctxName(DatabaseManager::GetDefaultDatabase(context)))); + relation->catalog->snapshot.catalog)); if (!current_catalog) { - throw BinderException("Semantic column qualifier must name the current database's semantic schema"); + throw BinderException("Semantic column qualifier must name the relation's database"); } names.erase(names.begin(), names.end() - 2); } else if (names.size() >= 3) { @@ -1151,7 +1190,9 @@ class SemanticRelations { sql += QuoteName(relation.alias) + "." + QuoteName(relation.fields[i]) + " AS " + QuoteName(relation.fields[i]); } - auto source = (*relation.slot)->ToString(); + // The compiler sees one catalog at a time. The host resolves the owner + // first; only its semantic schema/model name belongs in compiler SQL. + auto source = "semantic." + QuoteName(relation.model->name) + " AS " + QuoteName(relation.alias); sql += " FROM " + source; for (idx_t i = 0; i < relation.filters.size(); ++i) { sql += (i ? " AND (" : " WHERE (") + relation.filters[i]->ToString() + ")"; @@ -1160,7 +1201,7 @@ class SemanticRelations { parser.ParseQuery("SELECT * FROM (" + sql + ") AS " + QuoteName(relation.alias)); auto &wrapper = parser.statements.at(0)->Cast().node->Cast(); *relation.slot = std::move(wrapper.from_table); - relations.push_back((*relation.slot)->Cast()); + relations.push_back({(*relation.slot)->Cast(), relation.catalog->snapshot}); } }; @@ -1231,26 +1272,36 @@ unique_ptr CompileSemanticSelect(const SqlctxCatalogSnapshot &snapsho unique_ptr CompileSemanticStatement(ClientContext &context, SQLStatement &statement, const SqlctxCatalogSnapshot &snapshot, - bool explicit_semantic = false) { + bool explicit_semantic = false, + const SqlctxModelList *cached_models = nullptr) { auto rewritten = statement.Copy(); auto query = QueryInStatement(*rewritten, true); if (!query) return nullptr; - ModelListOwner models(snapshot.payload); - SemanticRelations relations(context, models.list, snapshot.payload); + unique_ptr owned_models; + if (!cached_models) owned_models = make_uniq(snapshot.payload); + auto &models = cached_models ? *cached_models : owned_models->list; + SemanticRelations relations(context, models, snapshot.payload); relations.Query(*query->node); unordered_set derived; - for (auto &relation : relations.relations) derived.insert(&relation.get()); - SemanticReferences references(context, models.list, explicit_semantic, derived); + for (auto &relation : relations.relations) derived.insert(&relation.relation.get()); + SemanticReferences references(context, models, explicit_semantic, derived); bool found = references.Query(*query->node) || explicit_semantic; references.ThrowUnknownField(found); + for (auto &relation : relations.relations) { + bool attached = !StringUtil::CIEquals(relation.snapshot.catalog, + SqlctxName(DatabaseManager::GetDefaultDatabase(context))); + // A whole-query rewrite already compiles current-catalog relations. + // Compile attached relations separately before giving that compiler + // their fully qualified physical SQL. + if (found && !attached) continue; + auto &subquery = *relation.relation.get().subquery; + subquery.node = CompileSemanticSelect(relation.snapshot, subquery.node->ToString()); + if (attached) QualifySqlctxSources(context, *subquery.node, relation.snapshot.catalog); + } if (!found) { if (relations.relations.empty()) return nullptr; // Only semantic relations: compile each derived table and leave the // rest of the statement, including DESCRIBE/SUMMARIZE, to DuckDB. - for (auto &relation : relations.relations) { - auto &subquery = *relation.get().subquery; - subquery.node = CompileSemanticSelect(snapshot, subquery.node->ToString()); - } return rewritten; } query->node = CompileSemanticSelect(snapshot, query->ToString()); @@ -1300,85 +1351,221 @@ unique_ptr SemanticShowStatement(SQLStatement &statement) { } constexpr const char *ROUTING_STATE = "sqlctx_native_routing"; -constexpr const char *ROUTING_PROBE = "sqlctx_pristine_statement"; +constexpr const char *QUERY_CARRIER = "__sqlctx_bind_query"; +constexpr const char *ROUTING_PROBE = "sqlctx_pristine_show"; + +// A cheap AST scan bounds catalog work. Scope and shadowing remain the +// responsibility of SemanticReferences, after this candidate-name filter. +struct RoutingReferences { + case_insensitive_set_t names; + bool semantic = false; + + void Query(QueryNode &node) { + auto expression = [&](unique_ptr &expr) { Expression(*expr); }; + auto table = [&](TableRef &ref) { +#if !SQLCTX_NEW_IDENTIFIER_API + // The stable host's generic iterator does not visit SHOW's query. + if (ref.type == TableReferenceType::SHOW_REF) { + auto &show = ref.Cast(); + if (show.query) Query(*show.query); + return; + } +#endif + if (ref.type != TableReferenceType::BASE_TABLE) return; + auto &base = ref.Cast(); +#if SQLCTX_QUALIFIED_TABLE_API + auto schema = SqlctxName(base.GetQualifiedName().Schema()); + auto catalog = SqlctxName(base.GetQualifiedName().Catalog()); + auto name = SqlctxName(base.Table()); +#else + auto schema = base.schema_name; + auto catalog = base.catalog_name; + auto name = base.table_name; +#endif + if (StringUtil::CIEquals(schema, "semantic")) semantic = true; + if (schema.empty() && catalog.empty()) names.insert(name); + }; + if (node.type == QueryNodeType::CTE_NODE) { + auto &cte = node.Cast(); + Query(*cte.query); + Query(*cte.child); + return; + } + ParsedExpressionIterator::EnumerateQueryNodeChildren(node, expression, table); + } + + void Expression(ParsedExpression &expr) { + if (expr.GetExpressionClass() == ExpressionClass::SUBQUERY) { +#if SQLCTX_NEW_EXPRESSION_API + Query(*expr.Cast().Subquery()->node); +#else + Query(*expr.Cast().subquery->node); +#endif + } + ParsedExpressionIterator::EnumerateChildren(expr, [&](ParsedExpression &child) { Expression(child); }); + } + + bool Possible() const { return semantic || !names.empty(); } + bool Matches(const SqlctxModelList &models) const { + if (semantic || names.count("metrics")) return true; + for (idx_t i = 0; i < models.count; ++i) if (names.count(models.models[i].name)) return true; + return false; + } +}; + +struct QueryCarrierData : DependencyItem { + explicit QueryCarrierData(unique_ptr query) : query(std::move(query)) {} + unique_ptr query; +}; + +unique_ptr PrivateCarrierQuery(const TableFunctionRef &table) { + if (!table.external_dependency) return nullptr; + auto item = table.external_dependency->GetDependency(QUERY_CARRIER); + if (!item) return nullptr; + return unique_ptr_cast(item->Cast().query->Copy()); +} + +string CarrierParserSettings(const ParserOptions &options) { + string settings = options.integer_division ? "1:" : "0:"; +#if SQLCTX_NEW_IDENTIFIER_API + switch (options.identifier_case_mode) { + case IdentifierCaseMode::PRESERVE_CASE: settings += "preserve:"; break; + case IdentifierCaseMode::LOWERCASE: settings += "lower:"; break; + case IdentifierCaseMode::UPPERCASE: settings += "upper:"; break; + } + settings += options.regex_match_operator_semantics == RegexMatchOperatorSemantics::FULL ? "full" : "partial"; +#else + settings += options.preserve_identifier_case ? "preserve:full" : "lower:full"; +#endif + return settings; +} + +unique_ptr ParseCarrier(const string &sql, const string &settings) { + auto options = SqlctxBuiltinParserOptions(); + if (!settings.empty()) { + auto parts = StringUtil::Split(settings, ':'); + if (parts.size() != 3 || (parts[0] != "0" && parts[0] != "1") || + (parts[1] != "preserve" && parts[1] != "lower" && parts[1] != "upper") || + (parts[2] != "partial" && parts[2] != "full")) { + throw InvalidInputException("Invalid sqlctx query carrier parser settings"); + } + options.integer_division = parts[0] == "1"; +#if SQLCTX_NEW_IDENTIFIER_API + options.identifier_case_mode = parts[1] == "lower" ? IdentifierCaseMode::LOWERCASE : + (parts[1] == "upper" ? IdentifierCaseMode::UPPERCASE : IdentifierCaseMode::PRESERVE_CASE); + options.regex_match_operator_semantics = parts[2] == "full" ? RegexMatchOperatorSemantics::FULL : + RegexMatchOperatorSemantics::PARTIAL; +#else + options.preserve_identifier_case = parts[1] == "preserve"; +#endif + } + Parser parser(options); + parser.ParseQuery(sql); + if (parser.statements.size() != 1) throw BinderException("sqlctx query carrier expects one query"); + auto statement = std::move(parser.statements[0]); + while (statement->type == StatementType::PREPARE_STATEMENT) { + auto prepared = std::move(statement->Cast().statement); + statement = std::move(prepared); + } + auto query = QueryInStatement(*statement, true); + if (!query) throw BinderException("sqlctx query carrier expects a SELECT query source"); + return unique_ptr_cast(query->Copy()); +} + +// con.sql and relational callers bind QueryNodes directly, bypassing Planner. +// Retain SELECT and defer catalog reads to their active binding transaction. +void WrapQueryCarrier(SelectStatement &query, const string &source, const ParserOptions &options) { + if (source.empty()) return; + RoutingReferences refs; + refs.Query(*query.node); + if (!refs.Possible()) return; + auto relation = make_uniq(); + vector> arguments; +#if SQLCTX_LITERAL_API + arguments.push_back(ConstantExpression::String(source)); + arguments.push_back(ConstantExpression::String(CarrierParserSettings(options))); +#else + arguments.push_back(make_uniq(Value(source))); + arguments.push_back(make_uniq(Value(CarrierParserSettings(options)))); +#endif + relation->function = make_uniq(QUERY_CARRIER, std::move(arguments)); + // Native AST copies keep the private input. DuckDB omits external + // dependencies from serialization; persisted views retain exact SQL source + // and reconstruct it through the parser on reopen, never a binary decoder. + relation->external_dependency = make_shared_ptr(); + relation->external_dependency->AddDependency(QUERY_CARRIER, make_shared_ptr(query.Copy())); + auto wrapper = make_uniq(); + // A normal subquery deduplicates result names (x, x -> x, x_1). Give the + // binder unique internal names, then restore the exact native labels with + // COLUMNS capture aliases, including SELECT * and expanding expressions. + auto columns = make_uniq(); + const string pattern = "^__sqlctx_column_[0-9]+_([\\s\\S]*)$"; +#if SQLCTX_NEW_EXPRESSION_API + columns->IsColumnsMutable() = true; + columns->ExpressionMutable() = ConstantExpression::String(pattern); +#else + columns->columns = true; + columns->expr = make_uniq(Value(pattern)); +#endif + columns->SetAlias(SqlctxIdentifier("\\1")); + wrapper->select_list.push_back(std::move(columns)); + wrapper->from_table = std::move(relation); + query.node = std::move(wrapper); +} + +unique_ptr UnwrapQueryCarrier(SelectStatement &query) { + if (query.node->type != QueryNodeType::SELECT_NODE) return nullptr; + auto &select = query.node->Cast(); + if (!select.from_table || select.from_table->type != TableReferenceType::TABLE_FUNCTION) return nullptr; + auto &table = select.from_table->Cast(); + if (FunctionName(*table.function) != QUERY_CARRIER) return nullptr; + // Only our private, untouched carrier is eligible. A user's direct call + // must keep its projections and predicates and receive normal validation. + if (select.select_list.size() != 1 || select.select_list[0]->GetExpressionClass() != ExpressionClass::STAR || + select.where_clause || select.having || select.qualify || !select.groups.group_expressions.empty() || + !select.modifiers.empty() || !select.cte_map.map.empty() || select.sample) return nullptr; + return PrivateCarrierQuery(table); +} -// DuckDB's native binder consumes expressions as it visits them. The client -// rebind API protects a pristine statement copy, unlike OperatorExtension's -// failure callback. A private post-bind signal also reaches that API when a -// same-name physical table made the first native bind succeed. class SqlctxRoutingState : public ClientContextState { public: explicit SqlctxRoutingState(ClientContext &context) : context(context) {} bool CanRequestRebind() override { candidate.reset(); + probing = !SQLCTX_PRE_BIND; probe_error = false; - probing = false; - has_models = false; - catalog_error = ErrorData(); - snapshot = {}; - // ROLLBACK must remain bindable after a transaction error. Do not read - // the semantic catalog while DuckDB's transaction is invalidated. - if (!context.transaction.HasActiveTransaction() || ValidChecker::IsInvalidated(context.ActiveTransaction())) { - return false; - } - probing = true; - try { - snapshot = ReadSqlctxCatalog(context); - if (!snapshot.payload.empty()) { - ModelListOwner models(snapshot.payload); - has_models = models.list.count != 0; - } - } catch (const std::exception &exception) { - ErrorData error(exception); - switch (error.Type()) { - case ExceptionType::INVALID_INPUT: - case ExceptionType::PARSER: - case ExceptionType::IO: - case ExceptionType::PERMISSION: - // Catalog discovery and explicit semantic statements perform - // their own read. Ordinary SQL and extension introspection - // must remain usable even if legacy definitions are invalid. - catalog_error = std::move(error); - snapshot = {}; - break; - default: - throw; - } - } - // With no models, normal SQL binds once. Keeping a pristine copy still - // lets a native SHOW failure reach our catalog discovery statements. - return true; + // Compatibility recovery for ASTs supplied by other parsers. Normal + // SQL and relational calls use the carrier without exception probes. + return !SQLCTX_PRE_BIND && context.transaction.HasActiveTransaction() && + !ValidChecker::IsInvalidated(context.ActiveTransaction()); } RebindQueryInfo OnPlanningError(ClientContext &, SQLStatement &statement, ErrorData &error) override { - if (!probing) return RebindQueryInfo::DO_NOT_REBIND; bool own_probe = probe_error && error.ExtraInfo().count(ROUTING_PROBE); probing = false; probe_error = false; - if (!own_probe && error.Type() != ExceptionType::BINDER && error.Type() != ExceptionType::CATALOG) { + if (own_probe) { + candidate = SemanticShowStatement(statement); + return RebindQueryInfo::ATTEMPT_TO_REBIND; + } + if (error.Type() != ExceptionType::BINDER && error.Type() != ExceptionType::CATALOG) { return RebindQueryInfo::DO_NOT_REBIND; } - candidate = Candidate(statement, !own_probe); - return candidate || own_probe ? RebindQueryInfo::ATTEMPT_TO_REBIND : RebindQueryInfo::DO_NOT_REBIND; + candidate = Candidate(statement); + return candidate ? RebindQueryInfo::ATTEMPT_TO_REBIND : RebindQueryInfo::DO_NOT_REBIND; } RebindQueryInfo OnRebindPreparedStatement(ClientContext &, BindPreparedStatementCallbackInfo &info, - RebindQueryInfo) override { - // SQL EXECUTE uses a nested Planner instead of the client preparation - // API. Its callback supplies the original prepared AST before binding. - if (!info.prepared_statement.unbound_statement) return RebindQueryInfo::DO_NOT_REBIND; - auto prepared = Candidate(*info.prepared_statement.unbound_statement); - if (!prepared) return RebindQueryInfo::DO_NOT_REBIND; - probing = false; - probe_error = false; - candidate = std::move(prepared); - return RebindQueryInfo::ATTEMPT_TO_REBIND; + RebindQueryInfo) override { + // On 1.5 a preceding parser may supply an unwrapped SELECT. SQL + // EXECUTE creates a nested Planner without the client error callback. + if (SQLCTX_PRE_BIND || !info.prepared_statement.unbound_statement) return RebindQueryInfo::DO_NOT_REBIND; + candidate = Candidate(*info.prepared_statement.unbound_statement); + return candidate ? RebindQueryInfo::ATTEMPT_TO_REBIND : RebindQueryInfo::DO_NOT_REBIND; } RebindQueryInfo OnFinalizePrepare(ClientContext &, PreparedStatementData &, PreparedStatementMode) override { - // C/API Prepare does not necessarily end a query. Disarm successful - // probes here too, so a later direct ExtractPlan never sees our signal. probing = false; probe_error = false; return RebindQueryInfo::DO_NOT_REBIND; @@ -1390,14 +1577,43 @@ class SqlctxRoutingState : public ClientContextState { probe_error = false; } + unique_ptr Candidate(SQLStatement &statement) { + if (statement.type == StatementType::PREPARE_STATEMENT) { + return Candidate(*statement.Cast().statement); + } + if (auto show = SemanticShowStatement(statement)) return show; + auto query = QueryInStatement(statement); + if (!query) return nullptr; + RoutingReferences refs; + refs.Query(*query->node); + if (!refs.Possible()) return nullptr; + SqlctxCatalogSnapshot snapshot; + try { + snapshot = ReadSqlctxCatalog(context); + } catch (const std::exception &exception) { + ErrorData error(exception); + if (refs.semantic || (error.Type() != ExceptionType::INVALID_INPUT && + error.Type() != ExceptionType::PARSER && error.Type() != ExceptionType::IO && + error.Type() != ExceptionType::PERMISSION)) throw; + // A malformed legacy sidecar must not disable ordinary tables. + // Keep the catalog diagnostic for references that need semantics. + for (auto &name : refs.names) { + SqlctxPhysicalRelation physical; + if (!SqlctxFindPhysicalRelation(context, name, physical)) throw; + } + return nullptr; + } + if (!models || snapshot.payload != model_snapshot) { + auto replacement = make_uniq(snapshot.payload); + model_snapshot = snapshot.payload; + models = std::move(replacement); + } + if (!refs.Matches(models->list)) return nullptr; + return CompileSemanticStatement(context, statement, snapshot, false, &models->list); + } + BoundStatement BindCandidate(Binder &binder) { - // Consume before binding: PREPARE and EXECUTE have nested planners, - // while our rewritten query may itself contain subqueries and views. auto statement = std::move(candidate); - probing = false; - // The discarded native plan may have inferred parameter types from - // same-name physical columns. Infer them again from the semantic plan, - // retaining only the values/types explicitly supplied by the caller. if (auto parameters = binder.GetParameters()) { parameters->GetParametersPtr()->clear(); parameters->rebind = false; @@ -1408,30 +1624,72 @@ class SqlctxRoutingState : public ClientContextState { return child->Bind(*statement); } + unique_ptr candidate; bool probing = false; bool probe_error = false; - bool has_models = false; - unique_ptr candidate; - private: - unique_ptr Candidate(SQLStatement &statement, bool native_failed = false) { - if (statement.type == StatementType::PREPARE_STATEMENT) { - return Candidate(*statement.Cast().statement, native_failed); - } - if (auto show = SemanticShowStatement(statement)) return show; - // A native query that already succeeded needs no recovery. If native - // binding failed, expose the real catalog error instead of pretending - // that semantic definitions were absent or returning a partial rewrite. - if (native_failed && catalog_error.HasError() && QueryInStatement(statement)) catalog_error.Throw(); - if (!has_models) return nullptr; - return CompileSemanticStatement(context, statement, snapshot); - } - ClientContext &context; - SqlctxCatalogSnapshot snapshot; - ErrorData catalog_error; + string model_snapshot; + unique_ptr models; }; +unique_ptr BindQueryCarrier(ClientContext &context, TableFunctionBindInput &input, +#if SQLCTX_NEW_IDENTIFIER_API + TableIndex bind_index, +#else + idx_t bind_index, +#endif + vector &names) { + if (input.inputs[0].IsNull()) throw InvalidInputException("sqlctx query carrier cannot be NULL"); + unique_ptr statement = PrivateCarrierQuery(input.ref); + if (!statement) { + if (input.inputs.size() > 1 && input.inputs[1].IsNull()) { + throw InvalidInputException("sqlctx query carrier parser settings cannot be NULL"); + } + statement = ParseCarrier(input.inputs[0].GetValue(), + input.inputs.size() > 1 ? input.inputs[1].GetValue() : ""); + } + auto state = context.registered_state->GetOrCreate(ROUTING_STATE, context); + auto compiled = state->Candidate(*statement); + if (compiled) { + statement = std::move(compiled); + if (input.binder) RegisterSqlctxCatalogRead(context, input.binder->GetStatementProperties()); + } + if (!input.binder) throw InternalException("sqlctx query carrier requires a binder"); + auto child = Binder::CreateBinder(context, input.binder.get()); + child->SetCanContainNulls(true); + auto bound = child->Bind(*statement); + input.binder->MergeCorrelatedColumns(child->correlated_columns); + auto bindings = bound.plan->GetColumnBindings(); + vector> expressions; + for (idx_t i = 0; i < bound.names.size(); ++i) { + names.emplace_back("__sqlctx_column_" + to_string(i) + "_" + SqlctxName(bound.names[i])); + expressions.push_back(make_uniq(bound.types[i], bindings[i])); + } + auto projection = make_uniq(bind_index, std::move(expressions)); + projection->children.push_back(std::move(bound.plan)); + return std::move(projection); +} + +#if SQLCTX_PRE_BIND +void SqlctxPreBind(PlannerExtensionInput &input, SQLStatement &statement) { + auto query = QueryInStatement(statement); + if (!query) return; + if (auto original = UnwrapQueryCarrier(*query)) query->node = std::move(original->node); + auto state = input.context.registered_state->GetOrCreate(ROUTING_STATE, input.context); + auto compiled = state->Candidate(statement); + if (!compiled) return; + if (compiled->type != statement.type) { + state->candidate = std::move(compiled); + return; + } + auto rewritten = QueryInStatement(*compiled); + if (!rewritten) return; + query->node = std::move(rewritten->node); + RegisterSqlctxCatalogRead(input.context, input.binder.GetStatementProperties()); +} +#endif + void SqlctxPostBind(PlannerExtensionInput &input, BoundStatement &bound) { auto state = input.context.registered_state->Get(ROUTING_STATE); if (!state) return; @@ -1439,16 +1697,13 @@ void SqlctxPostBind(PlannerExtensionInput &input, BoundStatement &bound) { bound = state->BindCandidate(input.binder); return; } - if (!state->probing || state->probe_error) return; - // SHOW of an existing physical table also binds successfully. Probe its - // small fixed description shape even in a database with no semantic models. - bool description = bound.names.size() >= 2 && bound.names[0] == "column_name" && bound.names[1] == "column_type"; - if (!state->has_models && !description) return; + // Only legacy SHOW needs the pristine client AST after a successful bind: + // another parser can interpret SHOW MODELS as DESCRIBE a physical table. + if (!state->probing || state->probe_error || bound.names.size() < 2 || + bound.names[0] != "column_name" || bound.names[1] != "column_type") return; state->probe_error = true; - // INVALID bypasses operator-extension error recovery in both supported - // planners. Only the client rebind callback should consume this signal. throw Exception(unordered_map {{ROUTING_PROBE, "true"}}, ExceptionType::INVALID, - "sqlctx requires the pristine statement for semantic binding"); + "sqlctx requires the pristine SHOW statement"); } class SqlctxConnectionCallback : public ExtensionCallback { @@ -1468,10 +1723,23 @@ void RegisterSqlctxRouting(DatabaseInstance &db) { // makes connections opened concurrently with LOAD harmless duplicates. for (auto &context : ConnectionManager::Get(db).GetConnectionList()) callback->OnConnectionOpened(*context); PlannerExtension planner; +#if SQLCTX_PRE_BIND + planner.pre_bind_function = SqlctxPreBind; +#endif planner.post_bind_function = SqlctxPostBind; PlannerExtension::Register(config, planner); } +void RegisterSqlctxQueryCarrier(ExtensionLoader &loader) { + TableFunctionSet carriers {SqlctxIdentifier(QUERY_CARRIER)}; + for (idx_t count = 1; count <= 2; ++count) { + TableFunction carrier(QUERY_CARRIER, vector(count, LogicalType::VARCHAR), nullptr, nullptr); + carrier.bind_operator = BindQueryCarrier; + carriers.AddFunction(carrier); + } + loader.RegisterFunction(carriers); +} + unique_ptr SqlctxParseData::Copy() const { auto copy = make_uniq(); copy->operation = operation; @@ -1554,15 +1822,17 @@ unique_ptr ParseSqlctxDefinition(const string &sql) { } if (Keyword(tokens, pos, "DROP")) { ++pos; + bool view = Keyword(tokens, pos, "SEMANTIC") && Keyword(tokens, pos + 1, "VIEW"); + if (view) ++pos; if (!(Keyword(tokens, pos, "MODEL") || Keyword(tokens, pos, "METRIC") || - Keyword(tokens, pos, "DIMENSION") || Keyword(tokens, pos, "SEGMENT"))) return nullptr; + Keyword(tokens, pos, "DIMENSION") || Keyword(tokens, pos, "SEGMENT") || view)) return nullptr; auto result = make_uniq(); result->operation = "drop_" + StringUtil::Lower(tokens[pos++].text); if (Keyword(tokens, pos, "IF") && Keyword(tokens, pos + 1, "EXISTS")) { result->replace = true; pos += 2; } - result->content = QualifiedNameJson(tokens, pos, result->operation == "drop_model" ? 1 : 2); + result->content = QualifiedNameJson(tokens, pos, view || result->operation == "drop_model" ? 1 : 2); return result; } bool create = Keyword(tokens, pos, "CREATE"); @@ -1575,6 +1845,17 @@ unique_ptr ParseSqlctxDefinition(const string &sql) { } } if (pos >= tokens.size()) return nullptr; + if (create && Keyword(tokens, pos, "SEMANTIC") && Keyword(tokens, pos + 1, "VIEW")) { + pos += 2; + if (pos + 2 >= tokens.size() || !Keyword(tokens, pos + 1, "AS")) { + throw ParserException("CREATE SEMANTIC VIEW expects name AS SELECT dimensions and metrics FROM model"); + } + auto result = make_uniq(); + result->replace = replace; + result->operation = "view"; + result->content = clean.substr(tokens[pos].start, tokens.back().end - tokens[pos].start); + return result; + } bool model = Keyword(tokens, pos, "MODEL"); bool item = Keyword(tokens, pos, "METRIC") || Keyword(tokens, pos, "DIMENSION") || Keyword(tokens, pos, "SEGMENT"); if (!model && !item) return nullptr; @@ -1619,7 +1900,7 @@ unique_ptr ParseSqlctxDefinition(const string &sql) { } else { auto rest = clean.substr(tokens[pos + 2].end, tokens.back().end - tokens[pos + 2].end); auto separator = pos + 3 < tokens.size() && tokens[pos + 3].text == ")" ? "" : ", "; - result->content = "MODEL (name " + Literal(name) + separator + rest; + result->content = "MODEL (name " + SqlctxLiteral(name) + separator + rest; } } else if (model && create) { result->content = "MODEL " + clean.substr(tokens[pos].end, tokens.back().end - tokens[pos].end); @@ -1627,7 +1908,14 @@ unique_ptr ParseSqlctxDefinition(const string &sql) { return result; } -unique_ptr WrapSqlctxQuery(unique_ptr statement, bool explicit_semantic) { +unique_ptr WrapSqlctxQuery(unique_ptr statement, bool explicit_semantic, + const string &source_override, const ParserOptions *parser_options) { + auto source = source_override.empty() ? statement->query : source_override; +#if !SQLCTX_NEW_IDENTIFIER_API + if (source_override.empty() && statement->stmt_location < source.size()) { + source = source.substr(statement->stmt_location, statement->stmt_length ? statement->stmt_length : string::npos); + } +#endif if (statement->type == StatementType::EXPLAIN_STATEMENT) { auto &explain = statement->Cast(); if (explain.stmt->type == StatementType::EXTENSION_STATEMENT) { @@ -1643,12 +1931,18 @@ unique_ptr WrapSqlctxQuery(unique_ptr statement, boo } } else if (statement->type == StatementType::PREPARE_STATEMENT) { auto &prepare = statement->Cast(); - prepare.statement = WrapSqlctxQuery(std::move(prepare.statement), explicit_semantic); + prepare.statement = WrapSqlctxQuery(std::move(prepare.statement), explicit_semantic, source, parser_options); return statement; } // Ordinary queries retain their native statement type. Routing happens // after parsing, including when another parser extension accepted them. - if (!explicit_semantic) return statement; + if (!explicit_semantic) { + if (auto query = QueryInStatement(*statement, true)) { + auto options = parser_options ? *parser_options : SqlctxBuiltinParserOptions(); + WrapQueryCarrier(*query, source, options); + } + return statement; + } if (QueryInStatement(*statement)) { auto data = make_uniq(); data->statement = std::move(statement); @@ -1660,10 +1954,45 @@ unique_ptr WrapSqlctxQuery(unique_ptr statement, boo return statement; } +static bool YardstickOwnsSyntax(ParserExtensionInfo *info, const string &query) { + auto parser_info = dynamic_cast(info); + if (!parser_info || !ExtensionManager::Get(parser_info->database).ExtensionIsLoaded("yardstick")) return false; + auto tokens = Tokens(query); + // SQLCtx declarations and explicit semantic queries remain ours, even if a + // definition contains an expression whose function is named aggregate. + if (Keyword(tokens, 0, "SEMANTIC") || Keyword(tokens, 0, "MODEL") || Keyword(tokens, 0, "METRIC") || + Keyword(tokens, 0, "DIMENSION") || Keyword(tokens, 0, "SEGMENT")) return false; + idx_t create_kind = Keyword(tokens, 1, "OR") && Keyword(tokens, 2, "REPLACE") ? 3 : 1; + if (Keyword(tokens, 0, "CREATE") && Keyword(tokens, create_kind, "SEMANTIC")) return false; + for (idx_t i = 0; i + 1 < tokens.size(); ++i) { + if (Keyword(tokens, i, "AS") && Keyword(tokens, i + 1, "MEASURE")) return true; + if (!Keyword(tokens, i, "AGGREGATE") || tokens[i + 1].text != "(") continue; + // DuckDB's aggregate(list, name, ...) is ordinary SQL. A measure call + // has one argument; commas inside nested expressions are not arguments. + idx_t depth = 1; + bool multiple_arguments = false; + for (idx_t argument = i + 2; argument < tokens.size(); ++argument) { + auto &token = tokens[argument].text; + if (token == "(" || token == "[" || token == "{") ++depth; + else if (token == ")" || token == "]" || token == "}") { + if (--depth == 0) { + if (!multiple_arguments) return true; + break; + } + } else if (token == "," && depth == 1) multiple_arguments = true; + } + } + return false; +} + ParserOverrideResult sqlctx_parser_override(ParserExtensionInfo *info, const string &query, ParserOptions &options) { + // A composed PEG grammar shares syntax, not another extension's private + // transformer state. Let Yardstick establish its capture scope for measure + // syntax before parsing it. The lexer excludes comments and quoted text. + if (YardstickOwnsSyntax(info, query)) return ParserOverrideResult(); vector> statements; if (ParseSqlctxGrammar(info, query, options, statements)) { - for (auto &statement : statements) statement = WrapSqlctxQuery(std::move(statement)); + for (auto &statement : statements) statement = WrapSqlctxQuery(std::move(statement), false, "", &options); } else { ParseCompatibility(query, options, statements); } @@ -1718,7 +2047,6 @@ BoundStatement sqlctx_bind(ClientContext &context, Binder &binder, OperatorExten auto parsed = std::move(state->data); auto &data = static_cast(*parsed); if (!data.statement) throw InternalException("sqlctx query statement is missing"); - if (routing) routing->probing = false; RegisterSqlctxCatalogRead(context, binder.GetStatementProperties()); auto snapshot = ReadSqlctxCatalog(context); auto original = CompileSemanticStatement(context, *data.statement, snapshot, data.explicit_semantic); diff --git a/sqlctx-duckdb/src/sqlctx_semantic_input.cpp b/sqlctx-duckdb/src/sqlctx_semantic_input.cpp new file mode 100644 index 000000000..22da9fd36 --- /dev/null +++ b/sqlctx-duckdb/src/sqlctx_semantic_input.cpp @@ -0,0 +1,102 @@ +#include "sqlctx_semantic_input.hpp" +#include "sqlctx_compat.hpp" +#include "sqlctx.h" + +#include "duckdb/common/vector_operations/binary_executor.hpp" +#include "duckdb/common/vector_operations/ternary_executor.hpp" +#include "duckdb/function/scalar_function.hpp" +#include "duckdb/function/table_function.hpp" +#include "duckdb/parser/expression/constant_expression.hpp" +#include "duckdb/parser/expression/function_expression.hpp" +#include "duckdb/parser/tableref/table_function_ref.hpp" + +namespace duckdb { +namespace { + +// Stateless SemanticInput entrypoints retain policies in the canonical input. +// Reject NULs before crossing the C string boundary instead of truncating input. +static string SemanticInputArgument(const string &text) { + if (text.find('\0') != string::npos) { + throw InvalidInputException("SemanticInput argument contains a NUL byte"); + } + return text; +} + +static string SemanticInputSQL(SqlctxRewriteResult compiled) { + if (compiled.error) { + string message(compiled.error); + sqlctx_free_result(compiled); + throw InvalidInputException("SemanticInput failed: %s", message); + } + if (!compiled.sql) { + sqlctx_free_result(compiled); + throw InvalidInputException("SemanticInput returned no SQL"); + } + string sql(compiled.sql); + sqlctx_free_result(compiled); + return sql; +} + +static void SqlctxCompileSemanticInputFunction(DataChunk &args, ExpressionState &, Vector &result) { + BinaryExecutor::Execute( + args.data[0], args.data[1], result, args.size(), [&](string_t input, string_t query) { + auto input_json = SemanticInputArgument(input.GetString()); + auto query_json = SemanticInputArgument(query.GetString()); + return StringVector::AddString(result, SemanticInputSQL( + sqlctx_compile_semantic_input(input_json.c_str(), query_json.c_str()))); + }); +} + +static void SqlctxRewriteSemanticInputFunction(DataChunk &args, ExpressionState &, Vector &result) { + TernaryExecutor::Execute( + args.data[0], args.data[1], args.data[2], result, args.size(), + [&](string_t input, string_t sql, string_t context) { + auto input_json = SemanticInputArgument(input.GetString()); + auto sql_text = SemanticInputArgument(sql.GetString()); + auto context_json = SemanticInputArgument(context.GetString()); + return StringVector::AddString(result, SemanticInputSQL(sqlctx_rewrite_semantic_input( + input_json.c_str(), sql_text.c_str(), context_json.c_str()))); + }); +} + +static unique_ptr SqlctxQuerySemanticInputBindReplace(ClientContext &, TableFunctionBindInput &input) { + if (input.inputs[0].IsNull() || input.inputs[1].IsNull()) { + throw InvalidInputException("SemanticInput relation arguments cannot be NULL"); + } + auto input_json = SemanticInputArgument(input.inputs[0].GetValue()); + auto query_json = SemanticInputArgument(input.inputs[1].GetValue()); + auto sql = SemanticInputSQL(sqlctx_compile_semantic_input(input_json.c_str(), query_json.c_str())); + + // Let DuckDB's query() binder expand the generated SELECT in the caller's + // scope and transaction. It also owns the host's prepared-parameter checks. + // No separate connection, execution, or result materialization is involved. + vector> arguments; +#if SQLCTX_LITERAL_API + arguments.push_back(ConstantExpression::String(sql)); +#else + arguments.push_back(make_uniq(Value(sql))); +#endif + auto relation = make_uniq(); + relation->function = make_uniq(SqlctxIdentifier("query"), std::move(arguments)); + return std::move(relation); +} + +} // namespace + +void RegisterSqlctxSemanticInput(ExtensionLoader &loader) { + auto compile_input = ScalarFunction("sqlctx_compile_semantic_input", + {LogicalType::VARCHAR, LogicalType::VARCHAR}, LogicalType::VARCHAR, SqlctxCompileSemanticInputFunction); + compile_input.SetFallible(); + loader.RegisterFunction(compile_input); + auto rewrite_input = ScalarFunction("sqlctx_rewrite_semantic_input", + {LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR}, LogicalType::VARCHAR, + SqlctxRewriteSemanticInputFunction); + rewrite_input.SetFallible(); + loader.RegisterFunction(rewrite_input); + TableFunction query_input("sqlctx_query_semantic_input", {LogicalType::VARCHAR, LogicalType::VARCHAR}, + nullptr, nullptr); + query_input.bind_replace = SqlctxQuerySemanticInputBindReplace; + loader.RegisterFunction(query_input); +} + +} // namespace duckdb diff --git a/sqlctx-duckdb/test/README.md b/sqlctx-duckdb/test/README.md index a55bffeaf..2128a1e9f 100644 --- a/sqlctx-duckdb/test/README.md +++ b/sqlctx-duckdb/test/README.md @@ -29,6 +29,11 @@ TPC-DS files, queries their metrics against seeded physical tables, and repeats the results after a read-only reopen. Provenance and licenses live beside the fixtures under `tests/ossie-fixtures/upstream/{faf5810,d27a6be}`; CI needs no network. +`test_client_routing_host.py` additionally requires the Python `duckdb` wheel +matching the built host version. It exercises `con.sql().show()` and fetches, +relation composition, parameters, physical-name collisions, transaction rollback, +persisted views with parser settings, duplicate output labels, and CLI agent mode. + `test_duckflight_host.py` runs the SQL through an authenticated DuckFlight PostgreSQL listener using psycopg. Set `DUCKFLIGHT_EXTENSION` as well as the two sqlctx host variables. It checks ordinary and prepared semantic SELECT, @@ -36,3 +41,30 @@ bound predicates, result metadata, discovery, and definition transactions. `test_release_workflow.py` exercises the release input allowlist without building or publishing artifacts. + +## Catalog benchmark + +From the repository root, run the same DuckDB shell with each extension binary. +The benchmark checks result values, field names, types and ordering before timing. + +```sh +uv run --no-project sqlctx-duckdb/scripts/benchmark_catalog.py --binary /path/to/duckdb --extension /path/to/sqlctx.duckdb_extension +``` + +On macOS ARM64 with DuckDB 2.0.1, 25 models shared a 1,000-row table. Each +model declared one dimension and eight decimal sum metrics. The table gives +median wall time across seven samples after two warmups. The baseline extension +had SHA-256 prefix `ca6127873395`. + +| Query | Baseline | With deferred metadata binding | +|---|---:|---:| +| List 25 semantic views | 912 ms | 4 ms | +| Read one model's nine names and types | 860 ms | 19 ms | +| Read those column names alone | 844 ms | 5 ms | +| Show one model's eight metrics | 34 ms | 14 ms | +| Query one semantic metric | 4 ms | 5 ms | + +For ordinary SQL with the extension loaded, median CPU time fell from 0.978 +to 0.250 ms for `select 42` and from 1.096 to 0.336 ms for the physical +aggregate. The same shell without the extension used 0.067 and 0.116 ms +respectively in the latter run. diff --git a/sqlctx-duckdb/test/sql/sqlctx_native_peg.test b/sqlctx-duckdb/test/sql/sqlctx_native_peg.test index 1c2c7bb1a..169f9ce13 100644 --- a/sqlctx-duckdb/test/sql/sqlctx_native_peg.test +++ b/sqlctx-duckdb/test/sql/sqlctx_native_peg.test @@ -30,6 +30,35 @@ SEMANTIC SELECT "o"."revenue" FROM "peg_orders" o; ---- 40 +statement ok +CREATE SEMANTIC VIEW peg_report AS SELECT id, revenue AS gross FROM peg_orders; + +statement ok +BEGIN; + +statement ok +PREPARE replace_report AS CREATE OR REPLACE SEMANTIC VIEW peg_report AS SELECT revenue AS total FROM peg_orders; + +statement ok +EXECUTE replace_report; + +query I +SEMANTIC SELECT total FROM peg_report; +---- +40 + +statement ok +ROLLBACK; + +query II +SEMANTIC SELECT id, gross FROM peg_report ORDER BY id; +---- +1 10 +2 30 + +statement ok +DROP SEMANTIC VIEW peg_report; + statement ok SEMANTIC CREATE VIEW peg_view AS SELECT peg_orders.revenue AS total FROM peg_orders; diff --git a/sqlctx-duckdb/test/test_attached_catalog_host.py b/sqlctx-duckdb/test/test_attached_catalog_host.py new file mode 100644 index 000000000..03b45cd70 --- /dev/null +++ b/sqlctx-duckdb/test/test_attached_catalog_host.py @@ -0,0 +1,177 @@ +# /// script +# dependencies = ["pytest"] +# /// +"""Attached semantic catalogs use their own definitions and physical sources.""" + +import pytest +from test_catalog_host import execute, literal + +FINANCE_SETUP = """ +create table sales(id integer, region varchar, amount integer); +insert into sales values (1, 'west', 10), (2, 'west', 30), (3, 'east', 5); +MODEL sales FROM sales ( + primary key(id) + region + sum(amount) AS revenue +); +""" + +ATTACHED_SETUP = ( + """ +attach ':memory:' as finance; +use finance; +""" + + FINANCE_SETUP + + """ +use memory; +create table sales(id integer, region varchar, amount integer); +insert into sales values (1, 'current', 999); +""" +) + + +def test_attached_catalog_qualification_aliases_and_source_ownership(): + results = execute( + """ + select revenue from finance.semantic.sales; + select finance.semantic.sales.revenue from finance.semantic.sales; + select s.region, s.revenue from finance.semantic.sales s order by s.region; + select * from finance.semantic.sales where region = 'west'; + with sales as (select 123 as revenue) select revenue from finance.semantic.sales; + select amount from memory.main.sales; + use finance; + select revenue from finance.semantic.sales; + """, + setup=ATTACHED_SETUP, + ) + assert results == [ + [{"revenue": "45"}], + [{"revenue": "45"}], + [{"region": "east", "revenue": "5"}, {"region": "west", "revenue": "40"}], + [{"region": "west", "revenue": "40"}], + [{"revenue": "45"}], + [{"amount": 999}], + [{"revenue": "45"}], + ] + + +def test_attached_catalog_prepared_definition_and_data_rollback(): + results = execute( + """ + prepare revenue_by_region as select s.revenue from finance.semantic.sales s where s.region = $1; + execute revenue_by_region('west'); + begin; + use finance; + insert into sales values (4, 'west', 20); + create or replace metric sales.revenue as count(*); + use memory; + execute revenue_by_region('west'); + rollback; + execute revenue_by_region('west'); + """, + setup=ATTACHED_SETUP, + ) + totals = [int(rows[0]["revenue"]) for rows in results if rows and "revenue" in rows[0]] + assert totals == [40, 3, 40] + + +def test_same_model_in_multiple_catalogs_and_metadata(): + results = execute( + """ + select f.revenue as finance_revenue, m.revenue as current_revenue + from finance.semantic.sales f cross join memory.semantic.sales m; + select table_catalog, table_name from information_schema.tables + where table_schema = 'semantic' order by table_catalog, table_name; + select table_catalog, column_name, data_type from information_schema.columns + where table_schema = 'semantic' and column_name = 'revenue' order by table_catalog; + select database_name, view_name from duckdb_views() + where schema_name = 'semantic' order by database_name, view_name; + """, + setup=ATTACHED_SETUP + + """ + MODEL sales FROM sales ( + primary key(id) + region + count(*) AS revenue + ); + """, + ) + assert results == [ + [{"finance_revenue": "45", "current_revenue": 1}], + [{"table_catalog": "finance", "table_name": "sales"}, {"table_catalog": "memory", "table_name": "sales"}], + [ + {"table_catalog": "finance", "column_name": "revenue", "data_type": "HUGEINT"}, + {"table_catalog": "memory", "column_name": "revenue", "data_type": "BIGINT"}, + ], + [{"database_name": "finance", "view_name": "sales"}, {"database_name": "memory", "view_name": "sales"}], + ] + + +def test_attached_physical_semantic_namespace_collision_is_catalog_local(): + results = execute( + """ + create schema semantic; + create table semantic.sales(revenue integer); + insert into semantic.sales values (777); + select revenue from memory.semantic.sales; + select revenue from finance.semantic.sales; + begin; + create schema finance.semantic; + create table finance.semantic.sales(revenue integer); + insert into finance.semantic.sales values (888); + select revenue from finance.semantic.sales; + rollback; + select revenue from finance.semantic.sales; + """, + setup=ATTACHED_SETUP, + ) + assert [int(rows[0]["revenue"]) for rows in results if rows and "revenue" in rows[0]] == [777, 45, 888, 45] + + +def test_attached_catalog_readonly_reopen(tmp_path): + database = tmp_path / "finance.duckdb" + execute("select revenue from semantic.sales;", setup=FINANCE_SETUP, database=database) + results = execute( + """ + select revenue from finance.semantic.sales; + select table_catalog, column_name from information_schema.columns + where table_catalog = 'finance' and table_schema = 'semantic' order by ordinal_position; + """, + setup=f"attach {literal(str(database))} as finance (read_only);", + ) + assert results == [ + [{"revenue": "45"}], + [{"table_catalog": "finance", "column_name": "region"}, {"table_catalog": "finance", "column_name": "revenue"}], + ] + + +def test_attached_catalog_sql_sources_keep_ctes_and_explicit_catalogs(): + definitions = """ +models: + - name: cte_sales + sql: "with sales as (select * from sales) select * from sales" + primary_key: id + metrics: + - name: revenue + agg: sum + sql: amount + - name: explicitly_current + table: memory.main.sales + primary_key: id + metrics: + - name: revenue + agg: sum + sql: amount +""" + results = execute( + """ + select revenue from finance.semantic.cte_sales; + select revenue from finance.semantic.explicitly_current; + """, + setup=ATTACHED_SETUP + f"use finance; select * from sqlctx_load({literal(definitions)}); use memory;", + ) + assert results == [[{"revenue": "45"}], [{"revenue": "999"}]] + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v", "-o", "addopts="])) diff --git a/sqlctx-duckdb/test/test_client_routing_host.py b/sqlctx-duckdb/test/test_client_routing_host.py new file mode 100644 index 000000000..110937a68 --- /dev/null +++ b/sqlctx-duckdb/test/test_client_routing_host.py @@ -0,0 +1,167 @@ +"""Exercise the actual Python client and shell against matching host artifacts.""" + +import os +import subprocess +from pathlib import Path + +import pytest + +duckdb = pytest.importorskip("duckdb") + +SETUP = """ +create table orders(id integer, status varchar, amount integer, revenue integer); +insert into orders values (1, 'paid', 10, 999), (2, 'paid', 30, 999), (3, 'pending', 5, 999); +MODEL orders FROM orders ( + primary key(id) + status + sum(amount) AS revenue + sum(amount) AS semantic_total +); +""" + + +@pytest.fixture +def connection(): + extension = Path(os.environ["SQLCTX_DUCKDB_EXTENSION"]).resolve() + with duckdb.connect(config={"allow_unsigned_extensions": "true", "threads": "2"}) as con: + con.execute("load '" + str(extension).replace("'", "''") + "'") + con.execute(SETUP) + yield con + + +@pytest.mark.parametrize("source", ["orders", "semantic.orders"]) +def test_sql_relation_fetch_show_and_composition(connection, source, capfd): + relation = connection.sql(f"select status, semantic_total from {source} order by status") + assert relation.columns == ["status", "semantic_total"] + assert relation.fetchall() == [("paid", 40), ("pending", 5)] + relation.show() + output = capfd.readouterr().out + assert "semantic_total" in output and "paid" in output and "40" in output + assert relation.filter("status = 'paid'").project("semantic_total * 2 as doubled").fetchall() == [(80,)] + + +def test_physical_shadowing_and_native_scope(connection): + assert connection.sql("select status, revenue from orders order by id").fetchall() == [ + ("paid", 999), + ("paid", 999), + ("pending", 999), + ] + assert connection.sql("select revenue from semantic.orders").fetchall() == [(45,)] + assert connection.sql("select main.orders.amount from orders order by id").fetchall() == [(10,), (30,), (5,)] + assert connection.sql( + "with orders as (select 7 as semantic_total) select semantic_total from orders" + ).fetchall() == [(7,)] + assert connection.sql("select o.semantic_total as total from semantic.orders o").fetchall() == [(45,)] + with pytest.raises(duckdb.Error, match="both table"): + connection.sql("select amount, semantic_total from orders").fetchall() + + +def test_parameters_prepare_views_and_transaction_snapshots(connection): + query = "select semantic_total from orders where status = $status" + assert connection.sql(query, params={"status": "paid"}).fetchall() == [(40,)] + connection.execute("prepare totals as select semantic_total from orders where status = $1") + connection.execute("begin") + connection.execute("create or replace view selected_totals as select semantic_total from orders") + assert connection.sql("select * from selected_totals").fetchall() == [(45,)] + connection.execute("create or replace metric orders.semantic_total as count(*)") + assert connection.execute("execute totals('paid')").fetchall() == [(2,)] + assert connection.sql(query, params={"status": "paid"}).fetchall() == [(2,)] + connection.execute("rollback") + assert connection.execute("execute totals('paid')").fetchall() == [(40,)] + assert connection.sql(query, params={"status": "paid"}).fetchall() == [(40,)] + assert connection.execute("select count(*) from duckdb_views() where view_name = 'selected_totals'").fetchone() == ( + 0, + ) + + +def test_ordinary_queries_keep_values_types_aliases_and_order(connection): + query = """ + with picked as (select id, status, amount from orders where amount > 5) + select p.id as order_id, p.status, p.amount::decimal(8, 2) as amount, + (select max(amount) from orders) as largest + from picked p order by p.id desc limit 1 + """ + assert connection.execute(query).fetchall() == [(2, "paid", 30, 30)] + relation = connection.sql(query) + assert relation.columns == ["order_id", "status", "amount", "largest"] + assert relation.fetchall() == [(2, "paid", 30, 30)] + assert str(relation.types[2]) == "DECIMAL(8,2)" + result = connection.execute("select 1 as x, 2 as x from orders limit 1") + assert [column[0] for column in result.description] == ["x", "x"] + assert result.fetchall() == [(1, 2)] + query = "select * from orders a cross join orders b where a.id = 1 and b.id = 2" + expected_names = ["id", "status", "amount", "revenue"] * 2 + result = connection.execute(query) + assert [column[0] for column in result.description] == expected_names + assert result.fetchall() == [(1, "paid", 10, 999, 2, "paid", 30, 999)] + assert connection.sql(query).columns == expected_names + result = connection.execute("select unnest({'x': 1, 'y': 2}), 3 as x from orders limit 1") + assert [column[0] for column in result.description] == ["x", "y", "x"] + assert result.fetchall() == [(1, 2, 3)] + + +def test_relation_created_view_survives_reopen(tmp_path): + database = tmp_path / "client.duckdb" + extension = str(Path(os.environ["SQLCTX_DUCKDB_EXTENSION"]).resolve()).replace("'", "''") + for initialize in (True, False): + with duckdb.connect(str(database), config={"allow_unsigned_extensions": "true", "threads": "2"}) as con: + con.execute(f"load '{extension}'") + if initialize: + con.execute(SETUP) + con.sql("select status, semantic_total from semantic.orders").create_view("saved_totals", replace=True) + con.execute("set integer_division = true") + con.sql("select id, amount / 3 as quotient from orders").create_view("saved_quotients", replace=True) + con.execute("set preserve_identifier_case = false") + con.sql("select amount as MiXeD from orders").create_view("saved_case", replace=True) + assert con.sql("select * from saved_totals order by status").fetchall() == [("paid", 40), ("pending", 5)] + assert con.sql("select quotient from saved_quotients order by id").fetchall() == [(3,), (10,), (1,)] + assert con.sql("select * from saved_case").columns == ["mixed"] + + +def test_private_carrier_cannot_discard_user_predicates_or_decode_arbitrary_data(connection): + assert connection.execute("select 7 as kept from __sqlctx_bind_query('select 1 as x') where false").fetchall() == [] + assert connection.execute("select 7 as kept from __sqlctx_bind_query('select 1 as x')").fetchall() == [(7,)] + assert connection.execute("select count(*) from __sqlctx_bind_query('show models')").fetchone() == (1,) + for sql in [ + "select * from __sqlctx_bind_query()", + "select * from __sqlctx_bind_query(NULL)", + "select * from __sqlctx_bind_query('not valid SQL')", + "select * from __sqlctx_bind_query('drop table orders')", + "select * from __sqlctx_bind_query('select 1; drop table orders')", + "select * from __sqlctx_bind_query('select 1', 'invalid settings')", + "select * from __sqlctx_bind_query('select 1', NULL)", + "select * from orders, __sqlctx_bind_query(status)", + ]: + with pytest.raises(duckdb.Error) as error: + connection.execute(sql) + assert "INTERNAL" not in str(error.value) + assert connection.execute("select count(*) from orders").fetchone() == (3,) + + +def test_agent_shell_create_or_replace_view_in_transaction(): + binary = Path(os.environ["SQLCTX_DUCKDB_BINARY"]).resolve() + extension = Path(os.environ["SQLCTX_DUCKDB_EXTENSION"]).resolve() + version = subprocess.run([str(binary), "--version"], capture_output=True, text=True, check=True).stdout + if not version.startswith("v2."): + pytest.skip("Agent mode is provided by the DuckDB 2.x shell") + sql = ( + f"load '{str(extension).replace(chr(39), chr(39) * 2)}';\n" + + SETUP + + """ + begin; + create or replace view selected_totals as select semantic_total from orders; + select * from selected_totals; + rollback; + select semantic_total from semantic.orders; + """ + ) + result = subprocess.run( + [str(binary), "-unsigned", "-no-init", "-agent", "-bail", ":memory:"], + input=sql, + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stderr + assert "45" in result.stdout + assert "INTERNAL" not in result.stderr diff --git a/sqlctx-duckdb/test/test_discovery_host.py b/sqlctx-duckdb/test/test_discovery_host.py new file mode 100644 index 000000000..a34b1b4f9 --- /dev/null +++ b/sqlctx-duckdb/test/test_discovery_host.py @@ -0,0 +1,66 @@ +# /// script +# dependencies = ["pytest"] +# /// +"""Deferred catalog binding and live physical source changes.""" + +import pytest +from test_catalog_host import execute + + +def test_prepared_discovery_rebinds_physical_types_and_missing_sources(): + results = execute(""" + prepare field_types as select column_name, data_type from information_schema.columns + where table_schema = 'semantic' and table_name = 'orders' order by ordinal_position; + prepare metric_types as show metrics from orders; + execute field_types; + execute metric_types; + begin; + alter table raw_orders alter amount type double; + execute field_types; + execute metric_types; + rollback; + execute field_types; + drop table raw_orders; + execute field_types; + select is_bound from duckdb_views() where schema_name = 'semantic' and view_name = 'orders'; + create table raw_orders(id integer, status varchar, amount bigint); + execute field_types; + select is_bound from duckdb_views() where schema_name = 'semantic' and view_name = 'orders'; + """) + fields = [rows for rows in results if rows and "column_name" in rows[0]] + assert [rows[1]["data_type"] for rows in fields] == ["DECIMAL(38,2)", "DOUBLE", "DECIMAL(38,2)", None, "HUGEINT"] + metrics = [rows for rows in results if rows and "kind" in rows[0]] + assert [rows[0]["data_type"] for rows in metrics] == ["DECIMAL(38,2)", "DOUBLE"] + assert [rows[0]["is_bound"] for rows in results if rows and "is_bound" in rows[0]] == [False, True] + + +def test_discovery_projection_and_restrictions_preserve_results(): + results = execute(""" + select count(*) as n from duckdb_columns() where schema_name = 'semantic'; + select column_name from duckdb_columns() + where schema_name = 'semantic' and table_name = 'orders' and column_name = 'revenue'; + select table_name, column_name, data_type from duckdb_columns() + where schema_name = 'semantic' and (table_name = 'orders' or table_name = 'unrelated') + order by table_name, column_index; + select view_name from duckdb_views() where schema_name = 'semantic' and view_name = 'unrelated'; + select data_type from duckdb_columns() + where schema_name = 'semantic' and table_name = 'orders' and data_type = 'VARCHAR'; + select count(*) as n from duckdb_columns() + where schema_name = 'not_semantic' and table_name = 'orders'; + """) + assert results == [ + [{"n": 4}], + [{"column_name": "revenue"}], + [ + {"table_name": "orders", "column_name": "status", "data_type": "VARCHAR"}, + {"table_name": "orders", "column_name": "revenue", "data_type": "DECIMAL(38,2)"}, + {"table_name": "unrelated", "column_name": "name", "data_type": None}, + ], + [{"view_name": "unrelated"}], + [{"data_type": "VARCHAR"}], + [{"n": 0}], + ] + + +if __name__ == "__main__": + raise SystemExit(pytest.main([__file__, "-v", "-o", "addopts="])) diff --git a/sqlctx-duckdb/test/test_duckflight_host.py b/sqlctx-duckdb/test/test_duckflight_host.py index eb78ac80c..6d33b4b64 100644 --- a/sqlctx-duckdb/test/test_duckflight_host.py +++ b/sqlctx-duckdb/test/test_duckflight_host.py @@ -1,7 +1,11 @@ # /// script # dependencies = ["psycopg[binary]>=3.2,<4", "pytest"] # /// -"""Exercise sqlctx through the real DuckFlight extension's PostgreSQL listener.""" +"""Exercise sqlctx through the real DuckFlight extension's PostgreSQL listener. + +Uses DuckFlight 0.2.1's account API by default. Set DUCKFLIGHT_TEST_LEGACY=1 +when testing DuckDB 1.5 with its DuckFlight 0.1.x build. +""" import hashlib import json @@ -29,10 +33,18 @@ def postgres(tmp_path): if any(not os.environ.get(name) for name in (*required, "SQLCTX_DUCKDB_BINARY")): pytest.skip("Set SQLCTX_DUCKDB_BINARY, SQLCTX_DUCKDB_EXTENSION, and DUCKFLIGHT_EXTENSION") password = secrets.token_urlsafe(24) - salt = secrets.token_bytes(16) - digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 10000).hex() - config = tmp_path / "users.toml" - config.write_text(f'[users.smoke]\npassword_hash = "{digest}"\nsalt = {list(salt)}\niterations = 10000\n') + # DuckDB 1.5's DuckFlight 0.1.x uses file credentials. Current releases + # initialize an account store through the host API, never by writing hashes. + legacy = os.environ.get("DUCKFLIGHT_TEST_LEGACY") == "1" + if legacy: + salt = secrets.token_bytes(16) + digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 10000).hex() + config = tmp_path / "users.toml" + config.write_text(f'[users.smoke]\npassword_hash = "{digest}"\nsalt = {list(salt)}\niterations = 10000\n') + else: + password_file = tmp_path / "smoke.password" + password_file.write_text(password) + password_file.chmod(0o600) # Bind-check within the project's permitted local port range before starting. for port in range(5400, 5500): with socket.socket() as probe: @@ -56,7 +68,11 @@ def postgres(tmp_path): shutil.copyfile(path, snapshot) path = snapshot setup += f"load {literal(path)};\n" - setup += f"select * from duckflight_pg_serve({literal(address)}, {literal(config)});\n" + if legacy: + setup += f"select * from duckflight_pg_serve({literal(address)}, {literal(config)});\n" + else: + setup += f"select * from duckflight_init('smoke', password_file := {literal(password_file)});\n" + setup += f"select * from duckflight_serve('postgres', {literal(address)});\n" with (tmp_path / "host.log").open("w+") as log: host = subprocess.Popen( [str(binary), "-unsigned", "-no-init", "-bail", ":memory:"], @@ -64,6 +80,9 @@ def postgres(tmp_path): stdout=log, stderr=log, text=True, + # In-memory DuckFlight hosts keep accounts in cwd/.duckflight. + # Isolate every test's store from other tests and the user's accounts. + cwd=tmp_path, ) try: host.stdin.write(setup) @@ -79,7 +98,8 @@ def postgres(tmp_path): except OSError: time.sleep(0.1) else: - pytest.fail("DuckFlight listener startup timed out") + log.seek(0) + pytest.fail(f"DuckFlight listener startup timed out:\n{log.read()}") with psycopg.connect( host="127.0.0.1", port=port, diff --git a/sqlctx-duckdb/test/test_explain_host.py b/sqlctx-duckdb/test/test_explain_host.py new file mode 100644 index 000000000..933a1e865 --- /dev/null +++ b/sqlctx-duckdb/test/test_explain_host.py @@ -0,0 +1,52 @@ +# /// script +# dependencies = ["pytest"] +# /// +"""Check compiler explanations against real SQL compiled by the extension.""" + +import json + +from test_catalog_host import execute, literal +from test_semantic_views_host import SETUP as VIEW_SETUP + + +def test_explain_matches_rewrite_and_reports_selected_join_population(): + sql = "select customers.country, orders.revenue from orders where customers.country = 'US'" + rows = execute(f"select sqlctx_explain({literal(sql)}) as report, sqlctx_rewrite_sql({literal(sql)}) as sql") + report = json.loads(rows[0][0]["report"]) + assert report["sql"] == rows[0][0]["sql"] + assert any(event["kind"] == "grain" and event["dimensions"] == ["customers.country"] for event in report["events"]) + joins = [event for event in report["events"] if event["kind"] == "join"] + assert [(event["from"], event["to"], event["join_type"]) for event in joins] == [ + ("orders", "customers", "INNER JOIN") + ] + assert "matching" in joins[0]["population_effect"] + assert not any(event["kind"] == "fanout_guard" for event in report["events"]) + + +def test_explain_fanout_guard_and_physical_passthrough(): + rows = execute(""" + metric customers.customer_count as count(*); + select sqlctx_explain('select orders.status, customers.customer_count from customers') as report; + select sqlctx_explain('select * from main.raw_orders') as report; + """) + reports = [json.loads(result[0]["report"]) for result in rows if "report" in result[0]] + events = reports[0]["events"] + guards = [event for event in events if event["kind"] == "fanout_guard"] + assert any(event["model"] == "customers" and event["strategy"] == "count_distinct_entity" for event in guards) + assert reports[1]["events"] == [] + + +def test_explain_invalid_query_errors_instead_of_guessing(): + execute("select sqlctx_explain('select orders.missing from orders')", error="missing") + + +def test_explain_view_expands_filtered_ratio_and_aliases_like_rewrite(): + sql = "select country, aov, paid from sales" + rows = execute( + f"select sqlctx_explain({literal(sql)}) as report, sqlctx_rewrite_sql({literal(sql)}) as sql", + setup=VIEW_SETUP.replace("numerator: revenue", "numerator: paid"), + ) + report = json.loads(rows[0][0]["report"]) + assert report["sql"] == rows[0][0]["sql"] + assert "NULLIF" in report["sql"] and "CASE WHEN" in report["sql"] + assert report["events"] diff --git a/sqlctx-duckdb/test/test_release_workflow.py b/sqlctx-duckdb/test/test_release_workflow.py index 411d13f88..bc01b2572 100644 --- a/sqlctx-duckdb/test/test_release_workflow.py +++ b/sqlctx-duckdb/test/test_release_workflow.py @@ -86,7 +86,10 @@ def test_release_packages_matching_platform_with_verifiable_checksum(tmp_path, p ) -@pytest.mark.parametrize("failure", ["mismatched_tag", "missing_platform", "corrupt_payload", "existing_release", None]) +@pytest.mark.parametrize( + "failure", + ["mismatched_tag", "missing_platform", "corrupt_payload", "missing_extension_license", "existing_release", None], +) @pytest.mark.parametrize("versions", [["v1.5.6"], ["v2.0.1"], VERSIONS]) def test_publication_checks_provenance_and_all_payloads_before_creating_release(tmp_path, failure, versions): dist = tmp_path / "dist" @@ -104,6 +107,10 @@ def test_publication_checks_provenance_and_all_payloads_before_creating_release( elif failure == "corrupt_payload": asset.write_bytes(b"changed") (tmp_path / "LICENSE").write_text("Test license\n") + extension_license = tmp_path / "sqlctx-duckdb/LICENSE" + extension_license.parent.mkdir() + if failure != "missing_extension_license": + extension_license.write_text("Extension template license\n") commands = tmp_path / "bin" commands.mkdir() git = commands / "git" @@ -136,13 +143,16 @@ def test_publication_checks_provenance_and_all_payloads_before_creating_release( assert result.returncode == 0, result.stderr assert len((dist / "SHA256SUMS").read_text().splitlines()) == len(PLATFORMS) * len(versions) assert (dist / "LICENSE").read_text() == "Test license\n" - if failure in {"mismatched_tag", "missing_platform", "corrupt_payload"}: + assert (dist / "LICENSE.duckdb-extension").read_text() == "Extension template license\n" + if failure in {"mismatched_tag", "missing_platform", "corrupt_payload", "missing_extension_license"}: assert not args.exists() else: arguments = args.read_text().splitlines() assert arguments[:3] == ["release", "create", "sqlctx-duckdb-v0.1.0"] assert "--verify-tag" in arguments assert "--clobber" not in arguments + assert "LICENSE" in arguments + assert "LICENSE.duckdb-extension" in arguments assert sum(arg.endswith(".duckdb_extension") for arg in arguments) == len(PLATFORMS) * len(versions) @@ -172,7 +182,9 @@ def git(directory, *arguments): source.mkdir() git(source, "init", "-q") (source / "LICENSE").write_text("Initial license\n") - git(source, "add", "LICENSE") + (source / "sqlctx-duckdb").mkdir() + (source / "sqlctx-duckdb/LICENSE").write_text("Extension template license\n") + git(source, "add", "LICENSE", "sqlctx-duckdb/LICENSE") git(source, "commit", "-qm", "Initial source") earlier_commit = git(source, "rev-parse", "HEAD") (source / "LICENSE").write_text("Release license\n") @@ -217,4 +229,7 @@ def git(directory, *arguments): ) assert (result.returncode == 0) == matching_commit, result.stderr assert args.exists() == matching_commit + if matching_commit: + assert (dist / "LICENSE").read_text() == "Release license\n" + assert (dist / "LICENSE.duckdb-extension").read_text() == "Extension template license\n" assert git(checkout, "rev-parse", f"refs/tags/{tag}") == built_commit diff --git a/sqlctx-duckdb/test/test_semantic_input_host.py b/sqlctx-duckdb/test/test_semantic_input_host.py index e21416b9d..c9137822d 100644 --- a/sqlctx-duckdb/test/test_semantic_input_host.py +++ b/sqlctx-duckdb/test/test_semantic_input_host.py @@ -59,6 +59,12 @@ def call(query=None, source=None, sql=None, context=None, error=False): return result if error else result[0]["sql"] +def relation(query=None, source=None): + input_json = literal(json.dumps(SOURCE if source is None else source)) + query_json = literal(json.dumps(QUERY if query is None else query)) + return f"sqlctx_query_semantic_input({input_json}, {query_json})" + + @pytest.mark.parametrize("expression", [False, True]) def test_graph_window_identity_shadows_same_named_local_aggregate(expression): source = { @@ -208,7 +214,8 @@ def test_fanout_null_ordering_precedes_pagination(rewrite, suffix): assert execute(compiled) == [{"label": None, "total": "10"} if nulls_first else {"label": "a", "total": "20"}] -def test_retention_table_keeps_inactive_cohort_members_in_denominator(): +@pytest.mark.parametrize("direct_relation", [False, True]) +def test_retention_table_keeps_inactive_cohort_members_in_denominator(direct_relation): source = { "version": 1, "input_dialect": "duckdb", @@ -232,7 +239,10 @@ def test_retention_table_keeps_inactive_cohort_members_in_denominator(): } ], } - compiled = call(source=source, query={"metrics": ["events.retention"]}) + query = {"metrics": ["events.retention"]} + compiled = ( + f"select * from {relation(source=source, query=query)}" if direct_relation else call(source=source, query=query) + ) rows = execute( """ create table retention_events(id integer, user_id varchar, event_type varchar, event_date date); @@ -327,5 +337,72 @@ def test_vectorized_callers_are_isolated(): assert [list(execute(row["sql"])[0].values()) for row in compiled] == [["10"], ["100"], ["10"]] +def test_relation_dynamic_schema_and_composition(): + selected = relation(query={**QUERY, "dimensions": ["orders.tenant"]}) + columns = execute(f"describe select * from {selected};") + assert [(column["column_name"], column["column_type"]) for column in columns] == [ + ("tenant", "VARCHAR"), + ("revenue", "HUGEINT"), + ] + assert execute( + f"with totals as (select * from {selected}) " + "select label, revenue from totals join (values ('a', 'Tenant A')) names(tenant, label) " + "using (tenant) where revenue > 5;" + ) == [{"label": "Tenant A", "revenue": "10"}] + + +@pytest.mark.parametrize("rollback", [False, True]) +def test_relation_observes_callers_transaction(rollback): + transaction = "begin; insert into orders values (4, 'a', 20, false);" + if rollback: + transaction += "rollback;" + assert execute(transaction + f"select * from {relation()};") == [{"revenue": "10" if rollback else "30"}] + + +def test_relation_observes_temporary_tables(): + source = copy.deepcopy(SOURCE) + source["models"][0]["table"] = "temporary_orders" + assert execute( + "create temp table temporary_orders as select * from orders;" + "insert into temporary_orders values (4, 'a', 20, false);" + f"select * from {relation(source=source)};" + ) == [{"revenue": "30"}] + + +def test_relation_rebinds_prepared_input_and_caller_parameters(): + source = literal(json.dumps(SOURCE)) + maximum = copy.deepcopy(SOURCE) + maximum["models"][0]["metrics"][0]["agg"] = "max" + maximum = literal(json.dumps(maximum)) + query_a = literal(json.dumps(QUERY)) + query_b = literal(json.dumps({**QUERY, "user_attributes": {"tenant": "b"}})) + assert execute( + "create temp table results(caller integer, revenue hugeint);" + "prepare semantic_query as insert into results " + "select $3, revenue from sqlctx_query_semantic_input($1, $2);" + f"execute semantic_query({source}, {query_a}, 1);" + f"execute semantic_query({source}, {query_b}, 2);" + "insert into orders values (4, 'a', 25, false);" + f"execute semantic_query({maximum}, {query_a}, 3);" + "select * from results order by caller;" + ) == [{"caller": 1, "revenue": "10"}, {"caller": 2, "revenue": "100"}, {"caller": 3, "revenue": "25"}] + + +@pytest.mark.parametrize( + "query", + [{"metrics": ["orders.revenue"]}, {"metrics": ["orders.secret"], **CONTEXT}], +) +def test_relation_enforces_policies(query): + execute(f"select * from {relation(query=query)};", error=True) + + +@pytest.mark.parametrize("argument", ["NULL", "'{}'", "'{}' || chr(0)"]) +@pytest.mark.parametrize("position", [0, 1]) +def test_relation_rejects_invalid_arguments(argument, position): + arguments = [literal(json.dumps(SOURCE)), literal(json.dumps(QUERY))] + arguments[position] = argument + execute(f"select * from sqlctx_query_semantic_input({', '.join(arguments)});", error=True) + + if __name__ == "__main__": raise SystemExit(pytest.main([__file__, "-q", "-o", "addopts="])) diff --git a/sqlctx-duckdb/test/test_semantic_views_host.py b/sqlctx-duckdb/test/test_semantic_views_host.py new file mode 100644 index 000000000..919636c0b --- /dev/null +++ b/sqlctx-duckdb/test/test_semantic_views_host.py @@ -0,0 +1,204 @@ +# /// script +# dependencies = ["pytest"] +# /// +"""Named semantic selections retain measures across grain and catalog changes.""" + +import os +from decimal import Decimal + +import pytest +from test_catalog_host import execute as execute_host +from test_catalog_host import literal + + +def execute(*args, **kwargs): + results = execute_host(*args, **kwargs) + for rows in results: + for row in rows: + for key in ("gross", "paid", "aov", "revenue", "total"): + if isinstance(row.get(key), str): + row[key] = Decimal(row[key]) + return results + + +DEFINITIONS = """ +models: + - name: orders + table: raw_orders + primary_key: id + dimensions: + - {name: status, type: categorical} + - {name: country, type: categorical} + metrics: + - {name: revenue, agg: sum, sql: amount} + - {name: paid, agg: sum, sql: amount, filters: ["status = 'paid'"]} + - {name: rows, agg: count} + - {name: average, type: ratio, numerator: revenue, denominator: rows} +""" + +SETUP = f""" +create table raw_orders as select * from (values + (1, 'paid', 'US', 10), (2, 'pending', 'US', 30), (3, 'paid', 'CA', 80) +) t(id, status, country, amount); +select * from sqlctx_load({literal(DEFINITIONS)}); +create semantic view sales as select country, revenue as gross, paid, average as aov from orders; +""" + + +def test_named_view_regrains_ratios_and_filtered_metrics(): + rows = execute( + """ + select gross, paid, aov from sales; + select country, gross, paid, aov from sales order by country; + select country, aov from semantic.sales where country = 'US'; + select gross as total from sales order by total; + """, + setup=SETUP, + ) + assert rows[0] == [{"gross": 120, "paid": 90, "aov": 40}] + assert rows[1] == [ + {"country": "CA", "gross": 80, "paid": 80, "aov": 80}, + {"country": "US", "gross": 40, "paid": 10, "aov": 20}, + ] + assert rows[2] == [{"country": "US", "aov": 20}] + assert rows[3] == [{"total": 120}] + + +def test_named_view_nested_selection_and_star(): + rows = execute( + """ + create semantic view report as select country as region, gross as total, aov from sales; + select total, aov from report; + select * from report order by region; + with sales as (select 7 as gross) select gross from sales; + """, + setup=SETUP, + ) + assert rows[-3] == [{"total": 120, "aov": 40}] + assert rows[-2] == [ + {"region": "CA", "total": 80, "aov": 80}, + {"region": "US", "total": 40, "aov": 20}, + ] + assert rows[-1] == [{"gross": 7}] + + +def test_view_wildcards_preserve_selection_order_and_filtered_ratio(): + rows = execute( + """ + create metric orders.paid_average (type ratio, numerator paid, denominator rows); + create semantic view paid_report as select paid_average as aov, country, paid from orders; + create semantic view copied_report as select * from paid_report; + select aov, paid from copied_report; + select * from copied_report order by country; + """, + setup=SETUP, + ) + assert rows[-2] == [{"aov": 30, "paid": 90}] + assert list(rows[-1][0]) == ["aov", "country", "paid"] + assert rows[-1] == [ + {"aov": 80, "country": "CA", "paid": 80}, + {"aov": 5, "country": "US", "paid": 10}, + ] + + +def test_prepared_view_query_rebinds_and_rollback_restores_definition(): + rows = execute( + """ + prepare total as select gross from sales; + execute total; + begin; + create or replace metric orders.revenue as sum(amount * 2); + execute total; + rollback; + execute total; + begin; + create or replace semantic view sales as select paid as gross from orders; + execute total; + rollback; + execute total; + """, + setup=SETUP, + ) + assert [result for result in rows if result and "gross" in result[0]] == [ + [{"gross": 120}], + [{"gross": 240}], + [{"gross": 120}], + [{"gross": 90}], + [{"gross": 120}], + ] + + +def test_view_reopens_and_failed_replacement_preserves_catalog(tmp_path): + database = tmp_path / "views.duckdb" + execute("select gross from sales;", setup=SETUP, database=database) + assert execute("select aov from sales;", setup="", database=database) == [[{"aov": 40}]] + execute( + "create or replace model orders (table raw_orders);", + setup="", + database=database, + error="semantic view 'sales' dependency", + ) + assert execute("select gross from sales;", setup="", database=database) == [[{"gross": 120}]] + + +@pytest.mark.parametrize( + "sql", + [ + "drop model orders;", + "drop metric orders.revenue;", + "drop dimension orders.country;", + "create semantic view nested as select gross from sales; drop semantic view sales;", + ], +) +def test_views_restrict_dependency_removal(sql): + execute(sql, setup=SETUP, error="RESTRICT") + + +def test_view_ddl_is_preparable_transactional_and_distinct_from_sql_views(): + rows = execute( + """ + prepare define_view as create semantic view prepared_sales as select revenue from orders; + begin; + execute define_view; + select revenue from prepared_sales; + rollback; + execute define_view; + select revenue from prepared_sales; + drop semantic view prepared_sales; + drop semantic view if exists prepared_sales; + create view ordinary as select gross from sales; + select gross from ordinary; + drop view ordinary; + """, + setup=SETUP, + ) + assert [result for result in rows if result and "revenue" in result[0]] == [ + [{"revenue": 120}], + [{"revenue": 120}], + ] + assert rows[-1] == [{"gross": 120}] + + +def test_view_visibility_across_live_connections_and_reader_transactions(tmp_path): + duckdb = pytest.importorskip("duckdb", reason="requires the matching DuckDB Python host") + database = str(tmp_path / "view-connections.duckdb") + with duckdb.connect(database, config={"allow_unsigned_extensions": "true"}) as writer: + writer.execute(f"load {literal(os.environ['SQLCTX_DUCKDB_EXTENSION'])}") + writer.execute(SETUP) + with writer.cursor() as reader: + reader.execute("prepare totals as select gross from sales") + reader.execute("begin") + assert reader.execute("execute totals").fetchall() == [(120,)] + writer.execute("begin") + writer.execute("create or replace semantic view sales as select paid as gross from orders") + assert writer.execute("select gross from sales").fetchall() == [(90,)] + assert reader.execute("execute totals").fetchall() == [(120,)] + writer.execute("rollback") + assert writer.execute("select gross from sales").fetchall() == [(120,)] + writer.execute("create or replace semantic view sales as select paid as gross from orders") + # A committed writer does not replace an existing reader snapshot. + assert reader.execute("execute totals").fetchall() == [(120,)] + reader.execute("commit") + assert reader.execute("execute totals").fetchall() == [(90,)] + writer.execute("create or replace metric orders.paid as sum(amount * 2)") + assert reader.execute("execute totals").fetchall() == [(240,)] diff --git a/sqlctx-duckdb/test/test_yardstick_host.py b/sqlctx-duckdb/test/test_yardstick_host.py new file mode 100644 index 000000000..8a7287482 --- /dev/null +++ b/sqlctx-duckdb/test/test_yardstick_host.py @@ -0,0 +1,79 @@ +"""Run both extensions' measure-aware views in one dynamically loaded host.""" + +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest + + +@pytest.mark.parametrize("first", ["sqlctx", "yardstick"]) +def test_measure_views_with_yardstick(tmp_path, first): + if not os.environ.get("YARDSTICK_EXTENSION"): + pytest.skip("Set YARDSTICK_EXTENSION to a Yardstick binary built for this host") + paths = { + "yardstick": str(Path(os.environ["YARDSTICK_EXTENSION"]).resolve()), + "sqlctx": str(Path(os.environ["SQLCTX_DUCKDB_EXTENSION"]).resolve()), + } + second = "sqlctx" if first == "yardstick" else "yardstick" + # The build's CLI can statically preload SQLCtx. Use the matching Python + # host in an isolated process so these are actual, independent load orders. + script = r''' +import duckdb +import json +import sys + +con = duckdb.connect(config={"allow_unsigned_extensions": True}) +for path in json.loads(sys.argv[1]): + con.execute("load '" + path.replace("'", "''") + "'") +if duckdb.__version__.startswith("2."): + con.execute("set active_grammar_extensions=['sqlctx','yardstick']") +con.execute("create table facts(id int, region varchar, amount int)") +con.execute("insert into facts values (1,'west',10), (2,'west',30), (3,'east',80)") +con.execute("create view yard_sales as select region, sum(amount) as measure revenue from facts") +con.execute(""" + model sales from facts ( + primary key (id) + region + sum(amount) as revenue + ) +""") +con.execute("create semantic view report as select region, revenue from sales") +queries = [ + "select region, aggregate(revenue) as total from yard_sales order by region", + "select region, revenue from report order by region", + "select revenue from report", + "select 'AS MEASURE AGGREGATE(revenue)' as words", + "select revenue from report -- AS MEASURE AGGREGATE(revenue)\n", + "select revenue /* AS MEASURE AGGREGATE(revenue) */ from report", + 'select revenue as "AS MEASURE" from report', + "select aggregate([1,2,3], 'sum')", + "select aggregate(list(amount), 'sum') from facts", + 'select "aggregate"([1,2,3], \'sum\')', + "semantic select sales.revenue from sales", +] +print(json.dumps([con.execute(query).fetchall() for query in queries])) +''' + result = subprocess.run( + [sys.executable, "-c", script, json.dumps([paths[first], paths[second]])], + cwd=tmp_path, + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stderr + assert json.loads(result.stdout) == [ + [["east", 80], ["west", 40]], + [["east", 80], ["west", 40]], + [[120]], + [["AS MEASURE AGGREGATE(revenue)"]], + [[120]], + [[120]], + [[120]], + [[6]], + [[120]], + [[6]], + [[120]], + ] diff --git a/sqlctx-rs/include/sqlctx.h b/sqlctx-rs/include/sqlctx.h index 604c264e8..6b392a4c0 100644 --- a/sqlctx-rs/include/sqlctx.h +++ b/sqlctx-rs/include/sqlctx.h @@ -54,6 +54,20 @@ SqlctxSnapshotResult sqlctx_snapshot_load_sources(const char *snapshot, const Sq */ SqlctxRewriteResult sqlctx_snapshot_rewrite(const char *snapshot, const char *sql); +/* Immutable decoded snapshot for repeated compilation. The host owns its + * lifetime and must replace the handle when its transactional payload changes. + * On failure create returns NULL and sets *error (free with sqlctx_free). + * On success *error is NULL. No physical database types/results are cached. + * Calls borrow the handle; do not free it while a call is in progress. + */ +typedef struct SqlctxCompiler SqlctxCompiler; +SqlctxCompiler *sqlctx_compiler_create(const char *snapshot, char **error); +SqlctxRewriteResult sqlctx_compiler_rewrite(const SqlctxCompiler *compiler, const char *sql); +SqlctxRewriteResult sqlctx_compiler_explain(const SqlctxCompiler *compiler, const char *sql); +void sqlctx_compiler_free(SqlctxCompiler *compiler); +/* Returns a JSON compiler report in result.sql; free with sqlctx_free_result. */ +SqlctxRewriteResult sqlctx_snapshot_explain(const char *snapshot, const char *sql); + typedef struct { char *name; char **fields; diff --git a/sqlctx-rs/src/ffi/catalog.rs b/sqlctx-rs/src/ffi/catalog.rs index 34befec08..f9128ecb5 100644 --- a/sqlctx-rs/src/ffi/catalog.rs +++ b/sqlctx-rs/src/ffi/catalog.rs @@ -26,6 +26,9 @@ use super::{ }; mod api; +mod compiler; +mod explain; +mod views; type CatalogResult = Result; @@ -82,7 +85,8 @@ impl Snapshot { snapshot } - fn into_graph(self) -> CatalogResult { + fn into_graph(mut self) -> CatalogResult { + views::refresh(&mut self.models)?; let mut graph = SemanticGraph::new(); // Register globals before model indexes, then validate dependencies once // the full graph exists. Declaration order must not affect reconstruction. @@ -330,7 +334,7 @@ fn drop_definition( let names: Vec = serde_json::from_str(content).map_err(|e| e.to_string())?; let (model_name, field) = match (kind, names.as_slice()) { - ("model", [model]) => (model.as_str(), None), + ("model" | "view", [model]) => (model.as_str(), None), ("metric" | "dimension" | "segment", [model, field]) => { (model.as_str(), Some(field.as_str())) } @@ -357,6 +361,18 @@ fn drop_definition( return missing(); }; let model = &snapshot.models[index]; + let is_view = views::definition(model)?.is_some(); + if kind == "view" && !is_view || kind == "model" && is_view { + return Err(format!( + "'{}' is a {}; use DROP {}", + model.name, + if is_view { "semantic view" } else { "model" }, + if is_view { "SEMANTIC VIEW" } else { "MODEL" } + )); + } + if is_view && field.is_some() { + return Err("semantic view fields are changed with CREATE OR REPLACE SEMANTIC VIEW".into()); + } let canonical_field = match kind { "metric" => model .metrics @@ -407,6 +423,7 @@ fn restrict_drop( removed_model: &Model, target_field: Option<&str>, ) -> CatalogResult<()> { + views::restrict(snapshot, &removed_model.name, target_field)?; let target_model = removed_model.name.as_str(); let target = target_field.map_or_else( || target_model.to_owned(), @@ -529,6 +546,11 @@ fn restrict_drop( Ok(()) }; for model in &snapshot.models { + // The view selection above is its dependency contract. Its copied + // field descriptors are for discovery, not additional declarations. + if views::definition(model)?.is_some() { + continue; + } let context = Some(model.name.as_str()); if target_field.is_none() && (model @@ -919,6 +941,9 @@ fn apply_item(state: &mut FfiState, content: &str, replace: bool) -> CatalogResu .find(|model| model.name.eq_ignore_ascii_case(&model_name)) .cloned() .ok_or_else(|| format!("model '{model_name}' not found"))?; + if views::definition(&model)?.is_some() { + return Err("semantic view fields are changed with CREATE OR REPLACE SEMANTIC VIEW".into()); + } let parsed = parse_sql_model(&format!( "MODEL (name __definition, table dummy);\n{adjusted}" )) @@ -985,6 +1010,16 @@ fn apply_on_semantic_worker( content: &str, replace: bool, ) -> CatalogResult<(String, String)> { + if operation == "view" { + let mut candidate = Snapshot::from_graph(&Snapshot::parse(snapshot)?.into_graph()?); + views::create(&mut candidate, content, replace)?; + let graph = candidate.into_graph()?; + return Ok(( + serde_json::to_string(&Snapshot::from_graph(&graph)) + .map_err(|error| error.to_string())?, + active_model.to_owned(), + )); + } if let Some(kind) = operation.strip_prefix("drop_") { return drop_definition(snapshot, active_model, kind, content, replace); } @@ -1021,6 +1056,12 @@ fn apply_on_semantic_worker( .models() .find(|old| old.name.eq_ignore_ascii_case(&model.name)) { + if views::definition(existing)?.is_some() { + return Err(format!( + "'{}' is a semantic view; use CREATE OR REPLACE SEMANTIC VIEW", + existing.name + )); + } if !replace { return Err(format!("model '{}' already exists", model.name)); } @@ -1065,8 +1106,11 @@ fn apply_on_semantic_worker( .validate_metric_dependencies(metric) .map_err(|e| e.to_string())?; } + // Reconstruct before publishing so source replacements are checked against + // every persisted view selection, including nested views. + let graph = Snapshot::from_graph(&state.graph).into_graph()?; let snapshot = - serde_json::to_string(&Snapshot::from_graph(&state.graph)).map_err(|e| e.to_string())?; + serde_json::to_string(&Snapshot::from_graph(&graph)).map_err(|e| e.to_string())?; Ok((snapshot, state.active_model.unwrap_or_default())) } @@ -1105,17 +1149,40 @@ pub extern "C" fn sqlctx_snapshot_rewrite( guard(|| { let graph = Snapshot::parse(&optional_arg(snapshot, "snapshot")?)?.into_graph()?; let sql = required_arg(sql, "sql")?; - // DuckDB callers own the database; `main.orders` names the - // physical table even when a model is also called `orders`. - QueryRewriter::new(&graph) - .with_qualified_tables_physical() - .rewrite_with_dialect(&sql, polyglot_sql::DialectType::DuckDB) - .map_err(|e| e.to_string()) + rewrite_graph(&graph, &sql) }) .map_err(semantic_error), ) } +fn rewrite_graph(graph: &SemanticGraph, sql: &str) -> CatalogResult { + rewrite_graph_diagnostics(graph, sql).map(|(sql, _)| sql) +} + +fn rewrite_graph_diagnostics( + graph: &SemanticGraph, + sql: &str, +) -> CatalogResult<(String, Vec)> { + let views = views::PreparedViews::new(graph)?; + rewrite_prepared_graph_diagnostics(graph, &views, sql) +} + +fn rewrite_prepared_graph_diagnostics( + graph: &SemanticGraph, + views: &views::PreparedViews, + sql: &str, +) -> CatalogResult<(String, Vec)> { + let sql = views.expand(sql)?; + let graph = views.graph(graph); + // DuckDB callers own the database; `main.orders` names the physical + // table even when a model is also called `orders`. + let rewriter = QueryRewriter::new(graph).with_qualified_tables_physical(); + let sql = rewriter + .rewrite_with_dialect(&sql, polyglot_sql::DialectType::DuckDB) + .map_err(|error| error.to_string())?; + Ok((sql, rewriter.take_warnings())) +} + #[repr(C)] pub struct SqlctxModelInfo { pub name: *mut c_char, diff --git a/sqlctx-rs/src/ffi/catalog/api.rs b/sqlctx-rs/src/ffi/catalog/api.rs index 3857f324a..b6b9c550b 100644 --- a/sqlctx-rs/src/ffi/catalog/api.rs +++ b/sqlctx-rs/src/ffi/catalog/api.rs @@ -86,10 +86,16 @@ fn entries(snapshot: &Snapshot, kind: &str, model: &str) -> CatalogResult CatalogResult CatalogResult Snapshot { let (snapshot, _) = apply( "", diff --git a/sqlctx-rs/src/ffi/catalog/compiler.rs b/sqlctx-rs/src/ffi/catalog/compiler.rs new file mode 100644 index 000000000..e6675f478 --- /dev/null +++ b/sqlctx-rs/src/ffi/catalog/compiler.rs @@ -0,0 +1,221 @@ +//! Host-owned immutable graph handles. Never cache physical source bindings. + +use super::*; + +pub struct SqlctxCompiler { + pub(super) graph: SemanticGraph, + pub(super) views: views::PreparedViews, +} + +impl SqlctxCompiler { + fn new(snapshot: &str) -> CatalogResult { + let graph = Snapshot::parse(snapshot)?.into_graph()?; + let views = views::PreparedViews::new(&graph)?; + Ok(Self { graph, views }) + } +} + +#[no_mangle] +pub extern "C" fn sqlctx_compiler_create( + snapshot: *const c_char, + error: *mut *mut c_char, +) -> *mut SqlctxCompiler { + if error.is_null() { + return ptr::null_mut(); + } + unsafe { *error = ptr::null_mut() }; + let result = guard(|| { + let source = optional_arg(snapshot, "snapshot")?; + crate::semantic_input::with_semantic_stack(|| Ok(SqlctxCompiler::new(&source))) + .map_err(|error| error.to_string())? + }); + match result { + Ok(compiler) => Box::into_raw(Box::new(compiler)), + Err(message) => { + unsafe { *error = semantic_error(message) }; + ptr::null_mut() + } + } +} + +#[no_mangle] +pub extern "C" fn sqlctx_compiler_rewrite( + compiler: *const SqlctxCompiler, + sql: *const c_char, +) -> SqlctxRewriteResult { + semantic_result( + guard(|| { + let compiler = unsafe { compiler.as_ref() }.ok_or("null compiler pointer")?; + let sql = required_arg(sql, "sql")?; + rewrite_prepared_graph_diagnostics(&compiler.graph, &compiler.views, &sql) + .map(|(sql, _)| sql) + }) + .map_err(semantic_error), + ) +} + +#[no_mangle] +pub extern "C" fn sqlctx_compiler_free(compiler: *mut SqlctxCompiler) { + if !compiler.is_null() { + drop(unsafe { Box::from_raw(compiler) }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compiler_is_snapshot_owned_and_matches_stateless_rewrite() { + let (source, _) = apply( + "", + "", + "model", + "MODEL orders FROM raw_orders (sum(amount) AS revenue)", + false, + ) + .unwrap(); + let snapshot = CString::new(source.clone()).unwrap(); + let mut error = ptr::null_mut(); + let compiler = sqlctx_compiler_create(snapshot.as_ptr(), &mut error); + assert!(!compiler.is_null()); + assert!(error.is_null()); + let handle = unsafe { &*compiler }; + assert!(std::ptr::eq( + &handle.graph, + handle.views.graph(&handle.graph) + )); + drop(snapshot); + let query = CString::new("SELECT orders.revenue FROM orders").unwrap(); + let expected = rewrite_graph( + &Snapshot::parse(&source).unwrap().into_graph().unwrap(), + query.to_str().unwrap(), + ) + .unwrap(); + for _ in 0..3 { + let result = sqlctx_compiler_rewrite(compiler, query.as_ptr()); + assert!(result.error.is_null()); + assert_eq!( + unsafe { CStr::from_ptr(result.sql) }.to_str().unwrap(), + expected + ); + super::super::super::sqlctx_free_result(result); + } + sqlctx_compiler_free(compiler); + } + + #[test] + fn named_view_handle_matches_stateless_rewrite_and_explain_at_each_grain() { + fn result_text(result: SqlctxRewriteResult) -> String { + assert!( + result.error.is_null(), + "{}", + if result.error.is_null() { + String::new() + } else { + unsafe { CStr::from_ptr(result.error) } + .to_string_lossy() + .into_owned() + } + ); + let text = unsafe { CStr::from_ptr(result.sql) } + .to_str() + .unwrap() + .to_owned(); + super::super::super::sqlctx_free_result(result); + text + } + let (source, _) = apply( + "", + "", + "yaml", + r#" +models: + - name: orders + table: raw_orders + primary_key: id + dimensions: + - {name: status, type: categorical} + metrics: + - {name: paid, agg: sum, sql: amount, filters: ["status = 'paid'"]} + - {name: rows, agg: count} + - {name: average, type: ratio, numerator: paid, denominator: rows} +"#, + false, + ) + .unwrap(); + let (source, _) = apply( + &source, + "orders", + "view", + "sales AS SELECT status AS state, paid, average AS aov FROM orders", + false, + ) + .unwrap(); + let (source, _) = apply( + &source, + "orders", + "view", + "report AS SELECT state, paid AS total, aov FROM sales", + false, + ) + .unwrap(); + let snapshot = CString::new(source.clone()).unwrap(); + let mut error = ptr::null_mut(); + let compiler = sqlctx_compiler_create(snapshot.as_ptr(), &mut error); + assert!(!compiler.is_null()); + assert!(error.is_null()); + drop(snapshot); + let graph = Snapshot::parse(&source).unwrap().into_graph().unwrap(); + for sql in [ + "SELECT total, aov FROM report", + "SELECT state, total, aov FROM report", + "SELECT aov FROM sales WHERE state = 'paid'", + "SELECT total, aov FROM report", + ] { + let query = CString::new(sql).unwrap(); + let expected = rewrite_graph(&graph, sql).unwrap(); + assert_eq!( + result_text(sqlctx_compiler_rewrite(compiler, query.as_ptr())), + expected + ); + let report: serde_json::Value = serde_json::from_str(&result_text( + explain::sqlctx_compiler_explain(compiler, query.as_ptr()), + )) + .unwrap(); + let expected_report: serde_json::Value = + serde_json::from_str(&explain::explain_graph(&graph, sql).unwrap()).unwrap(); + assert_eq!(report, expected_report); + assert_eq!(report["sql"], expected); + } + let (replacement, _) = apply( + &source, + "orders", + "item", + "METRIC paid AS SUM(replacement_amount)", + true, + ) + .unwrap(); + let query = CString::new("SELECT total FROM report").unwrap(); + let original_sql = result_text(sqlctx_compiler_rewrite(compiler, query.as_ptr())); + assert!(!original_sql.contains("replacement_amount")); + let updated_graph = Snapshot::parse(&replacement).unwrap().into_graph().unwrap(); + assert!(rewrite_graph(&updated_graph, query.to_str().unwrap()) + .unwrap() + .contains("replacement_amount")); + sqlctx_compiler_free(compiler); + } + + #[test] + fn compiler_reports_invalid_snapshots_and_null_handles() { + let snapshot = CString::new("{\"version\":99}").unwrap(); + let mut error = ptr::null_mut(); + assert!(sqlctx_compiler_create(snapshot.as_ptr(), &mut error).is_null()); + assert!(!error.is_null()); + sqlctx_free(error); + let result = sqlctx_compiler_rewrite(ptr::null(), ptr::null()); + assert!(!result.error.is_null()); + super::super::super::sqlctx_free_result(result); + sqlctx_compiler_free(ptr::null_mut()); + } +} diff --git a/sqlctx-rs/src/ffi/catalog/explain.rs b/sqlctx-rs/src/ffi/catalog/explain.rs new file mode 100644 index 000000000..f263b87f0 --- /dev/null +++ b/sqlctx-rs/src/ffi/catalog/explain.rs @@ -0,0 +1,282 @@ +use super::*; + +#[no_mangle] +pub extern "C" fn sqlctx_compiler_explain( + compiler: *const compiler::SqlctxCompiler, + sql: *const c_char, +) -> SqlctxRewriteResult { + semantic_result( + guard(|| { + let compiler = unsafe { compiler.as_ref() }.ok_or("null compiler pointer")?; + let sql = required_arg(sql, "sql")?; + explain_prepared_graph(&compiler.graph, &compiler.views, &sql) + }) + .map_err(semantic_error), + ) +} + +/// Compile against exactly the same catalog and routing rules as snapshot +/// rewrite, while retaining observations from the actual compiler invocation. +#[no_mangle] +pub extern "C" fn sqlctx_snapshot_explain( + snapshot: *const c_char, + sql: *const c_char, +) -> SqlctxRewriteResult { + semantic_result( + guard(|| { + let graph = Snapshot::parse(&optional_arg(snapshot, "snapshot")?)?.into_graph()?; + let sql = required_arg(sql, "sql")?; + explain_graph(&graph, &sql) + }) + .map_err(semantic_error), + ) +} + +pub(super) fn explain_graph(graph: &SemanticGraph, sql: &str) -> CatalogResult { + let views = views::PreparedViews::new(graph)?; + explain_prepared_graph(graph, &views, sql) +} + +fn explain_prepared_graph( + graph: &SemanticGraph, + views: &views::PreparedViews, + sql: &str, +) -> CatalogResult { + crate::semantic_input::with_semantic_stack(|| { + let ((compiled, warnings), events) = crate::sql::explain::capture(|| { + rewrite_prepared_graph_diagnostics(graph, views, sql) + .map_err(crate::error::SqlctxError::Validation) + })?; + let mut candidates = graph + .models() + .flat_map(|model| { + model.pre_aggregations.iter().map(|candidate| { + serde_json::json!({ + "model": model.name, "name": candidate.name, + "status": "declared; eligibility is reported only when evaluated", + }) + }) + }) + .collect::>(); + candidates.sort_by_key(serde_json::Value::to_string); + let coverage = concat!( + "Compiler observations; absent events do not imply safety or eligibility. ", + "Specialized routes may expose only their route and query. ", + "Database physical planning, table availability and row counts are not evaluated." + ); + Ok(serde_json::json!({ + "version": 1, "sql": compiled, "warnings": warnings, + "events": events, "rollup_candidates": candidates, "coverage": coverage, + }) + .to_string()) + }) + .map_err(|error| error.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::{Dimension, Metric, Model, Relationship}; + use serde_json::Value; + + fn graph() -> SemanticGraph { + let mut graph = SemanticGraph::new(); + graph + .add_model( + Model::new("orders", "id") + .with_table("raw_orders") + .with_dimension(Dimension::categorical("status")) + .with_metric(Metric::sum("revenue", "amount")) + .with_relationship(Relationship::many_to_one("customers")), + ) + .unwrap(); + graph + .add_model( + Model::new("customers", "id") + .with_table("raw_customers") + .with_dimension(Dimension::categorical("country")) + .with_metric(Metric::count("customers_count")), + ) + .unwrap(); + graph + } + + fn explain(sql: &str) -> Value { + let graph = graph(); + let snapshot = + CString::new(serde_json::to_string(&Snapshot::from_graph(&graph)).unwrap()).unwrap(); + let query = CString::new(sql).unwrap(); + let report = sqlctx_snapshot_explain(snapshot.as_ptr(), query.as_ptr()); + assert!( + report.error.is_null(), + "{}", + if report.error.is_null() { + String::new() + } else { + unsafe { CStr::from_ptr(report.error) } + .to_string_lossy() + .into_owned() + } + ); + let value = + serde_json::from_str(unsafe { CStr::from_ptr(report.sql) }.to_str().unwrap()).unwrap(); + super::super::super::sqlctx_free_result(report); + value + } + + #[test] + fn explanation_uses_the_same_compilation_and_reports_population_changes() { + let sql = + "select customers.country, orders.revenue from orders where customers.country = 'US'"; + let report = explain(sql); + assert_eq!( + report["sql"], + QueryRewriter::new(&graph()) + .with_qualified_tables_physical() + .rewrite_with_dialect(sql, polyglot_sql::DialectType::DuckDB) + .unwrap() + ); + let events = report["events"].as_array().unwrap(); + assert!(events.iter().any(|event| event["kind"] == "grain" + && event["dimensions"] == serde_json::json!(["customers.country"]))); + assert!(events.iter().any(|event| event["kind"] == "join" + && event["from"] == "orders" + && event["to"] == "customers" + && event["join_type"] == "INNER JOIN")); + assert!(!events.iter().any(|event| event["kind"] == "fanout_guard")); + } + + #[test] + fn fanout_explanation_records_symmetric_guard_and_physical_passthrough_is_empty() { + let report = explain("select orders.status, customers.customers_count from customers"); + let events = report["events"].as_array().unwrap(); + assert!(events.iter().any(|event| event["kind"] == "fanout_guard" + && event["model"] == "customers" + && event["strategy"] == "count_distinct_entity" + && event["entity_keys"] == serde_json::json!(["id"]))); + assert_eq!( + explain("select * from main.orders")["events"], + serde_json::json!([]) + ); + } + + #[test] + fn named_selection_explanation_uses_filtered_ratio_expansion() { + let (snapshot, _) = apply( + "", + "", + "yaml", + r#" +models: + - name: orders + table: raw_orders + primary_key: id + dimensions: + - {name: status, type: categorical} + metrics: + - {name: paid, agg: sum, sql: amount, filters: ["status = 'paid'"]} + - {name: rows, agg: count} + - {name: average, type: ratio, numerator: paid, denominator: rows} +"#, + false, + ) + .unwrap(); + let (snapshot, _) = apply( + &snapshot, + "orders", + "view", + "sales AS SELECT status, paid, average AS aov FROM orders", + false, + ) + .unwrap(); + let graph = Snapshot::parse(&snapshot).unwrap().into_graph().unwrap(); + for sql in [ + "select status, aov, paid from sales", + "select aov, paid from sales", + ] { + let report: Value = serde_json::from_str(&explain_graph(&graph, sql).unwrap()).unwrap(); + assert_eq!(report["sql"], rewrite_graph(&graph, sql).unwrap()); + let compiled = report["sql"].as_str().unwrap(); + assert!( + compiled.contains("NULLIF") && compiled.contains("CASE WHEN"), + "{compiled}" + ); + assert!(!report["events"].as_array().unwrap().is_empty()); + } + } + + #[test] + fn compiler_events_follow_actual_aggregate_and_rollup_routes() { + crate::semantic_input::with_semantic_stack(|| { + let mut graph = graph(); + graph.set_metric_scopes(Default::default()).unwrap(); + let query = crate::sql::SemanticQuery::new() + .with_dimensions(vec!["orders.status".into()]) + .with_metrics(vec!["customers.customers_count".into()]); + let (sql, events) = crate::sql::explain::capture(|| { + crate::sql::SqlGenerator::new(&graph).generate(&query) + })?; + assert!( + events.iter().any(|event| event["kind"] == "aggregate_plan"), + "{sql}\n{events:?}" + ); + assert!( + events + .iter() + .any(|event| event["strategy"] == "distinct_entity_rows"), + "{events:?}" + ); + + let mut graph = self::graph(); + let mut orders = graph.get_model("orders").unwrap().clone(); + orders.pre_aggregations.push( + serde_json::from_value(serde_json::json!({ + "name": "by_status", "dimensions": ["status"], "measures": ["revenue"] + })) + .unwrap(), + ); + graph.replace_model(orders).unwrap(); + let query = crate::sql::SemanticQuery::new() + .with_dimensions(vec!["orders.status".into()]) + .with_metrics(vec!["orders.revenue".into()]) + .with_use_preaggregations(true); + let (sql, events) = crate::sql::explain::capture(|| { + crate::sql::SqlGenerator::new(&graph).generate(&query) + })?; + assert!(sql.contains("used_preagg=true")); + assert!(events + .iter() + .any(|event| event["kind"] == "rollup_selected" && event["name"] == "by_status")); + Ok(()) + }) + .unwrap(); + } + + #[test] + fn declared_rollups_are_not_claimed_eligible_when_routing_is_disabled() { + let mut graph = graph(); + let mut orders = graph.get_model("orders").unwrap().clone(); + orders.pre_aggregations.push( + serde_json::from_value(serde_json::json!({ + "name": "by_status", "dimensions": ["status"], "measures": ["revenue"] + })) + .unwrap(), + ); + graph.replace_model(orders).unwrap(); + let report: Value = serde_json::from_str( + &explain_graph(&graph, "select status, revenue from orders").unwrap(), + ) + .unwrap(); + assert_eq!(report["rollup_candidates"][0]["name"], "by_status"); + assert!(report["events"] + .as_array() + .unwrap() + .iter() + .any(|event| event["kind"] == "query" && event["rollup_routing_enabled"] == false)); + assert!(!report["events"] + .as_array() + .unwrap() + .iter() + .any(|event| event["kind"] == "rollup_selected")); + } +} diff --git a/sqlctx-rs/src/ffi/catalog/views.rs b/sqlctx-rs/src/ffi/catalog/views.rs new file mode 100644 index 000000000..22d0c0ec7 --- /dev/null +++ b/sqlctx-rs/src/ffi/catalog/views.rs @@ -0,0 +1,801 @@ +//! Named selections retain semantic fields; they never persist an aggregated SQL result. +use std::collections::{HashMap, HashSet}; + +use polyglot_sql::{expressions::Identifier, DialectType, Expression}; +use serde_json::{json, Value}; + +use super::*; + +const VIEW_KEY: &str = "sqlctx_semantic_view"; + +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct ViewDefinition { + pub source: String, + pub fields: Vec, + pub sql: String, +} + +#[derive(Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(super) struct ViewField { + pub name: String, + pub source: String, + pub kind: String, +} + +pub(super) fn definition(model: &Model) -> CatalogResult> { + model + .metadata + .as_ref() + .and_then(|metadata| metadata.get(VIEW_KEY)) + .map(|value| { + serde_json::from_value(value.clone()) + .map_err(|error| format!("invalid semantic view '{}': {error}", model.name)) + }) + .transpose() +} + +fn source_field(source: &Model, name: &str) -> CatalogResult { + if let Some(field) = source + .dimensions + .iter() + .find(|field| field.name.eq_ignore_ascii_case(name)) + { + return Ok(ViewField { + name: field.name.clone(), + source: field.name.clone(), + kind: "dimension".into(), + }); + } + if let Some(field) = source + .metrics + .iter() + .find(|field| field.name.eq_ignore_ascii_case(name)) + { + return Ok(ViewField { + name: field.name.clone(), + source: field.name.clone(), + kind: "metric".into(), + }); + } + Err(format!( + "semantic view source '{}' has no dimension or metric '{name}'", + source.name + )) +} + +pub(super) fn create(snapshot: &mut Snapshot, content: &str, replace: bool) -> CatalogResult<()> { + let (name, rest) = declaration_identifier(content).ok_or("semantic view requires a name")?; + let (keyword, sql) = declaration_identifier(rest).ok_or("semantic view requires AS SELECT")?; + if !keyword.eq_ignore_ascii_case("AS") { + return Err("semantic view requires AS SELECT".into()); + } + let ast = crate::semantic_input::dialects::parse(sql, DialectType::DuckDB) + .map_err(|error| error.to_string())?; + let Expression::Select(select) = ast else { + return Err("semantic view requires a SELECT projection".into()); + }; + // A semantic selection has no fixed grain, ordering or row limit. Reject + // SQL shapes whose ordinary relational meaning would freeze that grain. + let mut shape = (*select).clone(); + shape.expressions.clear(); + shape.from = None; + shape.leading_comments.clear(); + shape.post_select_comments.clear(); + if shape != polyglot_sql::expressions::Select::new() { + return Err("semantic view expects dimensions and metrics from one source, without WHERE, GROUP BY, ORDER BY or LIMIT".into()); + } + let sources = select + .from + .as_ref() + .map(|from| from.expressions.as_slice()) + .unwrap_or_default(); + let [Expression::Table(table)] = sources else { + return Err("semantic view requires exactly one model or semantic view source".into()); + }; + if table.catalog.is_some() + || table + .schema + .as_ref() + .is_some_and(|schema| !schema.name.eq_ignore_ascii_case("semantic")) + || !table.column_aliases.is_empty() + { + return Err( + "semantic view source must be an unqualified model/view or semantic.".into(), + ); + } + let source = snapshot + .models + .iter() + .find(|model| model.name.eq_ignore_ascii_case(&table.name.name)) + .ok_or_else(|| format!("semantic view source '{}' not found", table.name.name))?; + let qualifier = table.alias.as_ref().unwrap_or(&table.name); + let mut fields = Vec::new(); + for expression in &select.expressions { + let (expression, alias) = match expression { + Expression::Alias(alias) => (&alias.this, Some(&alias.alias.name)), + other => (other, None), + }; + match expression { + Expression::Column(column) if column.table.as_ref().is_none_or(|table| table.name.eq_ignore_ascii_case(&qualifier.name)) => { + let mut field = source_field(source, &column.name.name)?; + if let Some(alias) = alias { field.name = alias.clone(); } + fields.push(field); + } + Expression::Star(star) if alias.is_none() + && star.table.as_ref().is_none_or(|table| table.name.eq_ignore_ascii_case(&qualifier.name)) + && star.except.is_none() && star.replace.is_none() && star.rename.is_none() => { + if let Some(view) = self::definition(source)? { + for field in view.fields { fields.push(source_field(source, &field.name)?); } + } else { + for name in source.dimensions.iter().map(|field| &field.name).chain(source.metrics.iter().map(|field| &field.name)) { + fields.push(source_field(source, name)?); + } + } + } + _ => return Err("semantic view selections must be dimension or metric references, optionally renamed with AS".into()), + } + } + let mut names = HashSet::new(); + if fields.is_empty() + || fields + .iter() + .any(|field| !names.insert(field.name.to_ascii_lowercase())) + { + return Err("semantic view requires nonempty, unique output names".into()); + } + let definition = ViewDefinition { + source: source.name.clone(), + fields, + sql: sql.trim().to_owned(), + }; + let existing = snapshot + .models + .iter() + .position(|model| model.name.eq_ignore_ascii_case(&name)); + let canonical_name = if let Some(index) = existing { + if self::definition(&snapshot.models[index])?.is_none() { + return Err(format!("'{name}' is a model, not a semantic view")); + } + if !replace { + return Err(format!("semantic view '{name}' already exists")); + } + snapshot.models[index].name.clone() + } else { + name + }; + // Discovery describes the authored selection. A semantic view has no + // physical table or fixed primary key because its grain belongs to a query. + let mut model = Model::new(canonical_name, "").with_sql(definition.sql.clone()); + model.metadata = Some(json!({VIEW_KEY: definition})); + if let Some(index) = existing { + snapshot.models[index] = model; + } else { + snapshot.models.push(model); + } + refresh(&mut snapshot.models) +} + +/// Rebind selections on every reconstruction. Compatible source replacements +/// flow through existing views; removed fields, changed field kinds and cycles +/// fail before the host can publish a candidate catalog. +pub(super) fn refresh(models: &mut Vec) -> CatalogResult<()> { + fn resolve( + index: usize, + models: &mut [Model], + resolved: &mut HashSet, + visiting: &mut HashSet, + ) -> CatalogResult<()> { + if resolved.contains(&index) { + return Ok(()); + } + let Some(view) = definition(&models[index])? else { + resolved.insert(index); + return Ok(()); + }; + if !visiting.insert(index) { + return Err(format!( + "cyclic semantic view dependency involving '{}'", + models[index].name + )); + } + let source_index = models + .iter() + .position(|model| model.name.eq_ignore_ascii_case(&view.source)) + .ok_or_else(|| { + format!( + "semantic view '{}' depends on missing source '{}' (RESTRICT)", + models[index].name, view.source + ) + })?; + resolve(source_index, models, resolved, visiting)?; + let source = models[source_index].clone(); + let model = &mut models[index]; + model.dimensions.clear(); + model.metrics.clear(); + for field in &view.fields { + let current = source_field(&source, &field.source).map_err(|error| { + format!( + "semantic view '{}' dependency: {error} (RESTRICT)", + model.name + ) + })?; + if current.kind != field.kind { + return Err(format!( + "semantic view '{}' field '{}' changed semantic kind (RESTRICT)", + model.name, field.source + )); + } + if field.kind == "dimension" { + let mut dimension = source + .dimensions + .iter() + .find(|item| item.name == current.source) + .unwrap() + .clone(); + dimension.name = field.name.clone(); + model.dimensions.push(dimension); + } else { + let mut metric = source + .metrics + .iter() + .find(|item| item.name == current.source) + .unwrap() + .clone(); + metric.name = field.name.clone(); + model.metrics.push(metric); + } + } + visiting.remove(&index); + resolved.insert(index); + Ok(()) + } + let mut resolved = HashSet::new(); + for index in 0..models.len() { + resolve(index, models, &mut resolved, &mut HashSet::new())?; + } + Ok(()) +} + +pub(super) fn restrict( + snapshot: &Snapshot, + source: &str, + field: Option<&str>, +) -> CatalogResult<()> { + for model in &snapshot.models { + if let Some(view) = definition(model)? { + if view.source.eq_ignore_ascii_case(source) + && field.is_none_or(|field| { + view.fields + .iter() + .any(|item| item.source.eq_ignore_ascii_case(field)) + }) + { + return Err(format!( + "cannot drop '{source}': dependent semantic view '{}' (RESTRICT)", + model.name + )); + } + } + } + Ok(()) +} + +#[derive(Clone)] +struct Binding { + source: String, + fields: Vec, +} + +fn bindings(graph: &SemanticGraph) -> CatalogResult> { + let mut result = HashMap::new(); + for model in graph.models() { + let Some(view) = definition(model)? else { + continue; + }; + let mut binding = Binding { + source: view.source, + fields: view.fields, + }; + while let Some(parent) = definition( + graph + .get_model(&binding.source) + .ok_or("missing semantic view source")?, + )? { + for field in &mut binding.fields { + field.source = parent + .fields + .iter() + .find(|parent| parent.name.eq_ignore_ascii_case(&field.source)) + .ok_or("missing nested semantic view field")? + .source + .clone(); + } + binding.source = parent.source; + } + result.insert(model.name.to_ascii_lowercase(), binding); + } + Ok(result) +} + +/// Resolve immutable catalog state once, independently of each query. View +/// descriptors belong to discovery, not source metric resolution; catalogs +/// without views reuse their original graph without allocating another copy. +pub(super) struct PreparedViews { + bindings: HashMap, + source_graph: Option, +} + +impl PreparedViews { + pub(super) fn new(graph: &SemanticGraph) -> CatalogResult { + let bindings = bindings(graph)?; + let source_graph = if bindings.is_empty() { + None + } else { + let mut snapshot = Snapshot::from_graph(graph); + snapshot + .models + .retain(|model| !bindings.contains_key(&model.name.to_ascii_lowercase())); + Some(snapshot.into_graph()?) + }; + Ok(Self { + bindings, + source_graph, + }) + } + + pub(super) fn graph<'a>(&'a self, original: &'a SemanticGraph) -> &'a SemanticGraph { + self.source_graph.as_ref().unwrap_or(original) + } + + pub(super) fn expand(&self, sql: &str) -> CatalogResult { + expand_bindings(&self.bindings, sql) + } +} + +/// Expand only column bindings, never an aggregate result subquery. The normal +/// compiler then selects source measures at the caller's requested grain. +fn expand_bindings(views: &HashMap, sql: &str) -> CatalogResult { + if views.is_empty() { + return Ok(sql.to_owned()); + } + type Scope = HashMap>; + fn source( + node: &mut Value, + views: &HashMap, + scope: &mut Scope, + ctes: &HashSet, + ) -> CatalogResult<()> { + if let Some(table) = node.get_mut("table") { + let name = table["name"]["name"].as_str().unwrap_or("").to_owned(); + let alias = table["alias"]["name"].as_str().unwrap_or(&name).to_owned(); + let semantic_schema = table["schema"]["name"] + .as_str() + .is_some_and(|schema| schema.eq_ignore_ascii_case("semantic")); + let binding = if table["catalog"].is_null() + && (semantic_schema + || table["schema"].is_null() && !ctes.contains(&name.to_ascii_lowercase())) + { + views.get(&name.to_ascii_lowercase()).cloned() + } else { + None + }; + if let Some(binding) = &binding { + table["name"] = serde_json::to_value(Identifier::quoted(&binding.source)).unwrap(); + table["alias"] = serde_json::to_value(Identifier::quoted(&alias)).unwrap(); + table["schema"] = Value::Null; + } + scope.insert(alias.to_ascii_lowercase(), binding); + return Ok(()); + } + if let Some(subquery) = node.get_mut("subquery") { + visit(&mut subquery["this"], views, scope, ctes, &HashSet::new())?; + if let Some(alias) = subquery["alias"]["name"].as_str() { + scope.insert(alias.to_ascii_lowercase(), None); + } + return Ok(()); + } + match node { + Value::Object(fields) => { + for child in fields.values_mut() { + source(child, views, scope, ctes)?; + } + } + Value::Array(children) => { + for child in children { + source(child, views, scope, ctes)?; + } + } + _ => {} + } + Ok(()) + } + fn visit( + node: &mut Value, + views: &HashMap, + outer: &Scope, + inherited_ctes: &HashSet, + output_aliases: &HashSet, + ) -> CatalogResult<()> { + if let Some(select) = node.get_mut("select") { + let mut ctes = inherited_ctes.clone(); + if let Some(with) = select.get_mut("with").filter(|value| !value.is_null()) { + let recursive = with["recursive"].as_bool() == Some(true); + for cte in with["ctes"].as_array_mut().into_iter().flatten() { + let name = cte["alias"]["name"] + .as_str() + .unwrap_or("") + .to_ascii_lowercase(); + if recursive { + ctes.insert(name.clone()); + } + visit(&mut cte["this"], views, outer, &ctes, &HashSet::new())?; + ctes.insert(name); + } + } + let mut scope = outer.clone(); + source(&mut select["from"], views, &mut scope, &ctes)?; + for join in select["joins"].as_array_mut().into_iter().flatten() { + source(&mut join["this"], views, &mut scope, &ctes)?; + } + let mut projections = Vec::new(); + for projection in select["expressions"].as_array().into_iter().flatten() { + if let Some(star) = projection.get("star") { + let target = star["table"]["name"].as_str().map(str::to_ascii_lowercase); + let binding = target + .as_ref() + .and_then(|target| scope.get_key_value(target)) + .or_else(|| { + if target.is_none() && scope.len() == 1 { + scope.iter().next() + } else { + None + } + }); + if let Some((alias, Some(binding))) = binding { + if !star["except"].is_null() + || !star["replace"].is_null() + || !star["rename"].is_null() + { + return Err( + "semantic view wildcard modifiers must be resolved by the host" + .into(), + ); + } + for field in &binding.fields { + let mut column = Expression::qualified_column(alias, &field.name); + if let Expression::Column(column) = &mut column { + column.name = Identifier::quoted(&field.name); + column.table = Some(Identifier::quoted(alias)); + } + projections.push( + serde_json::to_value(column).map_err(|error| error.to_string())?, + ); + } + continue; + } + } + projections.push(projection.clone()); + } + select["expressions"] = Value::Array(projections); + let output_aliases: HashSet<_> = select["expressions"] + .as_array() + .into_iter() + .flatten() + .filter_map(|projection| projection["alias"]["alias"]["name"].as_str()) + .map(str::to_ascii_lowercase) + .collect(); + // Preserve the authored column name when its source name differs. + for projection in select["expressions"].as_array_mut().into_iter().flatten() { + let original_name = projection + .get("column") + .and_then(|column| column["name"]["name"].as_str()) + .map(str::to_owned); + visit(projection, views, &scope, &ctes, &HashSet::new())?; + if let Some(name) = original_name { + if projection["column"]["name"]["name"].as_str() != Some(&name) { + let expression: Expression = serde_json::from_value(projection.clone()) + .map_err(|error| error.to_string())?; + let mut aliased = expression.alias(&name); + if let Expression::Alias(alias) = &mut aliased { + alias.alias = Identifier::quoted(name); + } + *projection = + serde_json::to_value(aliased).map_err(|error| error.to_string())?; + } + } + } + for (key, child) in select.as_object_mut().unwrap() { + if !matches!(key.as_str(), "from" | "with" | "expressions") { + if key == "joins" { + for join in child.as_array_mut().into_iter().flatten() { + for (key, child) in join.as_object_mut().unwrap() { + if key != "this" { + visit(child, views, &scope, &ctes, &output_aliases)?; + } + } + } + } else { + visit(child, views, &scope, &ctes, &output_aliases)?; + } + } + } + return Ok(()); + } + if let Some(column) = node.get_mut("column") { + let field = column["name"]["name"].as_str().unwrap_or("").to_owned(); + let binding = if let Some(table) = column["table"]["name"].as_str() { + outer + .get(&table.to_ascii_lowercase()) + .and_then(Option::as_ref) + } else if outer.len() == 1 { + outer.values().next().and_then(Option::as_ref) + } else { + None + }; + if let Some(binding) = binding { + let selected = binding + .fields + .iter() + .find(|item| item.name.eq_ignore_ascii_case(&field)); + if selected.is_none() + && column["table"].is_null() + && output_aliases.contains(&field.to_ascii_lowercase()) + { + return Ok(()); + } + let source = if let Some(selected) = selected { + selected.source.clone() + } else if let Some((base, granularity)) = field.rsplit_once("__") { + let selected = binding + .fields + .iter() + .find(|item| { + item.kind == "dimension" && item.name.eq_ignore_ascii_case(base) + }) + .ok_or_else(|| format!("semantic view has no selected field '{field}'"))?; + format!("{}__{granularity}", selected.source) + } else { + return Err(format!("semantic view has no selected field '{field}'")); + }; + column["name"] = serde_json::to_value(Identifier::quoted(source)).unwrap(); + } + return Ok(()); + } + match node { + Value::Object(fields) => { + for child in fields.values_mut() { + visit(child, views, outer, inherited_ctes, output_aliases)?; + } + } + Value::Array(children) => { + for child in children { + visit(child, views, outer, inherited_ctes, output_aliases)?; + } + } + _ => {} + } + Ok(()) + } + crate::semantic_input::with_semantic_stack(|| { + let ast = crate::semantic_input::dialects::parse(sql, DialectType::DuckDB)?; + let mut ast = serde_json::to_value(ast) + .map_err(|error| crate::error::SqlctxError::SqlGeneration(error.to_string()))?; + visit( + &mut ast, + views, + &Scope::new(), + &HashSet::new(), + &HashSet::new(), + ) + .map_err(crate::error::SqlctxError::SqlGeneration)?; + let ast = serde_json::from_value(ast) + .map_err(|error| crate::error::SqlctxError::SqlGeneration(error.to_string()))?; + polyglot_sql::generate(&ast, DialectType::DuckDB) + .map_err(|error| crate::error::SqlctxError::SqlGeneration(error.to_string())) + }) + .map_err(|error| error.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn expand(graph: &SemanticGraph, sql: &str) -> CatalogResult { + PreparedViews::new(graph)?.expand(sql) + } + + fn catalog() -> String { + apply( + "", + "", + "yaml", + r#" +models: + - name: orders + table: raw_orders + primary_key: id + dimensions: + - {name: status, type: categorical} + - {name: country, type: categorical} + metrics: + - {name: revenue, agg: sum, sql: amount} + - {name: paid, agg: sum, sql: amount, filters: ["status = 'paid'"]} + - {name: rows, agg: count} + - {name: average, type: ratio, numerator: revenue, denominator: rows} +"#, + false, + ) + .unwrap() + .0 + } + + fn view(snapshot: &str, content: &str, replace: bool) -> CatalogResult { + apply(snapshot, "orders", "view", content, replace).map(|result| result.0) + } + + fn compile(snapshot: &str, sql: &str) -> String { + let graph = Snapshot::parse(snapshot).unwrap().into_graph().unwrap(); + rewrite_graph(&graph, sql).unwrap() + } + + #[test] + fn selections_regrain_filtered_measures_and_ratios() { + let snapshot = view( + &catalog(), + "sales AS SELECT status, paid, average AS aov FROM orders", + false, + ) + .unwrap(); + let total = compile(&snapshot, "SELECT aov, paid FROM sales"); + assert!( + total.contains("NULLIF") && total.contains("CASE WHEN"), + "{total}" + ); + assert!(!total.contains("GROUP BY"), "{total}"); + let grouped = compile(&snapshot, "SELECT status, aov, paid FROM sales"); + assert!(grouped.contains("GROUP BY"), "{grouped}"); + assert!(grouped.contains("raw_orders"), "{grouped}"); + assert!(!grouped.contains("__semantic_view"), "{grouped}"); + let graph = Snapshot::parse(&snapshot).unwrap().into_graph().unwrap(); + let star = expand(&graph, "SELECT * FROM sales").unwrap(); + assert!( + !star.contains("country") && !star.contains("revenue"), + "{star}" + ); + assert!(expand(&graph, "SELECT country FROM sales").is_err()); + } + + #[test] + fn nested_views_preserve_names_and_bind_replacements_dynamically() { + let base = view( + &catalog(), + "sales AS SELECT status, revenue AS gross FROM orders", + false, + ) + .unwrap(); + let nested = view( + &base, + "report AS SELECT status AS state, gross AS total FROM sales", + false, + ) + .unwrap(); + let sql = compile(&nested, "SELECT state, total FROM report"); + assert!( + sql.contains("amount") && sql.contains("total") && sql.contains("state"), + "{sql}" + ); + let replaced = apply( + &nested, + "orders", + "item", + "METRIC revenue AS SUM(replacement_amount)", + true, + ) + .unwrap() + .0; + assert!(compile(&replaced, "SELECT total FROM report").contains("replacement_amount")); + assert!(!compile(&nested, "SELECT total FROM report").contains("replacement_amount")); + assert!(view(&nested, "sales AS SELECT status FROM orders", true) + .unwrap_err() + .contains("gross")); + assert!(compile(&nested, "SELECT total FROM report").contains("amount")); + let exported = serde_json::to_string(&Snapshot::from_graph( + &Snapshot::parse(&nested).unwrap().into_graph().unwrap(), + )) + .unwrap(); + assert_eq!( + compile(&nested, "SELECT total FROM report"), + compile(&exported, "SELECT total FROM report") + ); + } + + #[test] + fn view_dependencies_restrict_drop_and_incompatible_replacement() { + let snapshot = view( + &catalog(), + "sales AS SELECT status, revenue FROM orders", + false, + ) + .unwrap(); + for (operation, content) in [ + ("drop_model", r#"["orders"]"#), + ("drop_metric", r#"["orders","revenue"]"#), + ("drop_dimension", r#"["orders","status"]"#), + ] { + let error = apply(&snapshot, "orders", operation, content, false).unwrap_err(); + assert!( + error.contains("sales") && error.contains("RESTRICT"), + "{error}" + ); + } + assert!(apply( + &snapshot, + "orders", + "model", + "MODEL (name orders, table replacement)", + true + ) + .unwrap_err() + .contains("sales")); + let nested = view(&snapshot, "report AS SELECT revenue FROM sales", false).unwrap(); + assert!(apply(&nested, "orders", "drop_view", r#"["sales"]"#, false) + .unwrap_err() + .contains("report")); + assert!(view(&snapshot, "sales AS SELECT revenue FROM sales", true) + .unwrap_err() + .contains("cyclic")); + let dropped = apply(&snapshot, "orders", "drop_view", r#"["sales"]"#, false) + .unwrap() + .0; + assert_eq!(Snapshot::parse(&dropped).unwrap().models.len(), 1); + assert!(apply(&snapshot, "orders", "drop_model", r#"["sales"]"#, false).is_err()); + assert!(apply(&snapshot, "orders", "drop_view", r#"["orders"]"#, false).is_err()); + } + + #[test] + fn view_expansion_respects_cte_and_physical_scope() { + let snapshot = view( + &catalog(), + "sales AS SELECT revenue AS gross FROM orders", + false, + ) + .unwrap(); + let graph = Snapshot::parse(&snapshot).unwrap().into_graph().unwrap(); + for sql in [ + "SELECT gross FROM main.sales", + "WITH sales AS (SELECT 7 AS gross) SELECT gross FROM sales", + ] { + assert!(!expand(&graph, sql).unwrap().contains("orders")); + } + let sql = expand(&graph, "SELECT q.gross FROM (SELECT gross FROM sales) q").unwrap(); + assert!( + sql.contains("AS \"gross\"") && sql.contains("q.gross"), + "{sql}" + ); + let aliased = expand(&graph, "SELECT gross AS total FROM sales ORDER BY total").unwrap(); + assert!(aliased.contains("ORDER BY total"), "{aliased}"); + let quoted = view( + &catalog(), + "\"Sales Report\" AS SELECT revenue AS \"Gross Amount\" FROM orders", + false, + ) + .unwrap(); + let graph = Snapshot::parse("ed).unwrap().into_graph().unwrap(); + let star = expand(&graph, "SELECT * FROM \"Sales Report\"").unwrap(); + assert!(star.contains("AS \"Gross Amount\""), "{star}"); + assert!( + polyglot_sql::parse_one(&star, DialectType::DuckDB).is_ok(), + "{star}" + ); + for sql in [ + "sales AS SELECT SUM(revenue) FROM orders", + "sales AS SELECT revenue FROM orders GROUP BY ALL", + "sales AS SELECT revenue FROM missing", + "sales AS SELECT revenue, revenue FROM orders", + ] { + assert!(view(&catalog(), sql, false).is_err(), "{sql}"); + } + } +} diff --git a/sqlctx-rs/src/sql/explain.rs b/sqlctx-rs/src/sql/explain.rs new file mode 100644 index 000000000..09ef3d8fb --- /dev/null +++ b/sqlctx-rs/src/sql/explain.rs @@ -0,0 +1,68 @@ +//! Opt-in compiler observations. Events are recorded at planning decisions, +//! never inferred from generated SQL or a second approximation of the planner. + +use std::cell::RefCell; + +use serde_json::{json, Value}; + +use crate::error::Result; +use crate::sql::SemanticQuery; + +thread_local! { + static EVENTS: RefCell>> = const { RefCell::new(None) }; +} + +/// The caller must enter the protected semantic stack before capture so all +/// nested generators run on this thread. Drop restores state even on errors. +pub(crate) fn capture(operation: impl FnOnce() -> Result) -> Result<(T, Vec)> { + struct Restore(Option>); + impl Drop for Restore { + fn drop(&mut self) { + EVENTS.with(|events| *events.borrow_mut() = self.0.take()); + } + } + let previous = EVENTS.with(|events| events.replace(Some(Vec::new()))); + let _restore = Restore(previous); + let result = operation()?; + let events = EVENTS.with(|events| events.borrow_mut().take().unwrap_or_default()); + Ok((result, events)) +} + +pub(super) fn record(event: impl FnOnce() -> Value) { + EVENTS.with(|events| { + if let Some(events) = events.borrow_mut().as_mut() { + events.push(event()); + } + }); +} + +pub(super) fn query(query: &SemanticQuery) { + record(|| { + json!({ + "kind": "query", "metrics": query.metrics, "dimensions": query.dimensions, + "ungrouped": query.ungrouped, "filters": query.filters, "segments": query.segments, + "population_anchor": query.consumption_base_model, + "rollup_routing_enabled": query.use_preaggregations, + }) + }); +} + +pub(super) fn join(step: &crate::core::JoinStep, kind: &str) { + let effect = match kind { + "INNER JOIN" => "keep matching rows on both sides", + "LEFT JOIN" => "preserve left rows; unmatched right fields are null", + "RIGHT JOIN" => "preserve right rows; unmatched left fields are null", + "FULL JOIN" => "preserve unmatched rows on both sides", + "CROSS JOIN" => "cartesian population; an empty side removes all rows", + _ => "see compiled SQL", + }; + record(|| { + json!({ + "kind": "join", "from": step.from_model, "to": step.to_model, + "edge_id": step.edge_id, "relationship": step.relationship_type, + "from_keys": step.from_keys, "to_keys": step.to_keys, + "condition": step.custom_condition, "join_type": kind, + "population_effect": effect, "expands_left_grain": step.causes_fan_out(), + }) + }); +} diff --git a/sqlctx-rs/src/sql/generator.rs b/sqlctx-rs/src/sql/generator.rs index ede8bc53f..987bea348 100644 --- a/sqlctx-rs/src/sql/generator.rs +++ b/sqlctx-rs/src/sql/generator.rs @@ -250,7 +250,11 @@ impl<'a> SqlGenerator<'a> { // parsing, AST transformation, serialization and destruction on the same // protected stack instead of returning a deep AST to the caller stack. crate::semantic_input::with_semantic_stack(|| { + super::explain::query(query); if self.uses_latest_ossie() { + super::explain::record( + || serde_json::json!({"kind": "route", "name": "latest_ossie"}), + ); return self.generate_latest_ossie(query); } if let Some(graph) = self.prepare_imported_window_dimensions()? { @@ -467,6 +471,12 @@ impl<'a> SqlGenerator<'a> { // Detect fan-out risk for symmetric aggregate handling let fan_out_at_risk = self.detect_fan_out_risk(&base_model, &join_paths); + super::explain::record(|| { + let mut at_risk: Vec<_> = fan_out_at_risk.iter().collect(); + at_risk.sort(); + serde_json::json!({"kind": "source_plan", "anchor": base_model, "fanout_at_risk": at_risk, + "filters": all_filters}) + }); let cte_models = self.collect_models_in_join_plan(&base_model, &join_paths); let mut alias_collisions: HashMap = HashMap::new(); for dim_ref in &dimension_refs { @@ -702,6 +712,14 @@ impl<'a> SqlGenerator<'a> { )); } + super::explain::record(|| { + serde_json::json!({ + "kind": "grain", "dimensions": effective_dimensions, + "expressions": group_expressions, "ungrouped": query.ungrouped, + "meaning": if query.ungrouped { "source rows" } else { "one row per dimension tuple; empty dimensions means scalar aggregate" }, + }) + }); + // Add metrics to SELECT for metric_ref in &metric_refs { let model = self.graph.get_model(&metric_ref.model).ok_or_else(|| { @@ -724,6 +742,21 @@ impl<'a> SqlGenerator<'a> { let sql_expr = match metric.r#type { MetricType::Simple if query.ungrouped => raw_col.clone(), MetricType::Simple if use_symmetric => { + let guard = match metric.agg { + Some(Aggregation::Sum | Aggregation::Avg) => Some("row_number_per_entity"), + Some(Aggregation::Count) => Some("count_distinct_entity"), + Some(Aggregation::CountDistinct) => Some("count_distinct_value"), + _ => None, + }; + if let Some(strategy) = guard { + super::explain::record(|| { + serde_json::json!({ + "kind": "fanout_guard", "model": model.name, "metric": metric.name, + "strategy": strategy, "aggregation": metric.agg, + "entity_keys": model.primary_keys(), + }) + }); + } // Use symmetric aggregate to prevent fan-out inflation if self.graph.has_strict_metric_scope() && model.primary_keys().len() != 1 { if model.primary_keys().is_empty() { @@ -880,6 +913,7 @@ impl<'a> SqlGenerator<'a> { let to_alias = self.model_alias(&step.to_model); if step.relationship_type == RelationshipType::Cross { + super::explain::join(step, "CROSS JOIN"); sql.push_str(&format!( "CROSS JOIN {0} AS {0}\n", self.quote_identifier(&to_alias) @@ -925,6 +959,7 @@ impl<'a> SqlGenerator<'a> { } else { "LEFT JOIN" }; + super::explain::join(step, join_type); sql.push_str(&format!( "{join_type} {0} AS {0} ON {join_condition}\n", self.quote_identifier(&to_alias) @@ -4917,6 +4952,12 @@ impl<'a> SqlGenerator<'a> { if let Some(offset) = query.offset { sql.push_str(&format!("\nOFFSET {offset}")); } + super::explain::record(|| { + serde_json::json!({ + "kind": "rollup_selected", "model": model_name, "name": preagg.name, "route": "join_key" + }) + }); + super::explain::join(hop, "LEFT JOIN"); Ok(Some(format!("{sql}\n-- used_preagg=true"))) } @@ -5021,13 +5062,20 @@ impl<'a> SqlGenerator<'a> { continue; } } - if !self.preaggregation_can_satisfy_query( + let compatible = self.preaggregation_can_satisfy_query( model, preagg, &query_metric_names, dimension_refs, &filter_plan.dimensions, - ) { + ); + super::explain::record(|| { + serde_json::json!({ + "kind": "rollup_candidate", "model": model_name, "name": preagg.name, + "query_shape_compatible": compatible, + }) + }); + if !compatible { continue; } @@ -5063,6 +5111,11 @@ impl<'a> SqlGenerator<'a> { ungrouped, )?; + super::explain::record(|| { + serde_json::json!({ + "kind": "rollup_selected", "model": model_name, "name": best_preagg.name, "route": "single_source" + }) + }); Ok(Some(format!("{preagg_sql}\n-- used_preagg=true"))) } diff --git a/sqlctx-rs/src/sql/generator/aggregate_plan.rs b/sqlctx-rs/src/sql/generator/aggregate_plan.rs index a1fca3196..e985d1eac 100644 --- a/sqlctx-rs/src/sql/generator/aggregate_plan.rs +++ b/sqlctx-rs/src/sql/generator/aggregate_plan.rs @@ -941,6 +941,16 @@ pub(super) fn try_generate( row_filters.push(format!("({sql})")); } } + super::super::explain::record(|| { + serde_json::json!({ + "kind": "aggregate_plan", "grain": query.dimensions, + "populations": plan.populations.iter().map(|population| serde_json::json!({ + "name": population.name, "sources": population.sources, + })).collect::>(), + "rollup_routing_enabled": false, + "rollup_reason": "aggregate child populations compile from source rows", + }) + }); let mut ctes = Vec::new(); for population in &plan.populations { let model = &population.sources[0]; diff --git a/sqlctx-rs/src/sql/generator/fanout_complete.rs b/sqlctx-rs/src/sql/generator/fanout_complete.rs index 7b3eec018..d5d9404a5 100644 --- a/sqlctx-rs/src/sql/generator/fanout_complete.rs +++ b/sqlctx-rs/src/sql/generator/fanout_complete.rs @@ -125,6 +125,12 @@ pub(super) fn generate_entity_aggregates( "Model '{source}' has no primary key; cannot safely aggregate across a fanout join" ))); } + super::super::explain::record(|| { + serde_json::json!({ + "kind": "fanout_guard", "model": source, "strategy": "distinct_entity_rows", + "entity_keys": keys, "grain": query.dimensions, + }) + }); for key in keys { inputs.add(source, generator.key_sql(source_model, &key, None)?, &[]); } diff --git a/sqlctx-rs/src/sql/mod.rs b/sqlctx-rs/src/sql/mod.rs index b2c304438..f9f7ee7d6 100644 --- a/sqlctx-rs/src/sql/mod.rs +++ b/sqlctx-rs/src/sql/mod.rs @@ -1,5 +1,6 @@ //! SQL generation and query rewriting +pub(crate) mod explain; mod generator; mod order_by; mod rewriter; diff --git a/tests/test_duckdb_community_descriptor.py b/tests/test_duckdb_community_descriptor.py new file mode 100644 index 000000000..6031a3d8d --- /dev/null +++ b/tests/test_duckdb_community_descriptor.py @@ -0,0 +1,69 @@ +import subprocess +from pathlib import Path + +import pytest +import yaml + +from scripts.duckdb_community_descriptor import ROOT, TEMPLATE, git, render_descriptor + + +@pytest.fixture +def release_repo(tmp_path: Path) -> Path: + git(tmp_path, "init", "--quiet") + files = { + TEMPLATE: (ROOT / TEMPLATE).read_text(), + "sqlctx-rs/Cargo.toml": '[package]\nversion = "1.2.3"\n', + "sqlctx-rs/Cargo.lock": "version = 4\n", + "sqlctx-rs/include/sqlctx.h": "/* public API */\n", + "sqlctx-duckdb/Makefile": "all:\n", + "sqlctx-duckdb/CMakeLists.txt": "project(sqlctx)\n", + "sqlctx-duckdb/extension_config.cmake": "duckdb_extension_load(sqlctx)\n", + "sqlctx-duckdb/LICENSE": "MIT\n", + "LICENSE": "AGPL-3.0-only\n", + } + for name, content in files.items(): + path = tmp_path / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + git(tmp_path, "add", ".") + git(tmp_path, "-c", "user.name=Test", "-c", "user.email=test@example.invalid", "commit", "--quiet", "-m", "Release") + return tmp_path + + +def test_descriptor_pins_both_hosts_to_committed_monorepo(release_repo: Path) -> None: + commit = git(release_repo, "rev-parse", "HEAD") + # Uncommitted metadata must not describe bytes that the registry will not fetch. + (release_repo / "sqlctx-rs/Cargo.toml").write_text('[package]\nversion = "9.9.9"\n') + descriptor = yaml.safe_load(render_descriptor(release_repo, commit)) + assert descriptor["repo"] == { + "github": "sidequery/sqlctx", + "build_directory": "sqlctx-duckdb", + "ref": commit, + "variegata": commit, + } + assert descriptor["extension"]["version"] == "1.2.3" + assert descriptor["extension"]["requires_toolchains"] == "rust" + assert descriptor["extension"]["license"] == "AGPL-3.0-only AND MIT" + assert "@COMMIT@" not in render_descriptor(release_repo, commit) + + +def test_descriptor_rejects_missing_sibling_crate(release_repo: Path) -> None: + git(release_repo, "rm", "sqlctx-rs/include/sqlctx.h") + git( + release_repo, + "-c", + "user.name=Test", + "-c", + "user.email=test@example.invalid", + "commit", + "--quiet", + "-m", + "Incomplete", + ) + with pytest.raises(subprocess.CalledProcessError): + render_descriptor(release_repo, "HEAD") + + +def test_descriptor_rejects_unknown_ref(release_repo: Path) -> None: + with pytest.raises(subprocess.CalledProcessError): + render_descriptor(release_repo, "missing-release") From 9a49684c6fd3b996b3cc595a15f097ca3e07c11d Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Sat, 28 Nov 2026 11:20:12 -0800 Subject: [PATCH 2/2] Respect local column scopes and sort aliases in semantic views --- .../test/test_semantic_views_host.py | 13 ++ sqlctx-rs/src/ffi/catalog/views.rs | 131 +++++++++++++++--- 2 files changed, 121 insertions(+), 23 deletions(-) diff --git a/sqlctx-duckdb/test/test_semantic_views_host.py b/sqlctx-duckdb/test/test_semantic_views_host.py index 919636c0b..7e5940e64 100644 --- a/sqlctx-duckdb/test/test_semantic_views_host.py +++ b/sqlctx-duckdb/test/test_semantic_views_host.py @@ -82,6 +82,19 @@ def test_named_view_nested_selection_and_star(): assert rows[-1] == [{"gross": 7}] +def test_view_aliases_keep_the_grain_and_bind_in_scalar_subqueries(): + rows = execute( + """ + create semantic view report as select country as region, gross from sales; + select gross as region from report order by region; + select (select gross from report) as total from main.raw_orders; + """, + setup=SETUP, + ) + assert [int(row["region"]) for row in rows[-2]] == [120] + assert rows[-1] == [{"total": 120}] * 3 + + def test_view_wildcards_preserve_selection_order_and_filtered_ratio(): rows = execute( """ diff --git a/sqlctx-rs/src/ffi/catalog/views.rs b/sqlctx-rs/src/ffi/catalog/views.rs index 22d0c0ec7..43d91c731 100644 --- a/sqlctx-rs/src/ffi/catalog/views.rs +++ b/sqlctx-rs/src/ffi/catalog/views.rs @@ -180,7 +180,7 @@ pub(super) fn create(snapshot: &mut Snapshot, content: &str, replace: bool) -> C /// Rebind selections on every reconstruction. Compatible source replacements /// flow through existing views; removed fields, changed field kinds and cycles /// fail before the host can publish a candidate catalog. -pub(super) fn refresh(models: &mut Vec) -> CatalogResult<()> { +pub(super) fn refresh(models: &mut [Model]) -> CatalogResult<()> { fn resolve( index: usize, models: &mut [Model], @@ -360,7 +360,27 @@ fn expand_bindings(views: &HashMap, sql: &str) -> CatalogResult if views.is_empty() { return Ok(sql.to_owned()); } - type Scope = HashMap>; + #[derive(Default)] + struct Scope<'a> { + local: HashMap>, + parent: Option<&'a Scope<'a>>, + } + + impl Scope<'_> { + fn relation(&self, alias: &str) -> Option<(&String, &Option)> { + self.local + .get_key_value(alias) + .or_else(|| self.parent?.relation(alias)) + } + + fn single_source(&self) -> Option<(&String, &Option)> { + match self.local.len() { + 0 => self.parent?.single_source(), + 1 => self.local.iter().next(), + _ => None, + } + } + } fn source( node: &mut Value, views: &HashMap, @@ -386,13 +406,13 @@ fn expand_bindings(views: &HashMap, sql: &str) -> CatalogResult table["alias"] = serde_json::to_value(Identifier::quoted(&alias)).unwrap(); table["schema"] = Value::Null; } - scope.insert(alias.to_ascii_lowercase(), binding); + scope.local.insert(alias.to_ascii_lowercase(), binding); return Ok(()); } if let Some(subquery) = node.get_mut("subquery") { visit(&mut subquery["this"], views, scope, ctes, &HashSet::new())?; if let Some(alias) = subquery["alias"]["name"].as_str() { - scope.insert(alias.to_ascii_lowercase(), None); + scope.local.insert(alias.to_ascii_lowercase(), None); } return Ok(()); } @@ -434,7 +454,10 @@ fn expand_bindings(views: &HashMap, sql: &str) -> CatalogResult ctes.insert(name); } } - let mut scope = outer.clone(); + let mut scope = Scope { + local: HashMap::new(), + parent: Some(outer), + }; source(&mut select["from"], views, &mut scope, &ctes)?; for join in select["joins"].as_array_mut().into_iter().flatten() { source(&mut join["this"], views, &mut scope, &ctes)?; @@ -443,16 +466,10 @@ fn expand_bindings(views: &HashMap, sql: &str) -> CatalogResult for projection in select["expressions"].as_array().into_iter().flatten() { if let Some(star) = projection.get("star") { let target = star["table"]["name"].as_str().map(str::to_ascii_lowercase); - let binding = target - .as_ref() - .and_then(|target| scope.get_key_value(target)) - .or_else(|| { - if target.is_none() && scope.len() == 1 { - scope.iter().next() - } else { - None - } - }); + let binding = match target { + Some(alias) => scope.relation(&alias), + None => scope.single_source(), + }; if let Some((alias, Some(binding))) = binding { if !star["except"].is_null() || !star["replace"].is_null() @@ -516,6 +533,20 @@ fn expand_bindings(views: &HashMap, sql: &str) -> CatalogResult } } } + } else if key == "order_by" && !child.is_null() { + for item in child["expressions"].as_array_mut().into_iter().flatten() { + // DuckDB resolves a bare ORDER BY name against the output + // first. Inside a sort expression, input columns win. + let column = &item["this"]["column"]; + if column["table"].is_null() + && column["name"]["name"].as_str().is_some_and(|name| { + output_aliases.contains(&name.to_ascii_lowercase()) + }) + { + continue; + } + visit(item, views, &scope, &ctes, &output_aliases)?; + } } else { visit(child, views, &scope, &ctes, &output_aliases)?; } @@ -526,14 +557,11 @@ fn expand_bindings(views: &HashMap, sql: &str) -> CatalogResult if let Some(column) = node.get_mut("column") { let field = column["name"]["name"].as_str().unwrap_or("").to_owned(); let binding = if let Some(table) = column["table"]["name"].as_str() { - outer - .get(&table.to_ascii_lowercase()) - .and_then(Option::as_ref) - } else if outer.len() == 1 { - outer.values().next().and_then(Option::as_ref) + outer.relation(&table.to_ascii_lowercase()) } else { - None - }; + outer.single_source() + } + .and_then(|(_, binding)| binding.as_ref()); if let Some(binding) = binding { let selected = binding .fields @@ -585,7 +613,7 @@ fn expand_bindings(views: &HashMap, sql: &str) -> CatalogResult visit( &mut ast, views, - &Scope::new(), + &Scope::default(), &HashSet::new(), &HashSet::new(), ) @@ -754,6 +782,63 @@ models: assert!(apply(&snapshot, "orders", "drop_view", r#"["orders"]"#, false).is_err()); } + #[test] + fn order_by_output_alias_takes_precedence_over_view_dimension() { + let snapshot = view( + &catalog(), + "sales AS SELECT country AS region, revenue AS gross FROM orders", + false, + ) + .unwrap(); + let sql = compile( + &snapshot, + "SELECT gross AS region FROM sales ORDER BY region DESC", + ); + assert!(!sql.contains("GROUP BY"), "{sql}"); + let graph = Snapshot::parse(&snapshot).unwrap().into_graph().unwrap(); + for (order, expected) in [ + ("region DESC", "ORDER BY region DESC"), + ("sales.region", "sales.\"country\""), + ("region + 1", "\"country\" + 1"), + ] { + let sql = expand( + &graph, + &format!("SELECT gross AS region FROM sales ORDER BY {order}"), + ) + .unwrap(); + assert!(sql.contains(expected), "{sql}"); + } + } + + #[test] + fn scalar_subqueries_resolve_local_view_fields_before_outer_sources() { + let snapshot = view( + &catalog(), + "sales AS SELECT revenue AS gross FROM orders", + false, + ) + .unwrap(); + let graph = Snapshot::parse(&snapshot).unwrap().into_graph().unwrap(); + let sql = expand( + &graph, + "SELECT (SELECT gross FROM sales) AS total FROM main.raw_orders", + ) + .unwrap(); + assert!(sql.contains("\"revenue\" AS \"gross\""), "{sql}"); + let sql = expand( + &graph, + "SELECT (SELECT s.gross FROM main.raw_orders) FROM sales s", + ) + .unwrap(); + assert!(sql.contains("s.\"revenue\" AS \"gross\""), "{sql}"); + let sql = expand( + &graph, + "SELECT (SELECT gross FROM main.raw_orders s) FROM sales s", + ) + .unwrap(); + assert!(sql.contains("SELECT gross FROM main.raw_orders"), "{sql}"); + } + #[test] fn view_expansion_respects_cte_and_physical_scope() { let snapshot = view(