diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f8c231b27..ae4151034 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -834,11 +834,11 @@ jobs: strategy: fail-fast: false matrix: - duckdb: [v1.5.6, v2.0-cyanoptera] + duckdb: [v1.5.6, v2.0.1] env: GEN: ninja DUCKDB_VERSION: ${{ matrix.duckdb }} - SQLCTX_NATIVE_PEG: ${{ matrix.duckdb == 'v2.0-cyanoptera' && '1' || '' }} + SQLCTX_NATIVE_PEG: ${{ matrix.duckdb == 'v2.0.1' && '1' || '' }} steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/duckdb-extension-release.yml b/.github/workflows/duckdb-extension-release.yml index 70f4a4f53..20592d295 100644 --- a/.github/workflows/duckdb-extension-release.yml +++ b/.github/workflows/duckdb-extension-release.yml @@ -4,7 +4,7 @@ on: workflow_dispatch: inputs: duckdb_version: - description: "Stable DuckDB release to package (v1.5.6); Cyanoptera is tested separately in CI" + description: "Stable DuckDB release to package (v1.5.6 or v2.0.1)" required: true default: "v1.5.6" type: string @@ -32,13 +32,38 @@ env: MACOSX_DEPLOYMENT_TARGET: "11.0" jobs: + versions: + name: Select stable DuckDB releases + runs-on: ubuntu-latest + outputs: + versions: ${{ steps.duckdb.outputs.versions }} + steps: + - name: Resolve DuckDB versions + id: duckdb + env: + EVENT_NAME: ${{ github.event_name }} + REQUESTED_VERSION: ${{ inputs.duckdb_version }} + run: | + if [ "$EVENT_NAME" = "workflow_dispatch" ]; then + case "$REQUESTED_VERSION" in + v1.5.6|v2.0.1) ;; + *) echo "Unsupported DuckDB version" >&2; exit 1 ;; + esac + printf 'versions=["%s"]\n' "$REQUESTED_VERSION" >> "$GITHUB_OUTPUT" + else + echo 'versions=["v1.5.6","v2.0.1"]' >> "$GITHUB_OUTPUT" + fi + build: - name: Build ${{ matrix.platform }} extension package + name: Build ${{ matrix.duckdb_version }} ${{ matrix.platform }} extension package + needs: versions runs-on: ${{ matrix.runner }} container: ${{ matrix.container }} strategy: fail-fast: false matrix: + duckdb_version: ${{ fromJSON(needs.versions.outputs.versions) }} + platform: [linux_amd64, linux_arm64, osx_amd64, osx_arm64] include: - platform: linux_amd64 runner: ubuntu-24.04 @@ -72,30 +97,10 @@ jobs: with: suffix: ${{ github.workflow }}-${{ github.job }}-${{ strategy.job-index || 0 }} - - name: Resolve DuckDB version - id: duckdb - env: - EVENT_NAME: ${{ github.event_name }} - REQUESTED_VERSION: ${{ inputs.duckdb_version }} - run: | - if [ "$EVENT_NAME" = "workflow_dispatch" ]; then - VERSION="$REQUESTED_VERSION" - else - VERSION="v1.5.6" - fi - - # Publish stable artifacts only. CI separately tests the pinned PEG development build. - if [ "$VERSION" != "v1.5.6" ]; then - echo "Unsupported DuckDB version" >&2 - exit 1 - fi - - echo "version=$VERSION" >> "$GITHUB_OUTPUT" - - name: Fetch DuckDB dependencies working-directory: sqlctx-duckdb env: - DUCKDB_VERSION: ${{ steps.duckdb.outputs.version }} + DUCKDB_VERSION: ${{ matrix.duckdb_version }} run: make deps DUCKDB_VERSION="$DUCKDB_VERSION" - name: Build extension @@ -106,12 +111,19 @@ jobs: - name: Run extension tests working-directory: sqlctx-duckdb - run: make test + env: + SQLCTX_NATIVE_PEG: ${{ matrix.duckdb_version == 'v2.0.1' && '1' || '' }} + EXPECTED_VERSION: ${{ matrix.duckdb_version }} + run: | + VERSION=$(./build/release/duckdb -unsigned -csv -noheader :memory: -c \ + "LOAD 'build/release/extension/sqlctx/sqlctx.duckdb_extension'; SELECT version();") + test "$VERSION" = "$EXPECTED_VERSION" + make test - name: Package extension artifact working-directory: sqlctx-duckdb env: - DUCKDB_VERSION: ${{ steps.duckdb.outputs.version }} + DUCKDB_VERSION: ${{ matrix.duckdb_version }} PLATFORM: ${{ matrix.platform }} run: | mkdir -p dist @@ -128,7 +140,7 @@ jobs: - name: Upload extension artifact uses: actions/upload-artifact@v4 with: - name: sqlctx-duckdb-extension-${{ matrix.platform }} + name: sqlctx-duckdb-extension-${{ matrix.duckdb_version }}-${{ matrix.platform }} path: sqlctx-duckdb/dist/* if-no-files-found: error @@ -140,7 +152,7 @@ jobs: github-release: name: Attach extension artifact to GitHub release - needs: build + needs: [versions, build] if: ${{ startsWith(github.ref, 'refs/tags/') || (github.event_name == 'workflow_dispatch' && inputs.create_github_release == true) }} runs-on: ubuntu-latest permissions: @@ -181,6 +193,7 @@ jobs: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} TAG: ${{ steps.release.outputs.tag }} RELEASE_COMMIT: ${{ github.sha }} + DUCKDB_VERSIONS: ${{ join(fromJSON(needs.versions.outputs.versions), ' ') }} run: | set -euo pipefail # Checkout can create a lightweight local ref for an annotated tag. @@ -191,10 +204,12 @@ jobs: exit 1 fi cd dist - for PLATFORM in linux_amd64 linux_arm64 osx_amd64 osx_arm64; do - ASSET="sqlctx-duckdb-1.5.6-${PLATFORM}.duckdb_extension" - test -s "$ASSET" - sha256sum --check "$ASSET.sha256" + for VERSION in $DUCKDB_VERSIONS; do + for PLATFORM in linux_amd64 linux_arm64 osx_amd64 osx_arm64; do + ASSET="sqlctx-duckdb-${VERSION#v}-${PLATFORM}.duckdb_extension" + test -s "$ASSET" + sha256sum --check "$ASSET.sha256" + done done cat *.sha256 > SHA256SUMS cp ../LICENSE . diff --git a/docs/duckdb-extension.md b/docs/duckdb-extension.md index 52fa380f6..bca09cf08 100644 --- a/docs/duckdb-extension.md +++ b/docs/duckdb-extension.md @@ -4,7 +4,7 @@ The sqlctx DuckDB extension embeds the Rust native runtime in DuckDB. It is a na ## Status -The extension is experimental and targets **DuckDB 1.5.6** only. It is **not** in the +The extension is experimental and targets **DuckDB 2.0.1 and 1.5.6**. It is **not** in the DuckDB community extension registry, so `INSTALL sqlctx FROM community` fails. Community publication is planned; once it lands, installation will be: @@ -29,16 +29,14 @@ The extension build needs Rust, DuckDB extension build tooling, and Ninja. ```bash cd sqlctx-duckdb -make deps DUCKDB_VERSION=v1.5.6 +make deps DUCKDB_VERSION=v2.0.1 make -make test +SQLCTX_NATIVE_PEG=1 make test ``` -`make deps` accepts only `DUCKDB_VERSION=v1.5.6` (the default) or `v2.0-cyanoptera`, -a pinned DuckDB development commit that CI uses to exercise the native PEG grammar. -Release artifacts are built for v1.5.6 only. The repository vendors a matching -`extension-ci-tools` checkout; update both together before building against a -different DuckDB tag. +For the DuckDB 1.5.6 compatibility frontend, use `make deps DUCKDB_VERSION=v1.5.6` +(the default), then `make` and `make test`. Build each host version in a separate +checkout or clean build directory. The repository vendors the extension build tools. The local loadable extension is produced at: @@ -49,12 +47,10 @@ sqlctx-duckdb/build/release/extension/sqlctx/sqlctx.duckdb_extension Load it in the DuckDB shell built by the extension workflow: ```bash -./build/release/duckdb -unsigned +./build/release/duckdb -unsigned -cmd "LOAD '$PWD/build/release/extension/sqlctx/sqlctx.duckdb_extension';" ``` -```sql -LOAD 'build/release/extension/sqlctx/sqlctx.duckdb_extension'; -``` +The official macOS CLI requires an absolute path when loading the extension. For embedded clients, set DuckDB's `allow_unsigned_extensions` database configuration before opening the connection. @@ -137,10 +133,10 @@ Use `.github/workflows/duckdb-extension-release.yml`. The workflow: -- fetches DuckDB v1.5.6 with `make deps` and verifies the vendored `extension-ci-tools`, +- fetches each selected DuckDB release tag with `make deps` and verifies the vendored `extension-ci-tools`, - 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 the four extension artifacts with their checksums, +- 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. It does not publish to the DuckDB community extension registry. @@ -152,13 +148,11 @@ It does not publish to the DuckDB community extension registry. | Native format | `1` | | Rust runtime crate | `0.1.0` | | DuckDB extension release | `0.1.0` | -| DuckDB version | `1.5.6` | +| DuckDB version | `2.0.1` or `1.5.6` | DuckDB extension artifacts are ABI-sensitive. Rebuild the extension when changing the DuckDB target version or the Rust native runtime version. -The extension loads only into DuckDB 1.5.6. DuckDB 1.5.6 cannot open database files -written by DuckDB 2.x (`Trying to read a database file with version number 69`), so -a file created by a newer DuckDB, for example through a Python environment that -resolved `duckdb` 2.x, cannot be used with this extension. +For a database file written in DuckDB 2.0 storage format, open it with DuckDB +2.0.1 and load the matching 2.0.1 extension. The extension should accept the same native YAML and native SQL definition contract as the Rust runtime. If extension-only syntax is added, it should either be aligned with the Rust SQL loader or documented as DuckDB-only. diff --git a/docs/rust-native-runtime-packaging.md b/docs/rust-native-runtime-packaging.md index d23a8600a..6cb0e3293 100644 --- a/docs/rust-native-runtime-packaging.md +++ b/docs/rust-native-runtime-packaging.md @@ -16,7 +16,7 @@ Python remains the default engine; installing the Rust bindings does not promote Workflow files live in `.github/workflows/`. Rust crate and wheel versions must match; package metadata tests enforce this. Root Python and WASM versions are separate. The DuckDB extension is tied to the DuckDB build version, currently -`v1.5.6`. Do not use a release intended for a different DuckDB ABI. +`v2.0.1` or `v1.5.6`. Select the artifact matching the host version and platform. ## Install from a checkout or downloaded artifact diff --git a/sqlctx-duckdb/CMakeLists.txt b/sqlctx-duckdb/CMakeLists.txt index a742a2219..893d109c7 100644 --- a/sqlctx-duckdb/CMakeLists.txt +++ b/sqlctx-duckdb/CMakeLists.txt @@ -21,15 +21,15 @@ function(sqlctx_detect_apis) parser/expression/columnref_expression.hpp parser/tableref/basetableref.hpp parser/parser_options.hpp parser/expression/constant_expression.hpp parser/statement/insert_statement.hpp - parser/grammar_extension.hpp parser/peg/compiled_grammar.hpp - planner/operator/logical_get.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) 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) + 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) unset(SQLCTX_${api} CACHE) endforeach() set(SQLCTX_HOST_API "${host_api}" CACHE INTERNAL "DuckDB headers used for compatibility probes" FORCE) @@ -87,6 +87,21 @@ function(sqlctx_detect_apis) duckdb::CompiledGrammar::Create(duckdb::vector> {extension}); } " SQLCTX_GRAMMAR_EXTENSION_LIST) + check_cxx_source_compiles(" + #include + void probe(duckdb::PEGTransformer &transformer) { transformer.MakeResult(true); } + " SQLCTX_ARENA_TRANSFORM) + check_cxx_source_compiles(" + #include + #include + #include + using namespace duckdb; + void probe(ParserOptions &options) { + auto &config = ClientConfig::GetConfig(*options.context); + if (!config.current_dialect && !config.connected_grammar) + CompiledGrammar::Create(*options.context, vector{\"shell\", \"sqlctx\"}); + } + " SQLCTX_SHELL_GRAMMAR_CONTEXT) configure_file(src/include/sqlctx_compat.hpp.in sqlctx_compat.hpp) cmake_pop_check_state() endfunction() diff --git a/sqlctx-duckdb/Makefile b/sqlctx-duckdb/Makefile index 71df64d88..b70b9f3ba 100644 --- a/sqlctx-duckdb/Makefile +++ b/sqlctx-duckdb/Makefile @@ -5,19 +5,23 @@ PROJ_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST)))) EXT_NAME=sqlctx EXT_CONFIG=${PROJ_DIR}extension_config.cmake SUPPORTED_DUCKDB_VERSION := v1.5.6 +SUPPORTED_DUCKDB_2 := v2.0.1 SUPPORTED_DUCKDB_NEXT := v2.0-cyanoptera # Pin the moving development branch to the native PEG API exercised by CI. DUCKDB_NEXT_COMMIT := 80e17fc252edd6d9e9b090ae00a1100daef4876a DUCKDB_VERSION ?= $(SUPPORTED_DUCKDB_VERSION) +# DuckDB 2.0 derives a development ABI from the commit count unless the +# release version is supplied. Use the tag on the source being compiled. +OVERRIDE_GIT_DESCRIBE ?= $(filter $(SUPPORTED_DUCKDB_2),$(shell git -C $(DUCKDB_SRCDIR) tag --points-at HEAD 2>/dev/null)) # Exercise coexistence with the parser override preloaded by packaged shells. DEFAULT_TEST_EXTENSION_DEPS := autocomplete .PHONY: deps deps: - @if [ "$(DUCKDB_VERSION)" != "$(SUPPORTED_DUCKDB_VERSION)" ] && [ "$(DUCKDB_VERSION)" != "$(SUPPORTED_DUCKDB_NEXT)" ]; then \ - echo "Use DUCKDB_VERSION=$(SUPPORTED_DUCKDB_VERSION) or $(SUPPORTED_DUCKDB_NEXT)."; \ - exit 1; \ - fi + @case "$(DUCKDB_VERSION)" in \ + $(SUPPORTED_DUCKDB_VERSION)|$(SUPPORTED_DUCKDB_2)|$(SUPPORTED_DUCKDB_NEXT)) ;; \ + *) echo "Use DUCKDB_VERSION=$(SUPPORTED_DUCKDB_VERSION), $(SUPPORTED_DUCKDB_2), or $(SUPPORTED_DUCKDB_NEXT)."; exit 1 ;; \ + esac @if [ ! -d duckdb/.git ]; then \ rm -rf duckdb; \ git clone --depth 1 --branch $(DUCKDB_VERSION) https://github.com/duckdb/duckdb.git duckdb; \ diff --git a/sqlctx-duckdb/README.md b/sqlctx-duckdb/README.md index 3e3f90c77..46765a5bc 100644 --- a/sqlctx-duckdb/README.md +++ b/sqlctx-duckdb/README.md @@ -12,26 +12,22 @@ A DuckDB extension that adds a SQL-first semantic layer. Define metrics and dime - **Transactional Definitions**: Commit and roll back model changes with DuckDB transactions - **Catalog Discovery**: Inspect definitions, metadata, relationships and compatible dimensions with SQL - **SQL Containers**: Use semantic queries in views, `CREATE TABLE AS`, and `INSERT ... SELECT` -- **Native PEG Grammar**: Composable grammar on the pinned Cyanoptera development build, with a DuckDB 1.5.6 compatibility frontend +- **Native PEG Grammar**: Composable grammar on DuckDB 2.0.1, with a DuckDB 1.5.6 compatibility frontend ## Installation -Build locally against DuckDB 1.5.6: +Build locally against DuckDB 2.0.1: ```bash -make deps DUCKDB_VERSION=v1.5.6 +make deps DUCKDB_VERSION=v2.0.1 make -make test -./build/release/duckdb -unsigned -``` - -```sql -LOAD 'build/release/extension/sqlctx/sqlctx.duckdb_extension'; +SQLCTX_NATIVE_PEG=1 make test +./build/release/duckdb -unsigned -cmd "LOAD '$PWD/build/release/extension/sqlctx/sqlctx.duckdb_extension';" ``` 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 release workflow builds unsigned DuckDB 1.5.6 packages for Linux and macOS +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 `sqlctx.duckdb_extension` before loading it. @@ -333,7 +329,7 @@ files raise errors when the semantic catalog is accessed. ## Native PEG frontend -DuckDB 1.5.6 uses the compatibility frontend. The pinned `v2.0-cyanoptera` build +DuckDB 1.5.6 uses the compatibility frontend. DuckDB 2.0.1 registers a `sqlctx` grammar extension for definitions, discovery, removal, import/export and explicit semantic queries, including nested `PREPARE` and `EXPLAIN`. Definition properties still use the shared Rust configuration parser; semantic query compilation still @@ -586,8 +582,8 @@ rows, including equal-valued metrics on distinct customers. use `sqlctx_compile_semantic_input` and execute its returned SQL. 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 is tested against - the pinned 2.x commit, not an arbitrary future 2.x build. Rust still parses model +- DuckDB 1.5.6 uses the compatibility frontend. Native PEG support targets + the released DuckDB 2.0.1 host. Rust parses model properties and compiles semantic queries. - The release workflow packages unsigned Linux and macOS builds on AMD64 and ARM64. Signed community installation is not yet provided by this repository. @@ -626,8 +622,7 @@ SELECT sqlctx_rewrite_sql('SELECT orders.revenue FROM orders'); # From this repository checkout cd sqlctx-duckdb -# Fetch the DuckDB source version used by CI. -# Stable builds and release artifacts target v1.5.6. +# Build the compatibility frontend for DuckDB 1.5.6. make deps DUCKDB_VERSION=v1.5.6 # Build the extension. CMake builds the sibling sqlctx-rs static library automatically. @@ -640,12 +635,9 @@ make test ./build/release/duckdb -unsigned ``` -CI also builds `make deps DUCKDB_VERSION=v2.0-cyanoptera`, pinned in the Makefile to -commit `80e17fc252edd6d9e9b090ae00a1100daef4876a`. Run its tests with -`SQLCTX_NATIVE_PEG=1 make test`. Use separate build directories/checkouts when -switching DuckDB versions. CMake probes host APIs rather than assuming C++ ABI -compatibility across releases. Release packaging targets unsigned Linux and macOS -builds for 1.5.6; development-version CI does not publish stable artifacts. +CI builds both released hosts. For 2.0.1, use `make deps DUCKDB_VERSION=v2.0.1`, +`make`, and `SQLCTX_NATIVE_PEG=1 make test`. Use separate build directories/checkouts +when switching DuckDB versions. Each loadable binary targets its host's C++ ABI. A preview artifact for a published 2.0 alpha runtime must be built from that runtime's exact commit and carry its version string, because the C++ extension diff --git a/sqlctx-duckdb/docs/UPDATING.md b/sqlctx-duckdb/docs/UPDATING.md index 86089f8ab..21a84d399 100644 --- a/sqlctx-duckdb/docs/UPDATING.md +++ b/sqlctx-duckdb/docs/UPDATING.md @@ -3,15 +3,15 @@ The extension builds against DuckDB's internal C++ API. A loadable extension must match its host version and platform; source compatibility is not binary compatibility. -The Makefile selects stable DuckDB 1.5.6 or a pinned Cyanoptera development commit. -CI builds both and runs the SQL and SemanticInput host suites. The development job +The Makefile supports the DuckDB 1.5.6 and 2.0.1 release tags. +CI builds both and runs the SQL and SemanticInput host suites. The 2.0.1 job sets `SQLCTX_NATIVE_PEG=1` to require tests that disable parser overrides and use -sqlctx's registered native grammar. Release packaging intentionally accepts only -the stable version and currently produces unsigned Linux amd64 artifacts. +sqlctx's registered native grammar. Release packaging builds unsigned Linux and +macOS artifacts for AMD64 and ARM64 for the selected release tags. When updating: -1. Change the stable version or `DUCKDB_NEXT_COMMIT` in the Makefile and the CI matrix +1. Update the release tags in the Makefile and the CI matrix as appropriate. Keep the release workflow's stable allowlist and input tests aligned. 2. Use fresh build directories for each host. `src/include/sqlctx_compat.hpp.in` is generated from the API probes in CMake; adapt those probes and frontend code diff --git a/sqlctx-duckdb/src/include/sqlctx_compat.hpp.in b/sqlctx-duckdb/src/include/sqlctx_compat.hpp.in index 042a438ab..cca7435ba 100644 --- a/sqlctx-duckdb/src/include/sqlctx_compat.hpp.in +++ b/sqlctx-duckdb/src/include/sqlctx_compat.hpp.in @@ -10,6 +10,8 @@ #cmakedefine01 SQLCTX_INSERT_QUERY_NODE #cmakedefine01 SQLCTX_BOUND_TABLE_FUNCTION #cmakedefine01 SQLCTX_GRAMMAR_EXTENSION_LIST +#cmakedefine01 SQLCTX_ARENA_TRANSFORM +#cmakedefine01 SQLCTX_SHELL_GRAMMAR_CONTEXT #include "duckdb/parser/parser_options.hpp" #if SQLCTX_NEW_IDENTIFIER_API diff --git a/sqlctx-duckdb/src/sqlctx_grammar.cpp b/sqlctx-duckdb/src/sqlctx_grammar.cpp index d7bc9e9bb..2f1c5f52b 100644 --- a/sqlctx-duckdb/src/sqlctx_grammar.cpp +++ b/sqlctx-duckdb/src/sqlctx_grammar.cpp @@ -3,6 +3,9 @@ #if SQLCTX_GRAMMAR_EXTENSION #include "duckdb/main/connection.hpp" #include "duckdb/main/database.hpp" +#if SQLCTX_SHELL_GRAMMAR_CONTEXT +#include "duckdb/main/client_config.hpp" +#endif #include "duckdb/parser/grammar_extension.hpp" #include "duckdb/parser/peg/compiled_grammar.hpp" #include "duckdb/parser/peg/transformer/peg_transformer.hpp" @@ -33,7 +36,27 @@ class DefinitionAtomMatcher final : public AtomicMatcher { string ToString() const override { return "semantic definition property"; } }; -static unique_ptr TransformDefinition(PEGTransformer &transformer, ParseResult &result) { +// Released DuckDB 2.0 owns transform results and processes in its parser arena. +static auto StatementResult(PEGTransformer &transformer, unique_ptr statement) { +#if SQLCTX_ARENA_TRANSFORM + return transformer.MakeResult>(std::move(statement)); +#else + unique_ptr result = + make_uniq>>(std::move(statement)); + return result; +#endif +} + +template +static auto StartFinalizer(PEGTransformer &transformer, ParseResult &result, Finalizer finalize) { +#if SQLCTX_ARENA_TRANSFORM + return transformer.MakeProcess(transformer, result, finalize); +#else + return make_uniq(transformer, result, finalize); +#endif +} + +static auto TransformDefinition(PEGTransformer &transformer, ParseResult &result) { auto location = result.GetLocation(); string source(location.length, ' '); // Preserve token positions and quoted source; comments are intentionally @@ -49,22 +72,22 @@ static unique_ptr TransformDefinition(PEGTransformer &tran } auto definition = ParseSqlctxDefinition(source); if (!definition) throw InternalException("sqlctx grammar produced an invalid declaration"); - return make_uniq>>(SqlctxStatement(std::move(definition))); + return StatementResult(transformer, SqlctxStatement(std::move(definition))); } -static unique_ptr StartDefinition(PEGTransformer &transformer, ParseResult &result) { - return make_uniq(transformer, result, TransformDefinition); +static auto StartDefinition(PEGTransformer &transformer, ParseResult &result) { + return StartFinalizer(transformer, result, TransformDefinition); } -static unique_ptr TransformSemanticQuery(PEGTransformer &transformer, ParseResult &result) { +static auto TransformSemanticQuery(PEGTransformer &transformer, ParseResult &result) { auto &list = result.Cast(); auto &choice = list.Child(1).Child(0); auto statement = transformer.Transform>(choice.GetResult()); - return make_uniq>>(WrapSqlctxQuery(std::move(statement), true)); + return StatementResult(transformer, WrapSqlctxQuery(std::move(statement), true)); } -static unique_ptr StartSemanticQuery(PEGTransformer &transformer, ParseResult &result) { - return make_uniq(transformer, result, TransformSemanticQuery); +static auto StartSemanticQuery(PEGTransformer &transformer, ParseResult &result) { + return StartFinalizer(transformer, result, TransformSemanticQuery); } static unique_ptr TransformPreparable(PEGTransformer &transformer, ParseResult &result) { @@ -72,7 +95,7 @@ static unique_ptr TransformPreparable(PEGTransformer &transformer, return transformer.Transform>(choice.GetResult()); } -static unique_ptr TransformPrepare(PEGTransformer &transformer, ParseResult &result) { +static auto TransformPrepare(PEGTransformer &transformer, ParseResult &result) { auto &list = result.Cast(); auto statement = make_uniq(); statement->name = transformer.Transform(list.GetChild(1)); @@ -81,14 +104,14 @@ static unique_ptr TransformPrepare(PEGTransformer &transfo statement->statement->has_anonymous_parameters = transformer.has_anonymous_parameters; transformer.ClearParameters(); unique_ptr prepared = std::move(statement); - return make_uniq>>(std::move(prepared)); + return StatementResult(transformer, std::move(prepared)); } -static unique_ptr StartPrepare(PEGTransformer &transformer, ParseResult &result) { - return make_uniq(transformer, result, TransformPrepare); +static auto StartPrepare(PEGTransformer &transformer, ParseResult &result) { + return StartFinalizer(transformer, result, TransformPrepare); } -static unique_ptr TransformExplain(PEGTransformer &transformer, ParseResult &result) { +static auto TransformExplain(PEGTransformer &transformer, ParseResult &result) { auto &list = result.Cast(); optional analyze; auto &analyze_result = list.Child(1); @@ -100,11 +123,11 @@ static unique_ptr TransformExplain(PEGTransformer &transfo } auto inner = TransformPreparable(transformer, list.GetChild(3)); auto statement = PEGTransformerFactory::TransformExplainStatement(transformer, analyze, options, std::move(inner)); - return make_uniq>>(WrapSqlctxQuery(std::move(statement))); + return StatementResult(transformer, WrapSqlctxQuery(std::move(statement))); } -static unique_ptr StartExplain(PEGTransformer &transformer, ParseResult &result) { - return make_uniq(transformer, result, TransformExplain); +static auto StartExplain(PEGTransformer &transformer, ParseResult &result) { + return StartFinalizer(transformer, result, TransformExplain); } class SqlctxGrammar final : public GrammarExtension { @@ -181,6 +204,17 @@ bool ParseSqlctxGrammar(ParserExtensionInfo *info, const string &sql, const Pars if (!native.compiled_grammar || native.compiled_grammar == grammar_info->default_grammar) { native.compiled_grammar = grammar_info->grammar; } +#if SQLCTX_SHELL_GRAMMAR_CONTEXT + else if (native.context) { + auto &config = ClientConfig::GetConfig(*native.context); + // The 2.0 CLI enables its expression grammar by default. Compose the + // two grammars for this parse so bare shell expressions keep working. + if (!config.current_dialect && !config.connected_grammar && + config.active_grammar_extensions == vector {"shell"}) { + native.compiled_grammar = CompiledGrammar::Create(*native.context, vector {"shell", "sqlctx"}); + } + } +#endif Parser parser(native); parser.ParseQuery(sql); statements = std::move(parser.statements); diff --git a/sqlctx-duckdb/test/README.md b/sqlctx-duckdb/test/README.md index a10c76609..43d5f9023 100644 --- a/sqlctx-duckdb/test/README.md +++ b/sqlctx-duckdb/test/README.md @@ -12,7 +12,7 @@ or make test_debug ``` -For the pinned Cyanoptera build, use `SQLCTX_NATIVE_PEG=1 make test`. Its native +For DuckDB 2.0.1, use `SQLCTX_NATIVE_PEG=1 make test`. Its native grammar suite explicitly disables parser overrides before executing custom syntax. The same suite is skipped on DuckDB 1.5.6. diff --git a/sqlctx-duckdb/test/test_catalog_host.py b/sqlctx-duckdb/test/test_catalog_host.py index 47e54a8e9..19887d563 100644 --- a/sqlctx-duckdb/test/test_catalog_host.py +++ b/sqlctx-duckdb/test/test_catalog_host.py @@ -133,6 +133,21 @@ def test_catalog_discovery_and_select_combinations(): ] +def test_default_shell_grammar_composes_with_semantic_statements(): + settings = execute("select value from duckdb_settings() where name = 'active_grammar_extensions';")[0] + if settings != [{"value": "[shell]"}]: + pytest.skip("Host does not enable the DuckDB 2.0 shell grammar by default") + before, expression, metrics, after = execute(""" + select current_setting('active_grammar_extensions') as grammars; + 40 + 2 as answer; + show metrics from orders; + select current_setting('active_grammar_extensions') as grammars; + """) + assert expression == [{"answer": 42}] + assert [row["qualified_name"] for row in metrics] == ["orders.revenue"] + assert before == after == [{"grammars": ["shell"]}] + + @pytest.mark.parametrize( ("sql", "error"), [ diff --git a/sqlctx-duckdb/test/test_release_workflow.py b/sqlctx-duckdb/test/test_release_workflow.py index 60f1ade0a..411d13f88 100644 --- a/sqlctx-duckdb/test/test_release_workflow.py +++ b/sqlctx-duckdb/test/test_release_workflow.py @@ -1,6 +1,7 @@ """Execute the release input boundary without running builds or publishing.""" import hashlib +import json import os import subprocess from pathlib import Path @@ -9,6 +10,7 @@ import yaml WORKFLOW = Path(__file__).resolve().parents[2] / ".github/workflows/duckdb-extension-release.yml" +VERSIONS = ["v1.5.6", "v2.0.1"] PLATFORMS = ["linux_amd64", "linux_arm64", "osx_amd64", "osx_arm64"] @@ -23,7 +25,7 @@ def workflow_step(job, name): ) def test_release_rejects_unsupported_input_without_shell_execution(tmp_path, version): workflow = yaml.safe_load(WORKFLOW.read_text()) - step = next(step for step in workflow["jobs"]["build"]["steps"] if step.get("id") == "duckdb") + step = next(step for step in workflow["jobs"]["versions"]["steps"] if step.get("id") == "duckdb") output = tmp_path / "output" output.touch() result = subprocess.run( @@ -43,24 +45,28 @@ def test_release_rejects_unsupported_input_without_shell_execution(tmp_path, ver assert output.read_text() == "" -@pytest.mark.parametrize("event", ["workflow_dispatch", "push"]) -def test_release_accepts_supported_version(tmp_path, event): +@pytest.mark.parametrize("event", ["workflow_dispatch", "push", "pull_request"]) +@pytest.mark.parametrize("version", VERSIONS) +def test_release_accepts_supported_version(tmp_path, event, version): workflow = yaml.safe_load(WORKFLOW.read_text()) - step = next(step for step in workflow["jobs"]["build"]["steps"] if step.get("id") == "duckdb") + step = next(step for step in workflow["jobs"]["versions"]["steps"] if step.get("id") == "duckdb") output = tmp_path / "output" result = subprocess.run( ["bash", "-e", "-c", step["run"]], cwd=tmp_path, - env={**os.environ, "EVENT_NAME": event, "REQUESTED_VERSION": "v1.5.6", "GITHUB_OUTPUT": str(output)}, + env={**os.environ, "EVENT_NAME": event, "REQUESTED_VERSION": version, "GITHUB_OUTPUT": str(output)}, capture_output=True, text=True, ) assert result.returncode == 0, result.stderr - assert output.read_text() == "version=v1.5.6\n" + assert json.loads(output.read_text().removeprefix("versions=")) == ( + [version] if event == "workflow_dispatch" else VERSIONS + ) +@pytest.mark.parametrize("version", VERSIONS) @pytest.mark.parametrize("platform", PLATFORMS) -def test_release_packages_matching_platform_with_verifiable_checksum(tmp_path, platform): +def test_release_packages_matching_platform_with_verifiable_checksum(tmp_path, platform, version): extension = tmp_path / "build/release/extension/sqlctx/sqlctx.duckdb_extension" extension.parent.mkdir(parents=True) extension.write_bytes(b"extension payload") @@ -68,12 +74,12 @@ def test_release_packages_matching_platform_with_verifiable_checksum(tmp_path, p result = subprocess.run( ["bash", "-e", "-c", step["run"]], cwd=tmp_path, - env={**os.environ, "DUCKDB_VERSION": "v1.5.6", "PLATFORM": platform}, + env={**os.environ, "DUCKDB_VERSION": version, "PLATFORM": platform}, capture_output=True, text=True, ) assert result.returncode == 0, result.stderr - asset = tmp_path / "dist" / f"sqlctx-duckdb-1.5.6-{platform}.duckdb_extension" + asset = tmp_path / "dist" / f"sqlctx-duckdb-{version.removeprefix('v')}-{platform}.duckdb_extension" assert asset.read_bytes() == extension.read_bytes() assert asset.with_suffix(".duckdb_extension.sha256").read_text() == ( f"{hashlib.sha256(extension.read_bytes()).hexdigest()} {asset.name}\n" @@ -81,16 +87,18 @@ 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]) -def test_publication_checks_provenance_and_all_payloads_before_creating_release(tmp_path, failure): +@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" dist.mkdir() - for platform in PLATFORMS: - asset = dist / f"sqlctx-duckdb-1.5.6-{platform}.duckdb_extension" - payload = platform.encode() - asset.write_bytes(payload) - asset.with_suffix(".duckdb_extension.sha256").write_text( - f"{hashlib.sha256(payload).hexdigest()} {asset.name}\n" - ) + for version in versions: + for platform in PLATFORMS: + asset = dist / f"sqlctx-duckdb-{version.removeprefix('v')}-{platform}.duckdb_extension" + payload = platform.encode() + asset.write_bytes(payload) + asset.with_suffix(".duckdb_extension.sha256").write_text( + f"{hashlib.sha256(payload).hexdigest()} {asset.name}\n" + ) if failure == "missing_platform": asset.unlink() elif failure == "corrupt_payload": @@ -114,6 +122,7 @@ def test_publication_checks_provenance_and_all_payloads_before_creating_release( "PATH": f"{commands}{os.pathsep}{os.environ['PATH']}", "TAG": "sqlctx-duckdb-v0.1.0", "RELEASE_COMMIT": "built-commit", + "DUCKDB_VERSIONS": " ".join(versions), "TAG_COMMIT": "other-commit" if failure == "mismatched_tag" else "built-commit", "GH_ARGS": str(args), "GH_STATUS": "1" if failure == "existing_release" else "0", @@ -125,7 +134,7 @@ def test_publication_checks_provenance_and_all_payloads_before_creating_release( assert result.returncode != 0 else: assert result.returncode == 0, result.stderr - assert len((dist / "SHA256SUMS").read_text().splitlines()) == len(PLATFORMS) + 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 not args.exists() @@ -134,7 +143,7 @@ def test_publication_checks_provenance_and_all_payloads_before_creating_release( assert arguments[:3] == ["release", "create", "sqlctx-duckdb-v0.1.0"] assert "--verify-tag" in arguments assert "--clobber" not in arguments - assert sum(arg.endswith(".duckdb_extension") for arg in arguments) == len(PLATFORMS) + assert sum(arg.endswith(".duckdb_extension") for arg in arguments) == len(PLATFORMS) * len(versions) @pytest.mark.parametrize("matching_commit", [True, False]) @@ -200,6 +209,7 @@ def git(directory, *arguments): "PATH": f"{commands}{os.pathsep}{os.environ['PATH']}", "TAG": tag, "RELEASE_COMMIT": built_commit, + "DUCKDB_VERSIONS": "v1.5.6", "GH_ARGS": str(args), }, capture_output=True,