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
3 changes: 2 additions & 1 deletion sqlctx-duckdb/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,8 @@ 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 src/sqlctx_semantic_input.cpp src/sqlctx_explain.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 src/sqlctx_warnings.cpp src/sqlctx_measure_catalog.cpp)


build_static_extension(${TARGET_NAME} ${EXTENSION_SOURCES})
build_loadable_extension(${TARGET_NAME} " " ${EXTENSION_SOURCES})
Expand Down
125 changes: 102 additions & 23 deletions sqlctx-duckdb/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ A DuckDB extension that adds a SQL-first semantic layer. Define metrics and dime

## Installation

Build locally against DuckDB 2.0.1:
From the `sqlctx-duckdb` directory, build against DuckDB 2.0.1:

```bash
make deps DUCKDB_VERSION=v2.0.1
make
SQLCTX_NATIVE_PEG=1 make test
make DUCKDB_VERSION=v2.0.1
SQLCTX_NATIVE_PEG=1 make test DUCKDB_VERSION=v2.0.1
./build/release/duckdb -unsigned -cmd "LOAD '$PWD/build/release/extension/sqlctx/sqlctx.duckdb_extension';"
```

Expand All @@ -43,29 +43,23 @@ Semantic queries use ordinary `SELECT`, including in shells that preload
Define your semantic layer entirely in SQL, no YAML required:

```sql
-- 1. Create your data table
-- Create your data table
CREATE TABLE orders (order_id INT, status VARCHAR, amount DECIMAL(10,2));
INSERT INTO orders VALUES
(1, 'completed', 100.00),
(2, 'completed', 150.00),
(3, 'pending', 75.00);

-- 2. Define a semantic model
MODEL (
name orders_model,
table orders,
primary_key order_id
-- Keep the dimensions and their metrics together in one definition.
MODEL orders_model FROM orders (
primary key (order_id)
status
sum(amount) AS revenue
count(*) AS order_count
avg(amount) AS avg_order_value
);

-- 3. Define metrics (aggregations)
METRIC revenue AS SUM(amount);
METRIC order_count AS COUNT(*);
METRIC avg_order_value AS AVG(amount);

-- 4. Define dimensions (grouping attributes)
DIMENSION (name status, type categorical);

-- 5. Query using semantic layer: revenue is summed per status
-- Selecting status gives one total per status.
SELECT orders_model.status, orders_model.revenue FROM orders_model ORDER BY 1;

-- ┌───────────┬───────────────┐
Expand All @@ -88,10 +82,73 @@ Released Ossie `0.1.1` and flat `0.3.0.dev0` logical models load through
`select total_sales from metrics` for the upstream TPC-DS model.
[Ossie file examples and supported draft semantics](../docs/duckdb-extension.md#ossie-files)

### Choose a definition

| What you want to publish | SQL | What a later query sees |
| --- | --- | --- |
| A model with keys, relationships and business metrics | `MODEL` | Dimensions and metrics through `semantic.model_name`. The selected dimensions determine grouping. |
| Measures directly over the rows of a table, join or subquery | `CREATE VIEW … AS SELECT … AS MEASURE …` | A DuckDB view with measures that SQLCtx can recompute. Use `AGGREGATE(metric)` for the caller's filtered population. |
| A named selection of model fields | `CREATE SEMANTIC VIEW … AS SELECT …` | A live projection that follows changes to the underlying metric. Manage it with `DROP SEMANTIC VIEW`. |
| The result of a fixed semantic query | Ordinary `CREATE VIEW … AS SELECT …` | DuckDB stores the compiled query. Recreate the view to pick up a changed metric definition. |

### Define measures directly on rows

With only `sqlctx` loaded, use `AS MEASURE` to declare an aggregate over a
table, join or subquery. Other named projections become dimensions. For example:

```sql
LOAD sqlctx;
CREATE TABLE regional_orders(region VARCHAR, amount INTEGER);
INSERT INTO regional_orders VALUES ('west', 10), ('west', 30), ('east', 80);

CREATE VIEW yard_sales AS
SELECT region, avg(amount) AS MEASURE aov FROM regional_orders;

SELECT region, aggregate(aov) AS aov FROM yard_sales ORDER BY region;
-- east 80, west 20
SELECT aggregate(aov) AS aov FROM yard_sales;
-- 40 across the three source rows

