diff --git a/sqlctx-duckdb/CMakeLists.txt b/sqlctx-duckdb/CMakeLists.txt index 656528e46..fc5f27887 100644 --- a/sqlctx-duckdb/CMakeLists.txt +++ b/sqlctx-duckdb/CMakeLists.txt @@ -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}) diff --git a/sqlctx-duckdb/README.md b/sqlctx-duckdb/README.md index 9b0bb2225..082bf2518 100644 --- a/sqlctx-duckdb/README.md +++ b/sqlctx-duckdb/README.md @@ -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 @@ -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 @@ -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; @@ -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. diff --git a/sqlctx-duckdb/src/include/sqlctx_aggregate_decorations.hpp b/sqlctx-duckdb/src/include/sqlctx_aggregate_decorations.hpp new file mode 100644 index 000000000..af90a67e9 --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_aggregate_decorations.hpp @@ -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> *context); + SqlctxMeasureCteBindScope(const vector &queries, const ParserOptions &options); + ~SqlctxMeasureCteBindScope(); +private: + vector> definitions; + const vector> *previous; +}; +const vector> *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> &sources, const ParserOptions &options); + ~SqlctxMeasureSourceBindScope(); +private: + vector> definitions; + const vector> *previous; +}; +BoundStatement BindSqlctxMeasureProbe(QueryNode &probe, const vector &local_scopes = {}); + +inline vector> ParseSqlctxMeasureExpressions( + const string &sql, const ParserOptions &options = SqlctxBuiltinParserOptions()) { + Parser parser(options); + return parser.ParseExpressionList(sql); +} + +bool IsSqlctxMeasureAggregate(const string &name); +void RemoveSqlctxContextDimensions(unique_ptr &expression, + const vector> &dimensions, + const string &source_alias); +unique_ptr LowerSqlctxVisibleJoin(const string &source_alias, const string &query_sql, + const vector &excluded_dimensions, + const ParserOptions &options); +string DecorateSqlctxMeasureExpression(const string &measure_expression, const string &call_sql, + const vector> &dimensions, + const vector &qualifiers, const ParserOptions &options, + bool preserve_dimension_qualifiers = false); +#endif +} // namespace duckdb diff --git a/sqlctx-duckdb/src/include/sqlctx_aggregate_state.hpp b/sqlctx-duckdb/src/include/sqlctx_aggregate_state.hpp new file mode 100644 index 000000000..af189f369 --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_aggregate_state.hpp @@ -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 diff --git a/sqlctx-duckdb/src/include/sqlctx_compiler.hpp b/sqlctx-duckdb/src/include/sqlctx_compiler.hpp index ba959cd82..007a79627 100644 --- a/sqlctx-duckdb/src/include/sqlctx_compiler.hpp +++ b/sqlctx-duckdb/src/include/sqlctx_compiler.hpp @@ -1,6 +1,6 @@ #pragma once -#include "sqlctx.h" +#include "sqlctx_compiler_api.hpp" #include "duckdb/common/exception.hpp" #include "duckdb/common/types.hpp" @@ -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); diff --git a/sqlctx-duckdb/src/include/sqlctx_compiler_api.hpp b/sqlctx-duckdb/src/include/sqlctx_compiler_api.hpp new file mode 100644 index 000000000..6cdb09fbf --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_compiler_api.hpp @@ -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 diff --git a/sqlctx-duckdb/src/include/sqlctx_measure_windows.hpp b/sqlctx-duckdb/src/include/sqlctx_measure_windows.hpp new file mode 100644 index 000000000..ef9aa541e --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_measure_windows.hpp @@ -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 &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> dimensions; +}; + +struct MeasureWindowCall { + string marker_name; + string source_key; + string expression_sql; + vector 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 &sources, + const vector &calls, const vector &visible_ctes, + const vector &binding_ctes, const ParserOptions &options); + +} // namespace duckdb +#endif diff --git a/sqlctx-duckdb/src/include/sqlctx_pivot.hpp b/sqlctx-duckdb/src/include/sqlctx_pivot.hpp new file mode 100644 index 000000000..f8cc20b23 --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_pivot.hpp @@ -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 CompileSqlctxPivotCells(ClientContext &context, unique_ptr query, + const SqlctxCatalogSnapshot &snapshot); +} diff --git a/sqlctx-duckdb/src/include/sqlctx_query_syntax.hpp b/sqlctx-duckdb/src/include/sqlctx_query_syntax.hpp new file mode 100644 index 000000000..99ecf1dfd --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_query_syntax.hpp @@ -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> modifiers) + : FunctionExpression("__sqlctx_at", vector> {}), 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().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 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().GetLiteral().text; + vector> modifiers; + for (idx_t index = layout_index + 1; index < arguments.size(); ++index) { + modifiers.push_back(arguments[index].GetExpression().Copy()); + } + auto result = make_uniq(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 diff --git a/sqlctx-duckdb/src/sqlctx_aggregate_decorations.cpp b/sqlctx-duckdb/src/sqlctx_aggregate_decorations.cpp new file mode 100644 index 000000000..7f1e0afc5 --- /dev/null +++ b/sqlctx-duckdb/src/sqlctx_aggregate_decorations.cpp @@ -0,0 +1,446 @@ +// Adapted from sidequery/yardstick (MIT), revision 2b1318402b6be22b6417de5c83523f4b558c621f. +// See README.md#license in that revision. SQLCtx owns the model and compiler. +#include "sqlctx_aggregate_decorations.hpp" + +#if SQLCTX_GRAMMAR_EXTENSION +#include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/entry_lookup_info.hpp" +#include "duckdb/common/exception.hpp" +#include "duckdb/common/string_util.hpp" +#include "duckdb/parser/expression/columnref_expression.hpp" +#include "duckdb/parser/expression/conjunction_expression.hpp" +#include "duckdb/parser/expression/constant_expression.hpp" +#include "duckdb/parser/expression/function_expression.hpp" +#include "duckdb/parser/expression/lambda_expression.hpp" +#include "duckdb/parser/expression/star_expression.hpp" +#include "duckdb/parser/expression/subquery_expression.hpp" +#include "duckdb/parser/parsed_expression_iterator.hpp" +#include "duckdb/parser/parser.hpp" +#include "duckdb/parser/query_node/recursive_cte_node.hpp" +#include "duckdb/parser/query_node/select_node.hpp" +#include "duckdb/parser/query_node/set_operation_node.hpp" +#include "duckdb/parser/statement/select_statement.hpp" +#include "duckdb/parser/tableref/basetableref.hpp" +#include "duckdb/parser/tableref/expressionlistref.hpp" +#include "duckdb/parser/tableref/joinref.hpp" +#include "duckdb/parser/tableref/subqueryref.hpp" +#include "duckdb/parser/tableref/table_function_ref.hpp" +#include "duckdb/planner/binder.hpp" +#include +#include + +namespace duckdb { +namespace { +using Names = std::unordered_set; + +unique_ptr ParseOne(const string &sql, const ParserOptions &options) { + auto expressions = ParseSqlctxMeasureExpressions(sql, options); + if (expressions.size() != 1) { + throw ParserException("Expected one expression in decorated AGGREGATE"); + } + return std::move(expressions[0]); +} + +struct DecorationScope { + bool unqualified_is_local = true; + bool inner_alias_shadowed = false; + Names shadowed_qualifiers; + Names shadowed_columns; + Names aliases; + Names lambda_parameters; + vector cte_scopes; +}; + +// Call decorations are written against exposed dimensions. Resolve only names +// owned by the measure view; subquery and lambda bindings keep their own scope. +class DecorationReferences { +public: + DecorationReferences(const vector> &dimensions, const vector &qualifiers, + const ParserOptions &options, bool preserve_dimension_qualifiers) + : preserve_dimension_qualifiers(preserve_dimension_qualifiers) { + for (auto &qualifier : qualifiers) local_qualifiers.insert(StringUtil::Lower(qualifier)); + for (auto &dimension : dimensions) { + auto expression = ParseOne(dimension.second, options); + if (expression->HasSubquery()) { + throw ParserException("Subquery dimensions are not supported in AGGREGATE decorations"); + } + // Resolve base-row names without substituting exposed aliases again. + QualifyDimension(expression, {}, preserve_dimension_qualifiers); + dimension_expressions.emplace(StringUtil::Lower(dimension.first), std::move(expression)); + } + } + + void Expression(unique_ptr &expression, DecorationScope scope = {}) { + if (!expression) return; + if (expression->GetExpressionClass() == ExpressionClass::COLUMN_REF) { + auto &names = expression->Cast().ColumnNames(); + auto first = StringUtil::Lower(names[0].GetIdentifierName()); + if (scope.lambda_parameters.count(first)) return; + bool local = names.size() == 1 + ? scope.unqualified_is_local && !scope.aliases.count(first) && !scope.shadowed_columns.count(first) + : local_qualifiers.count(StringUtil::Lower(names[names.size() - 2].GetIdentifierName())) && + !scope.shadowed_qualifiers.count(StringUtil::Lower(names[names.size() - 2].GetIdentifierName())); + if (local) { + if (scope.inner_alias_shadowed) { + throw ParserException("Conflicting recomputation alias in AGGREGATE decoration"); + } + auto alias = expression->GetAlias(); + auto entry = dimension_expressions.find(StringUtil::Lower(names.back().GetIdentifierName())); + if (entry == dimension_expressions.end() && preserve_dimension_qualifiers && names.size() == 1) { + // The window's consumer may provide this input through a + // join. Let its schema-aware lineage binding resolve it. + return; + } + expression = entry == dimension_expressions.end() + ? make_uniq(names.back(), Identifier("_inner")) + : entry->second->Copy(); + expression->SetAlias(std::move(alias)); + } + return; + } + if (expression->GetExpressionClass() == ExpressionClass::LAMBDA) { + auto &lambda = expression->Cast(); + if (AddLambdaBindings(lambda, scope.lambda_parameters)) { + Expression(lambda.RightMutable(), scope); + return; + } + } + if (expression->GetExpressionClass() == ExpressionClass::SUBQUERY) { + auto &subquery = expression->Cast(); + Expression(subquery.GetChildMutable(), scope); + Query(*subquery.SubqueryMutable()->node, scope); + return; + } + ParsedExpressionIterator::EnumerateChildren(*expression, + [&](unique_ptr &child) { Expression(child, scope); }); + } + +private: + bool preserve_dimension_qualifiers; + Names local_qualifiers; + std::unordered_map> dimension_expressions; + + static bool AddLambdaBindings(LambdaExpression &lambda, Names &bindings) { + // Arrow syntax also means JSON access; only the lambda keyword has + // unambiguous lexical bindings before DuckDB's binder runs. + if (lambda.GetLambdaSyntaxType() != LambdaSyntaxType::LAMBDA_KEYWORD) return false; + string error; + auto parameters = lambda.ExtractColumnRefExpressions(error); + if (!error.empty()) throw ParserException(error); + for (auto ¶meter : parameters) { + auto &names = parameter.get().Cast().ColumnNames(); + if (names.size() != 1) throw ParserException("Invalid AGGREGATE decoration lambda parameter"); + bindings.insert(StringUtil::Lower(names[0].GetIdentifierName())); + } + return true; + } + + static void QualifyDimension(unique_ptr &expression, Names bindings, + bool preserve_dimension_qualifiers) { + if (expression->GetExpressionClass() == ExpressionClass::COLUMN_REF) { + auto &names = expression->Cast().ColumnNamesMutable(); + if (!bindings.count(StringUtil::Lower(names[0].GetIdentifierName()))) { + if (preserve_dimension_qualifiers) { + // Window recomputation projects against the original FROM, + // where joined relations may expose the same column name. + names.insert(names.begin(), Identifier("_inner")); + } else { + auto column = names.back(); + names = {Identifier("_inner"), std::move(column)}; + } + } + return; + } + if (expression->GetExpressionClass() == ExpressionClass::LAMBDA) { + auto &lambda = expression->Cast(); + if (AddLambdaBindings(lambda, bindings)) { + QualifyDimension(lambda.RightMutable(), bindings, preserve_dimension_qualifiers); + return; + } + } + ParsedExpressionIterator::EnumerateChildren(*expression, + [&](unique_ptr &child) { + QualifyDimension(child, bindings, preserve_dimension_qualifiers); + }); + } + + static void Qualifiers(const TableRef &table, Names &names) { + if (!table.alias.empty()) { + names.insert(StringUtil::Lower(table.alias.GetIdentifierName())); + } else if (table.type == TableReferenceType::BASE_TABLE) { + names.insert(StringUtil::Lower(table.Cast().Table().GetIdentifierName())); + } else if (table.type == TableReferenceType::TABLE_FUNCTION) { + auto &function = table.Cast().function; + if (function->GetExpressionClass() == ExpressionClass::FUNCTION) { + names.insert(StringUtil::Lower(function->Cast().FunctionName().GetIdentifierName())); + } + } + if (table.type == TableReferenceType::JOIN) { + auto &join = table.Cast(); + Qualifiers(*join.left, names); + Qualifiers(*join.right, names); + } + } + + static bool ProjectionNames(QueryNode &query, vector &names) { + if (query.type == QueryNodeType::SET_OPERATION_NODE) { + return ProjectionNames(*query.Cast().children[0], names); + } + if (query.type != QueryNodeType::SELECT_NODE) return false; + auto &select = query.Cast(); + for (auto &expression : select.select_list) { + bool expands = false; + ParsedExpressionIterator::VisitExpressionClass(*expression, ExpressionClass::STAR, + [&](const ParsedExpression &) { expands = true; }); + ParsedExpressionIterator::VisitExpression(*expression, + [&](const FunctionExpression &function) { + expands |= StringUtil::CIEquals(function.FunctionName().GetIdentifierName(), "unnest"); + }); + if (expands) return false; + names.push_back(expression->GetName()); + } + return true; + } + + static Names NamedColumns(vector names, const vector &aliases) { + for (idx_t i = 0; i < aliases.size() && i < names.size(); ++i) names[i] = aliases[i]; + Names result; + for (auto &name : names) result.insert(StringUtil::Lower(name.GetIdentifierName())); + return result; + } + + static Names InputColumns(TableRef &table, const DecorationScope &scope) { + if (table.type == TableReferenceType::JOIN) { + // ON conditions can correlate to the outer row. They do not change + // the set of input column names; USING only removes duplicates. + auto &join = table.Cast(); + auto names = InputColumns(*join.left, scope); + auto right = InputColumns(*join.right, scope); + names.insert(right.begin(), right.end()); + return names; + } + if (table.type == TableReferenceType::SUBQUERY) { + vector names; + if (ProjectionNames(*table.Cast().subquery->node, names)) { + return NamedColumns(std::move(names), table.column_name_alias); + } + } + if (table.type == TableReferenceType::BASE_TABLE) { + auto &name = table.Cast().GetQualifiedName(); + if (name.Path().size() == 1) { + for (auto it = scope.cte_scopes.rbegin(); it != scope.cte_scopes.rend(); ++it) { + auto entry = (*it)->cte_map.map.find(name.Name()); + if (entry == (*it)->cte_map.map.end()) continue; + vector names; + if (ProjectionNames(*entry->second->query_node, names)) { + for (idx_t i = 0; i < entry->second->aliases.size() && i < names.size(); ++i) { + names[i] = entry->second->aliases[i]; + } + return NamedColumns(std::move(names), table.column_name_alias); + } + break; + } + } + } + auto context = CurrentSqlctxMeasureContext(); + if (!context) { + throw BinderException("AGGREGATE decoration column resolution requires the originating bind context"); + } + // Binding a layout-only probe discovers table/function/CTE output names + // without evaluating the filter. A FROM clause shadows only its actual + // columns, not every unqualified reference in a correlated expression. + auto probe = make_uniq(); + probe->select_list.push_back(make_uniq()); + probe->from_table = table.Copy(); + auto bound = BindSqlctxMeasureProbe(*probe, scope.cte_scopes); + Names names; + for (auto &name : bound.names) names.insert(StringUtil::Lower(name.GetIdentifierName())); + return names; + } + + static DecorationScope WithBindings(TableRef &table, DecorationScope scope) { + if (table.type == TableReferenceType::EMPTY_FROM) return scope; + auto columns = InputColumns(table, scope); + scope.shadowed_columns.insert(columns.begin(), columns.end()); + Qualifiers(table, scope.shadowed_qualifiers); + scope.inner_alias_shadowed |= scope.shadowed_qualifiers.count("_inner") != 0; + return scope; + } + + void Query(QueryNode &query, DecorationScope outer) { + outer.cte_scopes.push_back(&query); + for (auto &entry : query.cte_map.map) { + if (!entry.second->query_node) throw ParserException("Unsupported CTE in AGGREGATE decoration"); + Query(*entry.second->query_node, outer); + } + auto scope = outer; + switch (query.type) { + case QueryNodeType::SELECT_NODE: { + auto &select = query.Cast(); + if (select.from_table) { + scope = WithBindings(*select.from_table, outer); + Table(*select.from_table, outer); + } + for (auto &item : select.select_list) { + Expression(item, scope); + if (item->HasAlias()) scope.aliases.insert(StringUtil::Lower(item->GetAlias().GetIdentifierName())); + } + for (auto &group : select.groups.group_expressions) Expression(group, scope); + Expression(select.where_clause, scope); + Expression(select.having, scope); + Expression(select.qualify, scope); + break; + } + case QueryNodeType::SET_OPERATION_NODE: + for (auto &child : query.Cast().children) Query(*child, outer); + scope.unqualified_is_local = false; + break; + case QueryNodeType::RECURSIVE_CTE_NODE: { + auto &cte = query.Cast(); + Query(*cte.left, outer); + Query(*cte.right, outer); + scope.unqualified_is_local = false; + for (auto &key : cte.key_targets) Expression(key, scope); + break; + } + default: + throw ParserException("Unsupported query in AGGREGATE decoration"); + } + ParsedExpressionIterator::EnumerateQueryNodeModifiers(query, + [&](unique_ptr &expression) { Expression(expression, scope); }); + } + + void Table(TableRef &table, DecorationScope scope) { + switch (table.type) { + case TableReferenceType::JOIN: { + auto &join = table.Cast(); + Table(*join.left, scope); + Table(*join.right, WithBindings(*join.left, scope)); + Expression(join.condition, WithBindings(table, scope)); + break; + } + case TableReferenceType::SUBQUERY: + Query(*table.Cast().subquery->node, scope); + break; + case TableReferenceType::EXPRESSION_LIST: + for (auto &row : table.Cast().values) + for (auto &expression : row) Expression(expression, scope); + break; + case TableReferenceType::TABLE_FUNCTION: { + auto &function = table.Cast(); + Expression(function.function, scope); + if (function.subquery) Query(*function.subquery->node, scope); + break; + } + case TableReferenceType::BASE_TABLE: + case TableReferenceType::EMPTY_FROM: + break; + default: + throw ParserException("Unsupported table in AGGREGATE decoration"); + } + } +}; + +bool IsAggregate(const FunctionExpression &function) { + if (auto context = CurrentSqlctxMeasureContext()) { + EntryLookupInfo lookup(CatalogType::AGGREGATE_FUNCTION_ENTRY, function.GetQualifiedName()); + auto entry = Catalog::GetEntry(*context, lookup, OnEntryNotFound::RETURN_NULL); + return entry && entry->type == CatalogType::AGGREGATE_FUNCTION_ENTRY; + } + return IsSqlctxMeasureAggregate(function.FunctionName().GetIdentifierName()); +} + +class AggregateDecorator { +public: + explicit AggregateDecorator(FunctionExpression &call) : call(call) { + } + + void Expression(unique_ptr &expression) { + if (expression->GetExpressionClass() == ExpressionClass::SUBQUERY || + expression->GetExpressionClass() == ExpressionClass::WINDOW) return; + if (expression->GetExpressionClass() == ExpressionClass::FUNCTION) { + auto &function = expression->Cast(); + if (IsAggregate(function)) { + function.DistinctMutable() |= call.Distinct(); + if (call.Filter()) { + function.FilterMutable() = function.Filter() + ? make_uniq(ExpressionType::CONJUNCTION_AND, + std::move(function.FilterMutable()), call.Filter()->Copy()) + : call.Filter()->Copy(); + } + if (call.OrderBy() && !call.OrderBy()->orders.empty()) { + auto ordering = make_uniq(); + for (auto &order : call.OrderBy()->orders) { + ordering->orders.emplace_back(order.type, order.null_order, order.expression->Copy()); + } + // The caller chooses primary ordering; declaration ordering + // remains deterministic for ties in those call-level keys. + if (function.OrderBy()) { + for (auto &order : function.OrderBy()->orders) { + ordering->orders.emplace_back(order.type, order.null_order, order.expression->Copy()); + } + } + function.OrderByMutable() = std::move(ordering); + } + aggregate_count++; + if (call.ExportState()) { + if (function.ExportState()) { + throw ParserException("Cannot export an already exported measure aggregate"); + } + function.ExportStateMutable() = true; + auto field = "s" + std::to_string(states.size()); + states.emplace_back(Identifier(field), expression->Copy()); + expression = make_uniq(Identifier(field)); + } + return; + } + } + ParsedExpressionIterator::EnumerateChildren(*expression, + [&](unique_ptr &child) { Expression(child); }); + } + + idx_t aggregate_count = 0; + vector states; + +private: + FunctionExpression &call; +}; +} // namespace + +string DecorateSqlctxMeasureExpression(const string &measure_expression, const string &call_sql, + const vector> &dimensions, + const vector &local_qualifiers, const ParserOptions &options, + bool preserve_dimension_qualifiers) { + auto expression = ParseOne(measure_expression, options); + auto parsed_call = ParseOne(call_sql, options); + if (parsed_call->GetExpressionClass() != ExpressionClass::FUNCTION) { + throw ParserException("Expected an AGGREGATE call for measure decorations"); + } + auto &call = parsed_call->Cast(); + if (!StringUtil::CIEquals(call.FunctionName().GetIdentifierName(), "aggregate") || + call.GetArguments().size() != 1) { + throw ParserException("Expected a single-argument AGGREGATE call for measure decorations"); + } + DecorationReferences references(dimensions, local_qualifiers, options, preserve_dimension_qualifiers); + references.Expression(call.FilterMutable()); + if (call.OrderBy()) { + for (auto &order : call.OrderByMutable()->orders) references.Expression(order.expression); + } + bool direct_aggregate = expression->GetExpressionClass() == ExpressionClass::FUNCTION && + IsAggregate(expression->Cast()); + AggregateDecorator decorator(call); + decorator.Expression(expression); + if (!decorator.aggregate_count) { + throw ParserException("Decorated AGGREGATE requires a measure containing aggregate functions"); + } + if (call.ExportState()) { + if (direct_aggregate) return decorator.states[0].GetExpression().ToString(); + vector> arguments; + arguments.push_back(ConstantExpression::String(expression->ToString())); + arguments.push_back(make_uniq(Identifier("struct_pack"), std::move(decorator.states))); + expression = make_uniq(Identifier("sqlctx_state"), std::move(arguments)); + } + return expression->ToString(); +} +} // namespace duckdb +#endif diff --git a/sqlctx-duckdb/src/sqlctx_aggregate_state.cpp b/sqlctx-duckdb/src/sqlctx_aggregate_state.cpp new file mode 100644 index 000000000..d014a6d1a --- /dev/null +++ b/sqlctx-duckdb/src/sqlctx_aggregate_state.cpp @@ -0,0 +1,263 @@ +// Adapted from Yardstick (MIT), revision 2b1318402b6be22b6417de5c83523f4b558c621f. +// https://github.com/sidequery/yardstick/blob/2b1318402b6be22b6417de5c83523f4b558c621f/src/aggregate_state.cpp +// SQLCtx owns registration and execution; no Yardstick runtime is used. +#include "sqlctx_aggregate_state.hpp" +#include "sqlctx_parser.hpp" + +#if SQLCTX_GRAMMAR_EXTENSION +#include "duckdb/common/exception.hpp" +#include "duckdb/common/string_util.hpp" +#include "duckdb/function/function_binder.hpp" +#include "duckdb/function/scalar_function.hpp" +#include "duckdb/main/extension/extension_loader.hpp" +#include "duckdb/parser/expression/columnref_expression.hpp" +#include "duckdb/parser/parser.hpp" +#include "duckdb/parser/parsed_data/create_scalar_function_info.hpp" +#include "duckdb/planner/binder.hpp" +#include "duckdb/planner/expression/bound_case_expression.hpp" +#include "duckdb/planner/expression/bound_cast_expression.hpp" +#include "duckdb/planner/expression/bound_constant_expression.hpp" +#include "duckdb/planner/expression/bound_operator_expression.hpp" +#include "duckdb/planner/expression_binder/constant_binder.hpp" + +namespace duckdb { +namespace { + +// Logical-type aliases are serialized with the type, including in persistent tables and prepared statements. +// The versioned alias owns the finalization expression; each sN field retains its native aggregate state type. +constexpr const char *STATE_ALIAS_PREFIX = "yardstick_state_v1:"; + +struct StateExpressionData : FunctionData { + explicit StateExpressionData(unique_ptr expression_p) : expression(std::move(expression_p)) { + } + unique_ptr expression; + + unique_ptr Copy() const override { + return make_uniq(expression->Copy()); + } + bool Equals(const FunctionData &other) const override { + return expression->Equals(*other.Cast().expression); + } +}; + +unique_ptr BindNative(ClientContext &context, const Identifier &name, + vector> arguments) { + FunctionBinder binder(context); + ErrorData error; + auto result = binder.BindScalarFunction(Identifier::DefaultSchema(), name, std::move(arguments), error); + if (!result) { + error.Throw(); + } + return result; +} + +unique_ptr ExtractState(ClientContext &context, const Expression &state, const Identifier &name) { + vector> arguments; + // DuckDB does not implicitly cast an aliased STRUCT to struct_extract's STRUCT parameter. + // Remove only the outer alias: native aggregate-state aliases on the fields must survive. + auto struct_type = state.GetReturnType().WithAlias(""); + arguments.push_back(BoundCastExpression::AddCastToType(context, state.Copy(), struct_type)); + arguments.push_back(make_uniq(Value(name.GetIdentifierName()))); + return BindNative(context, "struct_extract", std::move(arguments)); +} + +bool IsCompositeState(const LogicalType &type) { + return type.id() == LogicalTypeId::STRUCT && type.HasAlias() && + StringUtil::StartsWith(type.GetAlias(), STATE_ALIAS_PREFIX); +} + +void ValidateFields(const LogicalType &type) { + if (type.id() != LogicalTypeId::STRUCT || StructType::GetChildTypes(type).empty()) { + throw BinderException("yardstick_state requires a nonempty STRUCT of native aggregate states"); + } + auto &fields = StructType::GetChildTypes(type); + for (idx_t i = 0; i < fields.size(); i++) { + if (fields[i].first != "s" + std::to_string(i) || !fields[i].second.IsAggregateState()) { + throw BinderException("yardstick_state fields must be native aggregate states named s0, s1, ... in order"); + } + } +} + +class StateFormulaBinder : public ConstantBinder { +public: + StateFormulaBinder(Binder &binder, ClientContext &context, const Expression &state_p) + : ConstantBinder(binder, context, "yardstick_state formula"), state(state_p) { + } + +protected: + BindResult BindExpression(unique_ptr &expression, idx_t depth, bool root_expression) override { + if (expression->GetExpressionClass() != ExpressionClass::COLUMN_REF) { + return ConstantBinder::BindExpression(expression, depth, root_expression); + } + auto &reference = expression->Cast(); + if (!reference.IsQualified()) { + for (auto &field : StructType::GetChildTypes(state.GetReturnType())) { + if (reference.GetColumnName() == field.first) { + vector> arguments; + arguments.push_back(ExtractState(context, state, field.first)); + return BindResult(BindNative(context, "finalize", std::move(arguments))); + } + } + } + throw BinderException("yardstick_state formula references unknown state field %s", reference.ToString()); + } + +private: + const Expression &state; +}; + +unique_ptr ParseFormula(const string &formula) { + Parser parser(SqlctxBuiltinParserOptions()); + auto expressions = parser.ParseExpressionList(formula); + if (expressions.size() != 1 || !expressions[0]->GetAlias().empty()) { + throw BinderException("yardstick_state requires exactly one scalar finalization expression"); + } + return std::move(expressions[0]); +} + +unique_ptr BindFormula(ClientContext &context, const Expression &state, + unique_ptr formula) { + auto binder = Binder::CreateBinder(context); + StateFormulaBinder expression_binder(*binder, context, state); + return expression_binder.Bind(formula); +} + +unique_ptr IfNull(const Expression &input, unique_ptr when_null, + unique_ptr otherwise) { + auto condition = make_uniq(ExpressionType::OPERATOR_IS_NULL, LogicalType::BOOLEAN); + condition->GetChildrenMutable().push_back(input.Copy()); + return make_uniq(std::move(condition), std::move(when_null), std::move(otherwise)); +} + +unique_ptr ReturnExpression(BindScalarFunctionInput &input, unique_ptr expression) { + input.GetBoundFunction().SetReturnType(expression->GetReturnType()); + return make_uniq(std::move(expression)); +} + +unique_ptr ReplaceStateExpression(FunctionBindExpressionInput &input) { + return input.bind_data->Cast().expression->Copy(); +} + +unique_ptr BindState(BindScalarFunctionInput &input) { + auto &state = *input.GetArguments()[1]; + ValidateFields(state.GetReturnType()); + auto formula = ParseFormula(input.GetConstant(0, false).ToString()); + auto canonical_formula = formula->ToString(); + // Validate the complete formula now, rather than storing a state that only fails at finalization time. + BindFormula(input.GetClientContext(), state, std::move(formula)); + auto type = state.GetReturnType().WithAlias(string(STATE_ALIAS_PREFIX) + canonical_formula); + auto result = BoundCastExpression::AddCastToType(input.GetClientContext(), state.Copy(), type); + return ReturnExpression(input, std::move(result)); +} + +unique_ptr BindFinalize(BindScalarFunctionInput &input) { + auto &state = *input.GetArguments()[0]; + auto &type = state.GetReturnType(); + if (type.id() == LogicalTypeId::SQLNULL) { + return ReturnExpression(input, state.Copy()); + } + if (type.IsAggregateState()) { + vector> arguments; + arguments.push_back(state.Copy()); + return ReturnExpression(input, BindNative(input.GetClientContext(), "finalize", std::move(arguments))); + } + if (!IsCompositeState(type)) { + throw BinderException("yardstick_finalize requires a native aggregate state or yardstick_state"); + } + ValidateFields(type); + auto formula = type.GetAlias().substr(string(STATE_ALIAS_PREFIX).size()); + auto result = BindFormula(input.GetClientContext(), state, ParseFormula(formula)); + auto null_value = make_uniq(Value(result->GetReturnType())); + return ReturnExpression(input, IfNull(state, std::move(null_value), std::move(result))); +} + +unique_ptr BindCombine(BindScalarFunctionInput &input) { + auto &left = *input.GetArguments()[0]; + auto &right = *input.GetArguments()[1]; + auto &left_type = left.GetReturnType(); + auto &right_type = right.GetReturnType(); + if (left_type.id() == LogicalTypeId::SQLNULL && right_type.id() == LogicalTypeId::SQLNULL) { + return ReturnExpression(input, left.Copy()); + } + auto &type = left_type.id() == LogicalTypeId::SQLNULL ? right_type : left_type; + if (!type.IsAggregateState() && !IsCompositeState(type)) { + throw BinderException("yardstick_combine requires native aggregate states or yardstick_state values"); + } + if (left_type.id() == LogicalTypeId::SQLNULL || right_type.id() == LogicalTypeId::SQLNULL) { + return ReturnExpression(input, left_type.id() == LogicalTypeId::SQLNULL ? right.Copy() : left.Copy()); + } + if (left_type != right_type) { + throw BinderException("yardstick_combine requires matching state formulas and aggregate types"); + } + if (type.IsAggregateState()) { + vector> arguments; + arguments.push_back(left.Copy()); + arguments.push_back(right.Copy()); + return ReturnExpression(input, BindNative(input.GetClientContext(), "combine", std::move(arguments))); + } + ValidateFields(type); + vector> fields; + for (auto &field : StructType::GetChildTypes(type)) { + vector> arguments; + arguments.push_back(ExtractState(input.GetClientContext(), left, field.first)); + arguments.push_back(ExtractState(input.GetClientContext(), right, field.first)); + auto combined = BindNative(input.GetClientContext(), "combine", std::move(arguments)); + combined->SetAlias(field.first); + fields.push_back(std::move(combined)); + } + auto packed = BindNative(input.GetClientContext(), "struct_pack", std::move(fields)); + auto result = BoundCastExpression::AddCastToType(input.GetClientContext(), std::move(packed), type); + result = IfNull(right, left.Copy(), std::move(result)); + result = IfNull(left, right.Copy(), std::move(result)); + return ReturnExpression(input, std::move(result)); +} + +} // namespace + +void RegisterSqlctxAggregateStateFunctions(ExtensionLoader &loader) { + auto register_function = [&](ScalarFunction function, vector names, const string &description, + const string &example) { + for (idx_t index = 0; index < names.size(); index++) { + function.GetSignature().GetParameter(index).SetName(Identifier(names[index])); + } + FunctionDescription documentation; + documentation.parameter_names = std::move(names); + documentation.description = description; + documentation.examples = {example}; + documentation.categories = {"aggregate"}; + CreateScalarFunctionInfo info(std::move(function)); + info.on_conflict = OnCreateConflict::ALTER_ON_CONFLICT; + info.descriptions.push_back(std::move(documentation)); + loader.RegisterFunction(std::move(info)); + }; + for (auto prefix : {"sqlctx_", "yardstick_"}) { + string state_name = string(prefix) + "state"; + string finalize_name = string(prefix) + "finalize"; + string combine_name = string(prefix) + "combine"; + ScalarFunction state(Identifier(state_name), {LogicalType::VARCHAR, LogicalType::ANY}, LogicalType::ANY, nullptr, BindState); + state.SetBindExpressionCallback(ReplaceStateExpression); + state.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); + register_function(std::move(state), {"formula", "states"}, + "Attach a scalar finalization formula to a STRUCT of exported aggregate states named s0, s1, and so on.", + "SELECT " + state_name + "('s0', struct_pack(s0 := sum(i) EXPORT_STATE)) FROM range(3) t(i);"); + ScalarFunction finalize(Identifier(finalize_name), {LogicalType::ANY}, LogicalType::ANY, nullptr, BindFinalize); + finalize.SetBindExpressionCallback(ReplaceStateExpression); + finalize.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); + register_function(std::move(finalize), {"state"}, + "Finalize a native aggregate state or evaluate a composite state's formula.", + "SELECT " + finalize_name + "(avg(i) EXPORT_STATE) FROM range(6) t(i);"); + ScalarFunction combine(Identifier(combine_name), {LogicalType::ANY, LogicalType::ANY}, LogicalType::ANY, nullptr, BindCombine); + combine.SetBindExpressionCallback(ReplaceStateExpression); + combine.SetNullHandling(FunctionNullHandling::SPECIAL_HANDLING); + register_function(std::move(combine), {"left_state", "right_state"}, + "Combine aggregate states with matching formulas and aggregate types for later finalization.", + "WITH s AS (SELECT sum(i) EXPORT_STATE AS state FROM range(3) t(i)) SELECT " + finalize_name + "(" + combine_name + "(state, state)) FROM s;"); + } +} +} // namespace duckdb +#else +namespace duckdb { +void RegisterSqlctxAggregateStateFunctions(ExtensionLoader &) { +} +} // namespace duckdb +#endif diff --git a/sqlctx-duckdb/src/sqlctx_context_predicates.cpp b/sqlctx-duckdb/src/sqlctx_context_predicates.cpp new file mode 100644 index 000000000..7891cfdf8 --- /dev/null +++ b/sqlctx-duckdb/src/sqlctx_context_predicates.cpp @@ -0,0 +1,328 @@ +// Predicate projection adapted from sidequery/yardstick (MIT), revision +// 2b1318402b6be22b6417de5c83523f4b558c621f, src/yardstick_parser_ffi.cpp. +#include "sqlctx_aggregate_decorations.hpp" +#if SQLCTX_GRAMMAR_EXTENSION +#include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/catalog_entry/scalar_function_catalog_entry.hpp" +#include "duckdb/common/string_util.hpp" +#include "duckdb/parser/expression/columnref_expression.hpp" +#include "duckdb/parser/expression/conjunction_expression.hpp" +#include "duckdb/parser/expression/constant_expression.hpp" +#include "duckdb/parser/expression/function_expression.hpp" +#include "duckdb/parser/expression/operator_expression.hpp" +#include "duckdb/parser/expression/subquery_expression.hpp" +#include "duckdb/parser/parsed_expression_iterator.hpp" +#include "duckdb/parser/query_node/select_node.hpp" +#include "duckdb/parser/statement/select_statement.hpp" +#include "duckdb/parser/tableref/basetableref.hpp" +#include "duckdb/parser/tableref/joinref.hpp" +namespace duckdb { +// De Morgan, distributivity, idempotence, and absorption hold for SQL's +// three-valued AND/OR/NOT. Normalize before separating dimension predicates so +// equivalent NOT and factorable OR forms retain the same independent filters. +static unique_ptr ContextNegationNormalForm(const ParsedExpression &expression, bool negate = false) { + auto type = expression.GetExpressionType(); + if (type == ExpressionType::OPERATOR_NOT) { + auto &children = expression.Cast().GetChildren(); + if (children.size() == 1) return ContextNegationNormalForm(*children[0], !negate); + } + if (type == ExpressionType::CONJUNCTION_AND || type == ExpressionType::CONJUNCTION_OR) { + if (negate) type = type == ExpressionType::CONJUNCTION_AND + ? ExpressionType::CONJUNCTION_OR : ExpressionType::CONJUNCTION_AND; + vector> children; + for (auto &child : expression.Cast().GetChildren()) { + children.push_back(ContextNegationNormalForm(*child, negate)); + } + return make_uniq(type, std::move(children)); + } + auto result = expression.Copy(); + if (!negate) return result; + return make_uniq(ExpressionType::OPERATOR_NOT, std::move(result)); +} + +using ContextClause = vector>; +using ContextConjunction = vector; + +static bool ContextExpressionCanRepeat(const ParsedExpression &expression) { + if (expression.GetExpressionClass() == ExpressionClass::SUBQUERY) return false; + if (expression.GetExpressionClass() == ExpressionClass::FUNCTION) { +#if SQLCTX_GRAMMAR_EXTENSION + auto *context = CurrentSqlctxMeasureContext(); + if (!context) return false; + try { + auto &function = expression.Cast(); + auto entry = Catalog::GetEntry( + *context, function.GetQualifiedName(), OnEntryNotFound::RETURN_NULL); + if (!entry || entry->functions.functions.empty()) return false; + for (auto &overload : entry->functions.functions) { + if (overload->GetStability() == FunctionStability::VOLATILE) return false; + } + } catch (const std::exception &) { + return false; // No catalog proof permits no evaluation-changing rewrite. + } +#else + return false; // No bind context, so no catalog proof that the call is stable. +#endif + } + bool repeatable = true; + ParsedExpressionIterator::EnumerateChildren(expression, [&](const ParsedExpression &child) { + repeatable &= ContextExpressionCanRepeat(child); + }); + return repeatable; +} + +static ContextConjunction ContextConjunctiveNormalForm(const ParsedExpression &expression) { + constexpr idx_t MAX_CONTEXT_CLAUSES = 128; + auto type = expression.GetExpressionType(); + if (type != ExpressionType::CONJUNCTION_AND && type != ExpressionType::CONJUNCTION_OR) { + ContextClause clause; + clause.push_back(expression.Copy()); + ContextConjunction result; + result.push_back(std::move(clause)); + return result; + } + ContextConjunction result; + for (auto &child : expression.Cast().GetChildren()) { + auto next = ContextConjunctiveNormalForm(*child); + if (result.empty()) { + result = std::move(next); + } else if (type == ExpressionType::CONJUNCTION_AND) { + for (auto &clause : next) result.push_back(std::move(clause)); + } else { + if (next.size() > MAX_CONTEXT_CLAUSES / result.size()) { + throw ParserException("AT dimension replacement requires a simpler predicate; use an explicit AT WHERE predicate"); + } + ContextConjunction product; + for (auto &left : result) { + for (auto &right : next) { + ContextClause clause; + for (auto &atom : left) clause.push_back(atom->Copy()); + for (auto &atom : right) clause.push_back(atom->Copy()); + product.push_back(std::move(clause)); + } + } + result = std::move(product); + } + if (result.size() > MAX_CONTEXT_CLAUSES) { + throw ParserException("AT dimension replacement requires a simpler predicate; use an explicit AT WHERE predicate"); + } + } + return result; +} + +static unique_ptr ContextDimensionReference(const ParsedExpression &expression, + const string &source_alias) { + auto result = expression.Copy(); + ParsedExpressionIterator::VisitExpressionClassMutable(*result, ExpressionClass::COLUMN_REF, + [&](ParsedExpression &column) { + auto &names = column.Cast().ColumnNamesMutable(); + if (names.size() == 1 || (names.size() == 2 && StringUtil::CIEquals(names[0].GetIdentifierName(), source_alias))) { + auto name = names.back(); + names = {Identifier("_inner"), std::move(name)}; + } + }); + return result; +} + +static bool ContextReferencesDimension(const ParsedExpression &expression, + const vector> &dimensions, + const string &source_alias) { + auto canonical = ContextDimensionReference(expression, source_alias); + for (auto &dimension : dimensions) { + if (canonical->Equals(*dimension)) return true; + } + if (expression.GetExpressionClass() == ExpressionClass::SUBQUERY) return false; + bool found = false; + ParsedExpressionIterator::EnumerateChildren(expression, [&](const ParsedExpression &child) { + found |= ContextReferencesDimension(child, dimensions, source_alias); + }); + return found; +} + +static void DropContextDimensions(unique_ptr &expression, + const vector> &excluded, + const string &source_alias = string()) { + if (!expression || excluded.empty()) return; + // Unrelated subtrees are already valid context terms. Keep their original + // shape and repeated evaluations, including separate volatile OR calls. + if (!ContextReferencesDimension(*expression, excluded, source_alias)) return; + if (!ContextExpressionCanRepeat(*expression)) { + if (expression->GetExpressionType() == ExpressionType::CONJUNCTION_AND) { + ParsedExpressionIterator::EnumerateChildren(*expression, [&](unique_ptr &child) { + DropContextDimensions(child, excluded, source_alias); + }); + return; + } + bool boolean_reassociation = false; + ParsedExpressionIterator::VisitExpressionClass(*expression, ExpressionClass::CONJUNCTION, + [&](const ParsedExpression &) { boolean_reassociation = true; }); + if (boolean_reassociation) { + throw ParserException("AT dimension replacement cannot safely normalize a volatile or unproven predicate; " + "use an explicit AT WHERE predicate"); + } + } + auto normalized = ContextNegationNormalForm(*expression); + auto clauses = ContextConjunctiveNormalForm(*normalized); + // Deduplicate disjuncts, then absorb clauses containing a smaller clause. + // For example (year=A AND region=N) OR (year=B AND region=N) + // reduces to (year=A OR year=B) AND region=N before removing year. + for (auto &clause : clauses) { + for (idx_t i = 0; i < clause.size(); i++) { + for (idx_t j = i + 1; j < clause.size();) { + if (clause[i]->Equals(*clause[j])) clause.erase(clause.begin() + j); + else j++; + } + } + } + vector absorbed(clauses.size(), false); + for (idx_t i = 0; i < clauses.size(); i++) { + for (idx_t j = 0; j < clauses.size(); j++) { + if (i == j || clauses[i].size() > clauses[j].size() || + (clauses[i].size() == clauses[j].size() && i > j)) continue; + bool subset = true; + for (auto &atom : clauses[i]) { + bool present = false; + for (auto &candidate : clauses[j]) present |= atom->Equals(*candidate); + subset &= present; + } + if (subset) absorbed[j] = true; + } + } + std::function dependencies; + dependencies = [&](const ParsedExpression &term, bool &overridden, bool &other) { + auto canonical = ContextDimensionReference(term, source_alias); + for (auto &dimension : excluded) { + if (canonical->Equals(*dimension)) { + overridden = true; + return; + } + } + if (term.GetExpressionClass() == ExpressionClass::COLUMN_REF || + term.GetExpressionClass() == ExpressionClass::SUBQUERY) { + other = true; + return; + } + ParsedExpressionIterator::EnumerateChildren(term, [&](const ParsedExpression &child) { + dependencies(child, overridden, other); + }); + }; + vector> remaining; + for (idx_t i = 0; i < clauses.size(); i++) { + if (absorbed[i]) continue; + bool overridden = false, other = false; + for (auto &atom : clauses[i]) { + bool atom_overridden = false, atom_other = false; + dependencies(*atom, atom_overridden, atom_other); + if (atom_overridden && atom_other && atom->GetExpressionClass() == ExpressionClass::COMPARISON) { + // A join equality such as source.year = allowed.year constrains + // the source year using an external value. It is a year term; + // the external operand is not another source dimension. + bool other_source_dimension = false; + ParsedExpressionIterator::VisitExpressionClass(*atom, ExpressionClass::COLUMN_REF, + [&](const ParsedExpression &column) { + auto canonical = ContextDimensionReference(column, source_alias); + bool removed = false; + for (auto &dimension : excluded) removed |= canonical->Equals(*dimension); + if (removed) return; + auto &names = column.Cast().ColumnNames(); + other_source_dimension |= names.size() == 1 || + (names.size() == 2 && (StringUtil::CIEquals(names[0].GetIdentifierName(), source_alias) || StringUtil::CIEquals(names[0].GetIdentifierName(), "_inner"))); + }); + if (!other_source_dimension) atom_other = false; + } + overridden |= atom_overridden; + other |= atom_other; + } + if (overridden && other) { + throw ParserException("AT dimension replacement cannot separate a mixed VISIBLE predicate; " + "use an explicit AT WHERE predicate"); + } + if (overridden) continue; + if (clauses[i].size() == 1) remaining.push_back(std::move(clauses[i][0])); + else remaining.push_back(make_uniq(ExpressionType::CONJUNCTION_OR, std::move(clauses[i]))); + } + if (remaining.empty()) expression = ConstantExpression::Boolean(true); + else if (remaining.size() == 1) expression = std::move(remaining[0]); + else expression = make_uniq(ExpressionType::CONJUNCTION_AND, std::move(remaining)); +} + +#if SQLCTX_GRAMMAR_EXTENSION +void RemoveSqlctxContextDimensions(unique_ptr &expression, + const vector> &dimensions, + const string &source_alias) { + vector> canonical; + for (auto &dimension : dimensions) { + canonical.push_back(ContextDimensionReference(*dimension, source_alias)); + } + DropContextDimensions(expression, canonical, source_alias); +} + +unique_ptr LowerSqlctxVisibleJoin(const string &source_alias, const string &query_sql, + const vector &excluded_dimensions, + const ParserOptions &options) { + auto parsed = ParseSqlctxMeasureExpressions("EXISTS (" + query_sql + ")", options); + if (parsed.size() != 1 || parsed[0]->GetExpressionClass() != ExpressionClass::SUBQUERY) { + throw ParserException("Expected a joined visibility SELECT"); + } + auto &query = *parsed[0]->Cast().SubqueryMutable()->node; + if (query.type != QueryNodeType::SELECT_NODE) throw ParserException("Expected a joined visibility SELECT"); + auto &select = query.Cast(); + vector> excluded; + for (auto &sql : excluded_dimensions) { + auto dimensions = ParseSqlctxMeasureExpressions(sql, options); + if (dimensions.size() != 1) throw ParserException("Expected one excluded context dimension"); + excluded.push_back(ContextDimensionReference(*dimensions[0], source_alias)); + } + // Joining does not itself restrict a measure's population. Preserve its + // source rows, then apply the consumer's WHERE against the joined values. + std::function preserve_source = [&](TableRef &table) { + if (table.type != TableReferenceType::JOIN) { + if (!table.alias.empty()) return StringUtil::CIEquals(table.alias.GetIdentifierName(), source_alias); + return table.type == TableReferenceType::BASE_TABLE && + StringUtil::CIEquals(table.Cast().Table().GetIdentifierName(), source_alias); + } + auto &join = table.Cast(); + bool left = preserve_source(*join.left); + bool right = !left && preserve_source(*join.right); + if (!left && !right) return false; + if (join.ref_type == JoinRefType::CROSS) { + join.ref_type = JoinRefType::REGULAR; + join.type = JoinType::INNER; + join.condition = ConstantExpression::Boolean(true); + } + if (join.type == JoinType::INNER && + (join.ref_type == JoinRefType::REGULAR || join.ref_type == JoinRefType::NATURAL)) { + join.type = left ? JoinType::LEFT : JoinType::RIGHT; + } + return true; + }; + if (select.from_table) preserve_source(*select.from_table); + DropContextDimensions(select.where_clause, excluded, source_alias); + std::function prune_joins = [&](TableRef &table) { + if (table.type != TableReferenceType::JOIN) return; + auto &join = table.Cast(); + DropContextDimensions(join.condition, excluded, source_alias); + bool removed_using = false; + for (idx_t i = 0; i < join.using_columns.size();) { + auto column = make_uniq(join.using_columns[i]); + auto canonical = ContextDimensionReference(*column, source_alias); + bool removed = false; + for (auto &dimension : excluded) removed |= canonical->Equals(*dimension); + if (removed) { + join.using_columns.erase(join.using_columns.begin() + i); + removed_using = true; + } else i++; + } + if (removed_using && join.using_columns.empty() && !join.condition) { + join.condition = ConstantExpression::Boolean(true); + } + prune_joins(*join.left); + prune_joins(*join.right); + }; + if (select.from_table) prune_joins(*select.from_table); + return std::move(parsed[0]); +} +#endif + +} // namespace duckdb +#endif diff --git a/sqlctx-duckdb/src/sqlctx_extension.cpp b/sqlctx-duckdb/src/sqlctx_extension.cpp index 8ec6dfaee..c77300fa2 100644 --- a/sqlctx-duckdb/src/sqlctx_extension.cpp +++ b/sqlctx-duckdb/src/sqlctx_extension.cpp @@ -1,6 +1,7 @@ #define DUCKDB_EXTENSION_MAIN #include "sqlctx_extension.hpp" +#include "sqlctx_aggregate_state.hpp" #include "sqlctx_explain.hpp" #include "sqlctx_warnings.hpp" #include "sqlctx_parser.hpp" @@ -121,6 +122,7 @@ static void LoadInternal(ExtensionLoader &loader) { RegisterSqlctxDiscovery(db); RegisterSqlctxExplain(loader); RegisterSqlctxWarnings(loader); + RegisterSqlctxAggregateStateFunctions(loader); RegisterSqlctxFunction(loader, TableFunction("sqlctx_load", {LogicalType::VARCHAR}, LoadFunction, LoadBind, LoadInit), {"yaml"}, diff --git a/sqlctx-duckdb/src/sqlctx_grammar.cpp b/sqlctx-duckdb/src/sqlctx_grammar.cpp index cf2e4f12e..3dbc7b70c 100644 --- a/sqlctx-duckdb/src/sqlctx_grammar.cpp +++ b/sqlctx-duckdb/src/sqlctx_grammar.cpp @@ -1,4 +1,5 @@ #include "sqlctx_parser.hpp" +#include "sqlctx_query_syntax.hpp" #if SQLCTX_GRAMMAR_EXTENSION #include "duckdb/main/connection.hpp" @@ -58,6 +59,55 @@ class StandaloneMeasureMatcher final : public AtomicMatcher { DatabaseInstance &db; }; +// CURRENT is a normal identifier in SQL. Its prefix form belongs only to the +// value side of an enclosing AT clause, and never to a nested query's scope. +class ContextCurrentMatcher final : public AtomicMatcher { +public: + ContextCurrentMatcher() : AtomicMatcher(MatcherType::CUSTOM) {} + MatcherResult MatchAtomic(MatchState &state) const override { + auto token = state.token_iterator.Current(); + if (!token || !StringUtil::CIEquals(token->text, "CURRENT")) return MatcherResult::Failure(); + struct Scope { bool context = false; bool query = false; bool assignment = false; bool value = false; }; + vector scopes(1); + string previous; + for (idx_t i = 0; i < state.token_iterator.Size(); ++i) { + auto &part = state.token_iterator.GetToken(i); + if (part.offset >= token->offset) break; + if (part.type == TokenType::COMMENT) continue; + auto word = StringUtil::Upper(part.text); + if (word == "(") { + Scope scope; + scope.context = previous == "AT"; + scopes.push_back(scope); + } else if (word == ")") { + if (scopes.size() > 1) scopes.pop_back(); + } else if (word == "SELECT" || word == "VALUES" || word == "WITH" || word == "FROM" || + word == "TABLE" || word == "PIVOT" || word == "UNPIVOT") { + scopes.back().query = true; + } else if (scopes.back().context) { + auto &scope = scopes.back(); + if (word == "SET") { scope.assignment = true; scope.value = false; } + else if (word == "WHERE") { scope.assignment = false; scope.value = true; } + else if (word == "=" && scope.assignment) scope.value = true; + else if (word == "ALL" || word == "VISIBLE") { scope.assignment = false; scope.value = false; } + } + previous = word; + } + bool allowed = false; + for (auto scope = scopes.rbegin(); scope != scopes.rend(); ++scope) { + if (scope->query) break; + if (scope->context) { allowed = scope->value; break; } + } + if (!allowed) return MatcherResult::Failure(); + auto result = state.AllocateParseResult(token->text, token->offset, token->length); + state.token_iterator.Advance(); + state.UpdateMaxTokenIndex(); + return result; + } + SuggestionType AddSuggestionInternal(MatchState &) const override { return SuggestionType::OPTIONAL; } + string ToString() const override { return "CURRENT in an AT value"; } +}; + // 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 @@ -111,6 +161,84 @@ static auto StartDefinition(PEGTransformer &transformer, ParseResult &result) { return StartFinalizer(transformer, result, TransformDefinition); } +static ParseResult &UnwrapQuerySyntax(ParseResult &result) { + auto *node = &result; + while (true) { + if (node->type == ParseResultType::CHOICE) { + node = &node->Cast().GetResult(); + } else if (node->type == ParseResultType::LIST && node->Cast().GetChildren().size() == 1) { + node = &node->Cast().GetChild(0); + } else return *node; + } +} + +static string ContextExpression(PEGTransformer &transformer, ParseResult &result, + vector> &expressions) { + expressions.push_back(transformer.Transform>(result)); + return "\x1f"; +} + +static string ContextClauseSQL(PEGTransformer &transformer, ParseResult &result, + vector> &expressions) { + auto &node = UnwrapQuerySyntax(result); + if (node.type == ParseResultType::KEYWORD) return node.Cast().keyword; + auto &list = node.Cast(); + auto keyword = StringUtil::Upper(UnwrapQuerySyntax(list.GetChild(0)).Cast().keyword); + if (keyword == "WHERE") return "WHERE " + ContextExpression(transformer, list.GetChild(1), expressions); + if (keyword == "SET") { + auto dimension = ContextExpression(transformer, list.GetChild(1), expressions); + auto value = ContextExpression(transformer, list.GetChild(3), expressions); + return "SET " + dimension + " = " + value; + } + string sql = "ALL"; + auto &optional = list.Child(1); + auto *tail = optional.HasResult() ? &optional.GetResult() : nullptr; + while (tail) { + auto &item = UnwrapQuerySyntax(*tail); + auto &head = item.type == ParseResultType::LIST ? + UnwrapQuerySyntax(item.Cast().GetChild(0)) : item; + auto keyword = head.type == ParseResultType::KEYWORD ? + StringUtil::Upper(head.Cast().keyword) : string(); + if (keyword == "ALL" || keyword == "SET" || keyword == "WHERE" || keyword == "VISIBLE") { + sql += " " + ContextClauseSQL(transformer, item, expressions); + break; + } + auto &dimension = item.Cast(); + sql += " " + ContextExpression(transformer, dimension.GetChild(0), expressions); + auto &next = dimension.Child(1); + tail = next.HasResult() ? &next.GetResult() : nullptr; + } + return sql; +} + +static auto TransformContext(PEGTransformer &transformer, ParseResult &result) { + RequireCompatibilityOverride(transformer); + auto &clauses = result.Cast().Child(2); + vector modifiers; + vector> expressions; + for (auto &clause : clauses.GetChildren()) { + modifiers.push_back(ContextClauseSQL(transformer, clause.get(), expressions)); + } + unique_ptr expression = + make_uniq(StringUtil::Join(modifiers, " "), std::move(expressions)); + return transformer.MakeResult>(std::move(expression)); +} + +static auto StartContext(PEGTransformer &transformer, ParseResult &result) { + return StartFinalizer(transformer, result, TransformContext); +} + +static auto TransformCurrent(PEGTransformer &transformer, ParseResult &result) { + vector> arguments; + arguments.push_back(transformer.Transform>(result.Cast().GetChild(1))); + unique_ptr expression = make_uniq("current", std::move(arguments)); + return transformer.MakeResult>(std::move(expression)); +} + +static auto StartCurrent(PEGTransformer &transformer, ParseResult &result) { + return StartFinalizer(transformer, result, TransformCurrent); +} + static auto TransformSemanticQuery(PEGTransformer &transformer, ParseResult &result) { auto &list = result.Cast(); auto &choice = list.Child(1).Child(0); @@ -196,6 +324,19 @@ class SqlctxGrammar final : public GrammarExtension { GrammarChange::AddRule("SqlctxExport <- 'EXPORT' 'SEMANTIC' 'CATALOG'", StartDefinition), GrammarChange::AddRule("SqlctxImport <- 'IMPORT' 'SEMANTIC' 'CATALOG' ColIdOrString", StartDefinition), GrammarChange::AddRule("SqlctxQuery <- 'SEMANTIC' (SelectStatement / CreateStatement / InsertStatement / DropStatement)", StartSemanticQuery), + GrammarChange::AddRule("SqlctxCurrentKeyword <- 'CURRENT'"), + GrammarChange::AddTerminalRuleOverride("SqlctxCurrentKeyword", [](const PEGKeywordHelper &) { + return make_uniq(); + }), + GrammarChange::AddRule("SqlctxCurrent <- SqlctxCurrentKeyword ColumnReference", StartCurrent), + GrammarChange::PrependChoice("SingleExpression", "SqlctxCurrent"), + GrammarChange::AddRule("SqlctxContext <- 'AT' '(' SqlctxContextClause+ ')'", StartContext), + GrammarChange::AddRule("SqlctxContextClause <- SqlctxContextAll / SqlctxContextSet / SqlctxContextWhere / 'VISIBLE'"), + GrammarChange::AddRule("SqlctxContextAll <- 'ALL' SqlctxContextAllTail?"), + GrammarChange::AddRule("SqlctxContextAllTail <- SqlctxContextClause / BaseExpression SqlctxContextAllTail?"), + GrammarChange::AddRule("SqlctxContextSet <- 'SET' BaseExpression '=' Expression"), + GrammarChange::AddRule("SqlctxContextWhere <- 'WHERE' Expression"), + GrammarChange::PrependChoice("Indirection", "SqlctxContext"), GrammarChange::AddRule("SqlctxPreparable <- SqlctxShow / SqlctxDescribe / SqlctxExport / SqlctxImport / SqlctxDropView / SqlctxDrop / SqlctxView / SqlctxMeasureView / SqlctxDefinition / SqlctxQuery"), GrammarChange::AddRule("SqlctxPrepare <- 'PREPARE' ColIdOrString 'AS' SqlctxPreparable", StartPrepare), GrammarChange::AddRule("SqlctxExplain <- 'EXPLAIN' AnalyzeKeyword? ExplainOptionList? SqlctxPreparable", StartExplain), diff --git a/sqlctx-duckdb/src/sqlctx_measure_binding.cpp b/sqlctx-duckdb/src/sqlctx_measure_binding.cpp new file mode 100644 index 000000000..25c82679d --- /dev/null +++ b/sqlctx-duckdb/src/sqlctx_measure_binding.cpp @@ -0,0 +1,387 @@ +// CTE probe binding adapted from sidequery/yardstick (MIT), revision +// 2b1318402b6be22b6417de5c83523f4b558c621f, src/frontend_peg.cpp. +#include "sqlctx_aggregate_decorations.hpp" +#include "sqlctx_measure_windows.hpp" + +#if SQLCTX_GRAMMAR_EXTENSION +#include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/entry_lookup_info.hpp" +#include "duckdb/common/string_util.hpp" +#include "duckdb/parser/expression/constant_expression.hpp" +#include "duckdb/parser/expression/function_expression.hpp" +#include "duckdb/parser/expression/columnref_expression.hpp" +#include "duckdb/parser/expression/subquery_expression.hpp" +#include "duckdb/parser/expression/window_expression.hpp" +#include "duckdb/parser/parsed_expression_iterator.hpp" +#include "duckdb/parser/query_node/select_node.hpp" +#include "duckdb/parser/tableref/subqueryref.hpp" +#include "duckdb/parser/tableref/table_function_ref.hpp" +#include "duckdb/parser/statement/select_statement.hpp" +#include "duckdb/parser/statement/create_statement.hpp" +#include "duckdb/parser/parsed_data/create_view_info.hpp" +#include "duckdb/planner/binder.hpp" +#include "duckdb/planner/table_binding.hpp" + +namespace duckdb { +namespace { +thread_local ClientContext *active_context = nullptr; +thread_local const vector> *active_ctes = nullptr; +thread_local const vector> *active_sources = nullptr; +} + +SqlctxMeasureBindScope::SqlctxMeasureBindScope(ClientContext &context) : previous(active_context) { + active_context = &context; +} +SqlctxMeasureBindScope::~SqlctxMeasureBindScope() { active_context = previous; } +ClientContext *CurrentSqlctxMeasureContext() { return active_context; } +const vector> *CurrentSqlctxMeasureCtes() { return active_ctes; } + +SqlctxMeasureCteBindScope::SqlctxMeasureCteBindScope(const vector> *context) + : previous(active_ctes) { active_ctes = context; } +SqlctxMeasureCteBindScope::SqlctxMeasureCteBindScope(const vector &queries, const ParserOptions &options) + : previous(active_ctes) { + for (auto &sql : queries) { + Parser parser(options); + parser.ParseQuery(sql); + if (parser.statements.size() != 1 || parser.statements[0]->type != StatementType::SELECT_STATEMENT) { + throw ParserException("Expected a SELECT carrying SQLCtx CTE definitions"); + } + definitions.push_back(parser.statements[0]->Cast().node->Copy()); + } + active_ctes = &definitions; +} +SqlctxMeasureCteBindScope::~SqlctxMeasureCteBindScope() { active_ctes = previous; } + +SqlctxMeasureSourceBindScope::SqlctxMeasureSourceBindScope( + const vector> &sources, const ParserOptions &options) : previous(active_sources) { + for (auto &source : sources) { + Parser parser(options); + parser.ParseQuery(source.second); + if (parser.statements.size() != 1) throw BinderException("Expected one measure source query"); + auto definition = make_uniq(); + auto &statement = *parser.statements[0]; + if (statement.type == StatementType::CREATE_STATEMENT) { + auto &view = statement.Cast().info->Cast(); + definition->query_node = view.query->node->Copy(); + definition->aliases = view.aliases; + } else { + definition->query_node = statement.Cast().node->Copy(); + } + auto scope = make_uniq(); + scope->cte_map.map.insert(Identifier(source.first), std::move(definition)); + definitions.push_back(std::move(scope)); + } + active_sources = &definitions; +} +SqlctxMeasureSourceBindScope::~SqlctxMeasureSourceBindScope() { active_sources = previous; } + +BoundStatement BindSqlctxMeasureProbe(QueryNode &probe, const vector &local_scopes) { + if (!active_context) throw BinderException("Measure binding requires the originating context"); + vector> definitions; + vector> binders {Binder::CreateBinder(*active_context)}; + auto add_scope = [&](QueryNode &scope) { + for (auto &entry : scope.cte_map.map) { + definitions.push_back(entry.second->Copy()); + auto &definition = *definitions.back(); + auto &parent = *binders.back(); + auto state = make_shared_ptr(parent, *definition.query_node, definition.aliases); + auto child = Binder::CreateBinder(*active_context, parent); + child->bind_context.AddCTEBinding( + make_uniq(BindingAlias(entry.first), state, parent.GenerateTableIndex())); + binders.push_back(std::move(child)); + } + }; + if (active_sources) for (auto &scope : *active_sources) add_scope(*scope); + if (active_ctes) for (auto &scope : *active_ctes) add_scope(*scope); + for (auto *scope : local_scopes) add_scope(*scope); + // Bind the SELECT itself rather than a materialized WITH wrapper, whose + // BoundStatement omits the expanded original projection expressions. + // CTEs remain available lazily through the same lexical parent binders. + auto input = probe.Copy(); + add_scope(*input); + input->cte_map.map.clear(); + return binders.back()->Bind(*input); +} + +bool IsSqlctxMeasureAggregate(const string &name) { + if (!active_context) throw BinderException("Aggregate classification requires the originating context"); + EntryLookupInfo lookup(CatalogType::AGGREGATE_FUNCTION_ENTRY, QualifiedName(Identifier(name))); + auto entry = Catalog::GetEntry(*active_context, lookup, OnEntryNotFound::RETURN_NULL); + return entry && entry->type == CatalogType::AGGREGATE_FUNCTION_ENTRY; +} + +namespace { +bool IsDistinctState(const ParsedExpression &expression) { + if (expression.GetExpressionClass() != ExpressionClass::FUNCTION) return false; + auto &function = expression.Cast(); + return function.Distinct() && function.ExportState() && function.FunctionName() != "aggregate"; +} + +unique_ptr LowerDistinctState(FunctionExpression &function) { + // Native states intentionally retain sufficient statistics, not a global + // distinct-value set. Deduplicate within this input group before exporting + // the ordinary aggregate state, so combining shards sums their statistics. + auto sql = function.ToString(); + string alias = "__sqlctx_distinct_state"; + while (sql.find(alias) != string::npos) alias += "_"; + vector fields; + auto aggregate = function.Copy(); + auto &ordinary = aggregate->Cast(); + ordinary.DistinctMutable() = false; + ordinary.FilterMutable().reset(); + ordinary.ClearAlias(); + auto &arguments = ordinary.GetArgumentsMutable(); + for (idx_t i = 0; i < arguments.size(); i++) { + auto field = "v" + std::to_string(i); + fields.push_back(field + " := " + function.GetArguments()[i].GetExpression().ToString()); + auto replacement = ParseSqlctxMeasureExpressions(alias + ".value." + field); + arguments[i] = FunctionArgument(std::move(replacement[0])); + } + if (ordinary.OrderBy()) { + for (auto &order : ordinary.OrderByMutable()->orders) { + bool found = false; + for (idx_t i = 0; i < function.GetArguments().size(); i++) { + if (order.expression->Equals(function.GetArguments()[i].GetExpression())) { + order.expression = arguments[i].GetExpression().Copy(); + found = true; + break; + } + } + if (!found) throw BinderException("In a DISTINCT aggregate, ORDER BY expressions must appear in the argument list"); + } + } + string rows = "list(DISTINCT struct_pack(" + StringUtil::Join(fields, ", ") + "))"; + if (function.Filter()) rows += " FILTER (WHERE " + function.Filter()->ToString() + ")"; + auto rewritten = "(SELECT " + ordinary.ToString() + " FROM unnest(" + rows + ") " + alias + "(value))"; + auto parsed = ParseSqlctxMeasureExpressions(rewritten); + parsed[0]->SetAlias(function.GetAlias()); + return std::move(parsed[0]); +} + +string PayloadString(const FunctionExpression &function, idx_t index) { + auto &args = function.GetArguments(); + if (index >= args.size() || args[index].GetExpression().GetExpressionClass() != ExpressionClass::CONSTANT) { + throw BinderException("Invalid SQLCtx measure payload"); + } + auto &literal = args[index].GetExpression().Cast().GetLiteral(); + if (literal.kind != LiteralKind::STRING) throw BinderException("SQLCtx measure payload must contain strings"); + return literal.text; +} + +unique_ptr LowerWindowPayload(FunctionExpression &function, const ParserOptions &options) { + idx_t cursor = 0; + auto next = [&]() { return PayloadString(function, cursor++); }; + auto count = [&]() -> idx_t { + auto value = next(); + if (value.empty() || value.find_first_not_of("0123456789") != string::npos) { + throw BinderException("Invalid SQLCtx measure payload count"); + } + auto result = std::stoull(value); + if (result > function.GetArguments().size()) throw BinderException("Invalid SQLCtx measure payload size"); + return result; + }; + auto scope_sql = next(); + // Argument ORDER BY decoration resolves correlated subquery columns before + // the window plan is built, so it already needs the consumer's WITH scope. + vector> call_ctes; + if (active_ctes) for (auto &scope : *active_ctes) call_ctes.push_back(scope->Copy()); + Parser scope_parser(options); + scope_parser.ParseQuery(scope_sql); + if (scope_parser.statements.size() != 1 || + scope_parser.statements[0]->type != StatementType::SELECT_STATEMENT) { + throw BinderException("Expected a SELECT window scope"); + } + call_ctes.push_back(scope_parser.statements[0]->Cast().node->Copy()); + SqlctxMeasureCteBindScope call_scope(&call_ctes); + vector sources; + auto source_count = count(); + for (idx_t i = 0; i < source_count; i++) { + MeasureWindowSource source; + source.key = next(); + source.relation_name = next(); + source.alias = next(); + source.clean_select_sql = next(); + auto dimension_count = count(); + for (idx_t j = 0; j < dimension_count; j++) { + auto name = next(); + source.dimensions.emplace_back(std::move(name), next()); + } + sources.push_back(std::move(source)); + } + vector calls; + auto call_count = count(); + for (idx_t i = 0; i < call_count; i++) { + MeasureWindowCall call; + call.marker_name = next(); + call.source_key = next(); + auto measure_sql = next(); + auto decoration_sql = next(); + auto parsed = ParseSqlctxMeasureExpressions(decoration_sql, options); + if (parsed.size() != 1 || parsed[0]->GetExpressionClass() != ExpressionClass::FUNCTION) { + throw BinderException("Expected one native measure aggregate call"); + } + // FILTER selects frame occurrences, while DISTINCT/argument ordering + // decorate the defining aggregate leaves. Applying FILTER twice would + // corrupt AT expansion and joined/grouped consumer predicates. + auto &decoration = parsed[0]->Cast(); + decoration.FilterMutable().reset(); + auto source = std::find_if(sources.begin(), sources.end(), [&](const MeasureWindowSource &candidate) { + return candidate.key == call.source_key; + }); + if (source == sources.end()) throw BinderException("Missing SQLCtx window source"); + call.expression_sql = DecorateSqlctxMeasureExpression(measure_sql, decoration.ToString(), source->dimensions, + {source->relation_name, source->alias}, options, true); + auto modifier_count = count(); + for (idx_t j = 0; j < modifier_count; j++) { + auto kind = next(); + WindowContextModifier modifier; + if (kind == "ALL") modifier.type = WindowContextType::ALL; + else if (kind == "ALL_GLOBAL") modifier.type = WindowContextType::ALL_GLOBAL; + else if (kind == "SET") modifier.type = WindowContextType::SET; + else if (kind == "WHERE") modifier.type = WindowContextType::WHERE; + else if (kind == "VISIBLE") modifier.type = WindowContextType::VISIBLE; + else throw BinderException("Unknown SQLCtx window context modifier"); + modifier.dimension = next(); + modifier.value = next(); + call.modifiers.push_back(std::move(modifier)); + } + calls.push_back(std::move(call)); + } + if (cursor != function.GetArguments().size()) throw BinderException("Trailing SQLCtx window payload"); + vector visible_ctes, binding_ctes; + if (auto scopes = CurrentSqlctxMeasureCtes()) { + for (auto &scope : *scopes) { + binding_ctes.push_back(scope->ToString()); + for (auto &entry : scope->cte_map.map) visible_ctes.push_back(entry.first.GetIdentifierName()); + } + } + auto rewritten = RewriteSqlctxMeasureWindows(scope_sql, sources, calls, visible_ctes, binding_ctes, options); + Parser parser(options); + parser.ParseQuery(rewritten); + if (parser.statements.size() != 1 || parser.statements[0]->type != StatementType::SELECT_STATEMENT) { + throw BinderException("SQLCtx window lowering did not produce a SELECT"); + } + return std::move(parser.statements[0]->Cast().node); +} + +// Rust owns recomputation populations; this final AST pass supplies DuckDB's +// aggregate decorations and EXPORT_STATE, preserving its exact state types. +class DecorationLowerer { +public: + void Query(QueryNode &node) { + vector> ctes; + if (active_ctes) for (auto &scope : *active_ctes) ctes.push_back(scope->Copy()); + ctes.push_back(node.Copy()); + SqlctxMeasureCteBindScope scope(&ctes); + if (node.type == QueryNodeType::SELECT_NODE) { + auto &select = node.Cast(); + if (select.from_table && select.from_table->type == TableReferenceType::TABLE_FUNCTION) { + auto &table = select.from_table->Cast(); + if (table.function->GetExpressionClass() == ExpressionClass::FUNCTION) { + auto &function = table.function->Cast(); + if (function.FunctionName() == "__sqlctx_measure_windows") { + auto options = SqlctxBuiltinParserOptions(); + options.context = *active_context; + auto lowered = LowerWindowPayload(function, options); + auto statement = make_uniq(); + statement->node = std::move(lowered); + select.from_table = make_uniq(std::move(statement), Identifier("__sqlctx_window_result")); + } + } + } + } + for (auto &entry : node.cte_map.map) Query(*entry.second->query_node); + ParsedExpressionIterator::EnumerateQueryNodeChildren(node, + [&](unique_ptr &expression) { Expression(expression); }, + [&](TableRef &table) { + if (table.type == TableReferenceType::SUBQUERY) { + Query(*table.Cast().subquery->node); + } + }); + } + + void Expression(unique_ptr &expression) { + if (!expression) return; + if (IsDistinctState(*expression)) { + expression = LowerDistinctState(expression->Cast()); + return; + } + if (expression->GetExpressionClass() == ExpressionClass::SUBQUERY) { + auto &subquery = expression->Cast(); + Query(*subquery.SubqueryMutable()->node); + } + if (expression->GetExpressionClass() == ExpressionClass::FUNCTION) { + auto &function = expression->Cast(); + if (function.FunctionName() == "__sqlctx_visible_join") { + if (function.GetArguments().size() < 2) throw BinderException("Invalid joined visibility payload"); + vector excluded; + for (idx_t i = 2; i < function.GetArguments().size(); i++) excluded.push_back(PayloadString(function, i)); + auto options = SqlctxBuiltinParserOptions(); + options.context = *active_context; + auto lowered = LowerSqlctxVisibleJoin(PayloadString(function, 0), PayloadString(function, 1), excluded, options); + lowered->SetAlias(expression->GetAlias()); + expression = std::move(lowered); + Expression(expression); + return; + } + if (function.FunctionName() == "__sqlctx_decorated_measure") { + auto &args = function.GetArguments(); + if (args.size() < 4 || (args.size() - 4) % 2) throw BinderException("Invalid measure decoration payload"); + auto text = [&](idx_t index) { + auto &arg = args[index].GetExpression(); + if (arg.GetExpressionClass() != ExpressionClass::CONSTANT) { + throw BinderException("Measure decoration payload must contain string literals"); + } + auto &literal = arg.Cast().GetLiteral(); + if (literal.kind != LiteralKind::STRING) { + throw BinderException("Measure decoration payload must contain string literals"); + } + return literal.text; + }; + vector> dimensions; + for (idx_t i = 4; i < args.size(); i += 2) dimensions.emplace_back(text(i), text(i + 1)); + auto options = SqlctxBuiltinParserOptions(); + options.context = *active_context; + auto sql = DecorateSqlctxMeasureExpression(text(0), text(1), dimensions, {text(2), text(3)}, options); + auto parsed = ParseSqlctxMeasureExpressions(sql, options); + parsed[0]->SetAlias(expression->GetAlias()); + expression = std::move(parsed[0]); + Expression(expression); + return; + } + } + ParsedExpressionIterator::EnumerateChildren(*expression, + [&](unique_ptr &child) { Expression(child); }); + } +}; +} + +void LowerSqlctxAggregateDecorations(ClientContext &context, QueryNode &query) { + SqlctxMeasureBindScope binding(context); + DecorationLowerer().Query(query); +} + +bool RequiresSqlctxAggregateLowering(QueryNode &query) { + bool required = false; + std::function &)> inspect; + inspect = [&](unique_ptr &expression) { + if (!expression) return; + required |= IsDistinctState(*expression); + if (expression->GetExpressionClass() == ExpressionClass::FUNCTION) { + required |= expression->Cast().FunctionName() == "__sqlctx_visible_join"; + } + if (expression->GetExpressionClass() == ExpressionClass::SUBQUERY) { + required |= RequiresSqlctxAggregateLowering(*expression->Cast().Subquery()->node); + } + ParsedExpressionIterator::EnumerateChildren(*expression, inspect); + }; + ParsedExpressionIterator::EnumerateQueryNodeChildren(query, inspect); + return required; +} +} // namespace duckdb +#else +namespace duckdb { +void LowerSqlctxAggregateDecorations(ClientContext &, QueryNode &) { } +bool RequiresSqlctxAggregateLowering(QueryNode &) { return false; } +} +#endif diff --git a/sqlctx-duckdb/src/sqlctx_measure_windows.cpp b/sqlctx-duckdb/src/sqlctx_measure_windows.cpp new file mode 100644 index 000000000..877c9d8dd --- /dev/null +++ b/sqlctx-duckdb/src/sqlctx_measure_windows.cpp @@ -0,0 +1,1673 @@ +// Adapted from sidequery/yardstick (MIT), revision 2b1318402b6be22b6417de5c83523f4b558c621f. +#include "sqlctx_measure_windows.hpp" +#include "sqlctx_aggregate_decorations.hpp" + +#if SQLCTX_GRAMMAR_EXTENSION +#include "sqlctx_aggregate_decorations.hpp" +#include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/entry_lookup_info.hpp" +#include "duckdb/common/string_util.hpp" +#include "duckdb/parser/expression/columnref_expression.hpp" +#include "duckdb/parser/expression/comparison_expression.hpp" +#include "duckdb/parser/expression/constant_expression.hpp" +#include "duckdb/parser/expression/function_expression.hpp" +#include "duckdb/parser/expression/lambda_expression.hpp" +#include "duckdb/parser/expression/star_expression.hpp" +#include "duckdb/parser/expression/subquery_expression.hpp" +#include "duckdb/parser/expression/window_expression.hpp" +#include "duckdb/parser/parsed_data/create_view_info.hpp" +#include "duckdb/parser/parsed_expression_iterator.hpp" +#include "duckdb/parser/parser.hpp" +#include "duckdb/parser/query_node/select_node.hpp" +#include "duckdb/parser/query_node/set_operation_node.hpp" +#include "duckdb/parser/query_node/recursive_cte_node.hpp" +#include "duckdb/parser/statement/create_statement.hpp" +#include "duckdb/parser/statement/select_statement.hpp" +#include "duckdb/parser/tableref/basetableref.hpp" +#include "duckdb/parser/tableref/joinref.hpp" +#include "duckdb/parser/tableref/subqueryref.hpp" +#include "duckdb/parser/tableref/expressionlistref.hpp" +#include "duckdb/parser/tableref/table_function_ref.hpp" +#include "duckdb/planner/binder.hpp" + +#include +#include +#include + +namespace duckdb { +namespace { + +using ExpressionMap = std::unordered_map>; +using Names = std::unordered_set; + +string Key(const string &text) { + return StringUtil::Lower(text); +} + +string Quote(const string &text) { + return "\"" + StringUtil::Replace(text, "\"", "\"\"") + "\""; +} + +unique_ptr Expression(const string &sql, const ParserOptions &options) { + auto expressions = ParseSqlctxMeasureExpressions(sql, options); + if (expressions.size() != 1) { + throw ParserException("Expected one expression while rewriting a measure window"); + } + return std::move(expressions[0]); +} + +unique_ptr ModifierExpression(const string &sql, const ParserOptions &options) { + // The SQLCtx compiler normalizes CURRENT into an ordinary function AST. + return Expression(sql, options); +} + +unique_ptr Query(const string &sql, const ParserOptions &options, + vector *view_aliases = nullptr) { + Parser parser(options); + parser.ParseQuery(sql); + if (parser.statements.size() != 1) { + throw ParserException("Expected one query while rewriting a measure window"); + } + auto &statement = *parser.statements[0]; + if (statement.type == StatementType::CREATE_STATEMENT) { + auto &info = statement.Cast().info->Cast(); + if (view_aliases) { + *view_aliases = info.aliases; + } + return info.query->node->Copy(); + } + return statement.Cast().node->Copy(); +} + +void Walk(unique_ptr &expression, + const std::function &)> &visit, Names lambda_parameters = {}) { + if (expression && expression->GetExpressionClass() == ExpressionClass::COLUMN_REF && + lambda_parameters.count(Key(expression->Cast().ColumnNames()[0].GetIdentifierName()))) { + return; + } + if (!expression || !visit(expression) || expression->GetExpressionClass() == ExpressionClass::SUBQUERY) { + return; + } + if (expression->GetExpressionClass() == ExpressionClass::LAMBDA) { + auto &lambda = expression->Cast(); + if (lambda.GetLambdaSyntaxType() == LambdaSyntaxType::LAMBDA_KEYWORD) { + string error; + auto parameters = lambda.ExtractColumnRefExpressions(error); + if (!error.empty()) { + throw ParserException(error); + } + for (auto ¶meter : parameters) { + lambda_parameters.insert(Key(parameter.get().Cast() + .GetColumnName().GetIdentifierName())); + } + Walk(lambda.RightMutable(), visit, std::move(lambda_parameters)); + return; + } + } + ParsedExpressionIterator::EnumerateChildren(*expression, [&](unique_ptr &child) { + Walk(child, visit, lambda_parameters); + }); +} + +void SelectExpressions(SelectNode &select, + const std::function &)> &visit) { + for (auto &expression : select.select_list) { + visit(expression); + } + for (auto &expression : select.groups.group_expressions) { + visit(expression); + } + if (select.having) { + visit(select.having); + } + if (select.qualify) { + visit(select.qualify); + } + ParsedExpressionIterator::EnumerateQueryNodeModifiers(select, visit); +} + +ExpressionMap Aliases(const SelectNode &select) { + ExpressionMap aliases; + for (auto &expression : select.select_list) { + if (expression->HasAlias()) { + auto copy = expression->Copy(); + copy->ClearAlias(); + aliases.emplace(Key(expression->GetAlias().GetIdentifierName()), std::move(copy)); + } + } + return aliases; +} + +void ExpandAliases(unique_ptr &expression, const ExpressionMap &aliases, + const Names &input_columns = {}, Names expanding = {}) { + if (!expression || expression->GetExpressionClass() == ExpressionClass::SUBQUERY) { + return; + } + if (expression->GetExpressionClass() == ExpressionClass::LAMBDA) { + auto &lambda = expression->Cast(); + if (lambda.GetLambdaSyntaxType() == LambdaSyntaxType::LAMBDA_KEYWORD) { + auto bindings = input_columns; + string error; + auto parameters = lambda.ExtractColumnRefExpressions(error); + if (!error.empty()) { + throw ParserException(error); + } + for (auto ¶meter : parameters) { + bindings.insert(Key(parameter.get().Cast().GetColumnName().GetIdentifierName())); + } + ExpandAliases(lambda.RightMutable(), aliases, bindings, expanding); + return; + } + } + if (expression->GetExpressionClass() == ExpressionClass::COLUMN_REF) { + auto &column = expression->Cast(); + if (!column.IsQualified()) { + auto key = Key(column.GetColumnName().GetIdentifierName()); + auto match = aliases.find(key); + if (match != aliases.end() && !input_columns.count(key) && !expanding.count(key)) { + expanding.insert(key); + auto alias = expression->GetAlias(); + expression = match->second->Copy(); + expression->SetAlias(alias); + ExpandAliases(expression, aliases, input_columns, std::move(expanding)); + return; + } + } + } + ParsedExpressionIterator::EnumerateChildren(*expression, [&](unique_ptr &child) { + ExpandAliases(child, aliases, input_columns, expanding); + }); +} + +bool HasAggregate(unique_ptr &expression) { + bool found = false; + Walk(expression, [&](unique_ptr &node) { + if (node->GetExpressionClass() == ExpressionClass::WINDOW) { + return false; + } + if (node->GetExpressionClass() == ExpressionClass::FUNCTION) { + auto &function = node->Cast(); + if (auto context = CurrentSqlctxMeasureContext()) { + EntryLookupInfo lookup(CatalogType::AGGREGATE_FUNCTION_ENTRY, function.GetQualifiedName()); + auto entry = Catalog::GetEntry(*context, lookup, OnEntryNotFound::RETURN_NULL); + found |= entry && entry->type == CatalogType::AGGREGATE_FUNCTION_ENTRY; + } else { + found |= IsSqlctxMeasureAggregate(function.FunctionName().GetIdentifierName()); + } + } + return true; + }); + return found; +} + +Names InputColumns(SelectNode &select) { + Names result; + if (!select.from_table || select.from_table->type == TableReferenceType::EMPTY_FROM) { + return result; + } + auto context = CurrentSqlctxMeasureContext(); + if (!context) { + throw BinderException("Measure window binding requires the originating bind context"); + } + auto probe = select.Copy(); + auto &layout = probe->Cast(); + layout.select_list.clear(); + layout.select_list.push_back(make_uniq()); + layout.groups = GroupByNode(); + layout.having.reset(); + layout.qualify.reset(); + layout.where_clause.reset(); + layout.modifiers.clear(); + layout.aggregate_handling = AggregateHandling::STANDARD_HANDLING; + auto bound = BindSqlctxMeasureProbe(*probe); + for (auto &name : bound.names) { + result.insert(Key(name.GetIdentifierName())); + } + return result; +} + +void BaseQualifiers(const TableRef &table, Names &names) { + if (table.type == TableReferenceType::BASE_TABLE && table.alias.empty()) { + names.insert(Key(table.Cast().Table().GetIdentifierName())); + } else if (table.type == TableReferenceType::JOIN) { + auto &join = table.Cast(); + BaseQualifiers(*join.left, names); + BaseQualifiers(*join.right, names); + } +} + +bool IsGrouped(SelectNode &select) { + if (!select.groups.group_expressions.empty() || !select.groups.grouping_sets.empty() || + select.aggregate_handling == AggregateHandling::FORCE_AGGREGATES) { + return true; + } + for (auto &expression : select.select_list) { + if (HasAggregate(expression)) { + return true; + } + } + return select.having && HasAggregate(select.having); +} + +void ExpandStars(SelectNode &select, const vector &scopes = {}) { + auto contains_star = [](unique_ptr &expression) { + bool found = false; + Walk(expression, [&](unique_ptr &node) { + if (node->GetExpressionClass() == ExpressionClass::WINDOW || + (node->GetExpressionClass() == ExpressionClass::FUNCTION && + IsSqlctxMeasureAggregate(node->Cast().FunctionName().GetIdentifierName()))) { + return false; + } + found |= node->GetExpressionClass() == ExpressionClass::STAR; + return true; + }); + return found; + }; + bool has_star = false; + for (auto &projection : select.select_list) { + has_star |= contains_star(projection); + } + if (!has_star) { + return; + } + auto context = CurrentSqlctxMeasureContext(); + if (!context) { + throw BinderException("Measure window star expansion requires the originating bind context"); + } + auto probe = select.Copy(); + auto &layout = probe->Cast(); + layout.groups = GroupByNode(); + layout.having.reset(); + layout.qualify.reset(); + layout.where_clause.reset(); + layout.modifiers.clear(); + layout.aggregate_handling = AggregateHandling::STANDARD_HANDLING; + string prefix = "__ys_star_projection_"; + auto source_sql = select.ToString(); + while (source_sql.find(prefix) != string::npos) { + prefix += "_"; + } + std::unordered_map placeholders; + for (idx_t i = 0; i < layout.select_list.size(); i++) { + if (!contains_star(layout.select_list[i])) { + auto name = prefix + std::to_string(i); + auto placeholder = ConstantExpression::FromValue(Value()); + placeholder->SetAlias(Identifier(name)); + layout.select_list[i] = std::move(placeholder); + placeholders.emplace(name, i); + } + } + auto bound = BindSqlctxMeasureProbe(*probe, scopes); + Names base_qualifiers; + if (select.from_table) { + BaseQualifiers(*select.from_table, base_qualifiers); + } + vector> expanded; + for (auto &projection : bound.extra_info.original_expressions) { + auto found = placeholders.find(projection->GetAlias().GetIdentifierName()); + if (projection->GetExpressionClass() == ExpressionClass::CONSTANT && found != placeholders.end()) { + expanded.push_back(std::move(select.select_list[found->second])); + } else { + Walk(projection, [&](unique_ptr &node) { + if (node->GetExpressionClass() != ExpressionClass::COLUMN_REF) { + return true; + } + auto &names = node->Cast().ColumnNamesMutable(); + if (names.size() < 2) { + return false; + } + auto qualifier = names[names.size() - 2].GetIdentifierName(); + string visible_name; + auto qualifier_key = Key(qualifier); + for (auto &candidate : base_qualifiers) { + if ((qualifier_key == candidate || StringUtil::EndsWith(qualifier_key, "." + candidate)) && + candidate.size() > visible_name.size()) { + visible_name = candidate; + } + } + if (!visible_name.empty()) { + auto column = names.back(); + names = {Identifier(visible_name), std::move(column)}; + } + return false; + }); + expanded.push_back(std::move(projection)); + } + } + if (expanded.size() != bound.names.size()) { + throw BinderException("Unable to expand measure window projection columns"); + } + select.select_list = std::move(expanded); +} + +unique_ptr Relation(const string &name) { + auto relation = make_uniq(); + relation->SetTable(Identifier(name)); + return std::move(relation); +} + +unique_ptr Subquery(unique_ptr query, const string &alias) { + auto statement = make_uniq(); + statement->node = std::move(query); + return make_uniq(std::move(statement), Identifier(alias)); +} + +struct SourcePlan { + const MeasureWindowSource *spec; + string base_name; + string lineage_name; + string id_name; + unique_ptr base; + unique_ptr view; + vector> columns; + std::unordered_map column_index; + ExpressionMap dimensions; + ExpressionMap consumer_dimensions; + vector> input_predicates; + bool input_predicates_complete = true; + Names qualifiers; + Names input_columns; +}; + +struct ReferenceScope { + bool unqualified_is_outer = true; + Names local_qualifiers; + Names local_columns; + Names aliases; + Names lambda_parameters; + vector cte_scopes; +}; + +void RelationQualifiers(const TableRef &table, Names &names) { + if (!table.alias.empty()) { + names.insert(Key(table.alias.GetIdentifierName())); + } else if (table.type == TableReferenceType::BASE_TABLE) { + names.insert(Key(table.Cast().Table().GetIdentifierName())); + } else if (table.type == TableReferenceType::TABLE_FUNCTION) { + auto &function = table.Cast().function; + if (function->GetExpressionClass() == ExpressionClass::FUNCTION) { + names.insert(Key(function->Cast().FunctionName().GetIdentifierName())); + } + } + if (table.type == TableReferenceType::JOIN) { + auto &join = table.Cast(); + RelationQualifiers(*join.left, names); + RelationQualifiers(*join.right, names); + } +} + +// Only references captured from the surrounding base-row scope are changed. +// Lambda parameters and nested query relations retain their own namespaces. +class CapturedReferences { +public: + using Visitor = std::function &)>; + + CapturedReferences(const Names &qualifiers_p, Visitor visitor_p) + : qualifiers(qualifiers_p), visitor(std::move(visitor_p)) { + } + + void Expression(unique_ptr &expression, ReferenceScope scope = {}) { + if (!expression) { + return; + } + if (expression->GetExpressionClass() == ExpressionClass::COLUMN_REF) { + auto &names = expression->Cast().ColumnNames(); + auto first = Key(names[0].GetIdentifierName()); + if (scope.lambda_parameters.count(first)) { + return; + } + bool captured = names.size() == 1 + ? scope.unqualified_is_outer && !scope.aliases.count(first) && !scope.local_columns.count(first) + : (scope.unqualified_is_outer || qualifiers.count(first)) && !scope.local_qualifiers.count(first); + if (captured) { + visitor(expression); + } + return; + } + if (expression->GetExpressionClass() == ExpressionClass::FUNCTION && + StringUtil::CIEquals(expression->Cast().FunctionName().GetIdentifierName(), "current")) { + return; + } + if (expression->GetExpressionClass() == ExpressionClass::LAMBDA) { + auto &lambda = expression->Cast(); + if (lambda.GetLambdaSyntaxType() == LambdaSyntaxType::LAMBDA_KEYWORD) { + string error; + auto parameters = lambda.ExtractColumnRefExpressions(error); + if (!error.empty()) { + throw ParserException(error); + } + for (auto ¶meter : parameters) { + scope.lambda_parameters.insert(Key(parameter.get().Cast() + .GetColumnName().GetIdentifierName())); + } + Expression(lambda.RightMutable(), std::move(scope)); + return; + } + } + if (expression->GetExpressionClass() == ExpressionClass::SUBQUERY) { + auto &subquery = expression->Cast(); + Expression(subquery.GetChildMutable(), scope); + Query(*subquery.SubqueryMutable()->node, scope); + return; + } + ParsedExpressionIterator::EnumerateChildren(*expression, [&](unique_ptr &child) { + Expression(child, scope); + }); + } + +private: + ReferenceScope WithBindings(TableRef &table, ReferenceScope scope) { + if (table.type != TableReferenceType::EMPTY_FROM) { + auto probe = make_uniq(); + probe->select_list.push_back(make_uniq()); + probe->from_table = table.Copy(); + auto context = CurrentSqlctxMeasureContext(); + if (!context) { + throw BinderException("Measure window correlation requires the originating bind context"); + } + auto bound = BindSqlctxMeasureProbe(*probe, scope.cte_scopes); + for (auto &name : bound.names) { + scope.local_columns.insert(Key(name.GetIdentifierName())); + } + RelationQualifiers(table, scope.local_qualifiers); + } + return scope; + } + + void Query(QueryNode &query, ReferenceScope scope) { + scope.cte_scopes.push_back(&query); + for (auto &entry : query.cte_map.map) { + if (entry.second->query_node) { + Query(*entry.second->query_node, scope); + } + } + if (query.type == QueryNodeType::SELECT_NODE) { + auto &select = query.Cast(); + if (select.from_table) { + Table(*select.from_table, scope); + scope = WithBindings(*select.from_table, std::move(scope)); + } + for (auto &projection : select.select_list) { + Expression(projection, scope); + if (projection->HasAlias()) { + scope.aliases.insert(Key(projection->GetAlias().GetIdentifierName())); + } + } + for (auto &group : select.groups.group_expressions) { + Expression(group, scope); + } + Expression(select.where_clause, scope); + Expression(select.having, scope); + Expression(select.qualify, scope); + } else if (query.type == QueryNodeType::SET_OPERATION_NODE) { + for (auto &child : query.Cast().children) { + Query(*child, scope); + } + scope.unqualified_is_outer = false; + } else if (query.type == QueryNodeType::RECURSIVE_CTE_NODE) { + auto &cte = query.Cast(); + Query(*cte.left, scope); + Query(*cte.right, scope); + scope.unqualified_is_outer = false; + } + ParsedExpressionIterator::EnumerateQueryNodeModifiers(query, [&](unique_ptr &expression) { + Expression(expression, scope); + }); + } + + void Table(TableRef &table, ReferenceScope scope) { + if (table.type == TableReferenceType::JOIN) { + auto &join = table.Cast(); + Table(*join.left, scope); + Table(*join.right, WithBindings(*join.left, scope)); + Expression(join.condition, WithBindings(table, scope)); + } else if (table.type == TableReferenceType::SUBQUERY) { + Query(*table.Cast().subquery->node, scope); + } else if (table.type == TableReferenceType::EXPRESSION_LIST) { + for (auto &row : table.Cast().values) { + for (auto &expression : row) { + Expression(expression, scope); + } + } + } else if (table.type == TableReferenceType::TABLE_FUNCTION) { + auto &function = table.Cast(); + Expression(function.function, scope); + if (function.subquery) { + Query(*function.subquery->node, scope); + } + } + } + + const Names &qualifiers; + Visitor visitor; +}; + +unique_ptr BaseColumn(const ParsedExpression &expression, const SourcePlan &plan) { + auto result = expression.Copy(); + result->ClearAlias(); + auto &names = result->Cast().ColumnNamesMutable(); + if (names.size() > 1 && StringUtil::CIEquals(names[0].GetIdentifierName(), "_inner")) { + names.erase(names.begin()); + } else if (names.size() == 2 && + (StringUtil::CIEquals(names[0].GetIdentifierName(), plan.spec->relation_name) || + StringUtil::CIEquals(names[0].GetIdentifierName(), plan.spec->alias))) { + names.erase(names.begin()); + } + if (names.size() == 1) { + auto key = Key(names[0].GetIdentifierName()); + auto dimension = plan.dimensions.find(key); + if (!plan.input_columns.count(key) && dimension != plan.dimensions.end()) { + return dimension->second->Copy(); + } + } + return result; +} + +void NormalizeModifierReferences(unique_ptr &expression, const SourcePlan &plan) { + CapturedReferences references(plan.qualifiers, [&](unique_ptr &node) { + auto &column = node->Cast(); + auto match = plan.dimensions.find(Key(column.GetColumnName().GetIdentifierName())); + auto replacement = match == plan.dimensions.end() ? BaseColumn(*node, plan) : match->second->Copy(); + CapturedReferences base_references(plan.qualifiers, [&](unique_ptr &base) { + auto &names = base->Cast().ColumnNamesMutable(); + names.insert(names.begin(), Identifier("_inner")); + }); + base_references.Expression(replacement); + node = std::move(replacement); + }); + references.Expression(expression); +} + +bool IsSourceReference(const ParsedExpression &expression, const SourcePlan &plan, bool call_scope = false) { + auto &names = expression.Cast().ColumnNames(); + if (names.size() > 1) { + auto first = Key(names[0].GetIdentifierName()); + if (call_scope) { + // Decorated source keys carry _inner. A defining FROM alias can be + // reused by a different relation in the consumer's namespace. + return first == "_inner" || first == Key(plan.spec->relation_name) || + first == Key(plan.spec->alias); + } + return plan.qualifiers.count(first) || plan.input_columns.count(first) || plan.dimensions.count(first); + } + auto name = Key(names[0].GetIdentifierName()); + return plan.input_columns.count(name) || plan.dimensions.count(name); +} + +void CollectColumns(unique_ptr &expression, SourcePlan &plan, bool call_scope = false) { + CapturedReferences references(plan.qualifiers, [&](unique_ptr &node) { + if (!IsSourceReference(*node, plan, call_scope)) { + return; + } + auto base = BaseColumn(*node, plan); + auto key = Key(base->ToString()); + if (!plan.column_index.count(key)) { + plan.column_index.emplace(key, plan.columns.size()); + plan.columns.push_back(std::move(base)); + } + }); + references.Expression(expression); +} + +void RebindColumns(unique_ptr &expression, const SourcePlan &plan, + const string &qualifier = "") { + CapturedReferences references(plan.qualifiers, [&](unique_ptr &node) { + auto base = BaseColumn(*node, plan); + auto match = plan.column_index.find(Key(base->ToString())); + if (match != plan.column_index.end()) { + auto alias = node->GetAlias(); + auto name = Identifier("__ys_c" + std::to_string(match->second)); + node = qualifier.empty() ? make_uniq(name) + : make_uniq(name, Identifier(qualifier)); + node->SetAlias(alias); + } + }); + references.Expression(expression); +} + +void RebindContextExpression(unique_ptr &expression, const SourcePlan &plan, + const string &qualifier) { + struct Snapshot { + unique_ptr *slot; + unique_ptr expression; + }; + vector snapshots; + Walk(expression, [&](unique_ptr &node) { + if (node->GetExpressionClass() != ExpressionClass::SUBQUERY) return true; + auto &query = *node->Cast().Subquery()->node; + if (query.type != QueryNodeType::SELECT_NODE) return false; + auto &select = query.Cast(); + if (!select.from_table || select.from_table->type != TableReferenceType::BASE_TABLE) return false; + auto &table = select.from_table->Cast(); + if (table.Table() != Identifier(plan.base_name) || + !StringUtil::StartsWith(table.alias.GetIdentifierName(), "__ys_current_context_")) return false; + // This snapshot is already bound to generated base-column names. A + // schema probe during captured-reference rebinding would look for its + // generated CTE before it is attached to the final query. + snapshots.push_back({&node, std::move(node)}); + node = ConstantExpression::FromValue(Value()); + return false; + }); + RebindColumns(expression, plan, qualifier); + for (auto &snapshot : snapshots) *snapshot.slot = std::move(snapshot.expression); +} + +SourcePlan BuildSource(const MeasureWindowSource &source, const vector &calls, + const std::unordered_map &caller_order_counts, + idx_t index, Names &cte_names, const ParserOptions &options) { + auto consumer_ctes = CurrentSqlctxMeasureCtes(); + // A stored measure's defining query does not inherit consumer CTEs. + SqlctxMeasureCteBindScope defining_scope(nullptr); + SourcePlan plan; + plan.spec = &source; + auto prefix = "__ys_window_source_" + std::to_string(index); + plan.lineage_name = prefix + "_lineage"; + plan.id_name = prefix + "_id"; + vector view_aliases; + plan.view = Query(source.clean_select_sql, options, &view_aliases); + for (auto &entry : plan.view->cte_map.map) { + cte_names.insert(Key(entry.first.GetIdentifierName())); + } + plan.base_name = prefix + "_base"; + idx_t suffix = 0; + while (!cte_names.insert(Key(plan.base_name)).second) { + plan.base_name = prefix + "_base_" + std::to_string(++suffix); + } + auto &view = plan.view->Cast(); + if (view.from_table) { + RelationQualifiers(*view.from_table, plan.qualifiers); + } + plan.qualifiers.insert("_inner"); + plan.qualifiers.insert(Key(source.relation_name)); + plan.qualifiers.insert(Key(source.alias)); + ExpandStars(view); + auto input_columns = InputColumns(view); + plan.input_columns = input_columns; + auto aliases = Aliases(view); + for (auto &dimension : source.dimensions) { + plan.dimensions.emplace(Key(dimension.first), Expression(dimension.second, options)); + } + // Resolve output aliases before rebinding the defining query to generated + // base columns. Keep names stable even for originally unaliased dimensions. + for (auto &expression : view.select_list) { + auto name = expression->GetName(); + ExpandAliases(expression, aliases, input_columns); + expression->SetAlias(name); + } + for (auto &expression : view.groups.group_expressions) { + ExpandAliases(expression, aliases, input_columns); + } + if (view.having) { + ExpandAliases(view.having, aliases, input_columns); + } + if (view.qualify) { + ExpandAliases(view.qualify, aliases, input_columns); + } + for (auto &modifier : view.modifiers) { + if (modifier->type == ResultModifierType::ORDER_MODIFIER) { + for (auto &order : modifier->Cast().orders) { + auto &expression = order.expression; + bool output_alias = expression->GetExpressionClass() == ExpressionClass::COLUMN_REF && + !expression->Cast().IsQualified() && + aliases.count(Key(expression->Cast().GetColumnName().GetIdentifierName())); + // A bare ORDER BY name chooses an output alias; names inside + // an ORDER BY expression retain normal input precedence. + ExpandAliases(expression, aliases, output_alias ? Names {} : input_columns); + } + } else if (modifier->type == ResultModifierType::DISTINCT_MODIFIER) { + for (auto &expression : modifier->Cast().distinct_on_targets) { + bool output_alias = expression->GetExpressionClass() == ExpressionClass::COLUMN_REF && + !expression->Cast().IsQualified() && + aliases.count(Key(expression->Cast().GetColumnName().GetIdentifierName())); + ExpandAliases(expression, aliases, output_alias ? Names {} : input_columns); + } + } + } + // Legacy metadata stores only explicitly aliased dimensions. Recover the + // complete dimension set from the defining projection for AT contexts. + for (idx_t i = 0; i < view.select_list.size(); i++) { + auto &projection = view.select_list[i]; + if (HasAggregate(projection)) { + continue; + } + bool window = false; + Walk(projection, [&](unique_ptr &node) { + window |= node->GetExpressionClass() == ExpressionClass::WINDOW; + return !window; + }); + if (window) { + continue; + } + bool references_base = false; + CapturedReferences references(plan.qualifiers, [&](unique_ptr &) { references_base = true; }); + references.Expression(projection); + if (references_base) { + auto name = i < view_aliases.size() ? view_aliases[i] : projection->GetName(); + auto expression = projection->Copy(); + expression->ClearAlias(); + plan.dimensions[Key(name.GetIdentifierName())] = std::move(expression); + } + } + SelectExpressions(view, [&](unique_ptr &expression) { CollectColumns(expression, plan); }); + for (auto &dimension : plan.dimensions) { + CollectColumns(dimension.second, plan); + } + for (auto &call : calls) { + SqlctxMeasureCteBindScope consumer_scope(consumer_ctes); + if (call.source_key != source.key) { + continue; + } + auto expression = Expression(call.expression_sql, options); + auto order_count = caller_order_counts.at(call.marker_name); + if (order_count) { + Walk(expression, [&](unique_ptr &node) { + if (node->GetExpressionClass() != ExpressionClass::FUNCTION) { + return true; + } + auto &function = node->Cast(); + if (function.OrderBy() && function.OrderBy()->orders.size() >= order_count) { + auto &orders = function.OrderByMutable()->orders; + for (idx_t i = 0; i < order_count; i++) { + CollectColumns(orders[i].expression, plan, true); + } + // Only the caller's prefix uses the consumer namespace. + // Declaration arguments, filters and order ties retain the + // defining FROM namespace, even when aliases are reused. + orders.erase(orders.begin(), orders.begin() + order_count); + } + return true; + }); + } + CollectColumns(expression, plan); + for (auto &modifier : call.modifiers) { + if (modifier.type == WindowContextType::WHERE) { + auto condition = ModifierExpression(modifier.value, options); + NormalizeModifierReferences(condition, plan); + CollectColumns(condition, plan); + } + } + } + auto base = make_uniq(); + base->from_table = std::move(view.from_table); + base->where_clause = std::move(view.where_clause); + base->cte_map = std::move(view.cte_map); + base->sample = std::move(view.sample); + auto identity = Expression("row_number() OVER ()", options); + identity->SetAlias(Identifier(plan.id_name)); + base->select_list.push_back(std::move(identity)); + for (idx_t i = 0; i < plan.columns.size(); i++) { + auto column = plan.columns[i]->Copy(); + column->SetAlias(Identifier("__ys_c" + std::to_string(i))); + base->select_list.push_back(std::move(column)); + } + plan.base = std::move(base); + bool grouped = source.grouped || IsGrouped(view); + // Adding provenance to SELECT DISTINCT would otherwise prevent duplicate + // elimination. Equal visible rows form one lineage group instead. + if (!grouped) { + for (auto it = view.modifiers.begin(); it != view.modifiers.end();) { + if ((*it)->type == ResultModifierType::DISTINCT_MODIFIER && + (*it)->Cast().distinct_on_targets.empty()) { + GroupingSet set; + for (idx_t i = 0; i < view.select_list.size(); i++) { + auto group = view.select_list[i]->Copy(); + group->ClearAlias(); + view.groups.group_expressions.push_back(std::move(group)); + set.insert(ProjectionIndex(i)); + } + view.groups.grouping_sets.push_back(std::move(set)); + it = view.modifiers.erase(it); + grouped = true; + } else { + ++it; + } + } + } + SelectExpressions(view, [&](unique_ptr &expression) { RebindColumns(expression, plan); }); + for (idx_t i = 0; i < view_aliases.size() && i < view.select_list.size(); i++) { + view.select_list[i]->SetAlias(view_aliases[i]); + } + view.from_table = Relation(plan.base_name); + auto lineage = Expression((grouped ? "list(" : "list_value(") + Quote(plan.id_name) + ")", options); + lineage->SetAlias(Identifier(plan.lineage_name)); + view.select_list.push_back(std::move(lineage)); + return plan; +} + +struct LineageInput { + unique_ptr table; + string lineage; + ExpressionMap dimensions; + bool found = false; +}; + +bool MapLineageExpression(unique_ptr &expression, const ExpressionMap &dimensions) { + bool mapped = true; + Walk(expression, [&](unique_ptr &node) { + if (node->GetExpressionClass() == ExpressionClass::SUBQUERY || + node->GetExpressionClass() == ExpressionClass::WINDOW) { + mapped = false; + return false; + } + if (node->GetExpressionClass() != ExpressionClass::COLUMN_REF) return true; + auto &column = node->Cast(); + auto key = Key(column.GetColumnName().GetIdentifierName()); + if (column.IsQualified()) { + auto &names = column.ColumnNames(); + key = Key(names[names.size() - 2].GetIdentifierName()) + "." + key; + } + auto found = dimensions.find(key); + if (found == dimensions.end()) mapped = false; + else node = found->second->Copy(); + return false; + }); + return mapped; +} + +struct LineageQuery { + unique_ptr query; + ExpressionMap dimensions; + bool found = false; +}; + +// Retain the actual input relation above a measure definition. Its projection, +// predicates, DISTINCT and row selection determine which original identities +// belong to a window frame; substituting the definition itself would lose them. +class SourceLineage { +public: + SourceLineage(SourcePlan &plan_p, const ParserOptions &options_p) : plan(plan_p), options(options_p) { + } + + LineageInput Table(TableRef &table, vector scopes) { + auto alias = table.alias.GetIdentifierName(); + if (table.type == TableReferenceType::BASE_TABLE) { + auto &base = table.Cast(); + if (alias.empty()) alias = base.Table().GetIdentifierName(); + if (base.GetQualifiedName().Schema().empty()) { + for (idx_t i = scopes.size(); i > 0; i--) { + auto found = scopes[i - 1]->cte_map.map.find(base.Table()); + if (found == scopes[i - 1]->cte_map.map.end()) continue; + auto visible = vector(scopes.begin(), scopes.begin() + i - 1); + auto query = QueryInput(found->second->query_node->Copy(), found->second->aliases, visible); + return FromQuery(std::move(query), table, alias); + } + } + if (StringUtil::CIEquals(base.Table().GetIdentifierName(), plan.spec->relation_name)) { + LineageInput input; + input.table = Subquery(plan.view->Copy(), alias); + input.table->sample = table.sample ? table.sample->Copy() : nullptr; + input.table->column_name_alias = table.column_name_alias; + input.lineage = Quote(alias) + "." + Quote(plan.lineage_name); + for (auto &dimension : plan.dimensions) { + input.dimensions.emplace(dimension.first, dimension.second->Copy()); + input.dimensions.emplace(Key(alias) + "." + dimension.first, dimension.second->Copy()); + } + input.found = true; + return input; + } + } else if (table.type == TableReferenceType::SUBQUERY) { + if (alias.empty()) alias = "__ys_window_input"; + auto query = QueryInput(table.Cast().subquery->node->Copy(), table.column_name_alias, scopes); + return FromQuery(std::move(query), table, alias); + } else if (table.type == TableReferenceType::JOIN) { + plan.input_predicates_complete = false; + auto copy = table.Copy(); + auto &join = copy->Cast(); + auto left = Table(*join.left, scopes); + auto right = Table(*join.right, scopes); + if (left.found && right.found) { + throw BinderException("A measure window input must identify one contributing relation for its measure"); + } + join.left = std::move(left.table); + join.right = std::move(right.table); + LineageInput input; + input.table = std::move(copy); + auto &contributing = left.found ? left : right; + input.found = contributing.found; + input.lineage = contributing.lineage; + input.dimensions = std::move(contributing.dimensions); + return input; + } + LineageInput input; + input.table = table.Copy(); + return input; + } + +private: + LineageInput FromQuery(LineageQuery query, TableRef &original, const string &alias) { + LineageInput input; + if (!query.found) { + input.table = original.Copy(); + return input; + } + input.table = Subquery(std::move(query.query), alias); + input.table->sample = original.sample ? original.sample->Copy() : nullptr; + input.lineage = Quote(alias) + "." + Quote(plan.lineage_name); + for (auto &dimension : query.dimensions) { + input.dimensions.emplace(Key(alias) + "." + dimension.first, dimension.second->Copy()); + input.dimensions.emplace(dimension.first, std::move(dimension.second)); + } + input.found = true; + return input; + } + + LineageQuery QueryInput(unique_ptr query, const vector &column_aliases, + vector scopes) { + LineageQuery result; + if (query->type != QueryNodeType::SELECT_NODE) { + throw BinderException("Measure input lineage requires a SELECT projection"); + } + auto &select = query->Cast(); + scopes.push_back(query.get()); + ExpandStars(select, scopes); + auto input = Table(*select.from_table, scopes); + if (!input.found) { + result.query = std::move(query); + return result; + } + if (select.where_clause) { + auto predicate = select.where_clause->Copy(); + if (MapLineageExpression(predicate, input.dimensions)) { + plan.input_predicates.push_back(std::move(predicate)); + } else { + plan.input_predicates_complete = false; + } + } + for (auto &modifier : select.modifiers) { + if (modifier->type != ResultModifierType::ORDER_MODIFIER && + modifier->type != ResultModifierType::DISTINCT_MODIFIER) { + plan.input_predicates_complete = false; + } + } + for (idx_t i = 0; i < select.select_list.size(); i++) { + auto &projection = select.select_list[i]; + auto name = i < column_aliases.size() ? column_aliases[i] : projection->GetName(); + auto dimension = projection->Copy(); + dimension->ClearAlias(); + bool mapped = MapLineageExpression(dimension, input.dimensions); + if (mapped && !HasAggregate(dimension)) { + result.dimensions.emplace(Key(name.GetIdentifierName()), std::move(dimension)); + } + projection->SetAlias(name); + } + bool grouped = IsGrouped(select); + if (!grouped) { + for (auto modifier = select.modifiers.begin(); modifier != select.modifiers.end();) { + if ((*modifier)->type == ResultModifierType::DISTINCT_MODIFIER && + (*modifier)->Cast().distinct_on_targets.empty()) { + GroupingSet grouping; + for (auto &projection : select.select_list) { + auto dimension = projection->Copy(); + dimension->ClearAlias(); + grouping.insert(ProjectionIndex(select.groups.group_expressions.size())); + select.groups.group_expressions.push_back(std::move(dimension)); + } + select.groups.grouping_sets.push_back(std::move(grouping)); + modifier = select.modifiers.erase(modifier); + grouped = true; + } else { + ++modifier; + } + } + } + auto lineage_sql = grouped ? "flatten(list(" + input.lineage + "))" : input.lineage; + auto lineage = Expression(lineage_sql, options); + lineage->SetAlias(Identifier(plan.lineage_name)); + select.select_list.push_back(std::move(lineage)); + select.from_table = std::move(input.table); + result.query = std::move(query); + result.found = true; + return result; + } + + SourcePlan &plan; + const ParserOptions &options; +}; + +bool ReplaceSource(unique_ptr &relation, SourcePlan &plan, + const vector &scopes, const ParserOptions &options) { + if (!relation) { + return false; + } + if (relation->type == TableReferenceType::JOIN) { + auto &join = relation->Cast(); + bool left = ReplaceSource(join.left, plan, scopes, options); + bool right = ReplaceSource(join.right, plan, scopes, options); + return left || right; + } + auto alias = relation->alias.GetIdentifierName(); + if (alias.empty() && relation->type == TableReferenceType::BASE_TABLE) { + alias = relation->Cast().Table().GetIdentifierName(); + } + auto expected_alias = plan.spec->alias.empty() ? plan.spec->relation_name : plan.spec->alias; + if (!StringUtil::CIEquals(alias, expected_alias)) { + return false; + } + SourceLineage lineage(plan, options); + auto input = lineage.Table(*relation, scopes); + if (!input.found) return false; + plan.consumer_dimensions = std::move(input.dimensions); + relation = std::move(input.table); + return true; +} + +class WindowRewrite { +public: + WindowRewrite(SelectNode &owner_p, vector &sources_p, + const vector &calls_p, const ParserOptions &options_p, + const Names &input_columns_p, + const std::unordered_map> &cell_partitions_p) + : owner(owner_p), sources(sources_p), calls(calls_p), options(options_p), grouped(IsGrouped(owner_p)), + aliases(Aliases(owner_p)), input_columns(input_columns_p), cell_partitions(cell_partitions_p) { + } + + unique_ptr Run() { + auto output = make_uniq(); + auto projections = std::move(owner.select_list); + auto qualify = std::move(owner.qualify); + output->modifiers = std::move(owner.modifiers); + + if (owner.aggregate_handling == AggregateHandling::FORCE_AGGREGATES) { + // DuckDB's GROUP BY ALL binder cannot infer groups from the new + // list window. Infer them from the user's original projection. + owner.aggregate_handling = AggregateHandling::STANDARD_HANDLING; + owner.groups = GroupByNode(); + GroupingSet grouping; + for (auto &projection : projections) { + bool window = false; + Walk(projection, [&](unique_ptr &node) { + window |= node->GetExpressionClass() == ExpressionClass::WINDOW; + return !window; + }); + if (window || HasAggregate(projection)) { + continue; + } + auto group = projection->Copy(); + group->ClearAlias(); + grouping.insert(ProjectionIndex(owner.groups.group_expressions.size())); + owner.groups.group_expressions.push_back(std::move(group)); + } + owner.groups.grouping_sets.push_back(std::move(grouping)); + } + + for (auto &group : owner.groups.group_expressions) { + // SQL ordinal grouping is relative to the original projection. + if (group->GetExpressionClass() == ExpressionClass::CONSTANT) { + auto text = group->ToString(); + if (!text.empty() && text.find_first_not_of("0123456789") == string::npos) { + auto ordinal = std::stoull(text); + if (ordinal > 0 && ordinal <= projections.size()) { + group = projections[ordinal - 1]->Copy(); + group->ClearAlias(); + } + } + } + ExpandAliases(group, aliases, input_columns); + } + if (owner.having) { + ExpandAliases(owner.having, aliases, input_columns); + } + if (owner.where_clause) { + ExpandAliases(owner.where_clause, aliases, input_columns); + } + for (auto &projection : projections) { + auto name = projection->GetName(); + projection->ClearAlias(); + ExpandAliases(projection, aliases, input_columns); + Rewrite(projection); + projection->SetAlias(name); + output->select_list.push_back(std::move(projection)); + } + if (qualify) { + ExpandAliases(qualify, aliases, input_columns); + Rewrite(qualify); + output->where_clause = std::move(qualify); + } + for (auto &modifier : output->modifiers) { + if (modifier->type == ResultModifierType::ORDER_MODIFIER) { + for (auto &order : modifier->Cast().orders) { + RewriteModifier(order.expression); + } + } else if (modifier->type == ResultModifierType::DISTINCT_MODIFIER) { + for (auto &target : modifier->Cast().distinct_on_targets) { + RewriteModifier(target); + } + } + } + output->cte_map = std::move(owner.cte_map); + output->from_table = Subquery(owner.Copy(), "__ys_window_stage"); + return std::move(output); + } + +private: + const MeasureWindowCall *Call(const ParsedExpression &expression) const { + if (expression.GetExpressionClass() != ExpressionClass::WINDOW) { + return nullptr; + } + auto &window = expression.Cast(); + for (auto &call : calls) { + if (StringUtil::CIEquals(window.FunctionName().GetIdentifierName(), call.marker_name)) { + return &call; + } + } + return nullptr; + } + + bool ContainsCall(unique_ptr &expression) const { + bool found = false; + Walk(expression, [&](unique_ptr &node) { + found = found || Call(*node); + return !found; + }); + return found; + } + + string Project(unique_ptr expression) { + auto name = "__ys_window_value_" + std::to_string(owner.select_list.size()); + expression->SetAlias(Identifier(name)); + owner.select_list.push_back(std::move(expression)); + return name; + } + + void RewriteModifier(unique_ptr &expression) { + // Output aliases and ordinal references are resolved by the final query. + if (expression->GetExpressionClass() == ExpressionClass::CONSTANT) { + return; + } + if (expression->GetExpressionClass() == ExpressionClass::COLUMN_REF) { + auto &column = expression->Cast(); + if (!column.IsQualified() && aliases.count(Key(column.GetColumnName().GetIdentifierName()))) { + return; + } + } + ExpandAliases(expression, aliases, input_columns); + Rewrite(expression); + } + + unique_ptr DimensionExpression(const SourcePlan &source, const string &dimension, + bool validate = false) const { + auto expression = Expression(dimension, options); + if (validate) ExpandAliases(expression, aliases, input_columns); + Walk(expression, [&](unique_ptr &node) { + if (node->GetExpressionClass() != ExpressionClass::COLUMN_REF) return true; + auto &column = node->Cast(); + auto key = Key(column.GetColumnName().GetIdentifierName()); + auto visible = source.consumer_dimensions.find(key); + if (column.IsQualified()) { + auto &names = column.ColumnNames(); + auto qualified = Key(names[names.size() - 2].GetIdentifierName()) + "." + key; + auto found = source.consumer_dimensions.find(qualified); + if (found != source.consumer_dimensions.end()) visible = found; + } + if (visible != source.consumer_dimensions.end()) { + node = visible->second->Copy(); + } else { + auto original = source.dimensions.find(key); + if (original != source.dimensions.end()) node = original->second->Copy(); + else if (validate && (!column.IsQualified() || + StringUtil::CIEquals(column.ColumnNames()[column.ColumnNames().size() - 2].GetIdentifierName(), source.spec->alias) || + StringUtil::CIEquals(column.ColumnNames()[column.ColumnNames().size() - 2].GetIdentifierName(), source.spec->relation_name))) { + throw BinderException("Unknown dimension '%s' in AT context", column.GetColumnName().GetIdentifierName()); + } + } + return false; + }); + return expression; + } + + string DimensionSQL(const SourcePlan &source, const string &dimension, const string &qualifier) const { + auto expression = DimensionExpression(source, dimension); + RebindColumns(expression, source, qualifier); + return expression->ToString(); + } + + string Context(const SourcePlan &source, const MeasureWindowCall &call, const string &frame, + const string &visible_frame, const string &payload_ids = "") const { + auto frame_ids = payload_ids.empty() ? "SELECT unnest(flatten(" + Quote(frame) + "))" : payload_ids; + struct Predicate { + unique_ptr expression; + string dimension; + string members; + vector excluded; + }; + vector predicates; + predicates.push_back({nullptr, string(), frame_ids, {}}); + for (auto &condition : source.input_predicates) { + predicates.push_back({condition->Copy(), string(), string(), {}}); + } + auto dimension_key = [&](const string &dimension) { + auto expression = DimensionExpression(source, dimension, true); + return Key(expression->ToString()); + }; + vector context_dimensions; + auto cell = cell_partitions.find(call.marker_name); + if (cell != cell_partitions.end()) { + context_dimensions = cell->second; + } else { + for (auto &dimension : source.dimensions) context_dimensions.push_back(dimension.first); + } + auto render = [&](const string &candidate) { + vector conditions; + idx_t selection_index = 0; + for (auto &predicate : predicates) { + if (!predicate.members.empty()) { + if (predicate.excluded.empty()) { + conditions.push_back(candidate + "." + Quote(source.id_name) + + " IN (" + predicate.members + ")"); + continue; + } + auto selected = "__ys_context_selected_" + std::to_string(selection_index++); + vector correlations; + for (auto &dimension : context_dimensions) { + bool excluded = false; + for (auto &removed : predicate.excluded) { + excluded |= dimension_key(removed) == dimension_key(dimension); + } + if (!excluded) { + correlations.push_back(DimensionSQL(source, dimension, candidate) + + " IS NOT DISTINCT FROM " + DimensionSQL(source, dimension, selected)); + } + } + if (correlations.empty()) continue; + correlations.push_back(selected + "." + Quote(source.id_name) + + " IN (" + predicate.members + ")"); + conditions.push_back("EXISTS (SELECT 1 FROM " + Quote(source.base_name) + " " + selected + + " WHERE " + StringUtil::Join(correlations, " AND ") + ")"); + continue; + } + auto expression = predicate.expression->Copy(); + RebindContextExpression(expression, source, candidate); + vector> excluded; + for (auto &dimension : predicate.excluded) { + auto removed = DimensionExpression(source, dimension); + RebindColumns(removed, source, candidate); + excluded.push_back(std::move(removed)); + } + RemoveSqlctxContextDimensions(expression, excluded, candidate); + conditions.push_back("(" + expression->ToString() + ")"); + } + return conditions.empty() ? string("true") : StringUtil::Join(conditions, " AND "); + }; + auto remove_dimension = [&](const string &dimension) { + auto key = dimension_key(dimension); + for (auto predicate = predicates.begin(); predicate != predicates.end();) { + if (!predicate->dimension.empty() && predicate->dimension == key) { + predicate = predicates.erase(predicate); + } else { + predicate->excluded.push_back(dimension); + ++predicate; + } + } + }; + idx_t current_index = 0; + auto resolve_current = [&](unique_ptr &expression, bool bare_dimensions) { + Walk(expression, [&](unique_ptr &node) { + string dimension; + if (node->GetExpressionClass() == ExpressionClass::FUNCTION) { + auto &function = node->Cast(); + if (StringUtil::CIEquals(function.FunctionName().GetIdentifierName(), "current") && + function.GetArguments().size() == 1) { + dimension = function.GetArguments()[0].GetExpression().ToString(); + } + } else if (bare_dimensions && node->GetExpressionClass() == ExpressionClass::COLUMN_REF) { + auto &column = node->Cast(); + if (source.dimensions.count(Key(column.GetColumnName().GetIdentifierName())) || + source.consumer_dimensions.count(Key(column.GetColumnName().GetIdentifierName()))) { + dimension = node->ToString(); + } + } + if (dimension.empty()) { + return true; + } + auto selected = "__ys_current_context_" + std::to_string(current_index++); + auto dim = DimensionSQL(source, dimension, selected); + // CURRENT observes the context produced by preceding modifiers, + // rather than repeatedly reading the original window frame. + auto current_context = render(selected); + node = Expression("(SELECT CASE WHEN count(DISTINCT " + dim + + ") + max(CASE WHEN " + dim + " IS NULL THEN 1 ELSE 0 END) = 1 THEN first(" + dim + + ") ELSE NULL END FROM " + Quote(source.base_name) + " " + selected + " WHERE " + + current_context + ")", options); + return false; + }); + }; + for (auto &modifier : call.modifiers) { + switch (modifier.type) { + case WindowContextType::ALL_GLOBAL: + predicates.clear(); + break; + case WindowContextType::ALL: + remove_dimension(modifier.dimension); + break; + case WindowContextType::SET: { + auto value = ModifierExpression(modifier.value, options); + resolve_current(value, true); + value = DimensionExpression(source, value->ToString()); + remove_dimension(modifier.dimension); + auto dimension = DimensionExpression(source, modifier.dimension, true); + auto equality = make_uniq(ExpressionType::COMPARE_NOT_DISTINCT_FROM, + std::move(dimension), std::move(value)); + predicates.push_back({std::move(equality), dimension_key(modifier.dimension), string(), {}}); + break; + } + case WindowContextType::WHERE: { + auto condition = ModifierExpression(modifier.value, options); + resolve_current(condition, false); + condition = DimensionExpression(source, condition->ToString()); + predicates.clear(); + predicates.push_back({std::move(condition), string(), string(), {}}); + break; + } + case WindowContextType::VISIBLE: { + for (auto &condition : source.input_predicates) { + predicates.push_back({condition->Copy(), string(), string(), {}}); + } + bool mapped = source.input_predicates_complete && + owner.from_table->type != TableReferenceType::JOIN; + if (owner.where_clause) { + auto condition = owner.where_clause->Copy(); + if (MapLineageExpression(condition, source.consumer_dimensions)) { + predicates.push_back({std::move(condition), string(), string(), {}}); + } else mapped = false; + } + if (!mapped && !visible_frame.empty()) { + predicates.push_back({nullptr, string(), + "SELECT unnest(flatten(" + Quote(visible_frame) + "))", {}}); + } + break; + } + } + } + return render("__ys_candidate"); + } + + void Rewrite(unique_ptr &expression) { + if (auto call = Call(*expression)) { + SourcePlan *source = nullptr; + for (auto &candidate : sources) { + if (candidate.spec->key == call->source_key) { + source = &candidate; + break; + } + } + if (!source) { + throw InternalException("Missing source for measure window %s", call->marker_name); + } + auto window = expression->Copy(); + auto &list = window->Cast(); + auto measure = Expression(call->expression_sql, options); + const auto order_count = list.ArgOrders().size(); + vector> caller_keys; + Walk(measure, [&](unique_ptr &node) { + if (!caller_keys.empty() || node->GetExpressionClass() != ExpressionClass::FUNCTION) { + return caller_keys.empty(); + } + auto &function = node->Cast(); + if (order_count && function.OrderBy() && function.OrderBy()->orders.size() >= order_count) { + for (idx_t i = 0; i < order_count; i++) { + caller_keys.push_back(function.OrderBy()->orders[i].expression->Copy()); + } + return false; + } + return true; + }); + vector external_keys; + vector payload_fields; + bool external_order = false; + for (idx_t i = 0; i < caller_keys.size(); i++) { + bool external = false; + CapturedReferences references(source->qualifiers, [&](unique_ptr &node) { + if (IsSourceReference(*node, *source, true)) { + return; + } + external = true; + auto field = "__ys_ext_" + std::to_string(payload_fields.size()); + auto input = node->Copy(); + ExpandAliases(input, aliases, input_columns); + payload_fields.push_back(Quote(field) + " := " + input->ToString()); + node = Expression("__ys_payload." + Quote(field), options); + }); + // Grouped consumer keys are evaluated at the window input grain. + // Source-only keys instead remain expressions over original rows. + auto raw_key = list.ArgOrders()[i].expression->Copy(); + ExpandAliases(raw_key, aliases, input_columns); + if (HasAggregate(raw_key)) { + external = true; + auto field = "__ys_ext_" + std::to_string(payload_fields.size()); + payload_fields.push_back(Quote(field) + " := " + raw_key->ToString()); + caller_keys[i] = Expression("__ys_payload." + Quote(field), options); + } else { + references.Expression(caller_keys[i]); + } + external_keys.push_back(external); + external_order |= external; + } + vector occurrence_orders; + for (idx_t i = 0; i < caller_keys.size(); i++) { + auto &original = list.ArgOrders()[i]; + OrderByNode order(original.type, original.null_order, + Expression("__ys_key_" + std::to_string(i), options)); + occurrence_orders.push_back(order.ToString()); + } + list.SetFunctionName("list"); + list.DistinctMutable() = false; + list.ArgOrdersMutable().clear(); + list.GetArgumentsMutable().clear(); + auto alias = source->spec->alias.empty() ? source->spec->relation_name : source->spec->alias; + auto lineage_sql = Quote(alias) + "." + Quote(source->lineage_name); + if (grouped) { + lineage_sql = "flatten(list(" + lineage_sql + "))"; + } + auto frame_value = lineage_sql; + if (external_order) { + frame_value = "struct_pack(ids := " + lineage_sql + ", " + + StringUtil::Join(payload_fields, ", ") + ")"; + } + list.GetArgumentsMutable().emplace_back(Expression(frame_value, options)); + if (list.Filter()) { + ExpandAliases(list.FilterMutable(), aliases, input_columns); + } + for (auto &partition : list.PartitionsMutable()) { + ExpandAliases(partition, aliases, input_columns); + } + for (auto &order : list.OrderByMutable()) { + ExpandAliases(order.expression, aliases, input_columns); + } + if (list.StartExpr()) { + ExpandAliases(list.StartExprMutable(), aliases, input_columns); + } + if (list.EndExpr()) { + ExpandAliases(list.EndExprMutable(), aliases, input_columns); + } + auto frame = Project(std::move(window)); + string visible_frame; + for (auto &modifier : call->modifiers) { + if (modifier.type == WindowContextType::VISIBLE) { + auto existing = visible_frames.find(source->spec->key); + if (existing == visible_frames.end()) { + visible_frame = Project(Expression("list(" + lineage_sql + ") OVER ()", options)); + visible_frames.emplace(source->spec->key, visible_frame); + } else { + visible_frame = existing->second; + } + break; + } + } + string order_cte; + string order_join; + string frame_ids; + if (external_order) { + frame_ids = "SELECT unnest(__ys_payload.ids) FROM unnest(" + Quote(frame) + + ") __ys_frames(__ys_payload)"; + vector key_projections; + for (idx_t i = 0; i < caller_keys.size(); i++) { + RebindColumns(caller_keys[i], *source, "__ys_candidate"); + key_projections.push_back(caller_keys[i]->ToString() + " AS __ys_key_" + std::to_string(i)); + } + order_cte = "WITH __ys_occurrences AS MATERIALIZED (SELECT __ys_candidate." + + Quote(source->id_name) + ", " + StringUtil::Join(key_projections, ", ") + + " FROM unnest(" + Quote(frame) + ") __ys_frames(__ys_payload), " + + "unnest(__ys_payload.ids) __ys_ids(id) JOIN " + Quote(source->base_name) + + " __ys_candidate ON __ys_candidate." + Quote(source->id_name) + " = __ys_ids.id), " + + "__ys_order_keys AS (SELECT * FROM __ys_occurrences QUALIFY row_number() OVER " + + "(PARTITION BY " + Quote(source->id_name) + " ORDER BY " + + StringUtil::Join(occurrence_orders, ", ") + ") = 1) "; + // Context expansion can introduce rows without frame occurrences. + // Their joined-input keys are NULL; source keys still recompute. + order_join = " LEFT JOIN __ys_order_keys USING (" + Quote(source->id_name) + ")"; + Walk(measure, [&](unique_ptr &node) { + if (node->GetExpressionClass() != ExpressionClass::FUNCTION) { + return true; + } + auto &function = node->Cast(); + if (function.OrderBy() && function.OrderBy()->orders.size() >= order_count) { + for (idx_t i = 0; i < order_count; i++) { + if (external_keys[i]) { + function.OrderByMutable()->orders[i].expression = + Expression("__ys_order_keys.__ys_key_" + std::to_string(i), options); + } + } + } + return true; + }); + } + RebindColumns(measure, *source, "__ys_candidate"); + expression = Expression("(" + order_cte + "SELECT " + measure->ToString() + " FROM " + + Quote(source->base_name) + " __ys_candidate" + order_join + " WHERE " + + Context(*source, *call, frame, visible_frame, frame_ids) + ")", options); + return; + } + if (!ContainsCall(expression)) { + auto name = Project(std::move(expression)); + expression = make_uniq(Identifier(name)); + return; + } + ParsedExpressionIterator::EnumerateChildren(*expression, [&](unique_ptr &child) { + Rewrite(child); + }); + } + + SelectNode &owner; + vector &sources; + const vector &calls; + const ParserOptions &options; + bool grouped; + ExpressionMap aliases; + Names input_columns; + std::unordered_map visible_frames; + const std::unordered_map> &cell_partitions; +}; + +} // namespace + +void ExpandSqlctxMeasureProjectionStars(SelectNode &select, const vector &scopes) { + ExpandStars(select, scopes); +} + +string RewriteSqlctxMeasureWindows(const string &scope_sql, const vector &sources, + const vector &calls, const vector &visible_ctes, + const vector &binding_ctes, const ParserOptions &options) { + if (calls.empty()) { + return scope_sql; + } + SqlctxMeasureCteBindScope binding_scope(binding_ctes, options); + vector> probe_sources; + for (auto &source : sources) probe_sources.emplace_back(source.relation_name, source.clean_select_sql); + SqlctxMeasureSourceBindScope source_scope(probe_sources, options); + auto query = Query(scope_sql, options); + LowerSqlctxAggregateDecorations(*CurrentSqlctxMeasureContext(), *query); + // FILTER, AT and argument-order subqueries are detached expression ASTs; + // their schema probes still inherit this consumer's WITH definitions. + vector> consumer_scopes; + if (auto inherited = CurrentSqlctxMeasureCtes()) { + for (auto &scope : *inherited) consumer_scopes.push_back(scope->Copy()); + } + consumer_scopes.push_back(query->Copy()); + SqlctxMeasureCteBindScope consumer_scope(&consumer_scopes); + auto &owner = query->Cast(); + ExpandStars(owner); + auto input_columns = InputColumns(owner); + std::unordered_map> cell_partitions; + SelectExpressions(owner, [&](unique_ptr &expression) { + Walk(expression, [&](unique_ptr &node) { + if (node->GetExpressionClass() != ExpressionClass::FUNCTION) return true; + auto &function = node->Cast(); + if (function.FunctionName() != "__sqlctx_pivot_cell" || function.GetArguments().size() != 1) { + return true; + } + auto value = function.GetArguments()[0].GetExpression().Copy(); + auto alias = node->GetAlias(); + Walk(value, [&](unique_ptr &child) { + if (child->GetExpressionClass() != ExpressionClass::WINDOW) return true; + auto &window = child->Cast(); + for (auto &call : calls) { + if (window.FunctionName() != call.marker_name) continue; + auto &partitions = cell_partitions[call.marker_name]; + for (auto &partition : window.Partitions()) partitions.push_back(partition->ToString()); + } + return false; + }); + node = std::move(value); + node->SetAlias(alias); + return true; + }); + }); + std::unordered_map caller_order_counts; + for (auto &call : calls) { + caller_order_counts.emplace(call.marker_name, 0); + } + SelectExpressions(owner, [&](unique_ptr &expression) { + Walk(expression, [&](unique_ptr &node) { + if (node->GetExpressionClass() == ExpressionClass::WINDOW) { + auto &window = node->Cast(); + auto entry = caller_order_counts.find(window.FunctionName().GetIdentifierName()); + if (entry != caller_order_counts.end()) { + entry->second = window.ArgOrders().size(); + } + } + return true; + }); + }); + vector plans; + Names cte_names; + for (auto &name : visible_ctes) { + cte_names.insert(Key(name)); + } + for (auto &entry : owner.cte_map.map) { + cte_names.insert(Key(entry.first.GetIdentifierName())); + } + for (idx_t i = 0; i < sources.size(); i++) { + plans.push_back(BuildSource(sources[i], calls, caller_order_counts, i, cte_names, options)); + } + vector scopes; + if (auto inherited = CurrentSqlctxMeasureCtes()) { + for (auto &scope : *inherited) scopes.push_back(scope.get()); + } + scopes.push_back(&owner); + for (auto &plan : plans) { + if (!ReplaceSource(owner.from_table, plan, scopes, options)) { + throw BinderException("Cannot locate measure window source %s in the query", plan.spec->relation_name); + } + } + WindowRewrite rewrite(owner, plans, calls, options, input_columns, cell_partitions); + auto output = rewrite.Run(); + for (auto &plan : plans) { + auto cte = make_uniq(); + cte->query_node = std::move(plan.base); + cte->materialized = CTEMaterialize::CTE_MATERIALIZE_ALWAYS; + output->cte_map.map.insert(Identifier(plan.base_name), std::move(cte)); + } + if (!visible_ctes.empty()) { + // This SELECT is spliced into a statement with an enclosing WITH. + // Keep the generated WITH inside a subquery rather than emitting two + // adjacent WITH clauses at the same query level. + auto wrapper = make_uniq(); + wrapper->select_list.push_back(make_uniq()); + wrapper->from_table = Subquery(std::move(output), "__ys_window_result"); + return wrapper->ToString(); + } + return output->ToString(); +} + +} // namespace duckdb +#endif diff --git a/sqlctx-duckdb/src/sqlctx_parser.cpp b/sqlctx-duckdb/src/sqlctx_parser.cpp index d6a520739..42a28cbe5 100644 --- a/sqlctx-duckdb/src/sqlctx_parser.cpp +++ b/sqlctx-duckdb/src/sqlctx_parser.cpp @@ -4,7 +4,9 @@ #include "sqlctx_measure_catalog.hpp" #include "sqlctx_definition_store.hpp" #include "sqlctx_api.hpp" -#include "sqlctx.h" +#include "sqlctx_compiler_api.hpp" +#include "sqlctx_aggregate_decorations.hpp" +#include "sqlctx_pivot.hpp" #include "sqlctx_warnings.hpp" #include "duckdb/catalog/catalog.hpp" @@ -1932,6 +1934,7 @@ unique_ptr CompileSemanticSelect(ClientContext &context, const Sqlctx throw BinderException("sqlctx rewrite must produce one SELECT statement"); } auto node = std::move(parser.statements[0]->Cast().node); + LowerSqlctxAggregateDecorations(context, *node); return node; } @@ -1968,6 +1971,7 @@ unique_ptr CompileSemanticStatement(ClientContext &context, SQLSta // A native VIEW validates but never executes its defining SELECT. Reject // strict warnings before publishing it; ordinary EXPLAIN remains inert. bool validate_view_warnings = IsExecutingViewDefinition(statement); + bool pivot = LowerSqlctxMeasurePivots(context, *query->node, snapshot); unique_ptr owned_models; if (!cached_models) owned_models = make_uniq(snapshot.payload); auto &models = cached_models ? *cached_models : owned_models->list; @@ -1991,7 +1995,7 @@ unique_ptr CompileSemanticStatement(ClientContext &context, SQLSta if (attached) QualifySqlctxSources(context, *subquery.node, relation.snapshot.catalog); } if (!found) { - if (relations.relations.empty() && !relations.changed) return nullptr; + if (relations.relations.empty() && !relations.changed && !pivot) return nullptr; // Only semantic relations: compile each derived table and leave the // rest of the statement, including DESCRIBE/SUMMARIZE, to DuckDB. UpdateCompiledViewSQL(*rewritten); @@ -2209,7 +2213,7 @@ void WrapQueryCarrier(SelectStatement &query, const string &source, const Parser if (source.empty()) return; RoutingReferences refs; refs.Query(*query.node); - if (!refs.Possible()) return; + if (!refs.Possible() && !RequiresSqlctxAggregateLowering(*query.node)) return; auto relation = make_uniq(); vector> arguments; #if SQLCTX_LITERAL_API @@ -2579,6 +2583,9 @@ unique_ptr BindQueryCarrier(ClientContext &context, TableFuncti : (input.inputs.size() > 1 ? input.inputs[1].GetValue() : ""), !compatibility); } auto state = context.registered_state->GetOrCreate(ROUTING_STATE, context); + if (auto query = QueryInStatement(*statement)) { + if (RequiresSqlctxAggregateLowering(*query->node)) LowerSqlctxAggregateDecorations(context, *query->node); + } auto compiled = state->Candidate(*statement); if (compiled) { statement = std::move(compiled); @@ -2685,6 +2692,7 @@ void SqlctxPreBind(PlannerExtensionInput &input, SQLStatement &statement) { CheckPeerMeasureCarriers(input.context, *query->node); } if (auto original = UnwrapQueryCarrier(*query)) query->node = std::move(original->node); + if (RequiresSqlctxAggregateLowering(*query->node)) LowerSqlctxAggregateDecorations(input.context, *query->node); } auto state = input.context.registered_state->GetOrCreate(ROUTING_STATE, input.context); auto compiled = state->Candidate(statement); @@ -2857,6 +2865,14 @@ class SqlctxConnectionCallback : public ExtensionCallback { } // namespace +unique_ptr CompileSqlctxPivotCells(ClientContext &context, unique_ptr query, + const SqlctxCatalogSnapshot &snapshot) { + SelectStatement statement; + statement.node = std::move(query); + auto compiled = CompileSemanticStatement(context, statement, snapshot); + return compiled ? std::move(compiled->Cast().node) : std::move(statement.node); +} + ParserOptions SqlctxContextParserOptions(ClientContext &context) { #if SQLCTX_NEW_IDENTIFIER_API auto options = SqlctxBuiltinParserOptions(); @@ -2885,7 +2901,7 @@ SqlctxPublicQueryPlan PlanSqlctxPublicQuery(ClientContext &context, const string vector reports; SqlctxCompileCallback compile = [&](const SqlctxCatalogSnapshot &snapshot, const string &query) { if (explain) { - auto result = sqlctx_snapshot_plan_explanation(snapshot.payload.c_str(), query.c_str()); + auto result = ExplainSqlctxHostSnapshot(snapshot.payload.c_str(), query.c_str()); string error = result.error ? result.error : ""; string compiled = result.sql ? result.sql : ""; if (result.report) reports.emplace_back(result.report); @@ -2894,7 +2910,7 @@ SqlctxPublicQueryPlan PlanSqlctxPublicQuery(ClientContext &context, const string if (compiled.empty()) throw InternalException("sqlctx returned no explained SQL"); return compiled; } - auto result = sqlctx_snapshot_rewrite(snapshot.payload.c_str(), query.c_str()); + auto result = RewriteSqlctxHostSnapshot(snapshot.payload.c_str(), query.c_str()); string error = result.error ? result.error : ""; string compiled = result.sql ? result.sql : ""; sqlctx_free_result(result); diff --git a/sqlctx-duckdb/src/sqlctx_pivot.cpp b/sqlctx-duckdb/src/sqlctx_pivot.cpp new file mode 100644 index 000000000..392ad852e --- /dev/null +++ b/sqlctx-duckdb/src/sqlctx_pivot.cpp @@ -0,0 +1,267 @@ +#include "sqlctx_pivot.hpp" +#include "sqlctx_aggregate_decorations.hpp" +#include "sqlctx_measure_catalog.hpp" +#include "sqlctx.h" + +#if SQLCTX_GRAMMAR_EXTENSION +#include "duckdb/parser/expression/columnref_expression.hpp" +#include "duckdb/parser/expression/function_expression.hpp" +#include "duckdb/parser/expression/star_expression.hpp" +#include "duckdb/parser/expression/subquery_expression.hpp" +#include "duckdb/parser/parsed_expression_iterator.hpp" +#include "duckdb/parser/query_node/set_operation_node.hpp" +#include "duckdb/parser/statement/select_statement.hpp" +#include "duckdb/parser/tableref/basetableref.hpp" +#include "duckdb/parser/tableref/joinref.hpp" +#include "duckdb/parser/tableref/pivotref.hpp" +#include "duckdb/parser/tableref/subqueryref.hpp" +#include "duckdb/planner/bound_statement.hpp" +#include "duckdb/planner/logical_operator.hpp" + +namespace duckdb { +namespace { +class PivotLowerer { +public: + explicit PivotLowerer(const SqlctxCatalogSnapshot &snapshot) : snapshot(snapshot) { + auto entries = sqlctx_snapshot_catalog(snapshot.payload.c_str(), "metric", "", nullptr); + if (entries.error) { + string error(entries.error); + sqlctx_free_catalog_entries(entries); + throw BinderException("sqlctx: %s", error); + } + for (idx_t i = 0; i < entries.count; ++i) { + auto &entry = entries.entries[i]; + if (entry.model_name && entry.name) measures[entry.model_name].insert(entry.name); + } + sqlctx_free_catalog_entries(entries); + } + + bool Query(QueryNode &query) { + auto inherited_scopes = scopes.size(); + vector> declarations; + bool changed = false; + for (auto &entry : query.cte_map.map) { + changed |= Query(*entry.second->query_node); + auto declaration = make_uniq(); + declaration->cte_map.map.insert(entry.first, entry.second->Copy()); + scopes.push_back(declaration.get()); + declarations.push_back(std::move(declaration)); + } + if (query.type == QueryNodeType::SELECT_NODE) { + auto &select = query.Cast(); + if (select.from_table) changed |= Table(*select.from_table); + } else if (query.type == QueryNodeType::SET_OPERATION_NODE) { + for (auto &child : query.Cast().children) changed |= Query(*child); + } + scopes.resize(inherited_scopes); + return changed; + } + +private: + const SqlctxCatalogSnapshot &snapshot; + case_insensitive_map_t measures; + vector scopes; + + bool IsMeasure(const TableRef &source, const Identifier &column, idx_t scope_limit, + pair *origin = nullptr) { + auto projection = [&](QueryNode &node, const vector &aliases, idx_t limit) { + if (node.type != QueryNodeType::SELECT_NODE) return false; + auto &select = node.Cast(); + if (!select.from_table) return false; + for (idx_t i = 0; i < select.select_list.size(); ++i) { + auto &expr = *select.select_list[i]; + if (aliases.empty() && expr.GetExpressionClass() == ExpressionClass::STAR) { + if (IsMeasure(*select.from_table, column, limit, origin)) return true; + } + auto name = i < aliases.size() ? aliases[i] : expr.GetName(); + if (name == column && expr.GetExpressionClass() == ExpressionClass::COLUMN_REF) { + return IsMeasure(*select.from_table, expr.Cast().GetColumnName(), limit, origin); + } + } + return false; + }; + if (source.type == TableReferenceType::SUBQUERY) { + return projection(*source.Cast().subquery->node, source.column_name_alias, scope_limit); + } + if (source.type != TableReferenceType::BASE_TABLE) return false; + auto &base = source.Cast(); + if (base.GetQualifiedName().Schema().empty()) { + for (idx_t i = scope_limit; i > 0; --i) { + auto found = scopes[i - 1]->cte_map.map.find(base.Table()); + if (found != scopes[i - 1]->cte_map.map.end()) { + return projection(*found->second->query_node, found->second->aliases, i - 1); + } + } + } + auto relation = make_uniq(); + relation->SetQualifiedName(base.GetQualifiedName()); + auto key = ResolveSqlctxCatalogModel(*CurrentSqlctxMeasureContext(), snapshot, relation->ToString()); + auto found = measures.find(key); + bool measure = found != measures.end() && found->second.count(column.GetIdentifierName()); + if (measure && origin) *origin = {key, column}; + return measure; + } + + bool Table(TableRef &table) { + if (table.type == TableReferenceType::SUBQUERY) return Query(*table.Cast().subquery->node); + if (table.type == TableReferenceType::JOIN) { + auto &join = table.Cast(); + bool changed = Table(*join.left); + return Table(*join.right) || changed; + } + if (table.type != TableReferenceType::PIVOT) return false; + auto &pivot = table.Cast(); + bool changed = Table(*pivot.source); + bool measure = false; + // VisitExpressionClass stops at its first matching node. Measures can + // occur below scalar arithmetic and AT function-shaped syntax nodes. + std::function find_measure; + find_measure = [&](const ParsedExpression &expr) { + if (expr.GetExpressionClass() == ExpressionClass::FUNCTION) { + auto &function = expr.Cast(); + measure |= function.FunctionName() == "aggregate" && function.GetArguments().size() == 1; + } + ParsedExpressionIterator::EnumerateChildren(expr, find_measure); + }; + for (auto &aggregate : pivot.aggregates) find_measure(*aggregate); + if (!measure) { + // An ordinary PIVOT may consume an explicitly evaluated measure + // query. Compile that input before DuckDB binds SUM/FIRST over it. + auto inspect = [&](unique_ptr &expr) { find_measure(*expr); }; + ParsedExpressionIterator::EnumerateTableRefChildren(*pivot.source, inspect); + for (auto *scope : scopes) ParsedExpressionIterator::EnumerateQueryNodeChildren(*scope, inspect); + if (!measure) return changed; + auto input = make_uniq(); + input->select_list.push_back(make_uniq()); + input->from_table = pivot.source->Copy(); + CopyScopes(*input); + auto query = make_uniq(); + query->node = CompileSqlctxPivotCells(*CurrentSqlctxMeasureContext(), std::move(input), snapshot); + pivot.source = make_uniq(std::move(query), Identifier("__sqlctx_pivot_input")); + return true; + } + Stage(pivot); + return true; + } + + void CopyScopes(QueryNode &query) { + for (auto *scope : scopes) { + for (auto &entry : scope->cte_map.map) { + auto found = query.cte_map.map.find(entry.first); + if (found == query.cte_map.map.end()) query.cte_map.map.insert(entry.first, entry.second->Copy()); + else found->second = entry.second->Copy(); + } + } + } + + void Stage(PivotRef &pivot) { + auto probe = make_uniq(); + probe->from_table = pivot.source->Copy(); + probe->select_list.push_back(make_uniq()); + auto bound = BindSqlctxMeasureProbe(*probe, scopes); + string prefix = "__sqlctx_pivot_"; + for (auto &name : bound.names) { + while (StringUtil::StartsWith(name.GetIdentifierName(), prefix)) prefix += "_"; + } + case_insensitive_set_t consumed; + auto consume = [&](const ParsedExpression &expr) { + ParsedExpressionIterator::VisitExpressionClass(expr, ExpressionClass::COLUMN_REF, + [&](const ParsedExpression &child) { + consumed.insert(child.Cast().GetColumnName().GetIdentifierName()); + }); + }; + for (auto &column : pivot.pivots) for (auto &expr : column.pivot_expressions) consume(*expr); + for (auto &expr : pivot.aggregates) consume(*expr); + if (pivot.groups.empty()) { + for (auto &name : bound.names) { + if (!consumed.count(name.GetIdentifierName()) && !IsMeasure(*pivot.source, name, scopes.size())) { + pivot.groups.push_back(name); + } + } + } + auto stage = make_uniq(); + stage->from_table = pivot.source->Copy(); + if (stage->from_table->type == TableReferenceType::SUBQUERY && stage->from_table->alias.empty()) { + stage->from_table->alias = Identifier(prefix + "input"); + } + stage->modifiers.push_back(make_uniq()); + // Copy lexical CTE definitions into this independently compiled query. + // Later scopes shadow earlier declarations, as they do in DuckDB. + CopyScopes(*stage); + vector partitions; + for (auto &group : pivot.groups) { + stage->select_list.push_back(make_uniq(group)); + partitions.push_back(make_uniq(group)->ToString()); + } + idx_t key_index = 0; + for (auto &column : pivot.pivots) { + for (auto &expr : column.pivot_expressions) { + auto key = Identifier(prefix + "key_" + to_string(key_index++)); + partitions.push_back(expr->ToString()); + auto projected = expr->Copy(); + projected->SetAlias(key); + stage->select_list.push_back(std::move(projected)); + expr = make_uniq(key); + } + } + auto window = partitions.empty() ? " OVER ()" : + " OVER (PARTITION BY " + StringUtil::Join(partitions, ", ") + ")"; + std::function &)> window_aggregates; + window_aggregates = [&](unique_ptr &expr) { + if (expr->GetExpressionClass() == ExpressionClass::FUNCTION) { + auto &function = expr->Cast(); + auto name = function.FunctionName().GetIdentifierName(); + bool measure = StringUtil::CIEquals(name, "aggregate") && function.GetArguments().size() == 1; + // AT is a parser node, not a registered aggregate. Its operand + // becomes the window; the modifier stays outside that window. + if (measure || (name != "__sqlctx_at" && IsSqlctxMeasureAggregate(name))) { + if (measure) { + auto &arg = function.GetArgumentsMutable()[0].GetExpressionMutable(); + pair origin; + if (arg->GetExpressionClass() == ExpressionClass::COLUMN_REF && + IsMeasure(*pivot.source, arg->Cast().GetColumnName(), scopes.size(), &origin)) { + arg = make_uniq(origin.second, Identifier(origin.first)); + } + } + auto parsed = ParseSqlctxMeasureExpressions(expr->ToString() + window); + expr = std::move(parsed[0]); + return; + } + } + ParsedExpressionIterator::EnumerateChildren(*expr, window_aggregates); + }; + for (idx_t i = 0; i < pivot.aggregates.size(); ++i) { + auto &expr = pivot.aggregates[i]; + bool named = expr->HasAlias() || pivot.aggregates.size() > 1; + auto alias = expr->HasAlias() ? expr->GetAlias() : Identifier(expr->ToString()); + auto value = Identifier(prefix + "value_" + to_string(i)); + auto projected = expr->Copy(); + projected->ClearAlias(); + window_aggregates(projected); + vector> cell_arguments; + cell_arguments.push_back(std::move(projected)); + auto cell = make_uniq(Identifier("__sqlctx_pivot_cell"), std::move(cell_arguments)); + cell->SetAlias(value); + stage->select_list.push_back(std::move(cell)); + vector> arguments; + arguments.push_back(make_uniq(value)); + expr = make_uniq(Identifier("first"), std::move(arguments)); + if (named) expr->SetAlias(alias); + } + auto query = make_uniq(); + query->node = CompileSqlctxPivotCells(*CurrentSqlctxMeasureContext(), std::move(stage), snapshot); + pivot.source = make_uniq(std::move(query), Identifier(prefix + "cells")); + } +}; +} + +bool LowerSqlctxMeasurePivots(ClientContext &context, QueryNode &query, const SqlctxCatalogSnapshot &snapshot) { + SqlctxMeasureBindScope scope(context); + return PivotLowerer(snapshot).Query(query); +} +} +#else +namespace duckdb { +bool LowerSqlctxMeasurePivots(ClientContext &, QueryNode &, const SqlctxCatalogSnapshot &) { return false; } +} +#endif diff --git a/sqlctx-duckdb/src/sqlctx_warnings.cpp b/sqlctx-duckdb/src/sqlctx_warnings.cpp index c9d53984b..89d0aa6bc 100644 --- a/sqlctx-duckdb/src/sqlctx_warnings.cpp +++ b/sqlctx-duckdb/src/sqlctx_warnings.cpp @@ -1,6 +1,6 @@ #include "sqlctx_warnings.hpp" #include "sqlctx_parser.hpp" -#include "sqlctx.h" +#include "sqlctx_compiler_api.hpp" #include "duckdb/common/vector_operations/unary_executor.hpp" #include "duckdb/execution/expression_executor_state.hpp" @@ -42,7 +42,7 @@ string WrapSqlctxQueryWarnings(const string &query_sql, const string &warnings) string CompileSqlctxWithWarnings(const SqlctxCatalogSnapshot &snapshot, const string &sql, string *collected_warnings, bool wrap_runtime_warnings) { - auto result = sqlctx_snapshot_rewrite_with_warnings(snapshot.payload.c_str(), sql.c_str()); + auto result = RewriteSqlctxHostSnapshotWithWarnings(snapshot.payload.c_str(), sql.c_str()); string compiled = result.sql ? result.sql : ""; string warnings = result.warnings ? result.warnings : ""; string error = result.error ? result.error : ""; diff --git a/sqlctx-duckdb/test/test_measure_ergonomics_host.py b/sqlctx-duckdb/test/test_measure_ergonomics_host.py new file mode 100644 index 000000000..d2c666eb4 --- /dev/null +++ b/sqlctx-duckdb/test/test_measure_ergonomics_host.py @@ -0,0 +1,137 @@ +"""Public measure field names and context-dimension diagnostics.""" + +import json + +import pytest +from test_catalog_host import execute as execute_host +from test_catalog_host import literal + +SETUP = """ +create table sales(region varchar, amount integer); +insert into sales values ('east', 10), ('west', 20), ('west', 30); +create view sales_v as select region, sum(amount) as measure revenue from sales; +""" + + +def execute(*args, **kwargs): + results = execute_host(*args, **kwargs) + # The legacy CLI serializes HUGEINT sums as strings. + for rows in results: + for row in rows: + for name in ("revenue", "revenue_2", "revenue_3", "Gross revenue"): + if isinstance(row.get(name), str): + row[name] = int(row[name]) + return results + + +@pytest.fixture(scope="module") +def native_measure_grammar(): + return execute("select version() as v", setup="")[0][0]["v"].startswith("v2") + + +@pytest.mark.parametrize( + ("target", "error"), + [ + ("nope", "Unknown dimension 'nope'"), + ("s.nope", "measure view sales_v has no field 'nope'. Did you mean region? Fields: region, revenue"), + ("upper(nope)", "Unknown dimension 'nope'"), + ], +) +def test_unknown_all_dimension_is_an_error(target, error, native_measure_grammar): + if not native_measure_grammar: + pytest.skip("Native AT syntax requires DuckDB 2") + execute( + f"select region, aggregate(revenue) at (all {target}) from sales_v s group by region;", + setup=SETUP, + error=error, + error_excludes=("__sqlctx_view_",), + ) + + +@pytest.mark.parametrize("reference", ["sales_v.nope", "s.nope"]) +def test_unknown_qualified_measure_fields_use_public_relation_names(reference): + alias = " s" if reference.startswith("s.") else "" + execute( + f"select {reference} from sales_v{alias};", + setup=SETUP, + error="measure view sales_v has no field 'nope'. Did you mean region? Fields: region, revenue", + error_excludes=("__sqlctx_view_",), + ) + + +def test_all_dimension_accepts_group_alias_and_formula(native_measure_grammar): + if not native_measure_grammar: + pytest.skip("Native AT syntax requires DuckDB 2") + results = execute( + """ + select region as area, aggregate(revenue) at (all area) from sales_v order by area; + select upper(region) as area, aggregate(revenue) at (all upper(region)) from sales_v order by area; + with scoped as (select * from sales_v) + select region, aggregate(revenue) at (all region) from scoped order by region; + """, + setup=SETUP, + ) + assert results == [ + [{"area": "east", "revenue": 60}, {"area": "west", "revenue": 60}], + [{"area": "EAST", "revenue": 60}, {"area": "WEST", "revenue": 60}], + [{"region": "east", "revenue": 60}, {"region": "west", "revenue": 60}], + ] + + +def test_direct_measure_names_are_short_and_explicit_aliases_survive(native_measure_grammar): + repeated = "aggregate(revenue) at (all)" if native_measure_grammar else "aggregate(revenue)" + results = execute( + f""" + select aggregate(revenue) from sales_v; + select aggregate(revenue), {repeated}, aggregate(revenue) as revenue from sales_v; + select aggregate(revenue) as "Gross revenue" from sales_v; + """, + setup=SETUP, + ) + assert results == [ + [{"revenue": 60}], + [{"revenue_2": 60, "revenue_3": 60, "revenue": 60}], + [{"Gross revenue": 60}], + ] + + +def test_at_support_matches_the_host_grammar(native_measure_grammar): + sql = "select aggregate(revenue) at (all) from sales_v" + for query in (sql + ";", f"select * from yardstick({literal(sql)});"): + if native_measure_grammar: + assert execute(query, setup=SETUP) == [[{"revenue": 60}]] + else: + execute(query, setup=SETUP, error="Parser Error: syntax error at or near") + + +def test_window_measure_names_and_unknown_context_dimension(native_measure_grammar): + if not native_measure_grammar: + pytest.skip("Native measure windows require DuckDB 2") + assert execute("select distinct aggregate(revenue) over () from sales_v;", setup=SETUP) == [[{"revenue": 60}]] + execute( + "select aggregate(revenue) over () at (all nope) from sales_v;", + setup=SETUP, + error="Unknown dimension 'nope'", + ) + + +@pytest.mark.parametrize("route", ["direct", "yardstick", "rewrite", "explain"]) +def test_native_measure_helper_capability_matches_host(route, native_measure_grammar): + # Route through the compiler on both pins. The legacy binder checks FILTER + # on the physical view before SQLCtx can handle its unqualified name. + query = "select aggregate(revenue) filter (where region = 'west') as revenue from semantic.sales_v" + if route == "yardstick": + query = f"select * from yardstick({literal(query)})" + elif route == "rewrite": + query = f"select sqlctx_rewrite_sql({literal(query)}) as sql" + elif route == "explain": + query = f"select sqlctx_explain({literal(query)}) as plan" + if not native_measure_grammar: + execute(query, setup=SETUP, error="requires a DuckDB host with native measure helpers enabled") + else: + result = execute(query, setup=SETUP) + if route in ("direct", "yardstick"): + assert result == [[{"revenue": 50}]] + else: + sql = result[0][0]["sql"] if route == "rewrite" else json.loads(result[0][0]["plan"])["sql"] + assert "__sqlctx_decorated_measure" not in sql.lower() diff --git a/sqlctx-duckdb/test/test_measure_view_lifecycle_host.py b/sqlctx-duckdb/test/test_measure_view_lifecycle_host.py index eeeade34d..d20894136 100644 --- a/sqlctx-duckdb/test/test_measure_view_lifecycle_host.py +++ b/sqlctx-duckdb/test/test_measure_view_lifecycle_host.py @@ -53,6 +53,38 @@ def test_direct_measure_survives_prepare_and_ordinary_view_reopen(tmp_path): assert execute("select * from totals;", setup="", database=database) == [[{"aov": 40}]] +def test_ordinary_view_does_not_replay_definition_warnings(tmp_path): + database = tmp_path / "warnings.duckdb" + version = execute("select version() as version", setup="")[0][0]["version"] + definition = """ + create view totals as + select region, aggregate(revenue) at (all region) as total + from sales where year = 2023 group by region; + """ + if version.startswith("v1."): + # The legacy host has no native AT grammar. Its supported warning + # transport must have the same definition-time persistence boundary. + definition = """ + create view totals as select * from yardstick( + 'select region, aggregate(revenue) as total from sales group by region', + 'measure definition warning' + ); + """ + execute( + definition, + setup=""" + set enable_logging = false; + create table raw_sales(year integer, region varchar, amount integer); + insert into raw_sales values (2023, 'west', 10), (2023, 'east', 30), (2024, 'west', 80); + create view sales as select year, region, sum(amount) as measure revenue from raw_sales; + """, + database=database, + ) + assert execute( + "set warnings_as_errors = true; select count(*) as rows from totals;", setup="", database=database + ) == [[{"rows": 2}]] + + @pytest.mark.parametrize("reference", ["aov", "plain.aov"]) def test_ordinary_view_cannot_recompute_a_projected_measure(reference): execute( diff --git a/sqlctx-duckdb/test/test_public_helper_aliases_host.py b/sqlctx-duckdb/test/test_public_helper_aliases_host.py new file mode 100644 index 000000000..95ac0e1dc --- /dev/null +++ b/sqlctx-duckdb/test/test_public_helper_aliases_host.py @@ -0,0 +1,85 @@ +"""SQLCtx helper names execute the same catalog-aware paths as compatibility names.""" + +import pytest +from test_catalog_host import execute, literal + +SETUP = """ +create table facts(region varchar, amount integer); +insert into facts values ('east', 10), ('west', 20), ('west', 30); +create view sales_v as select region, sum(amount) as measure revenue from facts; +""" + + +@pytest.mark.parametrize("function", ["sqlctx_query", "sqlctx_query_scoped"]) +def test_public_query_helpers_compile_measure_sql_in_the_current_transaction(function): + query = literal("select region, aggregate(revenue)::bigint as total from sales_v order by region") + results = execute( + f""" + begin; + insert into facts values ('east', 5); + select * from {function}({query}); + rollback; + select * from {function}({query}); + """, + setup=SETUP, + ) + assert results == [ + [{"region": "east", "total": 15}, {"region": "west", "total": 50}], + [{"region": "east", "total": 10}, {"region": "west", "total": 50}], + ] + + +def test_query_and_warning_aliases_preserve_warning_policy(): + assert execute("select sqlctx_warning('') as ok;", setup="") == [[{"ok": True}]] + execute( + "set warnings_as_errors=true; select sqlctx_warning('public warning');", + setup="", + error="public warning", + ) + execute( + "set warnings_as_errors=true; select * from sqlctx_query('select 1 as value', 'query warning');", + setup="", + error="query warning", + ) + + +def test_state_aliases_interoperate_with_compatibility_states(): + if not execute("select version() as v", setup="")[0][0]["v"].startswith("v2"): + pytest.skip("Exported measure states require DuckDB 2") + results = execute( + """ + create table states as + select region, sqlctx_state('s0 / s1', struct_pack( + s0 := sum(amount) export_state, s1 := count(*) export_state)) as state + from facts group by region; + select sqlctx_finalize(sqlctx_combine(a.state, b.state)) as average + from states a, states b where a.region='east' and b.region='west'; + select yardstick_finalize(state) as average from states where region='west'; + select sqlctx_finalize(yardstick_state('s0', struct_pack(s0 := sum(amount) export_state)))::bigint as total from facts; + """, + setup=SETUP, + ) + assert results[-3:] == [[{"average": 20}], [{"average": 25}], [{"total": 60}]] + + +def test_public_helper_metadata_exposes_named_arguments_and_examples(): + native = execute("select version() as v", setup="")[0][0]["v"].startswith("v2") + names = ["sqlctx_query", "sqlctx_query_scoped", "sqlctx_warning"] + if native: + names += ["sqlctx_state", "sqlctx_finalize", "sqlctx_combine"] + rows = execute( + f""" + select function_name, parameters = ['sql'] as sql_only, + parameters = ['sql', 'warnings'] as sql_with_warnings, + len(parameters) as parameter_count, description, len(examples) as example_count + from duckdb_functions() where function_name in ({",".join(literal(name) for name in names)}) + order by function_name, array_length(parameters); + """, + setup="", + )[0] + assert {row["function_name"] for row in rows} == set(names) + assert [(row["sql_only"], row["sql_with_warnings"]) for row in rows if row["function_name"] == "sqlctx_query"] == [ + (True, False), + (False, True), + ] + assert all(row["description"] and row["example_count"] > 0 and row["parameter_count"] > 0 for row in rows)