Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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() }}
Expand Down
3 changes: 2 additions & 1 deletion .github/workflows/duckdb-extension-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
32 changes: 31 additions & 1 deletion docs/duckdb-extension.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -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.

Expand Down
51 changes: 51 additions & 0 deletions scripts/duckdb_community_descriptor.py
Original file line number Diff line number Diff line change
@@ -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()
18 changes: 15 additions & 3 deletions sqlctx-duckdb/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -102,6 +103,17 @@ function(sqlctx_detect_apis)
CompiledGrammar::Create(*options.context, vector<string>{\"shell\", \"sqlctx\"});
}
" SQLCTX_SHELL_GRAMMAR_CONTEXT)
check_cxx_source_compiles("
#include <duckdb/planner/planner_extension.hpp>
void probe(duckdb::PlannerExtension &extension) { extension.pre_bind_function = nullptr; }
" SQLCTX_PRE_BIND)
check_cxx_source_compiles("
#include <duckdb/common/types/data_chunk.hpp>
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()
Expand Down Expand Up @@ -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})
Expand Down
81 changes: 68 additions & 13 deletions sqlctx-duckdb/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 \
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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.
Loading
Loading