SELECT aggregate(aov) AS west_aov, aov AS overall_aov
FROM yard_sales WHERE region = 'west';
-- west_aov = 20, overall_aov = 40
```

Use `AGGREGATE(aov)` when a caller's `WHERE` should filter the rows used to
compute the measure. A bare `aov` uses the dimensions in the query for grouping
and evaluates the measure over its declared source. In a dashboard, removing
`region` from a West-only table to make a single KPI changes bare `aov` from 20
to 40. `AGGREGATE(aov)` stays at 20 in both layouts. For BI clients that only
emit ordinary field references, publish the metric on a `MODEL` and connect to
`semantic.model_name` so dimension filters apply before aggregation.

If a BI tool emits `SUM(revenue)` for a measure declared as `SUM(amount)`,
SQLCtx sums the underlying amounts once at the requested grain. For an average
or ratio, use `AGGREGATE(aov)`. To average a set of regional results, first
compute one row per region in a subquery and then apply `AVG` to its output.

The declaration creates a DuckDB view with a SQLCtx measure definition. Run
`SHOW METRICS FROM yard_sales` to inspect it. Use `CREATE OR REPLACE VIEW` to
update its definition and `DROP VIEW yard_sales` to remove it.

Opening a database without SQLCtx still lets DuckDB describe the view. Selecting
a virtual measure raises an error directing the reader to load SQLCtx. For views
created by an earlier development build that stored virtual measures as `NULL`,
rerun the original `CREATE OR REPLACE VIEW` declaration once to update the stored SQL.

A declaration can use a qualified view name, an explicit column-name list or
`SELECT *`. `WHERE` filters the source rows. A view can expose grouped rows
while retaining the original inputs used to recompute a measure at another
grain, for example a distinct customer count across regions.
When Yardstick is also loaded, its parser handles its measure declarations.
For an existing SQLCtx measure view in that configuration, select the metric
directly (`SELECT region, aov FROM yard_sales`) so SQLCtx evaluates it.

## Discover and manage definitions

```sql
SHOW MODELS;
SHOW SEMANTIC VIEWS;
SHOW METRICS FROM orders_model;
SHOW DIMENSIONS FROM orders_model;
SHOW RELATIONSHIPS FROM orders_model;
Expand All @@ -115,6 +172,9 @@ the JSON definition. Definition statements and file loads report what they
created, replaced or dropped. `DESCRIBE MODEL` includes the model and all its
fields. `SHOW DIMENSIONS FOR` checks each dimension with the query compiler;
use `EXPLAIN SELECT` to validate a complete combination of metrics and dimensions.
Segments can be selected by qualified name in a SemanticInput query's
`segments` array. In ordinary SQL, use a `WHERE` predicate on the model
dimensions. `SHOW SEGMENTS FROM model_name` displays each segment's SQL.
`SHOW SEMANTIC METRICS`, and the corresponding forms for other kinds, are also
accepted.

Expand Down Expand Up @@ -148,6 +208,10 @@ DESCRIBE semantic.orders_model;
one row per distinct combination of all dimensions.
- `WHERE` predicates that read only one relation's dimensions filter the model
before grouping and do not add to the grain.
- A predicate on a metric compares the computed value at the query grain.
For example, `SELECT status, revenue FROM semantic.orders_model WHERE revenue > 100`
keeps statuses whose total revenue exceeds 100. To filter individual orders
before summing, put a predicate on the source rows or in the metric definition.
- Aggregating a metric again is allowed when each group holds one row of the
relation, or when the aggregation composes: `sum` of a `sum` or `count`
metric, `min` of `min`, `max` of `max`. Other cases, such as `avg` of a ratio
Expand Down Expand Up @@ -202,6 +266,9 @@ for attached catalogs and ordinary DuckDB views.

## Versioned SemanticInput

