Skip to content
Open
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
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,7 @@ jobs:
filters: |
rust:
- 'sqlctx-rs/**'
- 'tests/ossie-fixtures/upstream/**'
- 'Cargo.toml'
- 'Cargo.lock'
- '.cargo/**'
Expand Down Expand Up @@ -588,8 +589,7 @@ jobs:
duckdb:
- 'sqlctx-duckdb/**'
- 'sqlctx-rs/**'
# The extension links the workspace crate; host tests and their
# shared SemanticInput fixture live under the two trees above.
- 'tests/ossie-fixtures/upstream/**'
- 'Cargo.toml'
- 'Cargo.lock'
- '.cargo/**'
Expand Down
6 changes: 4 additions & 2 deletions docs/compatibility/ossie.md
Original file line number Diff line number Diff line change
Expand Up @@ -468,8 +468,10 @@ Schema validation, ontology validation, permissive import, and export remain
owned by that shared interchange API for both engine choices.

The separate native Rust forward importer validates logical documents against
the same four immutable JSON Schemas as Python: `0.1.1` and all three pinned
development revisions. These schemas are bundled for offline native and WASM
five immutable logical schemas. Four are shared with Python (`0.1.1` and the
three `0.2.0.dev0` revisions). The fifth is the flat Apache `0.3.0.dev0`
draft at `d27a6be`. DuckDB can load that draft directly from a model file.
These schemas are bundled for offline native and WASM
builds. The evaluator covers every assertion used by those schemas and fails
closed if an unsupported assertion is introduced. Logical validation reports
`pinned_json_schema`; semantic checks also validate recognized SQL variants even
Expand Down
84 changes: 83 additions & 1 deletion docs/duckdb-extension.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# DuckDB Extension

The sqlctx DuckDB extension embeds the Rust native runtime in DuckDB. It is a native-format deployment path, separate from the Python CLI and Python adapter ecosystem.
The sqlctx DuckDB extension embeds the Rust native runtime in DuckDB. It reads native sqlctx definitions and Ossie logical model files directly.

## Status

Expand Down Expand Up @@ -82,6 +82,88 @@ Load native YAML from disk:
SELECT * FROM sqlctx_load_file('/path/to/models.yml');
```

### Ossie files

The same loader accepts the released wrapped `0.1.1` format and the flat
`0.3.0.dev0` logical draft pinned at Apache Ossie commit `d27a6be`.
In a database containing the TPC-DS physical tables named in the model, run:

```sql
select * from sqlctx_load_file('/path/to/tpcds_semantic_model.yaml');
select total_sales, total_profit from metrics;
select item.i_brand, sales_by_brand from metrics order by item.i_brand;
```

The draft also declares a dataset-scoped measure:

```sql
select agg(s.total_quantity) as total_quantity from store_sales s;
```

The imported definitions persist in the database. A physical table, view, or
CTE named `metrics` keeps its ordinary DuckDB meaning. The wrapped file uses
the OSI reader. Flat files use the Rust Ossie importer and its offline schema.
Draft dataset metrics that require source measure-relation metadata
(`AGG(source.measure)`) are currently unsupported.

#### Windowed metrics in plain SQL

Selecting any of the TPC-DS draft's three windowed metrics by name from
`metrics` returns `E_DEFERRED_WINDOWED_METRIC`, as required by the
[pinned Ossie wide-table specification](https://github.com/apache/ossie/blob/d27a6beab519c8d3bf08ad5fc901c293205134eb/core-spec/wide_table_semantics.md#52-metric-components).
To calculate them in plain SQL, select `total_sales` with the grouping
dimensions in a CTE, then apply the DuckDB window function to those rows.

**Running sales by day (`cumulative_sales`).** Each row adds that day's sales
to the total through the previous day.

```sql
with daily as (
select date_dim.d_date as sale_date, total_sales
from metrics
)
select sale_date,
sum(total_sales) over (
order by sale_date rows between unbounded preceding and current row
) as cumulative_sales
from daily
order by sale_date;
```

**Brand rank within each store (`brand_rank_in_store`).** Rank brands by
descending sales within each store. Brands with equal sales share a rank.

```sql
with brand_sales as (
select store.s_store_sk as store_id, item.i_brand as brand, total_sales
from metrics
)
select store_id, brand,
rank() over (
partition by store_id order by total_sales desc
) as brand_rank_in_store
from brand_sales
order by store_id, brand_rank_in_store, brand;
```

**Change in monthly sales (`monthly_sales_change`).** Subtract sales for the
previous month present in the result. The first month has a `NULL` change.

```sql
with monthly as (
select date_dim.d_year as sale_year, date_dim.d_moy as sale_month, total_sales
from metrics
)
select sale_year, sale_month,
total_sales - lag(total_sales) over (
order by sale_year, sale_month
) as monthly_sales_change
from monthly
order by sale_year, sale_month;
```

### Native SQL definitions

Load native SQL definitions from disk:

```sql
Expand Down
1 change: 1 addition & 0 deletions sqlctx-duckdb/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ endif()

