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,8 +185,9 @@ 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 src/sqlctx_warnings.cpp src/sqlctx_measure_catalog.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_aggregate_state.cpp src/sqlctx_aggregate_decorations.cpp src/sqlctx_measure_binding.cpp src/sqlctx_measure_catalog.cpp src/sqlctx_pivot.cpp)

list(APPEND EXTENSION_SOURCES src/sqlctx_measure_windows.cpp src/sqlctx_context_predicates.cpp)

build_static_extension(${TARGET_NAME} ${EXTENSION_SOURCES})
build_loadable_extension(${TARGET_NAME} " " ${EXTENSION_SOURCES})
Expand Down
17 changes: 15 additions & 2 deletions sqlctx-duckdb/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ 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.

SQLCtx implements measure declarations, context modifiers, windows, PIVOT and
persistent definitions in its compiler and DuckDB extension. The window, predicate,
decoration and aggregate-state helpers include code adapted from
[Yardstick under its MIT license](https://github.com/sidequery/yardstick/blob/2b1318402b6be22b6417de5c83523f4b558c621f/README.md#license).

## Discover and manage definitions

```sql
Expand Down Expand Up @@ -441,6 +446,12 @@ 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.

Measure context modifiers (`AT (...)`), measure windows and exported aggregate
states require DuckDB 2.0.1. DuckDB 1.5.6 supports measure declarations and direct
measure queries, including `AGGREGATE(metric)`, but its parser rejects `AT (...)`.
Passing SQL through `sqlctx_query` or its `yardstick` compatibility spelling does
not add syntax that the host parser cannot recognize.

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
Expand Down Expand Up @@ -681,7 +692,8 @@ rows, including equal-valued metrics on distinct customers.
export/import, active-model selection and dependency-restricted removal.
Use `CREATE OR REPLACE` to update definitions; there is no `ALTER MODEL` syntax.
- In the model query compiler, explicit `GROUP BY` must repeat the selected
semantic dimensions.
semantic dimensions. Measure views also support context modifiers, correlated
subqueries and grouping sets.
- 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 @@ -703,7 +715,8 @@ and the `sqlctx_*_semantic_input` entry points to submit a model and query toget
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.
an error instead. `sqlctx_state`, `sqlctx_combine` and `sqlctx_finalize` work with
exported aggregate states on DuckDB 2.0.1. Their `yardstick_*` spellings also work.
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.
Expand Down
67 changes: 67 additions & 0 deletions sqlctx-duckdb/src/include/sqlctx_aggregate_decorations.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#pragma once

#include "sqlctx_compat.hpp"
#include "duckdb/parser/parser.hpp"

namespace duckdb {
class QueryNode;
class ClientContext;

void LowerSqlctxAggregateDecorations(ClientContext &context, QueryNode &query);
bool RequiresSqlctxAggregateLowering(QueryNode &query);

#if SQLCTX_GRAMMAR_EXTENSION
struct BoundStatement;

// Schema inspection shares the caller's transaction and lexical CTE scopes.
// These bind-only plans are never executed or inserted into runtime SQL.
class SqlctxMeasureBindScope {
public:
explicit SqlctxMeasureBindScope(ClientContext &context);
~SqlctxMeasureBindScope();
private:
ClientContext *previous;
};
ClientContext *CurrentSqlctxMeasureContext();

class SqlctxMeasureCteBindScope {
public:
explicit SqlctxMeasureCteBindScope(const vector<unique_ptr<QueryNode>> *context);
SqlctxMeasureCteBindScope(const vector<string> &queries, const ParserOptions &options);
~SqlctxMeasureCteBindScope();
private:
vector<unique_ptr<QueryNode>> definitions;
const vector<unique_ptr<QueryNode>> *previous;
};
const vector<unique_ptr<QueryNode>> *CurrentSqlctxMeasureCtes();
// Canonical model keys are schema-only CTEs during window probes. They need
// not correspond to physical DuckDB views (external definitions do not).
class SqlctxMeasureSourceBindScope {
public:
SqlctxMeasureSourceBindScope(const vector<pair<string, string>> &sources, const ParserOptions &options);
~SqlctxMeasureSourceBindScope();
private:
vector<unique_ptr<QueryNode>> definitions;
const vector<unique_ptr<QueryNode>> *previous;
};
BoundStatement BindSqlctxMeasureProbe(QueryNode &probe, const vector<QueryNode *> &local_scopes = {});

inline vector<unique_ptr<ParsedExpression>> ParseSqlctxMeasureExpressions(
const string &sql, const ParserOptions &options = SqlctxBuiltinParserOptions()) {
Parser parser(options);
return parser.ParseExpressionList(sql);
}

bool IsSqlctxMeasureAggregate(const string &name);
void RemoveSqlctxContextDimensions(unique_ptr<ParsedExpression> &expression,
const vector<unique_ptr<ParsedExpression>> &dimensions,
const string &source_alias);
unique_ptr<ParsedExpression> LowerSqlctxVisibleJoin(const string &source_alias, const string &query_sql,
const vector<string> &excluded_dimensions,
const ParserOptions &options);
string DecorateSqlctxMeasureExpression(const string &measure_expression, const string &call_sql,
const vector<pair<string, string>> &dimensions,
const vector<string> &qualifiers, const ParserOptions &options,
bool preserve_dimension_qualifiers = false);
#endif
} // namespace duckdb
11 changes: 11 additions & 0 deletions sqlctx-duckdb/src/include/sqlctx_aggregate_state.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#pragma once

#include "sqlctx_compat.hpp"

namespace duckdb {
class ExtensionLoader;

// Compatibility functions preserve native DuckDB aggregate-state types and
// compound formulas through SQLCtx recomputation, storage and combination.
void RegisterSqlctxAggregateStateFunctions(ExtensionLoader &loader);
} // namespace duckdb
4 changes: 2 additions & 2 deletions sqlctx-duckdb/src/include/sqlctx_compiler.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#pragma once

#include "sqlctx.h"
#include "sqlctx_compiler_api.hpp"
#include "duckdb/common/exception.hpp"
#include "duckdb/common/types.hpp"

Expand All @@ -12,7 +12,7 @@ class SqlctxCompilerOwner {
public:
explicit SqlctxCompilerOwner(const string &snapshot) {
char *error = nullptr;
compiler = sqlctx_compiler_create(snapshot.c_str(), &error);
compiler = CreateSqlctxHostCompiler(snapshot.c_str(), &error);
if (!compiler) {
string message = error ? error : "cannot create semantic compiler";
sqlctx_free(error);
Expand Down
22 changes: 22 additions & 0 deletions sqlctx-duckdb/src/include/sqlctx_compiler_api.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#pragma once

#include "sqlctx.h"
#include "sqlctx_compat.hpp"

namespace duckdb {

// Native measure payloads require all three AST lowerers. Legacy DuckDB builds
// compile no-op binding hooks, so retain the portable compiler contract there.
#if SQLCTX_GRAMMAR_EXTENSION
static constexpr auto CreateSqlctxHostCompiler = sqlctx_compiler_create_native;
static constexpr auto RewriteSqlctxHostSnapshot = sqlctx_snapshot_rewrite_native;
static constexpr auto RewriteSqlctxHostSnapshotWithWarnings = sqlctx_snapshot_rewrite_with_warnings_native;
static constexpr auto ExplainSqlctxHostSnapshot = sqlctx_snapshot_plan_explanation_native;
#else
static constexpr auto CreateSqlctxHostCompiler = sqlctx_compiler_create;
static constexpr auto RewriteSqlctxHostSnapshot = sqlctx_snapshot_rewrite;
static constexpr auto RewriteSqlctxHostSnapshotWithWarnings = sqlctx_snapshot_rewrite_with_warnings;
static constexpr auto ExplainSqlctxHostSnapshot = sqlctx_snapshot_plan_explanation;
#endif

} // namespace duckdb
51 changes: 51 additions & 0 deletions sqlctx-duckdb/src/include/sqlctx_measure_windows.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// Adapted from sidequery/yardstick (MIT), revision 2b1318402b6be22b6417de5c83523f4b558c621f.
#pragma once

#include "sqlctx_compat.hpp"

#if SQLCTX_GRAMMAR_EXTENSION
#include "duckdb/common/common.hpp"
#include "duckdb/common/pair.hpp"
#include "duckdb/parser/parser_options.hpp"

namespace duckdb {

class SelectNode;
class QueryNode;

// Expand visible projection stars before adding hidden provenance columns.
void ExpandSqlctxMeasureProjectionStars(SelectNode &select, const vector<QueryNode *> &scopes = {});

enum class WindowContextType { ALL, ALL_GLOBAL, SET, WHERE, VISIBLE };

struct WindowContextModifier {
WindowContextType type;
string dimension;
string value;
};

struct MeasureWindowSource {
string key;
string relation_name;
string alias;
string clean_select_sql;
bool grouped = false;
vector<pair<string, string>> dimensions;
};

struct MeasureWindowCall {
string marker_name;
string source_key;
string expression_sql;
vector<WindowContextModifier> modifiers;
};

// Windows select a set of original base-row identities. Repeated identities
// introduced by joins never multiply a measure, while identical original rows
// retain their independent identities.
string RewriteSqlctxMeasureWindows(const string &scope_sql, const vector<MeasureWindowSource> &sources,
const vector<MeasureWindowCall> &calls, const vector<string> &visible_ctes,
const vector<string> &binding_ctes, const ParserOptions &options);

} // namespace duckdb
#endif
15 changes: 15 additions & 0 deletions sqlctx-duckdb/src/include/sqlctx_pivot.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#pragma once

#include "sqlctx_catalog.hpp"

namespace duckdb {
// Compile each measure cell at its final grouping grain before DuckDB rotates
// it into output columns. Returns true when a measure cell or an explicitly
// precomputed measure input was lowered.
bool LowerSqlctxMeasurePivots(ClientContext &context, QueryNode &query, const SqlctxCatalogSnapshot &snapshot);

// Pivot staging queries use the same catalog and CTE resolution as ordinary
// SELECTs before their cells reach the shared model compiler.
unique_ptr<QueryNode> CompileSqlctxPivotCells(ClientContext &context, unique_ptr<QueryNode> query,
const SqlctxCatalogSnapshot &snapshot);
}
60 changes: 60 additions & 0 deletions sqlctx-duckdb/src/include/sqlctx_query_syntax.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#pragma once

#include "sqlctx_parser.hpp"

#if SQLCTX_GRAMMAR_EXTENSION
#include "duckdb/parser/expression/constant_expression.hpp"
#include "duckdb/parser/expression/function_expression.hpp"

namespace duckdb {

// A native syntax node, never an executable SQL function. DuckDB inserts the
// preceding expression as the first argument when processing an indirection.
// Modifier expressions remain ordinary children so catalog qualification and
// nested query traversal reach them before the shared compiler consumes SQL.
class SqlctxAtExpression final : public FunctionExpression {
public:
SqlctxAtExpression(string layout, vector<unique_ptr<ParsedExpression>> modifiers)
: FunctionExpression("__sqlctx_at", vector<unique_ptr<ParsedExpression>> {}), modifier_count(modifiers.size()) {
GetArgumentsMutable().emplace_back(ConstantExpression::String(std::move(layout)));
for (auto &modifier : modifiers) GetArgumentsMutable().emplace_back(std::move(modifier));
}

string ToString() const override {
auto &arguments = GetArguments();
if (arguments.size() != modifier_count + 2) throw InternalException("SQLCtx AT has no operand");
auto &layout = arguments[1].GetExpression().Cast<ConstantExpression>().GetLiteral().text;
string modifiers;
idx_t start = 0;
for (idx_t index = 0; index < modifier_count; ++index) {
auto slot = layout.find('\x1f', start);
if (slot == string::npos) throw InternalException("SQLCtx AT modifier layout is incomplete");
modifiers += layout.substr(start, slot - start) + arguments[index + 2].GetExpression().ToString();
start = slot + 1;
}
modifiers += layout.substr(start);
return "(" + arguments[0].GetExpression().ToString() + ") AT (" + modifiers + ")";
}

unique_ptr<ParsedExpression> Copy() const override {
auto &arguments = GetArguments();
bool has_operand = arguments.size() == modifier_count + 2;
idx_t layout_index = has_operand ? 1 : 0;
auto &layout = arguments[layout_index].GetExpression().Cast<ConstantExpression>().GetLiteral().text;
vector<unique_ptr<ParsedExpression>> modifiers;
for (idx_t index = layout_index + 1; index < arguments.size(); ++index) {
modifiers.push_back(arguments[index].GetExpression().Copy());
}
auto result = make_uniq<SqlctxAtExpression>(layout, std::move(modifiers));
if (has_operand) {
result->GetArgumentsMutable().insert(result->GetArgumentsMutable().begin(), arguments[0].Copy());
}
result->CopyBase(*this);
return std::move(result);
}
private:
idx_t modifier_count;
};

} // namespace duckdb
#endif
Loading
Loading