The DuckDB functions default a missing `input_dialect` to `"duckdb"`.
For imported definitions, set it to the dialect used to write the model expressions.

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
Expand Down Expand Up @@ -374,7 +441,8 @@ import/export and explicit semantic queries, including nested `PREPARE` and `EXP
still use the shared Rust configuration parser; semantic query compilation still
uses the Rust SQL AST.

Loading sqlctx enables automatic routing, including a planning hook for
Loading sqlctx sets DuckDB's `allow_parser_override_extension` setting to
`fallback` and enables automatic routing, including a planning hook for
hosts with another parser override. To explicitly compose the native
grammar with other installed grammars, include it in `active_grammar_extensions`:

Expand Down Expand Up @@ -612,9 +680,8 @@ rows, including equal-valued metrics on distinct customers.
- Semantic definitions support creation, replacement, loading, discovery,
export/import, active-model selection and dependency-restricted removal.
Use `CREATE OR REPLACE` to update definitions; there is no `ALTER MODEL` syntax.
- Semantic queries support a subset of DuckDB SQL. Correlated semantic subqueries
and grouping modifiers such as `ROLLUP` are rejected; explicit `GROUP BY` must
repeat the selected semantic dimensions.
- In the model query compiler, explicit `GROUP BY` must repeat the selected
semantic dimensions.
- 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;
Expand All @@ -629,6 +696,18 @@ rows, including equal-valued metrics on distinct customers.

## Utility Functions

For interactive SQL, start with `SHOW MODELS`, `SHOW METRICS FROM model_name` and
`EXPLAIN SELECT`. Applications can use `sqlctx_models()` to get one model name per row,
and the `sqlctx_*_semantic_input` entry points to submit a model and query together.

Use `sqlctx_query(sql)` or `sqlctx_query_scoped(sql)` to run measure SQL supplied
as a string. The compatibility spellings are `yardstick` and `yardstick_scoped`.
`sqlctx_warning(message)` reports a warning. Enable `warnings_as_errors` to raise
an error instead.
To keep measure definitions in a
specific catalog table (including DuckLake), set `yardstick_definition_table` to a
fully qualified `catalog.schema.table` name before creating the views.

`sqlctx_explain(sql)` returns a JSON report from the same Rust compiler and current
catalog snapshot used by `sqlctx_rewrite_sql`:

Expand Down Expand Up @@ -663,7 +742,7 @@ Manually rewrite a SQL query (useful for debugging).

```sql
SELECT sqlctx_rewrite_sql('SELECT orders.revenue FROM orders');
-- Returns: SELECT SUM(orders.amount) FROM orders
-- Returns the executable SQL that computes revenue at the requested grain.
```

## How It Works
Expand Down
144 changes: 15 additions & 129 deletions sqlctx-duckdb/docs/README.md
Original file line number Diff line number Diff line change
@@ -1,99 +1,18 @@
# sqlctx DuckDB Extension Documentation

## Overview

sqlctx is a DuckDB extension that provides a SQL-first semantic layer. It allows you to define business metrics and dimensions once, then query them with automatic SQL generation.

## Core Concepts

### Models
A model maps to a physical table and defines:
- **Dimensions**: Attributes for grouping and filtering (categorical, time, boolean, numeric)
- **Metrics**: Aggregations like sum, count, avg, min, max
- **Relationships**: Joins to other models
- **Segments**: Reusable named filters

### Query Rewriting
When you write:
```sql
SEMANTIC SELECT orders.revenue, orders.status FROM orders
```

sqlctx rewrites it to:
```sql
SELECT SUM(orders.amount), orders.status FROM orders GROUP BY 2
```

## API Reference

### Table Functions

#### `sqlctx_load(yaml VARCHAR) -> TABLE(result VARCHAR)`
Loads semantic model definitions from a YAML string.

**Parameters:**
- `yaml`: YAML string containing model definitions

**Returns:** Single row with success message

**Example:**
```sql
SELECT * FROM sqlctx_load('
models:
- name: orders
table: orders
primary_key: order_id
dimensions:
- name: status
type: categorical
metrics:
- name: revenue
agg: sum
sql: amount
');
```

#### `sqlctx_models() -> TABLE(model_name VARCHAR)`
Lists all currently loaded semantic models.

**Returns:** One row per loaded model

**Example:**
```sql
SELECT * FROM sqlctx_models();
-- ┌────────────┐
-- │ model_name │
-- ├────────────┤
-- │ orders │
-- │ customers │
-- └────────────┘
```

### Scalar Functions

#### `sqlctx_rewrite_sql(sql VARCHAR) -> VARCHAR`
Rewrites a SQL query using semantic definitions without executing it.

**Parameters:**
- `sql`: SQL query string to rewrite

**Returns:** Rewritten SQL string

**Example:**
```sql
SELECT sqlctx_rewrite_sql('SELECT orders.revenue FROM orders');
-- Returns: SELECT SUM(orders.amount) FROM orders
```

### Parser Extension

#### `SEMANTIC` Keyword
Prefix any SELECT statement with `SEMANTIC` to trigger automatic query rewriting.

**Example:**
```sql
SEMANTIC SELECT orders.revenue, orders.status FROM orders;
```
# SQLCtx DuckDB extension reference

Start with the [DuckDB quick start](../README.md#quick-start-pure-sql) for an
executable model and measure queries. The [definition guide](../README.md#choose-a-definition)
covers models, measure views, reusable semantic views and ordinary DuckDB views.

| Task | Reference |
| --- | --- |
| Install or build the matching extension | [Installation](../README.md#installation) |
| Load SQL, native YAML, Cube or Ossie definitions | [Definition files](../README.md#alternative-definition-files) |
| Inspect measures, compatible dimensions and relationships | [Catalog discovery](../README.md#discover-and-manage-definitions) |
| Understand grouping and filter context | [Measures over rows](../README.md#define-measures-directly-on-rows) |
| Inspect a compiled query | [Explain and rewrite](../README.md#utility-functions) |
| Persist definitions, query attachments or use a BI client | [DuckDB guide](../../docs/duckdb-extension.md) |
| Submit a versioned query from an application | [SemanticInput](../README.md#versioned-semanticinput) |

## YAML Schema

Expand Down Expand Up @@ -159,36 +78,3 @@ cubes:
- name: string
sql: string # Use ${CUBE} for table reference
```

## Building

### Prerequisites
- Rust toolchain (for sqlctx-rs)
- CMake 3.5+
- C++11 compiler

### Build Steps

```bash
# 1. Build the Rust library
cd sqlctx-rs
cargo build --release

# 2. Build the DuckDB extension
cd sqlctx-duckdb
git submodule update --init --recursive
make

# 3. Run tests
make test
```

### Output Files
- `build/release/duckdb` - DuckDB shell with extension
- `build/release/unittest` - Test runner

## Limitations

- Parser extension requires `SEMANTIC` keyword prefix (DuckDB's parser handles valid SQL first)
- Single-statement queries only
- State is global (models persist across queries in same session)
Loading
Loading