file(GLOB_RECURSE SQLCTX_RUST_SOURCES
"${SQLCTX_RS_DIR}/src/*.rs"
"${SQLCTX_RS_DIR}/schemas/ossie/*.json"
"${SQLCTX_RS_DIR}/include/*.h")

add_custom_command(
Expand Down
5 changes: 5 additions & 0 deletions sqlctx-duckdb/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ SELECT status, revenue FROM semantic.orders_model;
SELECT sqlctx_rewrite_sql('SELECT orders_model.status, orders_model.revenue FROM orders_model');
```

Released Ossie `0.1.1` and flat `0.3.0.dev0` logical models load through
`sqlctx_load_file`. Query model metrics with ordinary SQL, for example
`select total_sales from metrics` for the upstream TPC-DS model.
[Ossie file examples and supported draft semantics](../docs/duckdb-extension.md#ossie-files)

## Discover and manage definitions

```sql
Expand Down
22 changes: 18 additions & 4 deletions sqlctx-duckdb/src/sqlctx_parser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -412,12 +412,15 @@ class SemanticReferences {
if (!use.semantic_field.empty() || explicit_semantic) return;
// Every reference binds to the table, so the query keeps its native
// meaning, including inside a statement that the compiler rewrites.
QualifyPhysicalTable(*use.table, use.model, use.physical);
}

static void QualifyPhysicalTable(BaseTableRef &table, const string &name, const SqlctxPhysicalRelation &physical) {
#if SQLCTX_QUALIFIED_TABLE_API
use.table->SetQualifiedName(Identifier(use.physical.catalog), Identifier(use.physical.schema),
Identifier(use.model));
table.SetQualifiedName(Identifier(physical.catalog), Identifier(physical.schema), Identifier(name));
#else
use.table->catalog_name = use.physical.catalog;
use.table->schema_name = use.physical.schema;
table.catalog_name = physical.catalog;
table.schema_name = physical.schema;
#endif
}

Expand Down Expand Up @@ -454,6 +457,17 @@ class SemanticReferences {
!SqlctxPhysicalRelationExists(context, name);
auto entry = models.find(name);
if (((!qualified && !ctes.count(name)) || semantic_schema) && entry != models.end()) model = entry->second.model;
// FROM metrics is the global semantic namespace. A CTE or a real
// table on the search path still owns its name in ordinary SQL.
if (!model && !qualified && !ctes.count(name) && !models.empty() &&
StringUtil::CIEquals(name, "metrics")) {
SqlctxPhysicalRelation physical;
if (!explicit_semantic && SqlctxFindPhysicalRelation(context, name, physical)) {
QualifyPhysicalTable(table, name, physical);
} else {
found = true;
}
}
if (model) {
virtual_relation = semantic_schema;
name = model->name;
Expand Down
4 changes: 4 additions & 0 deletions sqlctx-duckdb/test/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ for the complete invocation.
`test_catalog_host.py` uses the same environment variables and verifies
SHOW/DESCRIBE metadata, compatible dimensions, native SELECT, prepared reads,
transaction rollback, and export/import across restart and read-only connections.
It also imports unchanged, checksum-pinned upstream Ossie 0.1.1 and 0.3.0.dev0
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_duckflight_host.py` runs the SQL through an authenticated DuckFlight
PostgreSQL listener using psycopg. Set `DUCKFLIGHT_EXTENSION` as well as the two
Expand Down
121 changes: 121 additions & 0 deletions sqlctx-duckdb/test/test_catalog_host.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
# ///
"""Exercise semantic catalog SQL through each built DuckDB shell."""

import hashlib
import json
import os
import re
import subprocess
from decimal import Decimal
from pathlib import Path
Expand Down Expand Up @@ -430,5 +432,124 @@ def test_standard_catalog_numeric_metadata_matches_host():
assert native == semantic


def test_prefixless_metrics_namespace_respects_duckdb_tables_and_ctes():
totals = execute("select orders.revenue from metrics;")
assert totals == [[{"revenue": "45.00"}]]
rows = execute("""
create temp table metrics as select 7 as revenue;
select revenue from metrics;
with metrics as (select 9 as revenue) select revenue from metrics;
select revenue from metrics union all select orders.revenue from orders order by revenue;
""")
assert rows[-3:] == [[{"revenue": 7}], [{"revenue": 9}], [{"revenue": "7.00"}, {"revenue": "45.00"}]]


TPCDS_SETUP = """
create schema public;
create table public.store_sales(
ss_item_sk integer, ss_ticket_number integer, ss_customer_sk integer,
ss_store_sk integer, ss_sold_date_sk integer, ss_quantity integer,
ss_sales_price decimal(10,2), ss_ext_sales_price decimal(10,2), ss_net_profit decimal(10,2)
);
insert into public.store_sales values
(1, 100, 1, 1, 1, 2, 10, 20, 4),
(1, 101, 1, 1, 1, 3, 10, 30, 6),
(2, 102, 2, 2, 2, 1, 15, 15, -2);
create table public.item(
i_item_sk integer, i_item_id varchar, i_item_desc varchar,
i_brand varchar, i_category varchar, i_current_price decimal(10,2)
);
insert into public.item values
(1, 'A', 'First item', 'Acme', 'Home', 10),
(2, 'B', 'Second item', 'Beta', 'Garden', 15);
create table public.customer(
c_customer_sk integer, c_customer_id varchar, c_first_name varchar,
c_last_name varchar, c_email_address varchar
);
insert into public.customer values
(1, 'C1', 'Ada', 'Lovelace', 'ada@example.test'),
(2, 'C2', 'Grace', 'Hopper', 'grace@example.test');
create table public.store(
s_store_sk integer, s_store_id varchar, s_store_name varchar,
s_city varchar, s_state varchar, s_number_employees integer
);
insert into public.store values (1, 'S1', 'North', 'Seattle', 'WA', 5), (2, 'S2', 'South', 'Portland', 'OR', 3);
create table public.date_dim(
d_date_sk integer, d_date date, d_year integer, d_quarter_name varchar,
d_month_name varchar, d_moy integer
);
insert into public.date_dim values
(1, '2026-01-01', 2026, '2026Q1', 'January', 1),
(2, '2026-02-01', 2026, '2026Q1', 'February', 2);
"""


@pytest.mark.parametrize(
("pin", "checksum", "dataset_metric"),
[
("faf5810", "1c8c8e1a41d6b1b4d957ae5934b883b46ca07ad3901927ec6ce0ecff55d2cb6b", False),
("d27a6be", "72a98b17eda7daa6bcb777125ea44b1cbbb7788bdd6167430e0f58ea7e06a1ce", True),
],
ids=["upstream-0.1.1", "upstream-0.3.0.dev0"],
)
def test_upstream_ossie_file_metrics_and_reopen(tmp_path, pin, checksum, dataset_metric):
fixture = (
Path(__file__).resolve().parents[2]
/ "tests/ossie-fixtures/upstream"
/ pin
/ "examples/tpcds_semantic_model.yaml"
)
# Keep the upstream bytes unchanged, including physical source catalog names.
assert hashlib.sha256(fixture.read_bytes()).hexdigest() == checksum
database = tmp_path / "tpcds.duckdb"
query = """
select total_sales, total_profit from metrics;
select item.i_brand, sales_by_brand from metrics order by item.i_brand;
select total_sales from metrics where store_sales.ss_quantity > 1;
select customer_lifetime_value, store_productivity from metrics;
"""
if dataset_metric:
query += "select agg(s.total_quantity) as total_quantity from store_sales s; show metrics from store_sales;"
documentation = (Path(__file__).resolve().parents[2] / "docs/duckdb-extension.md").read_text()
window_section = documentation.split("#### Windowed metrics in plain SQL", 1)[1].split(
"### Native SQL definitions", 1
)[0]
window_queries = re.findall(r"```sql\n(.*?)```", window_section, re.DOTALL)
assert len(window_queries) == 3
query += "\n".join(window_queries)
results = execute(
query,
setup=TPCDS_SETUP + f"select * from sqlctx_load_file({literal(str(fixture))});",
database=database,
)
assert results[0] == [{"total_sales": "65.00", "total_profit": "8.00"}]
assert results[1] == [
{"i_brand": "Acme", "sales_by_brand": "50.00"},
{"i_brand": "Beta", "sales_by_brand": "15.00"},
]
assert results[2] == [{"total_sales": "50.00"}]
assert results[3] == [{"customer_lifetime_value": 32.5, "store_productivity": 8.125}]
if dataset_metric:
assert results[4] == [{"total_quantity": "6"}]
assert [row["qualified_name"] for row in results[5]] == ["store_sales.total_quantity"]
assert results[6] == [
{"sale_date": "2026-01-01", "cumulative_sales": "50.00"},
{"sale_date": "2026-02-01", "cumulative_sales": "65.00"},
]
assert results[7] == [
{"store_id": 1, "brand": "Acme", "brand_rank_in_store": 1},
{"store_id": 2, "brand": "Beta", "brand_rank_in_store": 1},
]
assert results[8] == [
{"sale_year": 2026, "sale_month": 1, "monthly_sales_change": None},
{"sale_year": 2026, "sale_month": 2, "monthly_sales_change": "-35.00"},
]
for metric in ["cumulative_sales", "brand_rank_in_store", "monthly_sales_change"]:
execute(f"select {metric} from metrics;", setup="", database=database, error="E_DEFERRED_WINDOWED_METRIC")
# Reopen with no definitions loaded and no write permission: both physical
# data and the imported semantic catalog must survive the shell process.
assert execute(query, setup="", database=database, readonly=True) == results


if __name__ == "__main__":
raise SystemExit(pytest.main([__file__, "-v", "-o", "addopts="]))
Loading
Loading