diff --git a/sqlctx-duckdb/CMakeLists.txt b/sqlctx-duckdb/CMakeLists.txt index 43a5e0901..656528e46 100644 --- a/sqlctx-duckdb/CMakeLists.txt +++ b/sqlctx-duckdb/CMakeLists.txt @@ -185,7 +185,8 @@ add_custom_target(sqlctx_rust_staticlib DEPENDS "${SQLCTX_LIB}") # Include Rust library headers include_directories(${SQLCTX_INCLUDE}) -set(EXTENSION_SOURCES src/sqlctx_extension.cpp src/sqlctx_parser.cpp src/sqlctx_grammar.cpp src/sqlctx_catalog.cpp src/sqlctx_api.cpp src/sqlctx_discovery.cpp src/sqlctx_semantic_input.cpp src/sqlctx_explain.cpp) +set(EXTENSION_SOURCES src/sqlctx_extension.cpp src/sqlctx_parser.cpp src/sqlctx_grammar.cpp src/sqlctx_catalog.cpp src/sqlctx_api.cpp src/sqlctx_discovery.cpp src/sqlctx_semantic_input.cpp src/sqlctx_explain.cpp src/sqlctx_warnings.cpp src/sqlctx_measure_catalog.cpp) + build_static_extension(${TARGET_NAME} ${EXTENSION_SOURCES}) build_loadable_extension(${TARGET_NAME} " " ${EXTENSION_SOURCES}) diff --git a/sqlctx-duckdb/README.md b/sqlctx-duckdb/README.md index 2b047401d..9b0bb2225 100644 --- a/sqlctx-duckdb/README.md +++ b/sqlctx-duckdb/README.md @@ -16,12 +16,12 @@ A DuckDB extension that adds a SQL-first semantic layer. Define metrics and dime ## Installation -Build locally against DuckDB 2.0.1: +From the `sqlctx-duckdb` directory, build against DuckDB 2.0.1: ```bash make deps DUCKDB_VERSION=v2.0.1 -make -SQLCTX_NATIVE_PEG=1 make test +make DUCKDB_VERSION=v2.0.1 +SQLCTX_NATIVE_PEG=1 make test DUCKDB_VERSION=v2.0.1 ./build/release/duckdb -unsigned -cmd "LOAD '$PWD/build/release/extension/sqlctx/sqlctx.duckdb_extension';" ``` @@ -43,29 +43,23 @@ Semantic queries use ordinary `SELECT`, including in shells that preload Define your semantic layer entirely in SQL, no YAML required: ```sql --- 1. Create your data table +-- Create your data table CREATE TABLE orders (order_id INT, status VARCHAR, amount DECIMAL(10,2)); INSERT INTO orders VALUES (1, 'completed', 100.00), (2, 'completed', 150.00), (3, 'pending', 75.00); --- 2. Define a semantic model -MODEL ( - name orders_model, - table orders, - primary_key order_id +-- Keep the dimensions and their metrics together in one definition. +MODEL orders_model FROM orders ( + primary key (order_id) + status + sum(amount) AS revenue + count(*) AS order_count + avg(amount) AS avg_order_value ); --- 3. Define metrics (aggregations) -METRIC revenue AS SUM(amount); -METRIC order_count AS COUNT(*); -METRIC avg_order_value AS AVG(amount); - --- 4. Define dimensions (grouping attributes) -DIMENSION (name status, type categorical); - --- 5. Query using semantic layer: revenue is summed per status +-- Selecting status gives one total per status. SELECT orders_model.status, orders_model.revenue FROM orders_model ORDER BY 1; -- ┌───────────┬───────────────┐ @@ -88,10 +82,73 @@ Released Ossie `0.1.1` and flat `0.3.0.dev0` logical models load through `select total_sales from metrics` for the upstream TPC-DS model. [Ossie file examples and supported draft semantics](../docs/duckdb-extension.md#ossie-files) +### Choose a definition + +| What you want to publish | SQL | What a later query sees | +| --- | --- | --- | +| A model with keys, relationships and business metrics | `MODEL` | Dimensions and metrics through `semantic.model_name`. The selected dimensions determine grouping. | +| Measures directly over the rows of a table, join or subquery | `CREATE VIEW … AS SELECT … AS MEASURE …` | A DuckDB view with measures that SQLCtx can recompute. Use `AGGREGATE(metric)` for the caller's filtered population. | +| A named selection of model fields | `CREATE SEMANTIC VIEW … AS SELECT …` | A live projection that follows changes to the underlying metric. Manage it with `DROP SEMANTIC VIEW`. | +| The result of a fixed semantic query | Ordinary `CREATE VIEW … AS SELECT …` | DuckDB stores the compiled query. Recreate the view to pick up a changed metric definition. | + +### Define measures directly on rows + +With only `sqlctx` loaded, use `AS MEASURE` to declare an aggregate over a +table, join or subquery. Other named projections become dimensions. For example: + +```sql +LOAD sqlctx; +CREATE TABLE regional_orders(region VARCHAR, amount INTEGER); +INSERT INTO regional_orders VALUES ('west', 10), ('west', 30), ('east', 80); + +CREATE VIEW yard_sales AS +SELECT region, avg(amount) AS MEASURE aov FROM regional_orders; + +SELECT region, aggregate(aov) AS aov FROM yard_sales ORDER BY region; +-- east 80, west 20 +SELECT aggregate(aov) AS aov FROM yard_sales; +-- 40 across the three source rows + +SELECT aggregate(aov) AS west_aov, aov AS overall_aov +FROM yard_sales WHERE region = 'west'; +-- west_aov = 20, overall_aov = 40 +``` + +Use `AGGREGATE(aov)` when a caller's `WHERE` should filter the rows used to +compute the measure. A bare `aov` uses the dimensions in the query for grouping +and evaluates the measure over its declared source. In a dashboard, removing +`region` from a West-only table to make a single KPI changes bare `aov` from 20 +to 40. `AGGREGATE(aov)` stays at 20 in both layouts. For BI clients that only +emit ordinary field references, publish the metric on a `MODEL` and connect to +`semantic.model_name` so dimension filters apply before aggregation. + +If a BI tool emits `SUM(revenue)` for a measure declared as `SUM(amount)`, +SQLCtx sums the underlying amounts once at the requested grain. For an average +or ratio, use `AGGREGATE(aov)`. To average a set of regional results, first +compute one row per region in a subquery and then apply `AVG` to its output. + +The declaration creates a DuckDB view with a SQLCtx measure definition. Run +`SHOW METRICS FROM yard_sales` to inspect it. Use `CREATE OR REPLACE VIEW` to +update its definition and `DROP VIEW yard_sales` to remove it. + +Opening a database without SQLCtx still lets DuckDB describe the view. Selecting +a virtual measure raises an error directing the reader to load SQLCtx. For views +created by an earlier development build that stored virtual measures as `NULL`, +rerun the original `CREATE OR REPLACE VIEW` declaration once to update the stored SQL. + +A declaration can use a qualified view name, an explicit column-name list or +`SELECT *`. `WHERE` filters the source rows. A view can expose grouped rows +while retaining the original inputs used to recompute a measure at another +grain, for example a distinct customer count across regions. +When Yardstick is also loaded, its parser handles its measure declarations. +For an existing SQLCtx measure view in that configuration, select the metric +directly (`SELECT region, aov FROM yard_sales`) so SQLCtx evaluates it. + ## Discover and manage definitions ```sql SHOW MODELS; +SHOW SEMANTIC VIEWS; SHOW METRICS FROM orders_model; SHOW DIMENSIONS FROM orders_model; SHOW RELATIONSHIPS FROM orders_model; @@ -115,6 +172,9 @@ the JSON definition. Definition statements and file loads report what they created, replaced or dropped. `DESCRIBE MODEL` includes the model and all its fields. `SHOW DIMENSIONS FOR` checks each dimension with the query compiler; use `EXPLAIN SELECT` to validate a complete combination of metrics and dimensions. +Segments can be selected by qualified name in a SemanticInput query's +`segments` array. In ordinary SQL, use a `WHERE` predicate on the model +dimensions. `SHOW SEGMENTS FROM model_name` displays each segment's SQL. `SHOW SEMANTIC METRICS`, and the corresponding forms for other kinds, are also accepted. @@ -148,6 +208,10 @@ DESCRIBE semantic.orders_model; one row per distinct combination of all dimensions. - `WHERE` predicates that read only one relation's dimensions filter the model before grouping and do not add to the grain. +- A predicate on a metric compares the computed value at the query grain. + For example, `SELECT status, revenue FROM semantic.orders_model WHERE revenue > 100` + keeps statuses whose total revenue exceeds 100. To filter individual orders + before summing, put a predicate on the source rows or in the metric definition. - Aggregating a metric again is allowed when each group holds one row of the relation, or when the aggregation composes: `sum` of a `sum` or `count` metric, `min` of `min`, `max` of `max`. Other cases, such as `avg` of a ratio @@ -202,6 +266,9 @@ for attached catalogs and ordinary DuckDB views. ## Versioned SemanticInput +The DuckDB functions default a missing `input_dialect` to `"duckdb"`. +For imported definitions, set it to the dialect used to write the model expressions. + The table function `sqlctx_query_semantic_input(input_json, query_json)` accepts the same SemanticInput v1 contract as the Python and WASM hosts and returns its query result directly. Its columns and types follow the requested metrics and @@ -374,7 +441,8 @@ import/export and explicit semantic queries, including nested `PREPARE` and `EXP still use the shared Rust configuration parser; semantic query compilation still uses the Rust SQL AST. -Loading sqlctx enables automatic routing, including a planning hook for +Loading sqlctx sets DuckDB's `allow_parser_override_extension` setting to +`fallback` and enables automatic routing, including a planning hook for hosts with another parser override. To explicitly compose the native grammar with other installed grammars, include it in `active_grammar_extensions`: @@ -612,9 +680,8 @@ rows, including equal-valued metrics on distinct customers. - Semantic definitions support creation, replacement, loading, discovery, export/import, active-model selection and dependency-restricted removal. Use `CREATE OR REPLACE` to update definitions; there is no `ALTER MODEL` syntax. -- Semantic queries support a subset of DuckDB SQL. Correlated semantic subqueries - and grouping modifiers such as `ROLLUP` are rejected; explicit `GROUP BY` must - repeat the selected semantic dimensions. +- In the model query compiler, explicit `GROUP BY` must repeat the selected + semantic dimensions. - Native execution tests cover derived, ratio, cumulative, time-comparison, conversion, retention, and cohort metrics. Retention produces a table with cohort date, elapsed periods, active users, cohort size, and retention percentage; @@ -629,6 +696,18 @@ rows, including equal-valued metrics on distinct customers. ## Utility Functions +For interactive SQL, start with `SHOW MODELS`, `SHOW METRICS FROM model_name` and +`EXPLAIN SELECT`. Applications can use `sqlctx_models()` to get one model name per row, +and the `sqlctx_*_semantic_input` entry points to submit a model and query together. + +Use `sqlctx_query(sql)` or `sqlctx_query_scoped(sql)` to run measure SQL supplied +as a string. The compatibility spellings are `yardstick` and `yardstick_scoped`. +`sqlctx_warning(message)` reports a warning. Enable `warnings_as_errors` to raise +an error instead. +To keep measure definitions in a +specific catalog table (including DuckLake), set `yardstick_definition_table` to a +fully qualified `catalog.schema.table` name before creating the views. + `sqlctx_explain(sql)` returns a JSON report from the same Rust compiler and current catalog snapshot used by `sqlctx_rewrite_sql`: @@ -663,7 +742,7 @@ Manually rewrite a SQL query (useful for debugging). ```sql SELECT sqlctx_rewrite_sql('SELECT orders.revenue FROM orders'); --- Returns: SELECT SUM(orders.amount) FROM orders +-- Returns the executable SQL that computes revenue at the requested grain. ``` ## How It Works diff --git a/sqlctx-duckdb/docs/README.md b/sqlctx-duckdb/docs/README.md index e39ce8ec0..9a492c7ce 100644 --- a/sqlctx-duckdb/docs/README.md +++ b/sqlctx-duckdb/docs/README.md @@ -1,99 +1,18 @@ -# sqlctx DuckDB Extension Documentation - -## Overview - -sqlctx is a DuckDB extension that provides a SQL-first semantic layer. It allows you to define business metrics and dimensions once, then query them with automatic SQL generation. - -## Core Concepts - -### Models -A model maps to a physical table and defines: -- **Dimensions**: Attributes for grouping and filtering (categorical, time, boolean, numeric) -- **Metrics**: Aggregations like sum, count, avg, min, max -- **Relationships**: Joins to other models -- **Segments**: Reusable named filters - -### Query Rewriting -When you write: -```sql -SEMANTIC SELECT orders.revenue, orders.status FROM orders -``` - -sqlctx rewrites it to: -```sql -SELECT SUM(orders.amount), orders.status FROM orders GROUP BY 2 -``` - -## API Reference - -### Table Functions - -#### `sqlctx_load(yaml VARCHAR) -> TABLE(result VARCHAR)` -Loads semantic model definitions from a YAML string. - -**Parameters:** -- `yaml`: YAML string containing model definitions - -**Returns:** Single row with success message - -**Example:** -```sql -SELECT * FROM sqlctx_load(' -models: - - name: orders - table: orders - primary_key: order_id - dimensions: - - name: status - type: categorical - metrics: - - name: revenue - agg: sum - sql: amount -'); -``` - -#### `sqlctx_models() -> TABLE(model_name VARCHAR)` -Lists all currently loaded semantic models. - -**Returns:** One row per loaded model - -**Example:** -```sql -SELECT * FROM sqlctx_models(); --- ┌────────────┐ --- │ model_name │ --- ├────────────┤ --- │ orders │ --- │ customers │ --- └────────────┘ -``` - -### Scalar Functions - -#### `sqlctx_rewrite_sql(sql VARCHAR) -> VARCHAR` -Rewrites a SQL query using semantic definitions without executing it. - -**Parameters:** -- `sql`: SQL query string to rewrite - -**Returns:** Rewritten SQL string - -**Example:** -```sql -SELECT sqlctx_rewrite_sql('SELECT orders.revenue FROM orders'); --- Returns: SELECT SUM(orders.amount) FROM orders -``` - -### Parser Extension - -#### `SEMANTIC` Keyword -Prefix any SELECT statement with `SEMANTIC` to trigger automatic query rewriting. - -**Example:** -```sql -SEMANTIC SELECT orders.revenue, orders.status FROM orders; -``` +# SQLCtx DuckDB extension reference + +Start with the [DuckDB quick start](../README.md#quick-start-pure-sql) for an +executable model and measure queries. The [definition guide](../README.md#choose-a-definition) +covers models, measure views, reusable semantic views and ordinary DuckDB views. + +| Task | Reference | +| --- | --- | +| Install or build the matching extension | [Installation](../README.md#installation) | +| Load SQL, native YAML, Cube or Ossie definitions | [Definition files](../README.md#alternative-definition-files) | +| Inspect measures, compatible dimensions and relationships | [Catalog discovery](../README.md#discover-and-manage-definitions) | +| Understand grouping and filter context | [Measures over rows](../README.md#define-measures-directly-on-rows) | +| Inspect a compiled query | [Explain and rewrite](../README.md#utility-functions) | +| Persist definitions, query attachments or use a BI client | [DuckDB guide](../../docs/duckdb-extension.md) | +| Submit a versioned query from an application | [SemanticInput](../README.md#versioned-semanticinput) | ## YAML Schema @@ -159,36 +78,3 @@ cubes: - name: string sql: string # Use ${CUBE} for table reference ``` - -## Building - -### Prerequisites -- Rust toolchain (for sqlctx-rs) -- CMake 3.5+ -- C++11 compiler - -### Build Steps - -```bash -# 1. Build the Rust library -cd sqlctx-rs -cargo build --release - -# 2. Build the DuckDB extension -cd sqlctx-duckdb -git submodule update --init --recursive -make - -# 3. Run tests -make test -``` - -### Output Files -- `build/release/duckdb` - DuckDB shell with extension -- `build/release/unittest` - Test runner - -## Limitations - -- Parser extension requires `SEMANTIC` keyword prefix (DuckDB's parser handles valid SQL first) -- Single-statement queries only -- State is global (models persist across queries in same session) diff --git a/sqlctx-duckdb/src/include/sqlctx_catalog.hpp b/sqlctx-duckdb/src/include/sqlctx_catalog.hpp index 2462d469d..6e4a89c9f 100644 --- a/sqlctx-duckdb/src/include/sqlctx_catalog.hpp +++ b/sqlctx-duckdb/src/include/sqlctx_catalog.hpp @@ -6,21 +6,28 @@ namespace duckdb { class QueryNode; +struct SqlctxDefinitionStore; struct SqlctxCatalogSnapshot { string payload; string active_model; string catalog; + shared_ptr definitions; + // Public discovery names for compiler-only measure-view identities. + case_insensitive_map_t measure_names; }; // Resolve definitions against the caller's current catalog transaction. Legacy // sidecars are read only when no native snapshot exists and are never modified. SqlctxCatalogSnapshot ReadSqlctxCatalog(ClientContext &context, const string &catalog = ""); vector SqlctxCatalogNames(ClientContext &context); +bool SqlctxIsMeasureView(ClientContext &context, const string &name, const string &catalog = ""); +bool SqlctxIsSemanticView(ClientContext &context, const string &name, const string &catalog = ""); // Physical sources compiled from a model belong to its catalog, even when the // caller selected it through an attachment from a different current database. void QualifySqlctxSources(ClientContext &context, QueryNode &node, const string &catalog); +void BindSqlctxSourceNames(ClientContext &context, QueryNode &node); // Virtual semantic relations are exposed through the host's standard catalogs. bool SqlctxPhysicalRelationExists(ClientContext &context, const string &model, const string &catalog = ""); diff --git a/sqlctx-duckdb/src/include/sqlctx_definition_store.hpp b/sqlctx-duckdb/src/include/sqlctx_definition_store.hpp new file mode 100644 index 000000000..ee2616fa4 --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_definition_store.hpp @@ -0,0 +1,46 @@ +#pragma once + +#include "duckdb/main/client_context.hpp" +#include "duckdb/parser/parser_extension.hpp" +#include "duckdb/planner/bound_statement.hpp" + +namespace duckdb { + +class Binder; +struct DBConfig; + +struct SqlctxStoredView { + string catalog; + string schema; + string name; + string definition_sql; + // Query-local compiler name; the durable identity is the three fields above. + string key; +}; + +struct SqlctxDefinitionStore { + string table; + string catalog; + bool exists = false; + string guard_token; + vector views; +}; + +string SqlctxDefinitionTable(const ClientContext &context); +string SqlctxViewModelKey(const string &catalog, const string &schema, const string &name); +bool SqlctxDefinitionStoreBypassed(); +void RegisterSqlctxDefinitionStore(DBConfig &config); +SqlctxDefinitionStore ReadSqlctxDefinitionStore(ClientContext &context); +optional_ptr FindSqlctxStoredView(ClientContext &context, SqlctxDefinitionStore &store, + const string &catalog, const string &schema, const string &name); + +// The caller validates the declaration and chooses its canonical identity. +// Store writes run at execution, under the caller's transaction and guard. +BoundStatement BindSqlctxDefinitionWrite(ClientContext &context, Binder &binder, const SqlctxDefinitionStore &store, + const SqlctxStoredView &view, bool drop = false); +ParserExtensionPlanResult PlanSqlctxDefinitionWrite(ClientContext &context, const SqlctxDefinitionStore &store, + const SqlctxStoredView &view, bool drop = false); +unique_ptr RewriteSqlctxStoredDDL(ClientContext &context, SQLStatement &statement); +ParserExtensionPlanResult PlanSqlctxStoredDDL(ClientContext &context, const string &sql); + +} // namespace duckdb diff --git a/sqlctx-duckdb/src/include/sqlctx_function_metadata.hpp b/sqlctx-duckdb/src/include/sqlctx_function_metadata.hpp new file mode 100644 index 000000000..6fde45056 --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_function_metadata.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "sqlctx_compat.hpp" +#include "duckdb/main/extension/extension_loader.hpp" +#include "duckdb/parser/parsed_data/create_scalar_function_info.hpp" +#include "duckdb/parser/parsed_data/create_table_function_info.hpp" + +namespace duckdb { + +// New hosts read argument names from the signature; legacy hosts read the +// matching FunctionDescription. Populate both from one public contract. +template +void RegisterSqlctxFunction(ExtensionLoader &loader, FUNCTION function, vector parameters, + string description, string example) { +#if SQLCTX_NEW_IDENTIFIER_API + for (idx_t i = 0; i < parameters.size(); ++i) { + function.GetSignature().GetParameter(i).SetName(Identifier(parameters[i])); + } +#endif + INFO info(std::move(function)); + FunctionDescription details; + details.parameter_names = std::move(parameters); + details.description = std::move(description); + details.examples.push_back(std::move(example)); + details.categories = {"utility"}; + info.descriptions.push_back(std::move(details)); + loader.RegisterFunction(info); +} + +} // namespace duckdb diff --git a/sqlctx-duckdb/src/include/sqlctx_measure_catalog.hpp b/sqlctx-duckdb/src/include/sqlctx_measure_catalog.hpp new file mode 100644 index 000000000..844e4b3c0 --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_measure_catalog.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include "sqlctx_catalog.hpp" +#include "sqlctx_measure_view.hpp" + +namespace duckdb { + +class CatalogEntry; + +// Only views carrying SQLCtx's declaration metadata are semantic relations. +// All other tables/views retain DuckDB's ordinary namespace precedence. +bool SqlctxIsNativeMeasureView(const CatalogEntry &entry); +bool ResolveSqlctxMeasureView(ClientContext &context, const string &catalog, const string &schema, + const string &name, SqlctxMeasureTarget &target, string &key); +void RefreshSqlctxNativeMeasureView(ClientContext &context, const SqlctxMeasureTarget &target); +void AppendSqlctxNativeMeasureViews(ClientContext &context, SqlctxCatalogSnapshot &snapshot, bool temporary_only = false); +case_insensitive_map_t SqlctxMeasureModelNames(ClientContext &context, const SqlctxCatalogSnapshot &snapshot); +string ResolveSqlctxCatalogModel(ClientContext &context, const SqlctxCatalogSnapshot &snapshot, const string &name); +void RelocateSqlctxSources(QueryNode &query, const string &old_catalog, const string &new_catalog); + +} // namespace duckdb diff --git a/sqlctx-duckdb/src/include/sqlctx_measure_view.hpp b/sqlctx-duckdb/src/include/sqlctx_measure_view.hpp new file mode 100644 index 000000000..8d1e09c84 --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_measure_view.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "sqlctx_parser.hpp" + +namespace duckdb { + +struct SqlctxMeasureTarget { + string catalog; + string schema; + string name; + bool temporary = false; + bool replace = false; + bool if_not_exists = false; +}; + +struct SqlctxMeasureDefinition { + string content; + string definition_sql; + string visible_sql; + vector virtual_measures; +}; + +SqlctxMeasureTarget SqlctxMeasureViewTarget(const string &sql); +SqlctxMeasureDefinition LowerSqlctxMeasureView(ClientContext &context, const string &sql, const string &model_key); +unique_ptr ParseSqlctxStoredDefinition(const string &sql, const string &model_key, + const string &old_catalog = "", const string &new_catalog = ""); +ParserExtensionPlanResult PlanSqlctxMeasureView(ClientContext &context, const string &sql, bool batch_temporary = false, + idx_t batch_remaining_queries = 1); + +} // namespace duckdb diff --git a/sqlctx-duckdb/src/include/sqlctx_parser.hpp b/sqlctx-duckdb/src/include/sqlctx_parser.hpp index be853aa73..ac7cb6e72 100644 --- a/sqlctx-duckdb/src/include/sqlctx_parser.hpp +++ b/sqlctx-duckdb/src/include/sqlctx_parser.hpp @@ -20,6 +20,8 @@ struct SqlctxParseData : ParserExtensionParseData { string content; bool replace = false; bool explicit_semantic = false; + bool batch_temporary = false; + idx_t batch_remaining_queries = 1; unique_ptr statement; unique_ptr Copy() const override; @@ -28,6 +30,15 @@ struct SqlctxParseData : ParserExtensionParseData { unique_ptr SqlctxStatement(unique_ptr data); unique_ptr ParseSqlctxDefinition(const string &sql); +ParserOptions SqlctxContextParserOptions(ClientContext &context); +struct SqlctxPublicQueryPlan { + string sql; + string explanation; +}; +// Public inspection uses the same caller catalog and semantic relation routing +// as execution, without executing queries or emitting runtime warnings. +SqlctxPublicQueryPlan PlanSqlctxPublicQuery(ClientContext &context, const string &sql, bool explain); +void CheckSqlctxMeasureScope(const string &sql); unique_ptr WrapSqlctxQuery(unique_ptr statement, bool explicit_semantic = false, const string &source_override = "", const ParserOptions *parser_options = nullptr); @@ -60,6 +71,7 @@ struct SqlctxOperatorExtension : OperatorExtension { // On hosts with the native grammar API, LOAD registers a composable grammar. // Parsing retains an explicitly selected caller grammar and never changes it. shared_ptr RegisterSqlctxGrammar(DatabaseInstance &db); +void EnsureSqlctxGrammarAlias(ParserExtensionInfo *info); bool ParseSqlctxGrammar(ParserExtensionInfo *, const string &, const ParserOptions &, vector> &statements); diff --git a/sqlctx-duckdb/src/include/sqlctx_warnings.hpp b/sqlctx-duckdb/src/include/sqlctx_warnings.hpp new file mode 100644 index 000000000..3ebe96de3 --- /dev/null +++ b/sqlctx-duckdb/src/include/sqlctx_warnings.hpp @@ -0,0 +1,15 @@ +#pragma once + +#include "sqlctx_catalog.hpp" + +namespace duckdb { +class ExtensionLoader; + +// Keep diagnostics in execution expressions: binding and nonexecuting EXPLAIN +// must never log warnings or add another statement/result to the caller. +void HandleSqlctxWarnings(ClientContext &context, const string &warnings); +string WrapSqlctxQueryWarnings(const string &query_sql, const string &warnings); +string CompileSqlctxWithWarnings(const SqlctxCatalogSnapshot &snapshot, const string &sql, + string *collected_warnings = nullptr, bool wrap_runtime_warnings = true); +void RegisterSqlctxWarnings(ExtensionLoader &loader); +} // namespace duckdb diff --git a/sqlctx-duckdb/src/sqlctx_api.cpp b/sqlctx-duckdb/src/sqlctx_api.cpp index 70d28a1ce..fd790266e 100644 --- a/sqlctx-duckdb/src/sqlctx_api.cpp +++ b/sqlctx-duckdb/src/sqlctx_api.cpp @@ -1,11 +1,15 @@ #include "sqlctx_api.hpp" #include "sqlctx_catalog.hpp" #include "sqlctx_compiler.hpp" +#include "sqlctx_measure_catalog.hpp" #include "sqlctx_compat.hpp" #include "sqlctx.h" #include "duckdb/common/error_data.hpp" #include "duckdb/function/table_function.hpp" +#include "duckdb/parser/expression/columnref_expression.hpp" +#include "duckdb/parser/query_node/select_node.hpp" +#include "duckdb/parser/statement/select_statement.hpp" #include "duckdb/planner/binder.hpp" namespace duckdb { @@ -22,6 +26,46 @@ struct CatalogState : GlobalTableFunctionState { idx_t offset = 0; }; +string JsonName(const string &name) { + string quoted = "\""; + static constexpr const char *hex = "0123456789abcdef"; + for (unsigned char character : name) { + if (character < 0x20) { + quoted += "\\u00"; + quoted += hex[character >> 4]; + quoted += hex[character & 15]; + } else { + if (character == '"' || character == '\\') quoted += '\\'; + quoted += static_cast(character); + } + } + return quoted + '"'; +} + +string CatalogMetric(ClientContext &context, const SqlctxCatalogSnapshot &snapshot, const string &name) { + if (name.empty()) return name; + Parser parser(SqlctxBuiltinParserOptions()); + parser.ParseQuery("SELECT " + name); + auto &fields = parser.statements[0]->Cast().node->Cast().select_list; + if (fields.size() != 1 || fields[0]->GetExpressionClass() != ExpressionClass::COLUMN_REF) { + throw ParserException("SHOW DIMENSIONS FOR expects model.metric"); + } + auto &column = fields[0]->Cast(); +#if SQLCTX_NEW_EXPRESSION_API + auto &parts = column.ColumnNames(); +#else + auto &parts = column.column_names; +#endif + if (parts.size() < 2 || parts.size() > 4) throw ParserException("SHOW DIMENSIONS FOR expects model.metric"); + string model; + for (idx_t i = 0; i + 1 < parts.size(); ++i) { + if (i) model += '.'; + model += "\"" + StringUtil::Replace(SqlctxName(parts[i]), "\"", "\"\"") + "\""; + } + auto key = ResolveSqlctxCatalogModel(context, snapshot, model); + return "[" + JsonName(key) + "," + JsonName(SqlctxName(parts.back())) + "]"; +} + static unique_ptr CatalogBind(ClientContext &context, TableFunctionBindInput &input, vector &types, vector &names) { if (input.binder) RegisterSqlctxCatalogRead(context, input.binder->GetStatementProperties()); @@ -62,11 +106,14 @@ static unique_ptr CatalogInit(ClientContext &context, state->rows.push_back({Value(definition)}); return std::move(state); } + auto model = ResolveSqlctxCatalogModel(context, snapshot, data.model); + auto metric = CatalogMetric(context, snapshot, data.metric); + auto public_names = SqlctxMeasureModelNames(context, snapshot); struct CatalogResult { SqlctxCatalogEntries result; ~CatalogResult() { sqlctx_free_catalog_entries(result); } - } result {sqlctx_snapshot_catalog(snapshot.payload.c_str(), data.kind.c_str(), data.model.c_str(), - data.metric.empty() ? nullptr : data.metric.c_str())}; + } result {sqlctx_snapshot_catalog(snapshot.payload.c_str(), data.kind.c_str(), model.c_str(), + metric.empty() ? nullptr : metric.c_str())}; if (result.result.error) throw InvalidInputException("sqlctx: %s", SqlctxErrorText(result.result.error)); unique_ptr compiler; for (idx_t i = 0; i < result.result.count; ++i) { @@ -80,6 +127,12 @@ static unique_ptr CatalogInit(ClientContext &context, // Bind against the live caller transaction on every execution, after // selecting the requested model/kind. Retain only the decoded graph. string kind(entry.kind); + auto public_model = public_names.find(kind == "model" ? entry.name : entry.model_name ? entry.model_name : ""); + if (public_model != public_names.end()) { + row[1] = Value(public_model->second); + if (kind == "model") row[2] = Value(public_model->second); + row[3] = Value(kind == "model" ? public_model->second : public_model->second + "." + entry.name); + } if (!entry.data_type && entry.model_name && (kind == "dimension" || kind == "metric")) { if (!compiler) compiler = make_uniq(snapshot.payload); try { @@ -102,10 +155,20 @@ static void CatalogFunction(ClientContext &, TableFunctionInput &input, DataChun auto count = MinValue(STANDARD_VECTOR_SIZE, state.rows.size() - state.offset); for (idx_t row = 0; row < count; ++row) { auto &values = state.rows[state.offset + row]; - for (idx_t column = 0; column < values.size(); ++column) output.SetValue(column, row, values[column]); + for (idx_t column = 0; column < values.size(); ++column) { +#if SQLCTX_VECTOR_APPEND + output.data[column].Append(values[column]); +#else + output.SetValue(column, row, values[column]); +#endif + } } state.offset += count; +#if SQLCTX_VECTOR_APPEND + output.CheckCardinality(count); +#else output.SetCardinality(count); +#endif } } // namespace diff --git a/sqlctx-duckdb/src/sqlctx_catalog.cpp b/sqlctx-duckdb/src/sqlctx_catalog.cpp index 960668369..c803fdd9b 100644 --- a/sqlctx-duckdb/src/sqlctx_catalog.cpp +++ b/sqlctx-duckdb/src/sqlctx_catalog.cpp @@ -1,11 +1,23 @@ #include "sqlctx_catalog.hpp" +#include "sqlctx_definition_store.hpp" +#include "sqlctx_parser.hpp" +#include "sqlctx_measure_view.hpp" +#include "sqlctx_measure_catalog.hpp" #include "sqlctx_compat.hpp" #include "sqlctx.h" #include "duckdb/catalog/catalog.hpp" #include "duckdb/catalog/catalog_entry/scalar_macro_catalog_entry.hpp" +#include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" +#include "duckdb/catalog/catalog_search_path.hpp" #include "duckdb/common/file_system.hpp" #include "duckdb/function/scalar_macro_function.hpp" +#include "duckdb/common/types/uuid.hpp" +#include "duckdb/execution/executor.hpp" +#include "duckdb/execution/physical_plan_generator.hpp" +#include "duckdb/main/client_data.hpp" +#include "duckdb/main/config.hpp" +#include "duckdb/main/query_profiler.hpp" #include "duckdb/main/attached_database.hpp" #include "duckdb/main/client_context_state.hpp" #include "duckdb/main/database_manager.hpp" @@ -13,6 +25,9 @@ #include "duckdb/parser/expression/subquery_expression.hpp" #include "duckdb/parser/parsed_expression_iterator.hpp" #include "duckdb/parser/parsed_data/create_macro_info.hpp" +#include "duckdb/parser/parsed_data/create_table_info.hpp" +#include "duckdb/parser/parsed_data/create_view_info.hpp" +#include "duckdb/parser/parsed_data/drop_info.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" @@ -21,7 +36,12 @@ #include "duckdb/parser/tableref/joinref.hpp" #include "duckdb/parser/tableref/subqueryref.hpp" #include "duckdb/parser/tableref/table_function_ref.hpp" +#include "duckdb/parser/statement/create_statement.hpp" +#include "duckdb/parser/statement/drop_statement.hpp" +#include "duckdb/parser/statement/explain_statement.hpp" +#include "duckdb/parser/statement/select_statement.hpp" #include "duckdb/planner/binder.hpp" +#include "duckdb/planner/operator/logical_extension_operator.hpp" #include "duckdb/storage/storage_manager.hpp" #include #include @@ -206,6 +226,21 @@ static optional_ptr FindCatalogMacro(ClientContext &context, Catal } SqlctxCatalogSnapshot ReadSqlctxCatalog(ClientContext &context, const string &catalog_name) { + if (catalog_name.empty() && !SqlctxDefinitionStoreBypassed() && !SqlctxDefinitionTable(context).empty()) { + SqlctxCatalogSnapshot snapshot; + snapshot.catalog = SqlctxName(DatabaseManager::GetDefaultDatabase(context)); + snapshot.definitions = make_shared_ptr(ReadSqlctxDefinitionStore(context)); + for (auto &view : snapshot.definitions->views) { + auto declaration = ParseSqlctxStoredDefinition(view.definition_sql, view.key); + if (!declaration) continue; + SnapshotResultOwner applied(sqlctx_snapshot_apply(snapshot.payload.c_str(), "", declaration->operation.c_str(), + declaration->content.c_str(), false)); + snapshot.payload = applied.Get().payload; + snapshot.measure_names[view.key] = view.name; + } + AppendSqlctxNativeMeasureViews(context, snapshot, true); + return snapshot; + } auto &catalog = SemanticCatalog(context, catalog_name); auto state = Session(context); auto entry = FindCatalogMacro(context, catalog, CATALOG_MACRO); @@ -250,6 +285,7 @@ SqlctxCatalogSnapshot ReadSqlctxCatalog(ClientContext &context, const string &ca snapshot.active_model = active->second; } snapshot.catalog = SqlctxName(catalog.GetName()); + if (catalog_name.empty() && !SqlctxDefinitionStoreBypassed()) AppendSqlctxNativeMeasureViews(context, snapshot); return snapshot; } @@ -267,7 +303,9 @@ vector SqlctxCatalogNames(ClientContext &context) { // physical table. Compiled semantic SQL uses CTEs for aggregation and joins. class SqlctxSourceQualifier { public: - SqlctxSourceQualifier(const string &catalog, const string &schema) : catalog(catalog), default_schema(schema) {} + SqlctxSourceQualifier(string catalog, string schema) + : catalog(std::move(catalog)), default_schema(std::move(schema)) {} + explicit SqlctxSourceQualifier(ClientContext &context) : context(&context) {} void Query(QueryNode &node, case_insensitive_set_t ctes = {}) { for (auto &cte : node.cte_map.map) { @@ -305,8 +343,16 @@ class SqlctxSourceQualifier { } private: - const string &catalog; - const string &default_schema; + string catalog; + string default_schema; + optional_ptr context; + unique_ptr definitions; + + optional_ptr StoredSource(const string &schema, const string &name) { + if (!context || SqlctxDefinitionTable(*context).empty()) return nullptr; + if (!definitions) definitions = make_uniq(ReadSqlctxDefinitionStore(*context)); + return FindSqlctxStoredView(*context, *definitions, "", schema, name); + } void Expression(ParsedExpression &expression, const case_insensitive_set_t &ctes) { if (expression.GetExpressionClass() == ExpressionClass::SUBQUERY) { @@ -327,12 +373,33 @@ class SqlctxSourceQualifier { auto schema = SqlctxName(table.GetQualifiedName().Schema()); if (!table.GetQualifiedName().Catalog().empty()) return; if (schema.empty() && ctes.count(name)) return; - table.SetQualifiedName(Identifier(catalog), Identifier(schema.empty() ? default_schema : schema), Identifier(name)); + if (context) { + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, table.GetQualifiedName()); + auto entry = Catalog::GetEntry(*context, lookup, OnEntryNotFound::RETURN_NULL); + if (entry) table.SetQualifiedName(entry->ParentCatalog().GetName(), entry->ParentSchema().name, Identifier(name)); + else if (auto stored = StoredSource(schema, name)) { + table.SetQualifiedName(Identifier(stored->catalog), Identifier(stored->schema), Identifier(stored->name)); + } + } else table.SetQualifiedName(Identifier(catalog), Identifier(schema.empty() ? default_schema : schema), Identifier(name)); #else if (!table.catalog_name.empty()) return; if (table.schema_name.empty() && ctes.count(table.table_name)) return; - table.catalog_name = catalog; - if (table.schema_name.empty()) table.schema_name = default_schema; + if (context) { + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, table.table_name); + auto entry = Catalog::GetEntry(*context, table.catalog_name, table.schema_name, lookup, + OnEntryNotFound::RETURN_NULL); + if (entry) { + table.catalog_name = entry->ParentCatalog().GetName(); + table.schema_name = entry->ParentSchema().name; + } else if (auto stored = StoredSource(table.schema_name, table.table_name)) { + table.catalog_name = stored->catalog; + table.schema_name = stored->schema; + table.table_name = stored->name; + } + } else { + table.catalog_name = catalog; + if (table.schema_name.empty()) table.schema_name = default_schema; + } #endif } else if (ref.type == TableReferenceType::SUBQUERY) { Query(*ref.Cast().subquery->node, ctes); @@ -353,6 +420,10 @@ class SqlctxSourceQualifier { } }; +void BindSqlctxSourceNames(ClientContext &context, QueryNode &node) { + SqlctxSourceQualifier(context).Query(node); +} + void QualifySqlctxSources(ClientContext &context, QueryNode &node, const string &catalog) { if (catalog.empty()) return; auto schema = SemanticCatalog(context, catalog).GetDefaultSchema(); @@ -394,30 +465,40 @@ string DescribeCatalogChange(const string &before_payload, const string &after_p auto before = CatalogDefinitions(before_payload); auto after = CatalogDefinitions(after_payload); vector created, replaced, dropped; - case_insensitive_set_t created_models, dropped_models, changed_models; + case_insensitive_set_t created_models, dropped_models, changed_models, replaced_views; + auto relation_name = [](const string &key) { + if (StringUtil::StartsWith(key, "model ")) return key.substr(6); + if (StringUtil::StartsWith(key, "view ")) return key.substr(5); + return string(); + }; auto model_of = [](const string &key) { + if (StringUtil::StartsWith(key, "model ") || StringUtil::StartsWith(key, "view ")) return string(); auto name = key.substr(key.find(' ') + 1); auto dot = name.find('.'); return dot == string::npos ? string() : name.substr(0, dot); }; for (auto &entry : after) { - if (StringUtil::StartsWith(entry.first, "model ") && !before.count(entry.first)) created_models.insert(entry.first.substr(6)); + auto name = relation_name(entry.first); + if (!name.empty() && !before.count(entry.first)) created_models.insert(name); + if (StringUtil::StartsWith(entry.first, "view ") && before.count(entry.first) && + before.at(entry.first) != entry.second) replaced_views.insert(name); } for (auto &entry : before) { - if (StringUtil::StartsWith(entry.first, "model ") && !after.count(entry.first)) dropped_models.insert(entry.first.substr(6)); + auto name = relation_name(entry.first); + if (!name.empty() && !after.count(entry.first)) dropped_models.insert(name); } for (auto &entry : after) { auto previous = before.find(entry.first); if (previous != before.end() && previous->second == entry.second) continue; auto model = model_of(entry.first); - if (created_models.count(model)) continue; + if (created_models.count(model) || replaced_views.count(model)) continue; if (!model.empty()) changed_models.insert(model); (previous == before.end() ? created : replaced).push_back(entry.first); } for (auto &entry : before) { if (after.count(entry.first)) continue; auto model = model_of(entry.first); - if (dropped_models.count(model)) continue; + if (dropped_models.count(model) || replaced_views.count(model)) continue; if (!model.empty()) changed_models.insert(model); dropped.push_back(entry.first); } @@ -428,23 +509,76 @@ string DescribeCatalogChange(const string &before_payload, const string &after_p vector parts; for (auto &group : {std::make_pair("Created", &created), std::make_pair("Replaced", &replaced), std::make_pair("Dropped", &dropped)}) { + for (auto &definition : *group.second) { + if (StringUtil::StartsWith(definition, "view ")) definition = "semantic " + definition; + } if (!group.second->empty()) parts.push_back(string(group.first) + " " + StringUtil::Join(*group.second, ", ")); } return parts.empty() ? "No semantic definitions changed" : StringUtil::Join(parts, "; "); } +bool SqlctxIsSemanticView(ClientContext &context, const string &name, const string &catalog) { + auto snapshot = ReadSqlctxCatalog(context, catalog); + if (snapshot.payload.empty()) return false; + auto entries = sqlctx_snapshot_catalog(snapshot.payload.c_str(), "view", "", nullptr); + if (entries.error) { + string error(entries.error); + sqlctx_free_catalog_entries(entries); + throw InvalidInputException("sqlctx: %s", SqlctxErrorText(error)); + } + bool found = false; + for (idx_t i = 0; i < entries.count; ++i) { + if (StringUtil::CIEquals(entries.entries[i].name, name)) { + found = true; + break; + } + } + sqlctx_free_catalog_entries(entries); + return found; +} + +bool SqlctxIsMeasureView(ClientContext &context, const string &name, const string &catalog) { + auto snapshot = ReadSqlctxCatalog(context, catalog); + if (snapshot.payload.empty()) return false; + auto models = sqlctx_snapshot_list_models(snapshot.payload.c_str()); + if (models.error) { + string error(models.error); + sqlctx_free_model_list(models); + throw InvalidInputException("sqlctx: %s", SqlctxErrorText(error)); + } + bool found = false; + for (idx_t i = 0; i < models.count; ++i) { + if (StringUtil::CIEquals(models.models[i].name, name)) { + found = models.models[i].is_measure_view; + break; + } + } + sqlctx_free_model_list(models); + return found; +} + string ExecuteSqlctxMutation(ClientContext &context, const string &operation, const string &content, bool replace) { if (content.find('\0') != string::npos) { throw InvalidInputException("sqlctx definition contains a NUL byte"); } auto &catalog = SemanticCatalog(context); - auto snapshot = ReadSqlctxCatalog(context); + // Compiler snapshots also contain query-local native/store view models. + // Only the owning macro's durable definitions belong in a MODEL mutation. + auto snapshot = ReadSqlctxCatalog(context, SqlctxName(catalog.GetName())); SnapshotResultOwner applied(operation == "file" ? ImportDefinitionFiles(context, snapshot.payload, content) : sqlctx_snapshot_apply(snapshot.payload.c_str(), snapshot.active_model.c_str(), operation.c_str(), content.c_str(), replace)); auto candidate = applied.Get(); + if (operation == "measure_view") { + SqlctxPhysicalRelation physical; + if (SqlctxFindPhysicalRelation(context, candidate.active_model, physical) || + SqlctxPhysicalRelationExists(context, candidate.active_model)) { + throw CatalogException("Cannot create measure view '%s': a physical table or view already exists", + candidate.active_model); + } + } if (operation != "use") { CreateMacroInfo info(CatalogType::MACRO_ENTRY); #if SQLCTX_NEW_IDENTIFIER_API @@ -529,4 +663,511 @@ ParserExtensionPlanResult PlanSqlctxMutation(ClientContext &context, const strin return result; } +namespace { + +constexpr const char *DEFINITION_TABLE_SETTING = "yardstick_definition_table"; +constexpr const char *DEFINITION_GUARD_PREFIX = "yardstick_guard_v1:"; +constexpr const char *DEFINITION_GUARD_PREDICATE = "view_catalog = '' AND view_schema = '' AND view_name = ''"; +thread_local idx_t definition_store_bypass = 0; + +struct DefinitionStoreBypass { + DefinitionStoreBypass() { ++definition_store_bypass; } + ~DefinitionStoreBypass() { --definition_store_bypass; } +}; + +string StoreIdentifier(const string &value) { + return "\"" + StringUtil::Replace(value, "\"", "\"\"") + "\""; +} + +string StoreLiteral(const string &value) { + return "'" + StringUtil::Replace(value, "'", "''") + "'"; +} + +SqlctxStoredView StoreTableName(const string &table) { + Parser parser(SqlctxBuiltinParserOptions()); + parser.ParseQuery("CREATE TABLE " + table + " (view_catalog VARCHAR)"); + if (parser.statements.size() != 1 || parser.statements[0]->type != StatementType::CREATE_STATEMENT || + parser.statements[0]->Cast().info->type != CatalogType::TABLE_ENTRY) { + throw InvalidInputException("yardstick_definition_table must be a catalog.schema.table name"); + } + auto &info = parser.statements[0]->Cast().info->Cast(); +#if SQLCTX_NEW_IDENTIFIER_API + auto &qualified = info.GetQualifiedName(); + if (qualified.Path().size() != 3) { + throw InvalidInputException("yardstick_definition_table must be catalog.schema.table"); + } + return {SqlctxName(qualified.Catalog()), SqlctxName(qualified.Schema()), SqlctxName(qualified.Name()), "", ""}; +#else + if (info.catalog.empty() || info.schema.empty()) { + throw InvalidInputException("yardstick_definition_table must be catalog.schema.table"); + } + return {info.catalog, info.schema, info.table, "", ""}; +#endif +} + +optional_ptr StoreNativeEntry(ClientContext &context, const SqlctxStoredView &name) { + auto catalog = name.catalog; + if (catalog.empty() && StringUtil::CIEquals(name.schema, DEFAULT_SCHEMA)) { + catalog = SqlctxName(DatabaseManager::GetDefaultDatabase(context)); + } +#if SQLCTX_NEW_IDENTIFIER_API + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, + QualifiedName(Identifier(catalog), Identifier(name.schema), Identifier(name.name))); + return Catalog::GetEntry(context, lookup, OnEntryNotFound::RETURN_NULL); +#else + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, name.name); + return Catalog::GetEntry(context, catalog, name.schema, lookup, OnEntryNotFound::RETURN_NULL); +#endif +} + +// Execute a small internal scan/DML plan in the caller's transaction. Opening +// another connection would lose uncommitted changes and transaction snapshots. +class DefinitionRowsSink : public PhysicalOperator { +public: + DefinitionRowsSink(PhysicalPlan &plan, PhysicalOperator &input, vector> &rows) + : PhysicalOperator(plan, PhysicalOperatorType::EXTENSION, {LogicalType::BOOLEAN}, 1), rows(rows) { + children.push_back(input); + } + vector> &rows; + bool IsSink() const override { return true; } + bool IsSource() const override { return true; } + SinkResultType Sink(ExecutionContext &, DataChunk &chunk, OperatorSinkInput &) const override { + for (idx_t row = 0; row < chunk.size(); ++row) { + vector values; + for (idx_t column = 0; column < chunk.ColumnCount(); ++column) values.push_back(chunk.GetValue(column, row)); + rows.push_back(std::move(values)); + } + return SinkResultType::NEED_MORE_INPUT; + } + SourceResultType GetDataInternal(ExecutionContext &, DataChunk &, OperatorSourceInput &) const override { + return SourceResultType::FINISHED; + } +}; + +struct DefinitionProfilerScope { + explicit DefinitionProfilerScope(ClientContext &context) + : data(ClientData::Get(context)), previous(data.profiler) { + data.profiler = make_shared_ptr(context); + } + ~DefinitionProfilerScope() { data.profiler = std::move(previous); } + ClientData &data; + shared_ptr previous; +}; + +vector> ExecuteDefinitionSQL(ClientContext &context, const string &sql) { + DefinitionStoreBypass bypass; + DefinitionProfilerScope profiler(context); + Parser parser(SqlctxBuiltinParserOptions()); + parser.ParseQuery(sql); + if (parser.statements.size() != 1) throw InternalException("Expected one definition-store operation"); + auto binder = Binder::CreateBinder(context); + auto bound = binder->Bind(*parser.statements[0]); + PhysicalPlanGenerator generator(context); + auto plan = generator.Plan(std::move(bound.plan)); + vector> rows; + auto &sink = plan->Make(plan->Root(), rows); + Executor executor(context); + try { + executor.Initialize(sink); + while (!executor.ExecutionIsFinished()) { + executor.ExecuteTask(); + if (!executor.ExecutionIsFinished()) executor.WaitForTask(); + } + if (executor.HasError()) executor.ThrowException(); + } catch (...) { + executor.CancelTasks(); + throw; + } + // Workers may still be releasing their pipeline state after completion. + executor.CancelTasks(); + return rows; +} + +bool SameStoredName(const SqlctxStoredView &left, const SqlctxStoredView &right) { + return StringUtil::CIEquals(left.catalog, right.catalog) && StringUtil::CIEquals(left.schema, right.schema) && + StringUtil::CIEquals(left.name, right.name); +} + +string StoredKeyPredicate(const SqlctxStoredView &view) { + return "lower(view_catalog) = lower(" + StoreLiteral(view.catalog) + ") AND lower(view_schema) = lower(" + + StoreLiteral(view.schema) + ") AND lower(view_name) = lower(" + StoreLiteral(view.name) + ")"; +} + +void SetSqlctxDefinitionTable(ClientContext &, SetScope scope, Value &value) { + if (scope == SetScope::GLOBAL) throw InvalidInputException("yardstick_definition_table is a session setting"); + if (value.IsNull() || value.GetValue().empty()) return; + auto name = StoreTableName(value.GetValue()); + value = Value(StoreIdentifier(name.catalog) + "." + StoreIdentifier(name.schema) + "." + StoreIdentifier(name.name)); +} + +struct DefinitionWriteData : TableFunctionData { + SqlctxDefinitionStore store; + SqlctxStoredView view; + bool drop = false; +}; + +struct DefinitionWriteInfo : TableFunctionInfo { + SqlctxDefinitionStore store; + SqlctxStoredView view; + bool drop = false; +}; + +void RegisterDefinitionWrite(ClientContext &context, StatementProperties &properties, const SqlctxDefinitionStore &store) { + auto modification = store.exists ? DatabaseModificationType::UPDATE_DATA : DatabaseModificationType::CREATE_CATALOG_ENTRY; + properties.RegisterDBModify(SemanticCatalog(context, store.catalog), context, modification); + properties.always_require_rebind = true; +} + +void ExecuteDefinitionWrite(ClientContext &context, const SqlctxDefinitionStore &store, + const SqlctxStoredView &view, bool drop) { + string guard = store.guard_token; + if (!store.exists) { + auto name = StoreTableName(store.table); + auto create = StringUtil::CIEquals(name.catalog, "temp") ? "CREATE TEMP TABLE " : "CREATE TABLE "; + ExecuteDefinitionSQL(context, create + store.table + + " AS SELECT ''::VARCHAR AS view_catalog, ''::VARCHAR AS view_schema, ''::VARCHAR AS view_name, " + + StoreLiteral(DEFINITION_GUARD_PREFIX + UUID::ToString(UUID::GenerateRandomUUID())) + "::VARCHAR AS definition_sql"); + auto rows = ExecuteDefinitionSQL(context, "SELECT definition_sql FROM " + store.table + " WHERE " + DEFINITION_GUARD_PREDICATE); + guard = rows.at(0).at(0).GetValue(); + } + if (guard.empty()) { + throw InvalidInputException("Yardstick definitions table %s has no concurrency guard. With exclusive writer access, " + "insert an empty-key row with a yardstick_guard_v1: UUID token", store.table); + } + auto token = DEFINITION_GUARD_PREFIX + UUID::ToString(UUID::GenerateRandomUUID()); + ExecuteDefinitionSQL(context, "UPDATE " + store.table + " SET definition_sql = " + StoreLiteral(token) + + " WHERE " + DEFINITION_GUARD_PREDICATE + " AND definition_sql = " + StoreLiteral(guard)); + // Rebind after acquiring the guard: lake catalogs can replace their + // transaction-local files and row identities during UPDATE. + auto rows = ExecuteDefinitionSQL(context, + "SELECT definition_sql FROM " + store.table + " WHERE " + DEFINITION_GUARD_PREDICATE); + if (rows.size() != 1 || rows[0][0].IsNull() || rows[0][0].GetValue() != token) { + throw TransactionException("Conflict: concurrent Yardstick definition change; retry in a fresh transaction"); + } + if (drop) { + ExecuteDefinitionSQL(context, "DELETE FROM " + store.table + " WHERE " + StoredKeyPredicate(view)); + return; + } + bool existing = false; + for (auto &entry : store.views) existing |= SameStoredName(entry, view); + if (existing) { + ExecuteDefinitionSQL(context, "UPDATE " + store.table + " SET definition_sql = " + + StoreLiteral(view.definition_sql) + " WHERE " + StoredKeyPredicate(view)); + } else { + ExecuteDefinitionSQL(context, "INSERT INTO " + store.table + + " (view_catalog, view_schema, view_name, definition_sql) VALUES (" + StoreLiteral(view.catalog) + ", " + + StoreLiteral(view.schema) + ", " + StoreLiteral(view.name) + ", " + StoreLiteral(view.definition_sql) + ")"); + } +} + +unique_ptr BindDefinitionWriteFunction(ClientContext &context, TableFunctionBindInput &input, + vector &types, vector &names) { + auto data = make_uniq(); + auto &info = input.info->Cast(); + data->store = info.store; + data->view = info.view; + data->drop = info.drop; + types.push_back(LogicalType::BOOLEAN); + names.emplace_back("Success"); + if (input.binder) RegisterDefinitionWrite(context, input.binder->GetStatementProperties(), data->store); + return std::move(data); +} + +void RunDefinitionWriteFunction(ClientContext &context, TableFunctionInput &input, DataChunk &) { + auto &state = input.global_state->Cast(); + if (state.done) return; + state.done = true; + auto &data = input.bind_data->Cast(); + ExecuteDefinitionWrite(context, data.store, data.view, data.drop); +} + +struct DefinitionWriteSourceState : GlobalSourceState { bool done = false; }; + +class DefinitionWriteSource : public PhysicalOperator { +public: + DefinitionWriteSource(PhysicalPlan &plan, SqlctxDefinitionStore store, SqlctxStoredView view, bool drop) + : PhysicalOperator(plan, PhysicalOperatorType::EXTENSION, {LogicalType::BOOLEAN}, 1), + store(std::move(store)), view(std::move(view)), drop(drop) {} + SqlctxDefinitionStore store; + SqlctxStoredView view; + bool drop; + bool IsSource() const override { return true; } + unique_ptr GetGlobalSourceState(ClientContext &) const override { + return make_uniq(); + } + SourceResultType GetDataInternal(ExecutionContext &context, DataChunk &, OperatorSourceInput &input) const override { + auto &state = input.global_state.Cast(); + if (!state.done) { + state.done = true; + ExecuteDefinitionWrite(context.client, store, view, drop); + } + return SourceResultType::FINISHED; + } +}; + +class LogicalDefinitionWrite : public LogicalExtensionOperator { +public: + LogicalDefinitionWrite(SqlctxDefinitionStore store, SqlctxStoredView view, bool drop) + : store(std::move(store)), view(std::move(view)), drop(drop) { ResolveTypes(); } + SqlctxDefinitionStore store; + SqlctxStoredView view; + bool drop; + string GetExtensionName() const override { return "sqlctx"; } + bool SupportSerialization() const override { return false; } + vector GetColumnBindings() override { +#if SQLCTX_NEW_IDENTIFIER_API + return {ColumnBinding(TableIndex(0), ProjectionIndex(0))}; +#else + return {ColumnBinding(0, 0)}; +#endif + } + void ResolveTypes() override { types = {LogicalType::BOOLEAN}; } + PhysicalOperator &CreatePlan(ClientContext &, PhysicalPlanGenerator &planner) override { + return planner.Make(store, view, drop); + } +}; + +} // namespace + +string SqlctxDefinitionTable(const ClientContext &context) { + Value value; + if (!context.TryGetCurrentSetting(DEFINITION_TABLE_SETTING, value) || value.IsNull()) return ""; + return value.GetValue(); +} + +string SqlctxViewModelKey(const string &catalog, const string &schema, const string &name) { + string key = "__sqlctx_view"; + for (auto &part : {catalog, schema, name}) { + auto lowered = StringUtil::Lower(part); + key += "_" + to_string(lowered.size()) + "_" + lowered; + } + return key; +} + +bool SqlctxDefinitionStoreBypassed() { return definition_store_bypass != 0; } + +void RegisterSqlctxDefinitionStore(DBConfig &config) { + config.AddExtensionOption(DEFINITION_TABLE_SETTING, "Fully qualified table holding semantic view definitions", + LogicalType::VARCHAR, Value(""), SetSqlctxDefinitionTable); +} + +SqlctxDefinitionStore ReadSqlctxDefinitionStore(ClientContext &context) { + SqlctxDefinitionStore store; + store.table = SqlctxDefinitionTable(context); + if (store.table.empty()) return store; + auto name = StoreTableName(store.table); + store.catalog = name.catalog; + store.exists = StoreNativeEntry(context, name) != nullptr; + if (!store.exists) return store; + auto rows = ExecuteDefinitionSQL(context, + "SELECT view_catalog, view_schema, view_name, definition_sql FROM " + store.table + + " ORDER BY lower(view_catalog), lower(view_schema), lower(view_name)"); + for (auto &row : rows) { + for (auto &value : row) { + if (value.IsNull() || value.type().id() != LogicalTypeId::VARCHAR) { + throw InvalidInputException("Yardstick definitions require non-NULL VARCHAR columns"); + } + } + SqlctxStoredView view {row[0].GetValue(), row[1].GetValue(), row[2].GetValue(), + row[3].GetValue(), ""}; + if (view.catalog.empty() && view.schema.empty() && view.name.empty()) { + if (!store.guard_token.empty() || !StringUtil::StartsWith(view.definition_sql, DEFINITION_GUARD_PREFIX)) { + throw InvalidInputException("Invalid or duplicate Yardstick concurrency guard in %s", store.table); + } + store.guard_token = std::move(view.definition_sql); + } else { + view.key = SqlctxViewModelKey(view.catalog, view.schema, view.name); + for (auto &existing : store.views) { + if (SameStoredName(existing, view)) throw InvalidInputException("Duplicate Yardstick definition for %s", view.name); + } + store.views.push_back(std::move(view)); + } + } + return store; +} + +optional_ptr FindSqlctxStoredView(ClientContext &context, SqlctxDefinitionStore &store, + const string &input_catalog, const string &input_schema, + const string &name) { + auto catalog = input_catalog; + auto schema = input_schema; + if (catalog.empty() && !schema.empty()) { +#if SQLCTX_NEW_IDENTIFIER_API + Identifier catalog_id, schema_id(schema); + Binder::BindSchemaOrCatalog(context, catalog_id, schema_id); + catalog = SqlctxName(catalog_id); + schema = SqlctxName(schema_id); +#else + Binder::BindSchemaOrCatalog(context, catalog, schema); +#endif + } + auto &path = *ClientData::Get(context).catalog_search_path; + vector candidates; + if (!catalog.empty() && !schema.empty()) candidates.push_back({catalog, schema, name, "", ""}); + else if (!catalog.empty()) candidates.push_back({catalog, SqlctxName(path.GetDefaultSchema(SqlctxIdentifier(catalog))), name, "", ""}); + else if (!schema.empty()) { + for (auto &entry : path.GetCatalogsForSchema(SqlctxIdentifier(schema))) { + candidates.push_back({SqlctxName(entry), schema, name, "", ""}); + } + if (candidates.empty()) candidates.push_back({SqlctxName(DatabaseManager::GetDefaultDatabase(context)), schema, name, "", ""}); + } else { + auto add = [&](const CatalogSearchEntry &entry) { +#if SQLCTX_NEW_IDENTIFIER_API + candidates.push_back({SqlctxName(entry.GetCatalog()), SqlctxName(entry.GetSchema()), name, "", ""}); +#else + candidates.push_back({entry.catalog, entry.schema, name, "", ""}); +#endif + }; + add(path.GetDefault()); + for (auto &entry : path.GetSetPaths()) add(entry); + } + for (auto &candidate : candidates) { + if (candidate.catalog.empty()) candidate.catalog = SqlctxName(DatabaseManager::GetDefaultDatabase(context)); + if (candidate.schema.empty()) candidate.schema = DEFAULT_SCHEMA; + for (auto &view : store.views) if (SameStoredName(candidate, view)) return &view; + } + return nullptr; +} + +BoundStatement BindSqlctxDefinitionWrite(ClientContext &context, Binder &binder, const SqlctxDefinitionStore &store, + const SqlctxStoredView &view, bool drop) { + RegisterDefinitionWrite(context, binder.GetStatementProperties(), store); + binder.GetStatementProperties().return_type = StatementReturnType::NOTHING; + BoundStatement bound; + bound.plan = make_uniq(store, view, drop); + bound.names = {"Success"}; + bound.types = {LogicalType::BOOLEAN}; + return bound; +} + +ParserExtensionPlanResult PlanSqlctxDefinitionWrite(ClientContext &context, const SqlctxDefinitionStore &store, + const SqlctxStoredView &view, bool drop) { + ParserExtensionPlanResult result; + auto info = make_shared_ptr(); + info->store = store; + info->view = view; + info->drop = drop; + result.function = TableFunction("sqlctx_definition_store_write", {}, RunDefinitionWriteFunction, + BindDefinitionWriteFunction, InitMutation); + result.function.function_info = std::move(info); + result.return_type = StatementReturnType::NOTHING; + StatementProperties properties; + RegisterDefinitionWrite(context, properties, store); + result.modified_databases = std::move(properties.modified_databases); + return result; +} + +namespace { + +SqlctxStoredView StoredTarget(const CreateViewInfo &view) { +#if SQLCTX_NEW_IDENTIFIER_API + auto &name = view.GetQualifiedName(); + return {SqlctxName(name.Catalog()), SqlctxName(name.Schema()), SqlctxName(name.Name()), "", ""}; +#else + return {view.catalog, view.schema, view.view_name, "", ""}; +#endif +} + +SqlctxStoredView StoredTarget(const DropInfo &drop) { +#if SQLCTX_NEW_IDENTIFIER_API + auto &name = drop.GetQualifiedName(); + return {SqlctxName(name.Catalog()), SqlctxName(name.Schema()), SqlctxName(name.Name()), "", ""}; +#else + return {drop.catalog, drop.schema, drop.name, "", ""}; +#endif +} + +void RunStoredNoop(ClientContext &, TableFunctionInput &, DataChunk &) {} + +ParserExtensionPlanResult StoredNoop() { + ParserExtensionPlanResult result; + result.function = TableFunction("sqlctx_stored_view_noop", {}, RunStoredNoop, + [](ClientContext &, TableFunctionBindInput &, vector &types, vector &names) + -> unique_ptr { + types.push_back(LogicalType::BOOLEAN); + names.emplace_back("Success"); + return nullptr; + }); + result.return_type = StatementReturnType::NOTHING; + return result; +} + +} // namespace + +unique_ptr RewriteSqlctxStoredDDL(ClientContext &context, SQLStatement &statement) { + if (SqlctxDefinitionStoreBypassed() || SqlctxDefinitionTable(context).empty()) return nullptr; + if (statement.type == StatementType::EXPLAIN_STATEMENT) { + auto &explanation = statement.Cast(); + auto child = RewriteSqlctxStoredDDL(context, *explanation.stmt); + if (!child) return nullptr; + auto rewritten = statement.Copy(); + rewritten->Cast().stmt = std::move(child); + return rewritten; + } + SqlctxStoredView target; + string sql; + if (statement.type == StatementType::CREATE_STATEMENT) { + auto &create = statement.Cast(); + if (create.info->type != CatalogType::VIEW_ENTRY || create.info->temporary) return nullptr; + auto info = create.info->Copy(); + auto &view = info->Cast(); + Binder::CreateBinder(context)->SearchSchema(view); + target = StoredTarget(view); + sql = view.ToString(); + } else if (statement.type == StatementType::DROP_STATEMENT) { + auto &drop = *statement.Cast().info; + if (drop.type != CatalogType::VIEW_ENTRY) return nullptr; + target = StoredTarget(drop); + sql = statement.ToString(); + } else return nullptr; + // Respect native objects, particularly temporary views shadowing a stored + // permanent view. Explicit catalog qualification still selects its row. + if (StoreNativeEntry(context, target)) return nullptr; + auto store = ReadSqlctxDefinitionStore(context); + if (!FindSqlctxStoredView(context, store, target.catalog, target.schema, target.name)) return nullptr; + auto data = make_uniq(); + data->operation = "stored_ddl"; + data->content = std::move(sql); + return SqlctxStatement(std::move(data)); +} + +ParserExtensionPlanResult PlanSqlctxStoredDDL(ClientContext &context, const string &sql) { + Parser parser(SqlctxBuiltinParserOptions()); + parser.ParseQuery(sql); + if (parser.statements.size() != 1) throw BinderException("Expected one stored view declaration"); + auto &statement = *parser.statements[0]; + auto store = ReadSqlctxDefinitionStore(context); + if (statement.type == StatementType::DROP_STATEMENT) { + auto &drop = *statement.Cast().info; + auto target = StoredTarget(drop); + auto existing = FindSqlctxStoredView(context, store, target.catalog, target.schema, target.name); + if (!existing) { + if (drop.if_not_found == OnEntryNotFound::RETURN_NULL) return StoredNoop(); + throw CatalogException("View '%s' does not exist", target.name); + } + return PlanSqlctxDefinitionWrite(context, store, *existing, true); + } + if (statement.type != StatementType::CREATE_STATEMENT || + statement.Cast().info->type != CatalogType::VIEW_ENTRY) { + throw BinderException("Expected CREATE VIEW or DROP VIEW for a stored definition"); + } + auto &view = statement.Cast().info->Cast(); + auto binder = Binder::CreateBinder(context); + binder->SearchSchema(view); + auto target = StoredTarget(view); + auto existing = FindSqlctxStoredView(context, store, target.catalog, target.schema, target.name); + if (existing && view.on_conflict == OnCreateConflict::IGNORE_ON_CONFLICT) return StoredNoop(); + if (existing && view.on_conflict != OnCreateConflict::REPLACE_ON_CONFLICT) { + throw CatalogException("View '%s' already exists", target.name); + } + // Persist the resolved source before DuckDB's native view validator strips + // same-catalog qualifiers for its separate native view search-path rules. + BindSqlctxSourceNames(context, *view.query->node); + target.definition_sql = view.ToString(); + target.key = SqlctxViewModelKey(target.catalog, target.schema, target.name); + auto validation = view.Copy(); + binder->BindCreateViewInfo(validation->Cast()); + return PlanSqlctxDefinitionWrite(context, store, target); +} + } // namespace duckdb diff --git a/sqlctx-duckdb/src/sqlctx_explain.cpp b/sqlctx-duckdb/src/sqlctx_explain.cpp index 5aebe0786..c0bb17244 100644 --- a/sqlctx-duckdb/src/sqlctx_explain.cpp +++ b/sqlctx-duckdb/src/sqlctx_explain.cpp @@ -1,40 +1,18 @@ #include "sqlctx_explain.hpp" #include "sqlctx_catalog.hpp" +#include "sqlctx_parser.hpp" +#include "sqlctx_function_metadata.hpp" #include "sqlctx.h" #include "duckdb/common/vector_operations/unary_executor.hpp" #include "duckdb/function/scalar_function.hpp" #include "duckdb/execution/expression_executor_state.hpp" -#include namespace duckdb { static void ExplainFunction(DataChunk &args, ExpressionState &state, Vector &result) { - auto snapshot = ReadSqlctxCatalog(state.GetContext()); - char *error = nullptr; - std::unique_ptr compiler( - sqlctx_compiler_create(snapshot.payload.c_str(), &error), sqlctx_compiler_free); - if (error) { - string message(error); - sqlctx_free(error); - throw InvalidInputException("sqlctx: %s", SqlctxErrorText(message)); - } - if (!compiler) throw InternalException("sqlctx returned no compiler"); UnaryExecutor::Execute(args.data[0], result, args.size(), [&](string_t input) { - auto sql = input.GetString(); - if (sql.find('\0') != string::npos) throw InvalidInputException("sqlctx SQL contains a NUL byte"); - auto report = sqlctx_compiler_explain(compiler.get(), sql.c_str()); - if (report.error) { - string error(report.error); - sqlctx_free_result(report); - throw InvalidInputException("sqlctx: %s", SqlctxErrorText(error)); - } - if (!report.sql) { - sqlctx_free_result(report); - throw InternalException("sqlctx returned no explanation"); - } - string json(report.sql); - sqlctx_free_result(report); - return StringVector::AddString(result, json); + auto plan = PlanSqlctxPublicQuery(state.GetContext(), input.GetString(), true); + return StringVector::AddString(result, plan.explanation); }); } @@ -42,7 +20,9 @@ void RegisterSqlctxExplain(ExtensionLoader &loader) { auto explain = ScalarFunction("sqlctx_explain", {LogicalType::VARCHAR}, LogicalType::VARCHAR, ExplainFunction); explain.SetStability(FunctionStability::VOLATILE); explain.SetFallible(); - loader.RegisterFunction(explain); + RegisterSqlctxFunction(loader, std::move(explain), {"sql"}, + "Return a JSON report containing compiled SQL, warnings, and compiler observations for one SELECT in the caller's catalog scope; no query is executed.", + "sqlctx_explain('select region, aggregate(revenue) from sales')"); } } // namespace duckdb diff --git a/sqlctx-duckdb/src/sqlctx_extension.cpp b/sqlctx-duckdb/src/sqlctx_extension.cpp index d0b1bc014..8ec6dfaee 100644 --- a/sqlctx-duckdb/src/sqlctx_extension.cpp +++ b/sqlctx-duckdb/src/sqlctx_extension.cpp @@ -2,9 +2,13 @@ #include "sqlctx_extension.hpp" #include "sqlctx_explain.hpp" +#include "sqlctx_warnings.hpp" #include "sqlctx_parser.hpp" #include "sqlctx_catalog.hpp" +#include "sqlctx_definition_store.hpp" +#include "sqlctx_measure_catalog.hpp" #include "sqlctx_semantic_input.hpp" +#include "sqlctx_function_metadata.hpp" #include "sqlctx.h" #include "duckdb/function/table_function.hpp" #include "duckdb/common/vector_operations/unary_executor.hpp" @@ -69,7 +73,11 @@ static unique_ptr ModelsInit(ClientContext &context, T sqlctx_free_model_list(models); throw InvalidInputException("sqlctx: %s", SqlctxErrorText(error)); } - for (idx_t i = 0; i < models.count; ++i) state->names.emplace_back(models.models[i].name); + auto public_names = SqlctxMeasureModelNames(context, snapshot); + for (idx_t i = 0; i < models.count; ++i) { + auto named = public_names.find(models.models[i].name); + state->names.emplace_back(named == public_names.end() ? models.models[i].name : named->second); + } sqlctx_free_model_list(models); return std::move(state); } @@ -77,35 +85,32 @@ static unique_ptr ModelsInit(ClientContext &context, T static void ModelsFunction(ClientContext &, TableFunctionInput &input, DataChunk &output) { auto &state = input.global_state->Cast(); auto count = MinValue(STANDARD_VECTOR_SIZE, state.names.size() - state.offset); - for (idx_t i = 0; i < count; ++i) output.SetValue(0, i, Value(state.names[state.offset + i])); + for (idx_t i = 0; i < count; ++i) { +#if SQLCTX_VECTOR_APPEND + output.data[0].Append(Value(state.names[state.offset + i])); +#else + output.SetValue(0, i, Value(state.names[state.offset + i])); +#endif + } state.offset += count; +#if SQLCTX_VECTOR_APPEND + output.CheckCardinality(count); +#else output.SetCardinality(count); +#endif } static void RewriteFunction(DataChunk &args, ExpressionState &state, Vector &result) { - auto snapshot = ReadSqlctxCatalog(state.GetContext()); UnaryExecutor::Execute(args.data[0], result, args.size(), [&](string_t input) { - auto sql = input.GetString(); - if (sql.find('\0') != string::npos) throw InvalidInputException("sqlctx SQL contains a NUL byte"); - auto rewritten = sqlctx_snapshot_rewrite(snapshot.payload.c_str(), sql.c_str()); - if (rewritten.error) { - string error(rewritten.error); - sqlctx_free_result(rewritten); - throw InvalidInputException("sqlctx: %s", SqlctxErrorText(error)); - } - if (!rewritten.sql) { - sqlctx_free_result(rewritten); - throw InternalException("sqlctx returned no SQL"); - } - string sql_result(rewritten.sql); - sqlctx_free_result(rewritten); - return StringVector::AddString(result, sql_result); + auto plan = PlanSqlctxPublicQuery(state.GetContext(), input.GetString(), false); + return StringVector::AddString(result, plan.sql); }); } static void LoadInternal(ExtensionLoader &loader) { auto &db = loader.GetDatabaseInstance(); auto &config = DBConfig::GetConfig(db); + RegisterSqlctxDefinitionStore(config); config.SetOptionByName("allow_parser_override_extension", Value("fallback")); SqlctxParserExtension parser; parser.parser_info = RegisterSqlctxGrammar(db); @@ -115,15 +120,27 @@ static void LoadInternal(ExtensionLoader &loader) { RegisterSqlctxQueryCarrier(loader); RegisterSqlctxDiscovery(db); RegisterSqlctxExplain(loader); - - loader.RegisterFunction(TableFunction("sqlctx_load", {LogicalType::VARCHAR}, LoadFunction, LoadBind, LoadInit)); - loader.RegisterFunction(TableFunction("sqlctx_load_file", {LogicalType::VARCHAR}, LoadFunction, LoadBind, LoadInit)); - loader.RegisterFunction(TableFunction("sqlctx_models", {}, ModelsFunction, ModelsBind, ModelsInit)); + RegisterSqlctxWarnings(loader); + + RegisterSqlctxFunction(loader, + TableFunction("sqlctx_load", {LogicalType::VARCHAR}, LoadFunction, LoadBind, LoadInit), {"yaml"}, + "Load YAML semantic models into the current catalog transaction and return a summary.", + "sqlctx_load('models: [{name: sales, table: raw_sales, primary_key: id}]')"); + RegisterSqlctxFunction(loader, + TableFunction("sqlctx_load_file", {LogicalType::VARCHAR}, LoadFunction, LoadBind, LoadInit), {"path"}, + "Load semantic definitions from a file or directory into the current catalog transaction.", + "sqlctx_load_file('models.yaml')"); + RegisterSqlctxFunction(loader, + TableFunction("sqlctx_models", {}, ModelsFunction, ModelsBind, ModelsInit), {}, + "List public semantic model and selection names visible in the current catalog transaction.", + "sqlctx_models()"); auto rewrite = ScalarFunction("sqlctx_rewrite_sql", {LogicalType::VARCHAR}, LogicalType::VARCHAR, RewriteFunction); rewrite.SetStability(FunctionStability::VOLATILE); rewrite.SetFallible(); - loader.RegisterFunction(rewrite); + RegisterSqlctxFunction(loader, std::move(rewrite), {"sql"}, + "Compile one semantic SELECT using the caller's catalog, schemas, aliases, and physical name precedence; return SQL without executing it.", + "sqlctx_rewrite_sql('select region, revenue from sales')"); RegisterSqlctxSemanticInput(loader); } diff --git a/sqlctx-duckdb/src/sqlctx_grammar.cpp b/sqlctx-duckdb/src/sqlctx_grammar.cpp index c45765b85..cf2e4f12e 100644 --- a/sqlctx-duckdb/src/sqlctx_grammar.cpp +++ b/sqlctx-duckdb/src/sqlctx_grammar.cpp @@ -3,6 +3,8 @@ #if SQLCTX_GRAMMAR_EXTENSION #include "duckdb/main/connection.hpp" #include "duckdb/main/database.hpp" +#include "duckdb/main/config.hpp" +#include "duckdb/main/extension_manager.hpp" #if SQLCTX_SHELL_GRAMMAR_CONTEXT #include "duckdb/main/client_config.hpp" #endif @@ -36,6 +38,26 @@ class DefinitionAtomMatcher final : public AtomicMatcher { string ToString() const override { return "semantic definition property"; } }; +// Yardstick installs its own AS MEASURE transformer when present. Keep the +// standalone declaration local to SQLCtx without changing AliasedExpression. +class StandaloneMeasureMatcher final : public AtomicMatcher { +public: + explicit StandaloneMeasureMatcher(DatabaseInstance &db) : AtomicMatcher(MatcherType::CUSTOM), db(db) {} + MatcherResult MatchAtomic(MatchState &state) const override { + auto token = state.token_iterator.Current(); + if (!token || !StringUtil::CIEquals(token->text, "MEASURE") || + ExtensionManager::Get(db).ExtensionIsLoaded("yardstick")) 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 "MEASURE"; } +private: + DatabaseInstance &db; +}; + // 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 @@ -56,6 +78,13 @@ static auto StartFinalizer(PEGTransformer &transformer, ParseResult &result, Fin #endif } +static void RequireCompatibilityOverride(PEGTransformer &transformer) { + if (transformer.grammar.GetRule("SqlctxYardstickCompatibility") && + transformer.options.parser_override_setting == AllowParserOverride::DEFAULT_OVERRIDE) { + throw ParserException("Yardstick syntax must be processed by the Yardstick parser override"); + } +} + static auto TransformDefinition(PEGTransformer &transformer, ParseResult &result) { auto location = result.GetLocation(); string source(location.length, ' '); @@ -71,7 +100,10 @@ static auto TransformDefinition(PEGTransformer &transformer, ParseResult &result source.replace(token.offset - location.offset, token.length, token.text); } auto definition = ParseSqlctxDefinition(source); - if (!definition) throw InternalException("sqlctx grammar produced an invalid declaration"); + if (!definition || definition->operation == "declare_measure_view") { + RequireCompatibilityOverride(transformer); + if (!definition) throw ParserException("AS MEASURE declarations must be in the top-level CREATE VIEW projection"); + } return StatementResult(transformer, SqlctxStatement(std::move(definition))); } @@ -132,9 +164,11 @@ static auto StartExplain(PEGTransformer &transformer, ParseResult &result) { class SqlctxGrammar final : public GrammarExtension { public: - SqlctxGrammar() : GrammarExtension("sqlctx", "Semantic models, metrics, dimensions, segments and queries") {} + explicit SqlctxGrammar(DatabaseInstance &db, bool compatibility = false) + : GrammarExtension(compatibility ? "yardstick" : "sqlctx", "Semantic models, metrics, dimensions, segments and queries"), + db(db), compatibility(compatibility) {} vector GetChanges() const override { - return { + vector changes { GrammarChange::AddRule("SqlctxAtom <- Identifier"), GrammarChange::AddTerminalRuleOverride("SqlctxAtom", [](const PEGKeywordHelper &) { return make_uniq(); @@ -148,14 +182,21 @@ class SqlctxGrammar final : public GrammarExtension { GrammarChange::AddRule("SqlctxItem <- ('METRIC' / 'DIMENSION' / 'SEGMENT') (SqlctxBlock / SqlctxSource ('AS' Expression / SqlctxBlock))"), GrammarChange::AddRule("SqlctxDefinition <- 'SEMANTIC'? ('CREATE' ('OR' 'REPLACE')?)? (SqlctxModel / SqlctxItem)", StartDefinition), GrammarChange::AddRule("SqlctxView <- 'CREATE' ('OR' 'REPLACE')? 'SEMANTIC' 'VIEW' ColIdOrString 'AS' SelectStatement", StartDefinition), + GrammarChange::AddRule("SqlctxMeasureKeyword <- Identifier"), + GrammarChange::AddTerminalRuleOverride("SqlctxMeasureKeyword", [this](const PEGKeywordHelper &) { + return make_uniq(db); + }), + GrammarChange::AddRule("SqlctxMeasuredField <- Expression 'AS' SqlctxMeasureKeyword ColIdOrString"), + GrammarChange::AddRule("SqlctxMeasureSelect <- WithClause? 'SELECT' (AliasedExpression ',')* SqlctxMeasuredField (',' (SqlctxMeasuredField / AliasedExpression))* ','? ('FROM' SqlctxBody+)?"), + GrammarChange::AddRule("SqlctxMeasureView <- 'SEMANTIC'? 'CREATE' ('OR' 'REPLACE')? ('TEMPORARY' / 'TEMP')? 'VIEW' ('IF' 'NOT' 'EXISTS')? SqlctxSource ColumnAliases? 'AS' SqlctxMeasureSelect", StartDefinition), GrammarChange::AddRule("SqlctxDropView <- 'DROP' 'SEMANTIC' 'VIEW' ('IF' 'EXISTS')? ColIdOrString", StartDefinition), GrammarChange::AddRule("SqlctxDrop <- 'SEMANTIC'? 'DROP' ('MODEL' / 'METRIC' / 'DIMENSION' / 'SEGMENT') ('IF' 'EXISTS')? SqlctxSource", StartDefinition), - GrammarChange::AddRule("SqlctxShow <- 'SHOW' 'SEMANTIC'? ('MODELS' / 'METRICS' / 'DIMENSIONS' / 'SEGMENTS' / 'RELATIONSHIPS') (('FROM' ColIdOrString) / ('FOR' SqlctxSource))?", StartDefinition), - GrammarChange::AddRule("SqlctxDescribe <- ('DESCRIBE' / 'DESC') 'MODEL' ColIdOrString", StartDefinition), + GrammarChange::AddRule("SqlctxShow <- 'SHOW' (('SEMANTIC' 'VIEWS') / ('SEMANTIC'? ('MODELS' / 'METRICS' / 'DIMENSIONS' / 'SEGMENTS' / 'RELATIONSHIPS'))) (('FROM' SqlctxSource) / ('FOR' SqlctxSource))?", StartDefinition), + GrammarChange::AddRule("SqlctxDescribe <- ('DESCRIBE' / 'DESC') 'MODEL' SqlctxSource", StartDefinition), GrammarChange::AddRule("SqlctxExport <- 'EXPORT' 'SEMANTIC' 'CATALOG'", StartDefinition), GrammarChange::AddRule("SqlctxImport <- 'IMPORT' 'SEMANTIC' 'CATALOG' ColIdOrString", StartDefinition), - GrammarChange::AddRule("SqlctxQuery <- 'SEMANTIC' (SelectStatement / CreateStatement / InsertStatement)", StartSemanticQuery), - GrammarChange::AddRule("SqlctxPreparable <- SqlctxShow / SqlctxDescribe / SqlctxExport / SqlctxImport / SqlctxDropView / SqlctxDrop / SqlctxView / SqlctxDefinition / SqlctxQuery"), + GrammarChange::AddRule("SqlctxQuery <- 'SEMANTIC' (SelectStatement / CreateStatement / InsertStatement / DropStatement)", StartSemanticQuery), + 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), GrammarChange::PrependChoice("Statement", "SqlctxDefinition"), @@ -167,22 +208,45 @@ class SqlctxGrammar final : public GrammarExtension { GrammarChange::PrependChoice("Statement", "SqlctxExport"), GrammarChange::PrependChoice("Statement", "SqlctxImport"), GrammarChange::PrependChoice("Statement", "SqlctxQuery"), + // The generic SEMANTIC CREATE branch can accept "AS measure" as + // an ordinary alias before reaching the measure's public name. + GrammarChange::PrependChoice("Statement", "SqlctxMeasureView"), GrammarChange::PrependChoice("Statement", "SqlctxPrepare"), GrammarChange::PrependChoice("Statement", "SqlctxExplain"), }; + if (compatibility) { + changes.push_back(GrammarChange::AddRule("SqlctxYardstickCompatibility <- 'SQLCTX_YARDSTICK_COMPATIBILITY'")); + changes.push_back(GrammarChange::AddRule("SqlctxMisplacedMeasure <- SqlctxMeasureSelect", StartDefinition)); + changes.push_back(GrammarChange::PrependChoice("Statement", "SqlctxMisplacedMeasure")); + } + return changes; } +private: + DatabaseInstance &db; + bool compatibility; }; struct SqlctxGrammarInfo : public SqlctxParserInfo { explicit SqlctxGrammarInfo(DatabaseInstance &database) : SqlctxParserInfo(database) {} shared_ptr default_grammar; shared_ptr grammar; + mutex alias_lock; }; } // namespace +void EnsureSqlctxGrammarAlias(ParserExtensionInfo *info) { + auto native = dynamic_cast(info); + if (!native || ExtensionManager::Get(native->database).ExtensionIsLoaded("yardstick")) return; + lock_guard guard(native->alias_lock); + auto &callbacks = DBConfig::GetConfig(native->database).GetCallbackManager(); + if (!callbacks.FindGrammarExtension("yardstick")) { + GrammarExtension::Register(native->database, make_shared_ptr(native->database, true)); + } +} + shared_ptr RegisterSqlctxGrammar(DatabaseInstance &db) { - auto extension = make_shared_ptr(); + auto extension = make_shared_ptr(db); GrammarExtension::Register(db, extension); auto info = make_shared_ptr(db); info->default_grammar = db.GetParserCache().GetMatcher(); @@ -221,7 +285,12 @@ bool ParseSqlctxGrammar(ParserExtensionInfo *info, const string &sql, const Pars } #endif Parser parser(native); - parser.ParseQuery(sql); + try { + parser.ParseQuery(sql); + } catch (const ParserException &) { + CheckSqlctxMeasureScope(sql); + throw; + } statements = std::move(parser.statements); return true; } @@ -229,6 +298,7 @@ bool ParseSqlctxGrammar(ParserExtensionInfo *info, const string &sql, const Pars } // namespace duckdb #else namespace duckdb { +void EnsureSqlctxGrammarAlias(ParserExtensionInfo *) {} shared_ptr RegisterSqlctxGrammar(DatabaseInstance &db) { return make_shared_ptr(db); } diff --git a/sqlctx-duckdb/src/sqlctx_measure_catalog.cpp b/sqlctx-duckdb/src/sqlctx_measure_catalog.cpp new file mode 100644 index 000000000..d423e129d --- /dev/null +++ b/sqlctx-duckdb/src/sqlctx_measure_catalog.cpp @@ -0,0 +1,551 @@ +#include "sqlctx_measure_catalog.hpp" +#include "sqlctx_definition_store.hpp" +#include "sqlctx_compiler.hpp" +#include "sqlctx_compat.hpp" +#include "sqlctx.h" + +#include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" +#include "duckdb/catalog/catalog_entry/view_catalog_entry.hpp" +#include "duckdb/catalog/catalog_transaction.hpp" +#include "duckdb/function/table_function.hpp" +#include "duckdb/main/attached_database.hpp" +#include "duckdb/main/client_data.hpp" +#include "duckdb/main/client_context_state.hpp" +#include "duckdb/main/database_manager.hpp" +#include "duckdb/parser/parsed_data/create_view_info.hpp" +#include "duckdb/parser/parsed_data/drop_info.hpp" +#include "duckdb/parser/expression/columnref_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/planner/binder.hpp" +#include "duckdb/transaction/meta_transaction.hpp" + +namespace duckdb { + +namespace { + +static constexpr const char *MEASURE_VIEW_TAG = "sqlctx_measure_view"; +static constexpr const char *MEASURE_CATALOG_TAG = "sqlctx_measure_catalog"; + +string QuotedName(const string &name) { + return "\"" + StringUtil::Replace(name, "\"", "\"\"") + "\""; +} + +string DisplayName(ClientContext &context, const string &catalog, const string &schema, const string &name, + const string &key) { + SqlctxMeasureTarget visible; + string visible_key; + if (ResolveSqlctxMeasureView(context, "", "", name, visible, visible_key) && visible_key == key) return name; + if (ResolveSqlctxMeasureView(context, "", schema, name, visible, visible_key) && visible_key == key) { + return QuotedName(schema) + "." + QuotedName(name); + } + return QuotedName(catalog) + "." + QuotedName(schema) + "." + QuotedName(name); +} + +optional_ptr FindRelation(ClientContext &context, const string &catalog, + const string &schema, const string &name) { +#if SQLCTX_NEW_IDENTIFIER_API + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, + QualifiedName(Identifier(catalog), Identifier(schema), Identifier(name))); + return Catalog::GetEntry(context, lookup, OnEntryNotFound::RETURN_NULL); +#else + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, name); + return Catalog::GetEntry(context, catalog, schema, lookup, OnEntryNotFound::RETURN_NULL); +#endif +} + +string ApplyMeasureDefinition(const string &snapshot, const string &content) { + auto result = sqlctx_snapshot_apply(snapshot.c_str(), "", "measure_view", content.c_str(), true); + string error = result.error ? result.error : ""; + string updated = result.snapshot ? result.snapshot : ""; + sqlctx_free_snapshot_result(result); + if (!error.empty()) throw InvalidInputException("sqlctx: %s", SqlctxErrorText(error)); + return updated; +} + +unique_ptr NativeMeasureQuery(ClientContext &context, const SqlctxMeasureDefinition &definition, + const string &key) { + // Validate the semantic model independently of its ordinary native VIEW. + // The native entry preserves the declaration's public rows and columns; + // semantic queries are compiled at the caller's requested grain. + auto snapshot = ApplyMeasureDefinition("", definition.content); + Parser parser(SqlctxBuiltinParserOptions()); + parser.ParseQuery(definition.visible_sql); + if (parser.statements.size() != 1 || parser.statements[0]->type != StatementType::SELECT_STATEMENT) { + throw InternalException("sqlctx measure view has no native SELECT"); + } + if (!definition.virtual_measures.empty()) { + auto probe = parser.statements[0]->Copy(); + auto columns = Binder::CreateBinder(context)->Bind(*probe); + case_insensitive_set_t virtual_measures; + for (auto &name : definition.virtual_measures) virtual_measures.insert(name); + SqlctxCompilerOwner compiler(snapshot); + vector slots, projections; + for (idx_t index = 0; index < columns.names.size(); ++index) { + auto name = SqlctxName(columns.names[index]); + auto slot = "__sqlctx_column_" + to_string(index); + slots.push_back(slot); + string projection = slot; + if (virtual_measures.count(name)) { + auto sql = "SELECT " + QuotedName(key) + "." + QuotedName(name) + " FROM " + QuotedName(key); + auto result = compiler.Rewrite(sql); + string compiled = result.sql ? result.sql : ""; + string error = result.error ? result.error : ""; + sqlctx_free_result(result); + if (!error.empty()) throw BinderException("sqlctx: %s", SqlctxErrorText(error)); + auto message = "SQLCtx measure '" + name + "' requires LOAD sqlctx before querying this view"; + // Bind the real metric expression to retain its type and source + // dependencies, but never evaluate it as a row-level value. + projection = "CASE WHEN true THEN error('" + StringUtil::Replace(message, "'", "''") + + "') ELSE (" + compiled + ") END"; + } + projections.push_back(projection + " AS " + QuotedName(name)); + } + // The compiler's visible row source keeps its required NULL placeholders. + // The persisted native view instead carries correctly typed guards, so + // catalog metadata is accurate and an unloaded reader cannot silently + // mistake an unevaluated virtual measure for missing data. + parser.statements.clear(); + parser.ParseQuery("SELECT " + StringUtil::Join(projections, ", ") + " FROM (" + definition.visible_sql + + ") AS __sqlctx_native(" + StringUtil::Join(slots, ", ") + ")"); + } + return unique_ptr_cast(std::move(parser.statements[0])); +} + +struct MeasureCreateInfo : public TableFunctionInfo { + unique_ptr view; + bool batch_temporary = false; + idx_t batch_remaining_queries = 1; +}; + +struct MeasureCreateData : public TableFunctionData { + unique_ptr view; + bool batch_temporary = false; + idx_t batch_remaining_queries = 1; +}; + +class BatchMeasureViews : public ClientContextState { +public: + struct Entry { + string catalog, schema, name, declaration; + unique_ptr previous; + }; + vector entries; + idx_t remaining_queries = 0; + + void Cleanup(ClientContext &context) { + if (entries.empty()) return; + if (context.transaction.HasActiveTransaction() && + ValidChecker::IsInvalidated(context.transaction.ActiveTransaction())) return; + bool own_transaction = !context.transaction.HasActiveTransaction(); + if (own_transaction) context.transaction.BeginTransaction(); + try { + for (auto i = entries.rbegin(); i != entries.rend(); ++i) { + auto current = FindRelation(context, i->catalog, i->schema, i->name); + // A failed batch may already have rolled back its creation. + if (!current || !SqlctxIsNativeMeasureView(*current) || + current->tags.at(MEASURE_VIEW_TAG) != i->declaration) continue; + auto &catalog = current->ParentCatalog(); + if (i->previous) { + auto restored = i->previous->Copy(); + restored->on_conflict = OnCreateConflict::REPLACE_ON_CONFLICT; + catalog.CreateView(context, restored->Cast()); + } else { + DropInfo drop; + drop.type = CatalogType::VIEW_ENTRY; +#if SQLCTX_NEW_IDENTIFIER_API + drop.SetQualifiedName(Identifier(i->catalog), Identifier(i->schema), Identifier(i->name)); +#else + drop.catalog = i->catalog; + drop.schema = i->schema; + drop.name = i->name; +#endif + catalog.DropEntry(context, drop); + } + } + if (own_transaction) context.transaction.Commit(); + entries.clear(); + remaining_queries = 0; + } catch (...) { + if (own_transaction && context.transaction.HasActiveTransaction()) context.transaction.Rollback(nullptr); + throw; + } + } + + void QueryEnd(ClientContext &context, optional_ptr error) override { + if (!deferred && !error && remaining_queries > 1) { + --remaining_queries; + return; + } + Cleanup(context); + deferred = !entries.empty(); + } + void QueryBegin(ClientContext &context) override { + // Only a failed, invalidated explicit transaction can defer cleanup. + if (deferred) { + Cleanup(context); + deferred = !entries.empty(); + } + } + bool deferred = false; +}; + +static constexpr const char *BATCH_MEASURE_STATE = "sqlctx_batch_measure_views"; + +struct MeasureCreateState : public GlobalTableFunctionState { + bool done = false; +}; + +unique_ptr BindMeasureCreate(ClientContext &context, TableFunctionBindInput &input, + vector &types, vector &names) { + auto &info = input.info->Cast(); + auto data = make_uniq(); + if (info.view) data->view = unique_ptr_cast(info.view->Copy()); + data->batch_temporary = info.batch_temporary; + data->batch_remaining_queries = info.batch_remaining_queries; + types.push_back(LogicalType::BOOLEAN); + names.emplace_back("Success"); + if (input.binder) { + auto &properties = input.binder->GetStatementProperties(); + properties.always_require_rebind = true; + if (data->view) { + auto target_binder = Binder::CreateBinder(context); + auto &schema = target_binder->BindSchema(*data->view); + properties.RegisterDBModify(schema.catalog, context, DatabaseModificationType::CREATE_CATALOG_ENTRY); + } + } + return std::move(data); +} + +unique_ptr InitMeasureCreate(ClientContext &, TableFunctionInitInput &) { + return make_uniq(); +} + +void RunMeasureCreate(ClientContext &context, TableFunctionInput &input, DataChunk &) { + auto &state = input.global_state->Cast(); + if (state.done) return; + auto &data = input.bind_data->Cast(); + if (data.view) { + // Native catalog creation owns conflicts and transactional replacement. + // The declaration metadata lives on the same entry, so DROP, rollback + // and replacement by an ordinary VIEW cannot leave stale definitions. + auto copy = data.view->Copy(); + auto &view = copy->Cast(); + auto binder = Binder::CreateBinder(context); + auto &schema = binder->BindSchema(view); + unique_ptr previous; + if (data.batch_temporary) { + auto prior = FindRelation(context, SqlctxName(schema.catalog.GetName()), SqlctxName(schema.name), +#if SQLCTX_NEW_IDENTIFIER_API + SqlctxName(view.GetViewName())); +#else + view.view_name); +#endif + if (prior && prior->type == CatalogType::VIEW_ENTRY) { + previous = unique_ptr_cast(prior->Cast().GetInfo()); + } + } + CatalogTransaction transaction(schema.catalog, context); + schema.catalog.CreateView(transaction, schema, view); + if (data.batch_temporary) { + auto state = context.registered_state->GetOrCreate(BATCH_MEASURE_STATE); + state->remaining_queries = MaxValue(state->remaining_queries, data.batch_remaining_queries); + state->entries.push_back({SqlctxName(schema.catalog.GetName()), SqlctxName(schema.name), +#if SQLCTX_NEW_IDENTIFIER_API + SqlctxName(view.GetViewName()), +#else + view.view_name, +#endif + view.tags.at(MEASURE_VIEW_TAG), std::move(previous)}); + } + } + state.done = true; +} + +ParserExtensionPlanResult NativeMeasurePlan(ClientContext &context, unique_ptr view, + bool batch_temporary = false, idx_t batch_remaining_queries = 1) { + ParserExtensionPlanResult result; + auto info = make_shared_ptr(); + info->batch_temporary = batch_temporary; + info->batch_remaining_queries = batch_remaining_queries; + if (view) { + auto binder = Binder::CreateBinder(context); + auto &schema = binder->BindSchema(*view); + StatementProperties properties; + properties.RegisterDBModify(schema.catalog, context, DatabaseModificationType::CREATE_CATALOG_ENTRY); + result.modified_databases = std::move(properties.modified_databases); + } + info->view = std::move(view); + result.function = TableFunction("sqlctx_create_measure_view", {}, RunMeasureCreate, + BindMeasureCreate, InitMeasureCreate); + result.function.function_info = std::move(info); + result.return_type = StatementReturnType::NOTHING; + return result; +} + +void SetTarget(CreateViewInfo &info, const SqlctxMeasureTarget &target) { +#if SQLCTX_NEW_IDENTIFIER_API + info.SetQualifiedName(QualifiedName(Identifier(target.catalog), Identifier(target.schema), Identifier(target.name))); +#else + info.catalog = target.catalog; + info.schema = target.schema; + info.view_name = target.name; +#endif + info.temporary = target.temporary; + info.on_conflict = target.replace ? OnCreateConflict::REPLACE_ON_CONFLICT + : target.if_not_exists ? OnCreateConflict::IGNORE_ON_CONFLICT + : OnCreateConflict::ERROR_ON_CONFLICT; +} + +SqlctxMeasureTarget TargetFromInfo(const CreateViewInfo &info) { + SqlctxMeasureTarget target; +#if SQLCTX_NEW_IDENTIFIER_API + target.catalog = SqlctxName(info.GetQualifiedName().Catalog()); + target.schema = SqlctxName(info.GetQualifiedName().Schema()); + target.name = SqlctxName(info.GetViewName()); +#else + target.catalog = info.catalog; + target.schema = info.schema; + target.name = info.view_name; +#endif + target.temporary = info.temporary; + target.replace = info.on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT; + target.if_not_exists = info.on_conflict == OnCreateConflict::IGNORE_ON_CONFLICT; + return target; +} + +} // namespace + +bool SqlctxIsNativeMeasureView(const CatalogEntry &entry) { + return entry.type == CatalogType::VIEW_ENTRY && entry.tags.contains(MEASURE_VIEW_TAG); +} + +bool ResolveSqlctxMeasureView(ClientContext &context, const string &catalog, const string &schema, + const string &name, SqlctxMeasureTarget &target, string &key) { + // An explicit main qualifier selects persistent measure metadata even + // when a session-local view shadows the unqualified name. + auto lookup_catalog = catalog.empty() && StringUtil::CIEquals(schema, DEFAULT_SCHEMA) + ? SqlctxName(DatabaseManager::GetDefaultDatabase(context)) : catalog; + auto entry = FindRelation(context, lookup_catalog, schema, name); + // Preserve SQLCtx's explicit semantic. spelling without masking a + // real object in a user-created semantic schema. + if (!entry && StringUtil::CIEquals(schema, "semantic")) entry = FindRelation(context, catalog, "", name); + if (!entry || !SqlctxIsNativeMeasureView(*entry)) return false; + target.catalog = SqlctxName(entry->ParentCatalog().GetName()); + target.schema = SqlctxName(entry->ParentSchema().name); + target.name = SqlctxName(entry->name); + target.temporary = entry->temporary; + key = SqlctxViewModelKey(target.catalog, target.schema, target.name); + return true; +} + +void RefreshSqlctxNativeMeasureView(ClientContext &context, const SqlctxMeasureTarget &target) { + auto entry = FindRelation(context, target.catalog, target.schema, target.name); + if (entry && SqlctxIsNativeMeasureView(*entry)) { + // Semantic routing replaces the native table reference before DuckDB + // binds it. Preserve the normal native-view metadata refresh, including + // source type changes that only become visible when a view is bound. + entry->Cast().BindView(context, BindViewAction::FORCE_REBIND); + } +} + +void AppendSqlctxNativeMeasureViews(ClientContext &context, SqlctxCatalogSnapshot &snapshot, bool temporary_only) { + struct NativeDefinition { + SqlctxStoredView view; + string origin_catalog; + }; + vector views; + auto collect = [&](Catalog &catalog) { + // These declarations are stored on DuckDB's native view entries. + // External catalogs own their metadata lifecycle and may be in the + // middle of ATTACH while binding internal setup queries. + if (catalog.GetCatalogType() != "duckdb") return; + catalog.ScanSchemas(context, [&](SchemaCatalogEntry &schema) { + schema.Scan(context, CatalogType::VIEW_ENTRY, [&](CatalogEntry &entry) { + if (!SqlctxIsNativeMeasureView(entry)) return; + auto origin = entry.tags.find(MEASURE_CATALOG_TAG); + views.push_back({{SqlctxName(catalog.GetName()), SqlctxName(schema.name), SqlctxName(entry.name), + entry.tags.at(MEASURE_VIEW_TAG), ""}, + origin == entry.tags.end() ? SqlctxName(catalog.GetName()) : origin->second}); + }); + }); + }; + // DatabaseManager's attached databases do not include the session's temp + // catalog. It must be read separately to preserve connection-local views. + if (!temporary_only) { + for (auto &database : DatabaseManager::Get(context).GetDatabases(context)) { + if (!database->IsSystem() && !database->IsTemporary()) collect(database->GetCatalog()); + } + } + collect(ClientData::Get(context).temporary_objects->GetCatalog()); + // CatalogSet scans hold their locks while invoking the callback. Name + // resolution and metadata parsing must happen after every scan unwinds. + for (auto &stored : views) { + auto &view = stored.view; + view.key = SqlctxViewModelKey(view.catalog, view.schema, view.name); + auto parsed = ParseSqlctxStoredDefinition(view.definition_sql, view.key, stored.origin_catalog, view.catalog); + if (!parsed) throw InvalidInputException("Invalid SQLCtx measure metadata on view '%s'", view.name); + snapshot.payload = ApplyMeasureDefinition(snapshot.payload, parsed->content); + snapshot.measure_names[view.key] = DisplayName(context, view.catalog, view.schema, view.name, view.key); + } +} + +void RelocateSqlctxSources(QueryNode &query, const string &old_catalog, const string &new_catalog) { + if (old_catalog.empty() || StringUtil::CIEquals(old_catalog, new_catalog)) return; + std::function expression; + expression = [&](ParsedExpression &value) { + if (value.GetExpressionClass() == ExpressionClass::COLUMN_REF) { + auto &column = value.Cast(); +#if SQLCTX_NEW_EXPRESSION_API + auto &parts = column.ColumnNamesMutable(); +#else + auto &parts = column.column_names; +#endif + if (parts.size() >= 4 && StringUtil::CIEquals(SqlctxName(parts[0]), old_catalog)) { + if (new_catalog.empty()) parts.erase(parts.begin()); + else parts[0] = SqlctxIdentifier(new_catalog); + } + } else if (value.GetExpressionClass() == ExpressionClass::SUBQUERY) { +#if SQLCTX_NEW_EXPRESSION_API + RelocateSqlctxSources(*value.Cast().Subquery()->node, old_catalog, new_catalog); +#else + RelocateSqlctxSources(*value.Cast().subquery->node, old_catalog, new_catalog); +#endif + } + ParsedExpressionIterator::EnumerateChildren(value, [&](ParsedExpression &child) { expression(child); }); + }; + ParsedExpressionIterator::EnumerateQueryNodeChildren(query, + [&](unique_ptr &value) { expression(*value); }, + [&](TableRef &ref) { + if (ref.type != TableReferenceType::BASE_TABLE) return; + auto &table = ref.Cast(); +#if SQLCTX_QUALIFIED_TABLE_API + auto &name = table.GetQualifiedName(); + if (StringUtil::CIEquals(SqlctxName(name.Catalog()), old_catalog)) { + table.SetQualifiedName(Identifier(new_catalog), name.Schema(), name.Name()); + } +#else + if (StringUtil::CIEquals(table.catalog_name, old_catalog)) table.catalog_name = new_catalog; +#endif + }); +} + +case_insensitive_map_t SqlctxMeasureModelNames(ClientContext &context, const SqlctxCatalogSnapshot &snapshot) { + auto names = snapshot.measure_names; + if (snapshot.definitions) { + for (auto &view : snapshot.definitions->views) { + auto visible = FindSqlctxStoredView(context, *snapshot.definitions, "", "", view.name); + if (visible && visible->key == view.key && !FindRelation(context, "", "", view.name)) { + names[view.key] = view.name; + } else { + names[view.key] = QuotedName(view.catalog) + "." + QuotedName(view.schema) + "." + QuotedName(view.name); + } + } + } + return names; +} + +string ResolveSqlctxCatalogModel(ClientContext &context, const SqlctxCatalogSnapshot &snapshot, const string &name) { + if (name.empty()) return name; + Parser parser(SqlctxBuiltinParserOptions()); + parser.ParseQuery("SELECT * FROM " + name); + if (parser.statements.size() != 1) throw ParserException("Expected one semantic model name"); + auto &select = parser.statements[0]->Cast().node->Cast(); + if (!select.from_table || select.from_table->type != TableReferenceType::BASE_TABLE) { + throw ParserException("Expected a semantic model name"); + } + auto &table = select.from_table->Cast(); +#if SQLCTX_NEW_IDENTIFIER_API + auto catalog = SqlctxName(table.GetQualifiedName().Catalog()); + auto schema = SqlctxName(table.GetQualifiedName().Schema()); + auto model = SqlctxName(table.Table()); +#else + auto catalog = table.catalog_name; + auto schema = table.schema_name; + auto model = table.table_name; +#endif + SqlctxMeasureTarget target; + string key; + if (ResolveSqlctxMeasureView(context, catalog, schema, model, target, key) && snapshot.measure_names.count(key)) { + return key; + } + if (snapshot.definitions) { + auto entry = FindSqlctxStoredView(context, *snapshot.definitions, catalog, schema, model); + if (entry) return entry->key; + } + if (catalog.empty() && (schema.empty() || StringUtil::CIEquals(schema, "semantic"))) return model; + return name; +} + +ParserExtensionPlanResult PlanSqlctxMeasureView(ClientContext &context, const string &sql, bool batch_temporary, + idx_t batch_remaining_queries) { + auto target = SqlctxMeasureViewTarget(sql); + auto info = make_uniq(); + SetTarget(*info, target); + auto binder = Binder::CreateBinder(context); + auto &schema = binder->BindSchema(*info); + target = TargetFromInfo(*info); + if (schema.catalog.IsSystemCatalog()) throw BinderException("Cannot create view in system catalog"); + auto key = SqlctxViewModelKey(target.catalog, target.schema, target.name); + + if (!target.temporary && !SqlctxDefinitionTable(context).empty() && !SqlctxDefinitionStoreBypassed()) { + auto physical = FindRelation(context, target.catalog, target.schema, target.name); + if (physical) { + if (target.if_not_exists && physical->type == CatalogType::VIEW_ENTRY) { + return NativeMeasurePlan(context, nullptr); + } + throw CatalogException("Cannot create stored measure view '%s': a native table or view already exists", + target.name); + } + auto store = ReadSqlctxDefinitionStore(context); + auto existing = FindSqlctxStoredView(context, store, target.catalog, target.schema, target.name); + if (existing && target.if_not_exists) return NativeMeasurePlan(context, nullptr); + if (existing && !target.replace) throw CatalogException("View '%s' already exists", target.name); + auto definition = LowerSqlctxMeasureView(context, sql, key); + info->query = NativeMeasureQuery(context, definition, key); + binder->BindCreateViewInfo(*info); + SqlctxStoredView view {target.catalog, target.schema, target.name, definition.definition_sql, key}; + return PlanSqlctxDefinitionWrite(context, store, view); + } + + auto existing = FindRelation(context, target.catalog, target.schema, target.name); + if (existing) { + if (existing->type != CatalogType::VIEW_ENTRY) { + throw CatalogException("Cannot create measure view '%s': a physical table already exists", target.name); + } + if (target.if_not_exists) return NativeMeasurePlan(context, nullptr); + if (!target.replace) throw CatalogException("View '%s' already exists", target.name); + } + // Keep ordinary MODEL definitions separate from native measure views. + if (!target.temporary && StringUtil::CIEquals(target.schema, DEFAULT_SCHEMA)) { + auto snapshot = ReadSqlctxCatalog(context, target.catalog); + auto models = sqlctx_snapshot_list_models(snapshot.payload.c_str()); + string conflict; + for (idx_t i = 0; !models.error && i < models.count; ++i) { + if (StringUtil::CIEquals(models.models[i].name, target.name) && !models.models[i].is_measure_view) { + conflict = target.name; + } + } + string error = models.error ? models.error : ""; + sqlctx_free_model_list(models); + if (!error.empty()) throw InvalidInputException("sqlctx: %s", SqlctxErrorText(error)); + if (!conflict.empty()) throw CatalogException("'%s' is not a SQLCtx measure view; cannot replace the model", conflict); + } + auto definition = LowerSqlctxMeasureView(context, sql, key); + info->query = NativeMeasureQuery(context, definition, key); + // Resolve local sources through the view's catalog search path on reopen. + // DuckDB 2 does this during CREATE binding; stable hosts also need it when + // a database is later attached under a different name without SQLCtx. + RelocateSqlctxSources(*info->query->node, target.catalog, ""); + binder->BindCreateViewInfo(*info); + info->tags.insert(MEASURE_VIEW_TAG, definition.definition_sql); + info->tags.insert(MEASURE_CATALOG_TAG, target.catalog); + info->sql = sql; + return NativeMeasurePlan(context, std::move(info), batch_temporary, batch_remaining_queries); +} + +} // namespace duckdb diff --git a/sqlctx-duckdb/src/sqlctx_parser.cpp b/sqlctx-duckdb/src/sqlctx_parser.cpp index f4768aae0..d6a520739 100644 --- a/sqlctx-duckdb/src/sqlctx_parser.cpp +++ b/sqlctx-duckdb/src/sqlctx_parser.cpp @@ -1,14 +1,28 @@ #include "sqlctx_parser.hpp" #include "sqlctx_catalog.hpp" +#include "sqlctx_measure_view.hpp" +#include "sqlctx_measure_catalog.hpp" +#include "sqlctx_definition_store.hpp" #include "sqlctx_api.hpp" #include "sqlctx.h" +#include "sqlctx_warnings.hpp" +#include "duckdb/catalog/catalog.hpp" +#include "duckdb/catalog/catalog_transaction.hpp" +#include "duckdb/catalog/catalog_entry/table_function_catalog_entry.hpp" +#include "duckdb/catalog/catalog_entry/schema_catalog_entry.hpp" +#include "duckdb/catalog/catalog_entry/view_catalog_entry.hpp" #include "duckdb/common/error_data.hpp" #include "duckdb/main/config.hpp" +#if SQLCTX_NEW_IDENTIFIER_API +#include "duckdb/main/settings.hpp" +#include "duckdb/parser/peg/compiled_grammar.hpp" +#endif #include "duckdb/main/connection_manager.hpp" #include "duckdb/main/database_manager.hpp" #include "duckdb/main/extension_manager.hpp" #include "duckdb/main/prepared_statement_data.hpp" +#include "duckdb/main/query_result.hpp" #include "duckdb/main/valid_checker.hpp" #include "duckdb/parser/expression/columnref_expression.hpp" #include "duckdb/parser/expression/constant_expression.hpp" @@ -17,7 +31,9 @@ #include "duckdb/parser/expression/subquery_expression.hpp" #include "duckdb/parser/expression/star_expression.hpp" #include "duckdb/parser/parsed_data/create_table_info.hpp" +#include "duckdb/parser/parsed_data/create_type_info.hpp" #include "duckdb/parser/parsed_data/create_view_info.hpp" +#include "duckdb/parser/parsed_data/create_table_function_info.hpp" #include "duckdb/parser/parsed_expression_iterator.hpp" #include "duckdb/parser/query_node/select_node.hpp" #include "duckdb/parser/query_node/set_operation_node.hpp" @@ -25,6 +41,15 @@ #include "duckdb/parser/query_node/cte_node.hpp" #include "duckdb/parser/statement/explain_statement.hpp" #include "duckdb/parser/statement/create_statement.hpp" +#include "duckdb/parser/statement/drop_statement.hpp" +#include "duckdb/parser/statement/copy_statement.hpp" +#if SQLCTX_NEW_IDENTIFIER_API +#include "duckdb/parser/statement/update_statement.hpp" +#include "duckdb/parser/statement/delete_statement.hpp" +#include "duckdb/parser/statement/multi_statement.hpp" +#include "duckdb/parser/query_node/update_query_node.hpp" +#include "duckdb/parser/query_node/delete_query_node.hpp" +#endif #include "duckdb/parser/statement/insert_statement.hpp" #include "duckdb/parser/statement/prepare_statement.hpp" #include "duckdb/parser/statement/select_statement.hpp" @@ -41,6 +66,13 @@ #include "duckdb/planner/planner_extension.hpp" #include "duckdb/planner/operator/logical_extension_operator.hpp" #include "duckdb/planner/operator/logical_projection.hpp" +#include "duckdb/planner/operator/logical_get.hpp" +#include "duckdb/planner/operator/logical_create.hpp" +#if SQLCTX_NEW_IDENTIFIER_API +#include "duckdb/planner/operator/logical_drop.hpp" +#else +#include "duckdb/planner/operator/logical_simple.hpp" +#endif #include "duckdb/planner/expression/bound_columnref_expression.hpp" namespace duckdb { @@ -52,6 +84,13 @@ struct SourceToken { idx_t end; }; +void BlankComment(string *source, idx_t start, idx_t end) { + if (!source) return; + for (auto i = start; i < end; ++i) { + if ((*source)[i] != '\n') (*source)[i] = ' '; + } +} + // Use DuckDB's lexer for strings, quoted names and comments on both hosts. // Offsets remain byte offsets into the original SQL, including UTF-8 text. vector Tokens(const string &sql, string *without_comments = nullptr) { @@ -64,15 +103,32 @@ vector Tokens(const string &sql, string *without_comments = nullptr auto start = tokens[i].start; auto end = i + 1 < tokens.size() ? tokens[i + 1].start : sql.size(); if (tokens[i].type == SimplifiedTokenType::SIMPLIFIED_TOKEN_COMMENT) { - if (without_comments) { - for (auto j = start; j < end; ++j) { - if ((*without_comments)[j] != '\n') { - (*without_comments)[j] = ' '; - } + BlankComment(without_comments, start, end); + continue; + } +#if !SQLCTX_GRAMMAR_EXTENSION + // The 1.x lexer gives token starts but omits comments entirely. A + // keyword or punctuation span can therefore include a following + // comment. Keep literals opaque and skip doubled quotes in identifiers. + if (tokens[i].type != SimplifiedTokenType::SIMPLIFIED_TOKEN_STRING_CONSTANT) { + idx_t cursor = start; + if (sql[start] == '"') { + while (++cursor < end) { + if (sql[cursor] != '"') continue; + ++cursor; + if (cursor == end || sql[cursor] != '"') break; + } + } + for (; cursor + 1 < end; ++cursor) { + if ((sql[cursor] == '/' && sql[cursor + 1] == '*') || + (sql[cursor] == '-' && sql[cursor + 1] == '-')) { + BlankComment(without_comments, cursor, end); + end = cursor; + break; } } - continue; } +#endif while (end > start && StringUtil::CharacterIsSpace(sql[end - 1])) { --end; } @@ -99,6 +155,21 @@ string SqlctxLiteral(const string &text) { return "'" + StringUtil::Replace(text, "'", "''") + "'"; } +string JsonString(const string &value) { + string result = "\""; + for (char character : value) { + auto byte = static_cast(character); + if (character == '"' || character == '\\') result += '\\'; + if (byte < 0x20) { + static const char hex[] = "0123456789abcdef"; + result += "\\u00"; + result += hex[byte >> 4]; + result += hex[byte & 15]; + } else result += character; + } + return result + '"'; +} + string QualifiedNameJson(const vector &tokens, idx_t pos, idx_t max_names) { string result = "["; idx_t count = 0; @@ -108,18 +179,7 @@ string QualifiedNameJson(const vector &tokens, idx_t pos, idx_t max throw ParserException("Expected a semantic identifier"); } if (count++) result += ","; - result += '"'; - for (auto character : IdentifierText(token)) { - auto byte = static_cast(character); - if (character == '"' || character == '\\') result += '\\'; - if (byte < 0x20) { - static const char hex[] = "0123456789abcdef"; - result += "\\u00"; - result += hex[byte >> 4]; - result += hex[byte & 15]; - } else result += character; - } - result += '"'; + result += JsonString(IdentifierText(token)); if (pos == tokens.size()) break; if (tokens[pos++].text != "." || pos == tokens.size()) { throw ParserException("Expected one qualified semantic name"); @@ -271,7 +331,10 @@ bool CanonicalField(const SqlctxModelInfo *model, string &name) { return false; } -string UnknownFieldMessage(const SqlctxModelInfo &model, const string &field) { +string UnknownFieldMessage(const SqlctxModelInfo &model, const string &field, + const case_insensitive_map_t &public_names) { + auto public_name = public_names.find(model.name); + auto name = public_name == public_names.end() ? string(model.name) : public_name->second; vector fields(model.fields, model.fields + model.field_count); auto suffix = field.rfind("__"); if (suffix != string::npos) { @@ -279,11 +342,12 @@ string UnknownFieldMessage(const SqlctxModelInfo &model, const string &field) { if (StringUtil::CIEquals(candidate, field.substr(0, suffix))) { return StringUtil::Format("sqlctx: unknown time grain '%s' in %s.%s. Valid grains: year, " "quarter, month, week, day, hour, minute, second", - field.substr(suffix + 2), model.name, field); + field.substr(suffix + 2), name, field); } } } - auto message = StringUtil::Format("sqlctx: model %s has no field '%s'.", model.name, field); + auto message = StringUtil::Format("sqlctx: %s %s has no field '%s'.", + model.is_measure_view ? "measure view" : "model", name, field); auto close = StringUtil::TopNLevenshtein(fields, field, 3); if (!close.empty()) message += " Did you mean " + StringUtil::Join(close, ", ") + "?"; return message + " Fields: " + StringUtil::Join(fields, ", "); @@ -313,11 +377,14 @@ struct ModelBinding { using ModelScope = case_insensitive_map_t; using CteNames = case_insensitive_set_t; +string StarRelation(ParsedExpression &expression); + class SemanticReferences { public: - SemanticReferences(ClientContext &context, const SqlctxModelList &list, bool explicit_semantic, + SemanticReferences(ClientContext &context, const SqlctxModelList &list, const SqlctxCatalogSnapshot &snapshot, + bool explicit_semantic, const unordered_set &compiled) - : context(context), explicit_semantic(explicit_semantic), compiled(compiled) { + : context(context), snapshot(snapshot), explicit_semantic(explicit_semantic), compiled(compiled) { for (idx_t i = 0; i < list.count; ++i) { models[list.models[i].name] = {&list.models[i], false}; } @@ -368,7 +435,17 @@ class SemanticReferences { auto inspect = [&](unique_ptr &expression) { found |= Expression(*expression, scope, ctes); }; - for (auto &expression : select.select_list) inspect(expression); + for (auto &expression : select.select_list) { + if (expression->GetExpressionClass() == ExpressionClass::STAR) { + auto qualifier = StarRelation(*expression); + for (auto &source : sources) { + auto &binding = scope[source]; + if ((qualifier.empty() || StringUtil::CIEquals(qualifier, source)) && + binding.model && !binding.use) found = true; + } + } + inspect(expression); + } for (auto &expression : select.groups.group_expressions) inspect(expression); if (select.where_clause) inspect(select.where_clause); if (select.having) inspect(select.having); @@ -384,12 +461,19 @@ class SemanticReferences { // a lambda parameter or alias, so it is reported only for an otherwise // non-semantic query, which could not bind against a model natively either. void ThrowUnknownField(bool found) { - if (qualified_unknown.model) throw BinderException(UnknownFieldMessage(*qualified_unknown.model, qualified_unknown.field)); - if (!found && bare_unknown.model) throw BinderException(UnknownFieldMessage(*bare_unknown.model, bare_unknown.field)); + if (qualified_unknown.model) { + throw BinderException(UnknownFieldMessage(*qualified_unknown.model, qualified_unknown.field, + SqlctxMeasureModelNames(context, snapshot))); + } + if (!found && bare_unknown.model) { + throw BinderException(UnknownFieldMessage(*bare_unknown.model, bare_unknown.field, + SqlctxMeasureModelNames(context, snapshot))); + } } private: ClientContext &context; + const SqlctxCatalogSnapshot &snapshot; bool explicit_semantic; const unordered_set &compiled; ModelScope models; @@ -465,6 +549,17 @@ class SemanticReferences { !SqlctxPhysicalRelationExists(context, name); auto entry = models.find(name); if (((!qualified && !ctes.count(name)) || semantic_schema) && entry != models.end()) model = entry->second.model; + if (explicit_semantic && !model && !ctes.count(name) && !StringUtil::CIEquals(name, "metrics")) { + // Preserve the host's missing-relation diagnostic before the + // semantic compiler tries to resolve fields in that source. +#if SQLCTX_QUALIFIED_TABLE_API + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, table.GetQualifiedName()); + Catalog::GetEntry(context, lookup, OnEntryNotFound::THROW_EXCEPTION); +#else + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, name); + Catalog::GetEntry(context, catalog, schema, lookup, OnEntryNotFound::THROW_EXCEPTION); +#endif + } // FROM metrics is the global semantic namespace. A CTE or a real // table on the search path still owns its name in ordinary SQL. if (!model && !qualified && !ctes.count(name) && !models.empty() && @@ -667,16 +762,342 @@ string QuoteName(const string &name) { return "\"" + StringUtil::Replace(name, "\"", "\"\"") + "\""; } +string DiscoveryName(const vector &tokens, idx_t pos, idx_t max_names) { + QualifiedNameJson(tokens, pos, max_names); // Validate the same identifier grammar as mutation names. + vector parts; + for (; pos < tokens.size(); pos += 2) parts.push_back(QuoteName(IdentifierText(tokens[pos].text))); + return StringUtil::Join(parts, "."); +} + +// Evaluate each referenced input in its original FROM scope. In particular, +// a.price and b.price in a join must remain distinct when a measure is later +// compiled against the model's row source at the caller's requested grain. +void ProjectMeasureInputs(unique_ptr &expr, SelectNode &rows, + case_insensitive_set_t &names, unordered_map &inputs, + const case_insensitive_map_t &measures, bool inside_aggregate = false) { + switch (expr->GetExpressionClass()) { + case ExpressionClass::COLUMN_REF: { + auto &column = expr->Cast(); + auto derived = measures.find(SqlctxName(column.GetColumnName())); + if (!inside_aggregate && !column.IsQualified() && derived != measures.end()) { + // A formula such as revenue / order_count refers to declared + // measures. Inside SUM(revenue), revenue is a source column. + expr = make_uniq(SqlctxIdentifier(derived->second)); + return; + } + // Physical columns and scalar subqueries both evaluate in the original + // row scope. Keep the entire subquery there, including its correlations. + [[fallthrough]]; + } + case ExpressionClass::SUBQUERY: { + auto key = expr->ToString(); + auto &name = inputs[key]; + if (name.empty()) { + idx_t index = rows.select_list.size(); + do { + name = "__sqlctx_measure_input_" + to_string(index++); + } while (!names.insert(name).second); + expr->SetAlias(SqlctxIdentifier(name)); + rows.select_list.push_back(std::move(expr)); + } + expr = make_uniq(SqlctxIdentifier(name)); + return; + } + case ExpressionClass::LAMBDA: + throw ParserException("Place lambdas in the measure view's FROM source"); + default: + if (expr->GetExpressionClass() == ExpressionClass::WINDOW || + (expr->GetExpressionClass() == ExpressionClass::FUNCTION && IsAggregateFunction(FunctionName(*expr)))) { + inside_aggregate = true; + } + ParsedExpressionIterator::EnumerateChildren(*expr, [&](unique_ptr &child) { + ProjectMeasureInputs(child, rows, names, inputs, measures, inside_aggregate); + }); + } +} + +struct MeasureViewSyntax { + idx_t body = 0; + unordered_set measures; +}; + +bool IsMeasureAlias(const vector &tokens, idx_t i) { + if (!Keyword(tokens, i, "AS") || !Keyword(tokens, i + 1, "MEASURE") || i + 2 >= tokens.size()) return false; + auto &alias = tokens[i + 2].text; + if (alias == "," || alias == ")" || alias == ";" || Keyword(tokens, i + 2, "FROM")) return false; + return i + 3 == tokens.size() || tokens[i + 3].text == "," || tokens[i + 3].text == ")" || + tokens[i + 3].text == ";" || Keyword(tokens, i + 3, "FROM"); +} + +MeasureViewSyntax FindMeasureFields(string &clean, const vector &tokens) { + MeasureViewSyntax syntax; + // Erase only projection-level markers, leaving DuckDB to parse ordinary + // expressions, aliases, source relations, filters and literal contents. + idx_t field = 0; + int depth = 0; + bool projection = false; + for (idx_t i = 0; i < tokens.size(); ++i) { + auto &token = tokens[i].text; + if (depth > 0 && IsMeasureAlias(tokens, i)) { + throw ParserException("AS MEASURE declarations must be in the top-level CREATE VIEW projection"); + } + if (token == "(" || token == "[" || token == "{") ++depth; + else if (token == ")" || token == "]" || token == "}") --depth; + else if (depth == 0) { + if (!syntax.body && Keyword(tokens, i, "AS")) { + syntax.body = i + 1; + continue; + } + if (!projection) { + projection = syntax.body && Keyword(tokens, i, "SELECT"); + continue; + } + if (Keyword(tokens, i, "FROM")) break; + if (token == ",") ++field; + if (IsMeasureAlias(tokens, i)) { + syntax.measures.insert(field); + auto &marker = tokens[i + 1]; + clean.replace(marker.start, marker.end - marker.start, marker.end - marker.start, ' '); + } + } + } + return syntax; +} + +// The visible DuckDB view materializes order statistics and DISTINCT values +// at its declared grain. AGGREGATE can still recompute them from original rows. +bool MaterializedMeasure(const ParsedExpression &expression) { + if (expression.GetExpressionClass() == ExpressionClass::SUBQUERY) return false; + if (expression.GetExpressionClass() == ExpressionClass::FUNCTION) { + auto &function = expression.Cast(); +#if SQLCTX_NEW_EXPRESSION_API + auto name = SqlctxName(function.FunctionName()); + if (function.Distinct()) return true; +#else + auto name = function.function_name; + if (function.distinct) return true; +#endif + static const case_insensitive_set_t ordered { + "median", "mode", "quantile", "quantile_cont", "quantile_disc", "percentile_cont", "percentile_disc"}; + if (ordered.count(name)) return true; + } + bool materialized = false; + ParsedExpressionIterator::EnumerateChildren(expression, [&](const ParsedExpression &child) { + materialized |= MaterializedMeasure(child); + }); + return materialized; +} + +SqlctxMeasureDefinition BuildMeasureDefinition(ClientContext *context, const string &declaration, + const string &model_key, const string &old_catalog = "", + const string &new_catalog = "") { + string clean; + auto tokens = Tokens(declaration, &clean); + while (!tokens.empty() && tokens.back().text == ";") tokens.pop_back(); + auto syntax = FindMeasureFields(clean, tokens); + if (syntax.measures.empty()) return {}; + auto options = context ? SqlctxContextParserOptions(*context) : SqlctxBuiltinParserOptions(); + Parser parser(options); + parser.ParseQuery(clean); + auto &info = parser.statements.at(0)->Cast().info->Cast(); +#if SQLCTX_NEW_IDENTIFIER_API + const string public_name = SqlctxName(info.GetViewName()); +#else + const string public_name = info.view_name; +#endif + auto &query = *info.query; + if (query.node->type != QueryNodeType::SELECT_NODE) { + throw ParserException("A measure view requires one SELECT over a row source"); + } + auto &rows = query.node->Cast(); + if (context) BindSqlctxSourceNames(*context, rows); + else if (!old_catalog.empty() && old_catalog != new_catalog) RelocateSqlctxSources(rows, old_catalog, new_catalog); + auto projections = std::move(rows.select_list); + vector> fields; + unordered_set measures; + // Stored definitions freeze expanded column names so they can be restored + // without binding the source. Preserve how those names were declared for + // VISIBLE modifiers, which require listed dimensions in joined queries. + static constexpr const char *wildcard_marker = " /* sqlctx: expanded wildcard projection */"; + bool wildcard_projection = !context && StringUtil::EndsWith(declaration, wildcard_marker); + for (idx_t i = 0; i < projections.size(); ++i) { + if (syntax.measures.count(i)) measures.insert(fields.size()); + if (projections[i]->GetExpressionClass() != ExpressionClass::STAR) { + fields.push_back(std::move(projections[i])); + continue; + } + if (!context) throw InvalidInputException("Stored measure view contains an unbound star"); + wildcard_projection = true; + auto probe = rows.Copy(); + auto &selection = probe->Cast(); + selection.select_list.push_back(std::move(projections[i])); + auto bound = Binder::CreateBinder(*context)->Bind(*probe); + // DuckDB retains the expanded parsed expressions with source qualifiers, + // REPLACE expressions and RENAME aliases. Output names alone cannot + // reconstruct these projections (and may be ambiguous across joins). + for (auto &expression : bound.extra_info.original_expressions) { + fields.push_back(std::move(expression)); + } + } + if (info.aliases.size() > fields.size()) throw BinderException("More VIEW aliases than columns in query result"); + case_insensitive_set_t names; + case_insensitive_map_t measure_names; + vector aliases, header, declared_projection, window_dimensions, window_measures, materialized_measures; + vector virtual_measures; + bool renamed = false; + auto visible_node = rows.Copy(); + auto &visible = visible_node->Cast(); + bool materialized_aggregate = false; + for (idx_t i = 0; i < fields.size(); ++i) { + auto &expr = fields[i]; + auto declared = SqlctxName(expr->GetName()); + auto name = i < info.aliases.size() ? SqlctxName(info.aliases[i]) : declared; + renamed |= name != declared; + if (!names.insert(name).second) throw ParserException("Duplicate measure view field '%s'", name); + if (measures.count(i)) measure_names[declared] = name; + aliases.push_back(name); + header.push_back(QuoteName(name)); + auto expression_sql = expr->ToString(); + bool measure = measures.count(i) != 0; + declared_projection.push_back(expression_sql + (measure ? " AS MEASURE " : " AS ") + QuoteName(declared)); + bool materialize = measure && MaterializedMeasure(*expr); + materialized_aggregate |= materialize && !expr->IsWindow(); + if (measure && (materialize || expr->IsWindow())) materialized_measures.push_back(JsonString(name)); + unique_ptr projected; + if (!measure || materialize || expr->IsWindow()) { + projected = expr->Copy(); + } else { + virtual_measures.push_back(name); +#if SQLCTX_LITERAL_API + projected = ConstantExpression::Null(); +#else + projected = make_uniq(Value()); +#endif + } + projected->SetAlias(SqlctxIdentifier(declared)); + visible.select_list.push_back(std::move(projected)); + (measure ? window_measures : window_dimensions).push_back( + "{\"name\":" + JsonString(name) + ",\"sql\":" + JsonString(expression_sql) + "}"); + } + // Let DuckDB render the complete relation, including its CTEs and result + // modifiers. Substitute the one projection we supplied at this SELECT's + // depth, leaving any identically named columns in nested queries alone. + const string placeholder = "__sqlctx_declaration_projection"; + rows.select_list.push_back(make_uniq(SqlctxIdentifier(placeholder))); + auto skeleton = rows.ToString(); + rows.select_list.clear(); + idx_t projection_start = string::npos; + int depth = 0; + bool at_select = false; + for (auto &token : Tokens(skeleton)) { + if (token.text == "(") ++depth; + else if (token.text == ")") --depth; + else if (!depth && StringUtil::CIEquals(token.text, "SELECT")) at_select = true; + else if (!depth && at_select && token.text == placeholder) { + projection_start = token.start; + break; + } + } + if (projection_start == string::npos) throw InternalException("Cannot locate SQLCtx declaration projection"); + auto render_projection = [&](const vector &projection) { + string result = skeleton; + result.replace(projection_start, placeholder.size(), StringUtil::Join(projection, ", ")); + return result; + }; + if (materialized_aggregate && visible.groups.grouping_sets.empty()) { + visible.aggregate_handling = AggregateHandling::FORCE_AGGREGATES; + } + // Outer rows retain the declaration's own grain and modifiers. The model + // reads the underlying rows so distinct counts and averages can be + // recomputed across grains, including groups with overlapping values. + rows.groups = GroupByNode(); + rows.aggregate_handling = AggregateHandling::STANDARD_HANDLING; + rows.modifiers.clear(); + rows.having.reset(); + rows.qualify.reset(); + vector dimensions, metrics, projection_order; + unordered_map inputs; + for (idx_t i = 0; i < fields.size(); ++i) { + auto &expr = fields[i]; + auto &name = aliases[i]; + projection_order.push_back(JsonString(name)); + expr->ClearAlias(); + string sql; + bool measure = measures.count(i); + if (measure) { + ProjectMeasureInputs(expr, rows, names, inputs, measure_names); + sql = expr->ToString(); + } else { + if (expr->IsAggregate() || expr->IsWindow()) { + throw ParserException("Declare aggregate fields with AS MEASURE; put window expressions in the FROM source"); + } + expr->SetAlias(SqlctxIdentifier(name)); + rows.select_list.push_back(std::move(expr)); + sql = QuoteName(name); + } + (measure ? metrics : dimensions).push_back("{\"name\":" + JsonString(name) + ",\"sql\":" + JsonString(sql) + "}"); + } + // COUNT(*) needs the row cardinality even when no columns are projected. + if (rows.select_list.empty()) { +#if SQLCTX_LITERAL_API + rows.select_list.push_back(ConstantExpression::Integer(1)); +#else + rows.select_list.push_back(make_uniq(Value::INTEGER(1))); +#endif + } + if (context) { + auto source = rows.Copy(); + Binder::CreateBinder(*context)->Bind(*source); + auto output = visible.Copy(); + Binder::CreateBinder(*context)->Bind(*output); + } + auto source_sql = rows.ToString(); + auto visible_sql = visible.ToString(); + auto column_list = "(" + StringUtil::Join(header, ", ") + ")"; + auto view_header = "CREATE VIEW " + QuoteName(public_name) + column_list + " AS "; + SqlctxMeasureDefinition result; + result.virtual_measures = std::move(virtual_measures); + result.visible_sql = visible_sql; + if (renamed) { + // View headers rename by position. Polyglot's derived-table alias list + // stores plain strings, so keep public identifiers in the projection + // AST where quoting (including embedded quotes) survives generation. + vector slots, named_slots; + for (idx_t i = 0; i < header.size(); ++i) { + auto slot = "__sqlctx_column_" + to_string(i); + slots.push_back(slot); + named_slots.push_back(slot + " AS " + header[i]); + } + result.visible_sql = "SELECT " + StringUtil::Join(named_slots, ", ") + " FROM (" + visible_sql + + ") AS __sqlctx_visible(" + StringUtil::Join(slots, ", ") + ")"; + } + result.content = "{\"name\":" + JsonString(model_key) + + ",\"public_name\":" + JsonString(public_name) + + ",\"wildcard_projection\":" + (wildcard_projection ? "true" : "false") + + ",\"source_sql\":" + JsonString(source_sql) + + ",\"dimensions\":[" + StringUtil::Join(dimensions, ",") + + "],\"measures\":[" + StringUtil::Join(metrics, ",") + + "],\"projection_order\":[" + StringUtil::Join(projection_order, ",") + + "],\"materialized_measures\":[" + StringUtil::Join(materialized_measures, ",") + + "],\"visible_source_sql\":" + JsonString(result.visible_sql) + + ",\"window_source_sql\":" + JsonString(view_header + visible_sql) + + ",\"window_dimensions\":[" + StringUtil::Join(window_dimensions, ",") + + "],\"window_measures\":[" + StringUtil::Join(window_measures, ",") + "]}"; + result.definition_sql = view_header + render_projection(declared_projection); + if (wildcard_projection) result.definition_sql += wildcard_marker; + return result; +} + // semantic. behaves like a view whose grain is the set of model // dimensions the surrounding query uses. Each reference becomes a derived // table; DuckDB keeps ownership of joins, outer aggregates and other SQL. class SemanticRelations { public: - SemanticRelations(ClientContext &context, const SqlctxModelList &list, const string &snapshot) + SemanticRelations(ClientContext &context, const SqlctxModelList &list, const SqlctxCatalogSnapshot &snapshot) : context(context) { auto current = SqlctxName(DatabaseManager::GetDefaultDatabase(context)); auto catalog = make_uniq(); - catalog->snapshot = {snapshot, "", current}; + catalog->snapshot = snapshot; for (idx_t i = 0; i < list.count; ++i) catalog->models[list.models[i].name] = &list.models[i]; catalogs[current] = std::move(catalog); } @@ -687,29 +1108,34 @@ class SemanticRelations { const SqlctxCatalogSnapshot &snapshot; }; vector relations; + bool changed = false; + bool measure_bindings = false; - void Query(QueryNode &node) { + void Query(QueryNode &node, CteNames ctes = {}) { for (auto &cte : node.cte_map.map) { #if SQLCTX_NEW_IDENTIFIER_API - Query(*cte.second->query_node); + Query(*cte.second->query_node, ctes); #else - Query(*cte.second->query->node); + Query(*cte.second->query->node, ctes); #endif + ctes.insert(SqlctxName(cte.first)); } switch (node.type) { case QueryNodeType::SET_OPERATION_NODE: - for (auto &child : node.Cast().children) Query(*child); + for (auto &child : node.Cast().children) Query(*child, ctes); return; case QueryNodeType::RECURSIVE_CTE_NODE: - Query(*node.Cast().left); - Query(*node.Cast().right); + ctes.insert(SqlctxName(node.Cast().ctename)); + Query(*node.Cast().left, ctes); + Query(*node.Cast().right, ctes); return; case QueryNodeType::CTE_NODE: - Query(*node.Cast().query); - Query(*node.Cast().child); + Query(*node.Cast().query, ctes); + ctes.insert(SqlctxName(node.Cast().ctename)); + Query(*node.Cast().child, ctes); return; case QueryNodeType::SELECT_NODE: - Select(node.Cast()); + Select(node.Cast(), ctes); return; default: return; @@ -736,6 +1162,13 @@ class SemanticRelations { vector> filters; }; + struct StoredBinding { + string catalog; + string schema; + string name; + string alias; + }; + ClientContext &context; case_insensitive_map_t> catalogs; @@ -791,10 +1224,14 @@ class SemanticRelations { return model_fields[base]; } - void Select(SelectNode &select) { + void Select(SelectNode &select, const CteNames &ctes) { vector found; - if (select.from_table) Collect(select.from_table, false, found); - auto nested = [&](unique_ptr &expression) { Subqueries(*expression); }; + vector bindings; + if (select.from_table) Collect(select.from_table, false, found, bindings, ctes); + CheckOrdinaryViewMeasures(select, bindings, ctes); + auto normalize = [&](unique_ptr &expression) { StoredQualifiers(*expression, bindings); }; + Expressions(select, normalize); + auto nested = [&](unique_ptr &expression) { Subqueries(*expression, ctes); }; Expressions(select, nested); if (found.empty()) return; @@ -834,6 +1271,84 @@ class SemanticRelations { for (auto &relation : found) Replace(relation); } + void CheckOrdinaryViewMeasures(SelectNode &select, const vector &bindings, const CteNames &ctes) { + // A native ordinary view exposes values, not a defining measure. Keep + // this boundary explicit instead of letting DuckDB's unrelated list + // aggregate overload report a type error for AGGREGATE(view_column). + std::function check = [&](ParsedExpression &expression) { + if (expression.GetExpressionClass() == ExpressionClass::SUBQUERY || + expression.GetExpressionClass() == ExpressionClass::WINDOW) return; + if (expression.GetExpressionClass() == ExpressionClass::FUNCTION && FunctionName(expression) == "aggregate") { + auto &function = expression.Cast(); +#if SQLCTX_NEW_EXPRESSION_API + auto &arguments = function.GetArguments(); + const ParsedExpression *argument = arguments.size() == 1 ? &arguments[0].GetExpression() : nullptr; +#else + auto &arguments = function.children; + const ParsedExpression *argument = arguments.size() == 1 ? arguments[0].get() : nullptr; +#endif + if (argument && argument->GetExpressionClass() == ExpressionClass::COLUMN_REF) { + auto &column = argument->Cast(); +#if SQLCTX_NEW_EXPRESSION_API + auto &names = column.ColumnNames(); +#else + auto &names = column.column_names; +#endif + auto field = SqlctxName(names.back()); + auto qualifier = names.size() > 1 ? SqlctxName(names[names.size() - 2]) : string(); + bool direct = false; + for (auto &binding : bindings) { + direct |= qualifier.empty() || StringUtil::CIEquals(qualifier, binding.alias); + } + if (!direct && select.from_table) { + std::function source = [&](TableRef &ref) { + if (ref.type == TableReferenceType::JOIN) { + auto &join = ref.Cast(); + source(*join.left); + source(*join.right); + return; + } + if (ref.type != TableReferenceType::BASE_TABLE) return; + auto &base = ref.Cast(); +#if SQLCTX_NEW_IDENTIFIER_API + auto &name = base.GetQualifiedName(); + auto table = SqlctxName(name.Name()); + if (name.Catalog().empty() && name.Schema().empty() && ctes.count(table)) return; +#else + auto table = base.table_name; + if (base.catalog_name.empty() && base.schema_name.empty() && ctes.count(table)) return; +#endif + auto alias = ref.alias.empty() ? table : SqlctxName(ref.alias); + if (!qualifier.empty() && !StringUtil::CIEquals(qualifier, alias)) return; +#if SQLCTX_NEW_IDENTIFIER_API + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, name); + auto entry = Catalog::GetEntry(context, lookup, OnEntryNotFound::RETURN_NULL); +#else + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, table); + auto entry = Catalog::GetEntry(context, base.catalog_name, base.schema_name, lookup, + OnEntryNotFound::RETURN_NULL); +#endif + if (!entry || entry->type != CatalogType::VIEW_ENTRY || SqlctxIsNativeMeasureView(*entry)) return; + auto &view = entry->Cast(); + view.BindView(context); + auto columns = view.GetColumnInfo(); + if (!columns) return; + for (auto &name : columns->names) { + if (StringUtil::CIEquals(field, SqlctxName(name))) { + throw BinderException("Measure %s is read through %s, which does not define it", field, alias); + } + } + }; + source(*select.from_table); + } + } + } + ParsedExpressionIterator::EnumerateChildren(expression, [&](ParsedExpression &child) { check(child); }); + }; + auto visit = [&](unique_ptr &expression) { check(*expression); }; + Expressions(select, visit); + } + template void Expressions(SelectNode &select, CALLBACK &callback) { for (auto &expression : select.select_list) callback(expression); @@ -854,34 +1369,80 @@ class SemanticRelations { JoinConditions(*join.right, callback); } - void Subqueries(ParsedExpression &expression) { + void Subqueries(ParsedExpression &expression, const CteNames &ctes) { if (expression.GetExpressionClass() == ExpressionClass::SUBQUERY) { #if SQLCTX_NEW_EXPRESSION_API - Query(*expression.Cast().Subquery()->node); + Query(*expression.Cast().Subquery()->node, ctes); #else - Query(*expression.Cast().subquery->node); + Query(*expression.Cast().subquery->node, ctes); #endif } - ParsedExpressionIterator::EnumerateChildren(expression, [&](ParsedExpression &child) { Subqueries(child); }); + ParsedExpressionIterator::EnumerateChildren(expression, [&](ParsedExpression &child) { Subqueries(child, ctes); }); } - void Collect(unique_ptr &slot, bool nullable, vector &found) { + void StoredQualifiers(ParsedExpression &expression, const vector &bindings) { + if (expression.GetExpressionClass() == ExpressionClass::SUBQUERY) { +#if SQLCTX_NEW_EXPRESSION_API + auto &query = *expression.Cast().Subquery()->node; +#else + auto &query = *expression.Cast().subquery->node; +#endif + StoredQueryQualifiers(query, bindings); + return; + } + if (expression.GetExpressionClass() == ExpressionClass::COLUMN_REF) { + auto &column = expression.Cast(); +#if SQLCTX_NEW_EXPRESSION_API + auto &names = column.ColumnNamesMutable(); +#else + auto &names = column.column_names; +#endif + if (names.size() == 3 || names.size() == 4) { + for (auto &binding : bindings) { + if (!StringUtil::CIEquals(binding.alias, binding.name) || + !StringUtil::CIEquals(SqlctxName(names[names.size() - 2]), binding.name) || + !StringUtil::CIEquals(SqlctxName(names[names.size() - 3]), binding.schema) || + (names.size() == 4 && !StringUtil::CIEquals(SqlctxName(names[0]), binding.catalog))) continue; + names.erase(names.begin(), names.end() - 2); + names[0] = SqlctxIdentifier(binding.alias); + break; + } + } + } + ParsedExpressionIterator::EnumerateChildren(expression, [&](ParsedExpression &child) { StoredQualifiers(child, bindings); }); + } + + void StoredQueryQualifiers(QueryNode &query, const vector &bindings) { + // Qualified outer references retain their catalog identity across a + // subquery boundary. Canonical model keys use the preserved SQL alias, + // including correlations inside EXISTS and scalar SELECTs. + ParsedExpressionIterator::EnumerateQueryNodeChildren(query, + [&](unique_ptr &expression) { StoredQualifiers(*expression, bindings); }, + [&](TableRef &table) { + if (table.type == TableReferenceType::SUBQUERY) { + StoredQueryQualifiers(*table.Cast().subquery->node, bindings); + } + }); + } + + void Collect(unique_ptr &slot, bool nullable, vector &found, + vector &bindings, const CteNames &ctes) { auto &ref = *slot; switch (ref.type) { case TableReferenceType::JOIN: { auto &join = ref.Cast(); bool left_nullable = join.type == JoinType::RIGHT || join.type == JoinType::OUTER; bool right_nullable = join.type == JoinType::LEFT || join.type == JoinType::OUTER; - Collect(join.left, nullable || left_nullable, found); - Collect(join.right, nullable || right_nullable, found); + Collect(join.left, nullable || left_nullable, found, bindings, ctes); + Collect(join.right, nullable || right_nullable, found, bindings, ctes); return; } case TableReferenceType::SUBQUERY: - Query(*ref.Cast().subquery->node); + Query(*ref.Cast().subquery->node, ctes); return; case TableReferenceType::SHOW_REF: { auto &show = ref.Cast(); - if (show.query) Query(*show.query); + if (show.query) Query(*show.query, ctes); return; } case TableReferenceType::BASE_TABLE: @@ -899,6 +1460,70 @@ class SemanticRelations { auto schema = table.schema_name; auto catalog_name = table.catalog_name; #endif + if (catalog_name.empty() && schema.empty() && ctes.count(name)) return; + auto ¤t = GetCatalog(""); + string model_key; + SqlctxMeasureTarget target; + optional_ptr stored; + if (current.snapshot.definitions) { + // Native objects, including temporary views, retain precedence. + auto lookup_catalog = catalog_name; + if (lookup_catalog.empty() && StringUtil::CIEquals(schema, DEFAULT_SCHEMA)) { + lookup_catalog = SqlctxName(DatabaseManager::GetDefaultDatabase(context)); + } +#if SQLCTX_NEW_IDENTIFIER_API + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, + QualifiedName(Identifier(lookup_catalog), Identifier(schema), Identifier(name))); + auto physical = Catalog::GetEntry(context, lookup, OnEntryNotFound::RETURN_NULL); +#else + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, name); + auto physical = Catalog::GetEntry(context, lookup_catalog, schema, lookup, OnEntryNotFound::RETURN_NULL); +#endif + if (physical && physical->temporary && SqlctxIsNativeMeasureView(*physical)) { + ResolveSqlctxMeasureView(context, catalog_name, schema, name, target, model_key); + } else if (!physical) { + stored = FindSqlctxStoredView(context, *current.snapshot.definitions, catalog_name, schema, name); + } + if (stored) { + target.catalog = stored->catalog; + target.schema = stored->schema; + target.name = stored->name; + model_key = stored->key; + } + } else { + ResolveSqlctxMeasureView(context, catalog_name, schema, name, target, model_key); + } + if (!model_key.empty()) { + if (!stored) RefreshSqlctxNativeMeasureView(context, target); + auto alias = ref.alias.empty() ? name : SqlctxName(ref.alias); + bindings.push_back({target.catalog, target.schema, target.name, alias}); + if (!current.models.count(model_key)) { + if (!stored) throw InternalException("Native measure view missing from compiler snapshot"); + Parser parser(SqlctxBuiltinParserOptions()); + parser.ParseQuery(stored->definition_sql); + if (parser.statements.size() != 1 || parser.statements[0]->type != StatementType::CREATE_STATEMENT || + parser.statements[0]->Cast().info->type != CatalogType::VIEW_ENTRY) { + throw InvalidInputException("Stored definition for '%s' must be one CREATE VIEW statement", stored->name); + } + auto &view = parser.statements.at(0)->Cast().info->Cast(); + auto replacement = make_uniq(std::move(view.query), SqlctxIdentifier(alias)); + replacement->column_name_alias = view.aliases; + Query(*replacement->subquery->node, ctes); + slot = std::move(replacement); + } else { + measure_bindings = true; +#if SQLCTX_QUALIFIED_TABLE_API + table.SetQualifiedName(Identifier(), Identifier(), Identifier(model_key)); +#else + table.catalog_name.clear(); + table.schema_name.clear(); + table.table_name = model_key; +#endif + table.alias = SqlctxIdentifier(alias); + } + changed = true; + return; + } if (!StringUtil::CIEquals(schema, "semantic")) return; // A user-created semantic schema keeps its physical relations. if (SqlctxPhysicalRelationExists(context, name, catalog_name)) return; @@ -912,6 +1537,11 @@ class SemanticRelations { throw BinderException("sqlctx: no semantic model named '%s'%s", name, close.empty() ? "" : ". Did you mean " + StringUtil::Join(close, ", ") + "?"); } + // Measure views have query-scoped AGGREGATE semantics. Keep current- + // catalog references intact for the whole-query compiler instead of + // computing their metrics in a derived table below AGGREGATE. + if (entry->second->is_measure_view && StringUtil::CIEquals(catalog.snapshot.catalog, + SqlctxName(DatabaseManager::GetDefaultDatabase(context)))) return; Relation relation; relation.slot = &slot; relation.model = entry->second; @@ -975,7 +1605,8 @@ class SemanticRelations { for (auto &candidate : found) { auto base = suffix == string::npos ? string() : name.substr(0, suffix); if (!base.empty() && CanonicalField(candidate.model, base)) { - throw BinderException(UnknownFieldMessage(*candidate.model, name)); + throw BinderException(UnknownFieldMessage(*candidate.model, name, + SqlctxMeasureModelNames(context, candidate.catalog->snapshot))); } } return nullptr; @@ -985,7 +1616,8 @@ class SemanticRelations { } field = SqlctxName(names.back()); if (!CanonicalField(relation->model, field)) { - throw BinderException(UnknownFieldMessage(*relation->model, field)); + throw BinderException(UnknownFieldMessage(*relation->model, field, + SqlctxMeasureModelNames(context, relation->catalog->snapshot))); } return relation; } @@ -1125,13 +1757,42 @@ class SemanticRelations { void CheckReaggregation(SelectNode &select, vector &found) { case_insensitive_map_t grouped; auto group = [&](ParsedExpression &expression) { - if (expression.GetExpressionClass() != ExpressionClass::COLUMN_REF) return; + auto target = &expression; + if (target->GetExpressionClass() == ExpressionClass::CONSTANT) { + auto &constant = target->Cast(); + int64_t ordinal; +#if SQLCTX_LITERAL_API + if (!constant.GetLiteral().TryGetInt64(ordinal)) return; +#else + auto type = constant.value.type().id(); + if (constant.value.IsNull() || (type != LogicalTypeId::INTEGER && type != LogicalTypeId::BIGINT)) return; + ordinal = constant.value.GetValue(); +#endif + if (ordinal < 1 || idx_t(ordinal) > select.select_list.size()) return; + // A preceding star changes positions during binding. Leave that + // proof to DuckDB rather than treating the unexpanded slot as a field. + for (idx_t i = 0; i < idx_t(ordinal); ++i) { + if (select.select_list[i]->GetExpressionClass() == ExpressionClass::STAR) return; + } + target = select.select_list[idx_t(ordinal) - 1].get(); + } + if (target->GetExpressionClass() != ExpressionClass::COLUMN_REF) return; string field; - auto relation = Resolve(expression.Cast(), found, field); + auto relation = Resolve(target->Cast(), found, field); if (relation) grouped[relation->alias].insert(field); }; bool group_all = select.aggregate_handling == AggregateHandling::FORCE_AGGREGATES; - for (auto &expression : select.groups.group_expressions) group(*expression); + for (idx_t i = 0; i < select.groups.group_expressions.size(); ++i) { + // A rollup or grouping set can remove dimensions: only fields + // present in every set prove that each outer group holds one row. + bool always_grouped = true; + for (auto &set : select.groups.grouping_sets) { + bool present = false; + for (auto index : set) present |= idx_t(index) == i; + if (!present) always_grouped = false; + } + if (always_grouped) group(*select.groups.group_expressions[i]); + } if (group_all) { for (auto &expression : select.select_list) group(*expression); } @@ -1225,6 +1886,9 @@ SelectStatement *QueryInStatement(SQLStatement &statement, bool include_insert_c auto &info = *statement.Cast().info; if (info.type == CatalogType::VIEW_ENTRY) return info.Cast().query.get(); if (info.type == CatalogType::TABLE_ENTRY) return info.Cast().query.get(); + if (info.type == CatalogType::TYPE_ENTRY && info.Cast().query) { + return QueryInStatement(*info.Cast().query, include_insert_ctes); + } } if (statement.type == StatementType::INSERT_STATEMENT) { #if SQLCTX_INSERT_QUERY_NODE @@ -1249,43 +1913,70 @@ SelectStatement *QueryInStatement(SQLStatement &statement, bool include_insert_c return nullptr; } -unique_ptr CompileSemanticSelect(const SqlctxCatalogSnapshot &snapshot, const string &sql) { - auto result = sqlctx_snapshot_rewrite(snapshot.payload.c_str(), sql.c_str()); - if (result.error) { - string error(result.error); - sqlctx_free_result(result); - throw BinderException("sqlctx: %s", SqlctxErrorText(error)); - } - if (!result.sql) { - sqlctx_free_result(result); - throw InternalException("sqlctx returned no rewritten SQL"); +using SqlctxCompileCallback = std::function; + +unique_ptr CompileSemanticSelect(ClientContext &context, const SqlctxCatalogSnapshot &snapshot, const string &sql, + bool validate_view_warnings = false, + const SqlctxCompileCallback *compile = nullptr) { + string warnings; + auto compiled = compile ? (*compile)(snapshot, sql) + : CompileSqlctxWithWarnings(snapshot, sql, &warnings, !validate_view_warnings); + if (validate_view_warnings && !warnings.empty()) { + // Definition diagnostics belong to CREATE VIEW. Persist only the + // compiled query so later reads cannot replay them under new settings. + HandleSqlctxWarnings(context, warnings); } - string compiled(result.sql); - sqlctx_free_result(result); - Parser parser(SqlctxBuiltinParserOptions()); + Parser parser(SqlctxContextParserOptions(context)); parser.ParseQuery(compiled); if (parser.statements.size() != 1 || parser.statements[0]->type != StatementType::SELECT_STATEMENT) { throw BinderException("sqlctx rewrite must produce one SELECT statement"); } - return std::move(parser.statements[0]->Cast().node); + auto node = std::move(parser.statements[0]->Cast().node); + return node; +} + +bool IsExecutingViewDefinition(SQLStatement &statement) { + if (statement.type == StatementType::EXPLAIN_STATEMENT) { + auto &explain = statement.Cast(); + return explain.explain_type == ExplainType::EXPLAIN_ANALYZE && IsExecutingViewDefinition(*explain.stmt); + } + return statement.type == StatementType::CREATE_STATEMENT && + statement.Cast().info->type == CatalogType::VIEW_ENTRY; +} + +void UpdateCompiledViewSQL(SQLStatement &statement) { + if (statement.type == StatementType::EXPLAIN_STATEMENT) { + UpdateCompiledViewSQL(*statement.Cast().stmt); + } else if (statement.type == StatementType::CREATE_STATEMENT) { + auto &info = *statement.Cast().info; + if (info.type == CatalogType::VIEW_ENTRY) { + // The extension grammar does not populate DuckDB's original-SQL + // field. Persist the SQL that agrees with the compiled view AST. + info.sql = info.ToString(); + } + } } unique_ptr CompileSemanticStatement(ClientContext &context, SQLStatement &statement, const SqlctxCatalogSnapshot &snapshot, bool explicit_semantic = false, - const SqlctxModelList *cached_models = nullptr) { + const SqlctxModelList *cached_models = nullptr, + const SqlctxCompileCallback *compile = nullptr) { auto rewritten = statement.Copy(); auto query = QueryInStatement(*rewritten, true); if (!query) return nullptr; + // 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); unique_ptr owned_models; if (!cached_models) owned_models = make_uniq(snapshot.payload); auto &models = cached_models ? *cached_models : owned_models->list; - SemanticRelations relations(context, models, snapshot.payload); + SemanticRelations relations(context, models, snapshot); relations.Query(*query->node); unordered_set derived; for (auto &relation : relations.relations) derived.insert(&relation.relation.get()); - SemanticReferences references(context, models, explicit_semantic, derived); - bool found = references.Query(*query->node) || explicit_semantic; + SemanticReferences references(context, models, snapshot, explicit_semantic, derived); + bool found = references.Query(*query->node) || explicit_semantic || relations.measure_bindings; references.ThrowUnknownField(found); for (auto &relation : relations.relations) { bool attached = !StringUtil::CIEquals(relation.snapshot.catalog, @@ -1295,16 +1986,19 @@ unique_ptr CompileSemanticStatement(ClientContext &context, SQLSta // their fully qualified physical SQL. if (found && !attached) continue; auto &subquery = *relation.relation.get().subquery; - subquery.node = CompileSemanticSelect(relation.snapshot, subquery.node->ToString()); + subquery.node = CompileSemanticSelect(context, relation.snapshot, subquery.node->ToString(), validate_view_warnings, + compile); if (attached) QualifySqlctxSources(context, *subquery.node, relation.snapshot.catalog); } if (!found) { - if (relations.relations.empty()) return nullptr; + if (relations.relations.empty() && !relations.changed) return nullptr; // Only semantic relations: compile each derived table and leave the // rest of the statement, including DESCRIBE/SUMMARIZE, to DuckDB. + UpdateCompiledViewSQL(*rewritten); return rewritten; } - query->node = CompileSemanticSelect(snapshot, query->ToString()); + query->node = CompileSemanticSelect(context, snapshot, query->ToString(), validate_view_warnings, compile); + UpdateCompiledViewSQL(*rewritten); return rewritten; } @@ -1358,7 +2052,9 @@ constexpr const char *ROUTING_PROBE = "sqlctx_pristine_show"; // responsibility of SemanticReferences, after this candidate-name filter. struct RoutingReferences { case_insensitive_set_t names; + vector sources; bool semantic = false; + bool aggregate = false; void Query(QueryNode &node) { auto expression = [&](unique_ptr &expr) { Expression(*expr); }; @@ -1373,6 +2069,7 @@ struct RoutingReferences { #endif if (ref.type != TableReferenceType::BASE_TABLE) return; auto &base = ref.Cast(); + sources.push_back(&base); #if SQLCTX_QUALIFIED_TABLE_API auto schema = SqlctxName(base.GetQualifiedName().Schema()); auto catalog = SqlctxName(base.GetQualifiedName().Catalog()); @@ -1383,7 +2080,7 @@ struct RoutingReferences { auto name = base.table_name; #endif if (StringUtil::CIEquals(schema, "semantic")) semantic = true; - if (schema.empty() && catalog.empty()) names.insert(name); + names.insert(name); }; if (node.type == QueryNodeType::CTE_NODE) { auto &cte = node.Cast(); @@ -1395,6 +2092,9 @@ struct RoutingReferences { } void Expression(ParsedExpression &expr) { + if (expr.GetExpressionClass() == ExpressionClass::FUNCTION && FunctionName(expr) == "aggregate") { + aggregate = true; + } if (expr.GetExpressionClass() == ExpressionClass::SUBQUERY) { #if SQLCTX_NEW_EXPRESSION_API Query(*expr.Cast().Subquery()->node); @@ -1406,6 +2106,21 @@ struct RoutingReferences { } bool Possible() const { return semantic || !names.empty(); } + bool OnlyNativeTables(ClientContext &context) const { + if (sources.empty()) return false; + for (auto source : sources) { +#if SQLCTX_QUALIFIED_TABLE_API + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, source->GetQualifiedName()); + auto entry = Catalog::GetEntry(context, lookup, OnEntryNotFound::RETURN_NULL); +#else + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, source->table_name); + auto entry = Catalog::GetEntry(context, source->catalog_name, source->schema_name, lookup, + OnEntryNotFound::RETURN_NULL); +#endif + if (!entry || entry->type != CatalogType::TABLE_ENTRY) return false; + } + return true; + } bool Matches(const SqlctxModelList &models) const { if (semantic || names.count("metrics")) return true; for (idx_t i = 0; i < models.count; ++i) if (names.count(models.models[i].name)) return true; @@ -1440,8 +2155,9 @@ string CarrierParserSettings(const ParserOptions &options) { return settings; } -unique_ptr ParseCarrier(const string &sql, const string &settings) { - auto options = SqlctxBuiltinParserOptions(); +unique_ptr ParseCarrier(ClientContext &context, const string &sql, const string &settings, + bool allow_discovery) { + auto options = SqlctxContextParserOptions(context); if (!settings.empty()) { auto parts = StringUtil::Split(settings, ':'); if (parts.size() != 3 || (parts[0] != "0" && parts[0] != "1") || @@ -1459,14 +2175,29 @@ unique_ptr ParseCarrier(const string &sql, const string &settin options.preserve_identifier_case = parts[1] == "preserve"; #endif } - Parser parser(options); - parser.ParseQuery(sql); - if (parser.statements.size() != 1) throw BinderException("sqlctx query carrier expects one query"); - auto statement = std::move(parser.statements[0]); + vector> statements; + for (auto &extension : DBConfig::GetConfig(context).GetCallbackManager().ParserExtensions()) { + if (extension.plan_function == sqlctx_plan && + ParseSqlctxGrammar(extension.parser_info.get(), sql, options, statements)) break; + } + if (statements.empty()) { + Parser parser(options); + parser.ParseQuery(sql); + statements = std::move(parser.statements); + } + if (statements.size() != 1) throw BinderException("sqlctx query carrier expects one query"); + auto statement = std::move(statements[0]); while (statement->type == StatementType::PREPARE_STATEMENT) { auto prepared = std::move(statement->Cast().statement); statement = std::move(prepared); } + if (allow_discovery && statement->type == StatementType::EXTENSION_STATEMENT) { + auto &extension = statement->Cast(); + if (extension.extension.plan_function == sqlctx_plan && + StringUtil::StartsWith(static_cast(*extension.parse_data).operation, "show_")) { + return statement; + } + } auto query = QueryInStatement(*statement, true); if (!query) throw BinderException("sqlctx query carrier expects a SELECT query source"); return unique_ptr_cast(query->Copy()); @@ -1527,6 +2258,134 @@ unique_ptr UnwrapQueryCarrier(SelectStatement &query) { return PrivateCarrierQuery(table); } +bool IsSqlctxQueryCarrier(TableFunctionCatalogEntry &entry); + +vector ViewWrapperWarnings(ClientContext &context, QueryNode &query, bool remove) { + vector warnings; + auto expression = [&](unique_ptr &) {}; + auto table = [&](TableRef &ref) { + if (ref.type != TableReferenceType::TABLE_FUNCTION) return; + auto &function = ref.Cast().function; + if (!function || function->GetExpressionClass() != ExpressionClass::FUNCTION || + (FunctionName(*function) != "yardstick" && FunctionName(*function) != "sqlctx_query")) return; + auto &call = function->Cast(); +#if SQLCTX_NEW_IDENTIFIER_API + EntryLookupInfo lookup(CatalogType::TABLE_FUNCTION_ENTRY, call.GetQualifiedName()); + auto entry = Catalog::GetEntry(context, lookup, OnEntryNotFound::RETURN_NULL); +#else + EntryLookupInfo lookup(CatalogType::TABLE_FUNCTION_ENTRY, call.function_name); + auto entry = Catalog::GetEntry(context, call.catalog, call.schema, lookup, OnEntryNotFound::RETURN_NULL); +#endif + if (!entry || !IsSqlctxQueryCarrier(entry->Cast())) return; +#if SQLCTX_NEW_EXPRESSION_API + auto &arguments = call.GetArgumentsMutable(); + if (arguments.size() != 2) return; + auto &message = arguments[1].GetExpressionMutable(); +#else + auto &arguments = call.children; + if (arguments.size() != 2) return; + auto &message = arguments[1]; +#endif + if (message->GetExpressionClass() != ExpressionClass::CONSTANT) return; +#if SQLCTX_LITERAL_API + auto value = message->Cast().GetLiteral().ToValue(); +#else + auto value = message->Cast().value; +#endif + if (value.IsNull() || value.type().id() != LogicalTypeId::VARCHAR || value.GetValue().empty()) return; + warnings.push_back(value.GetValue()); + if (remove) { +#if SQLCTX_LITERAL_API + message = ConstantExpression::String(""); +#else + message = make_uniq(Value("")); +#endif + } + }; + ParsedExpressionIterator::EnumerateQueryNodeChildren(query, expression, table); + return warnings; +} + +unique_ptr RewriteViewWrapperWarnings(ClientContext &context, SQLStatement &statement) { + if (!IsExecutingViewDefinition(statement) || + ExtensionManager::Get(*context.db).ExtensionIsLoaded("yardstick")) return nullptr; + auto rewritten = statement.Copy(); + auto query = QueryInStatement(*rewritten); + if (!query) return nullptr; + if (auto original = UnwrapQueryCarrier(*query)) query->node = std::move(original->node); + auto warnings = ViewWrapperWarnings(context, *query->node, true); + if (warnings.empty()) return nullptr; + for (auto &warning : warnings) HandleSqlctxWarnings(context, warning); + return rewritten; +} + +bool MeasureViewNamespace(ClientContext &context, const string &catalog, const string &schema) { + return (catalog.empty() || StringUtil::CIEquals(catalog, SqlctxName(DatabaseManager::GetDefaultDatabase(context)))) && + (schema.empty() || StringUtil::CIEquals(schema, "main") || StringUtil::CIEquals(schema, "semantic")); +} + +unique_ptr MeasureViewDrop(ClientContext &context, const DropInfo &info) { + if (info.type != CatalogType::VIEW_ENTRY) return nullptr; +#if SQLCTX_NEW_IDENTIFIER_API + auto catalog = SqlctxName(info.GetQualifiedName().Catalog()); + auto schema = SqlctxName(info.GetQualifiedName().Schema()); + auto name = SqlctxName(info.GetQualifiedName().Name()); + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, info.GetQualifiedName()); + auto physical = Catalog::GetEntry(context, lookup, OnEntryNotFound::RETURN_NULL); +#else + auto &catalog = info.catalog; + auto &schema = info.schema; + auto &name = info.name; + EntryLookupInfo lookup(CatalogType::TABLE_ENTRY, name); + auto physical = Catalog::GetEntry(context, catalog, schema, lookup, OnEntryNotFound::RETURN_NULL); +#endif + if (catalog.empty() && StringUtil::CIEquals(schema, DEFAULT_SCHEMA)) { + SqlctxMeasureTarget target; + string key; + if (ResolveSqlctxMeasureView(context, catalog, schema, name, target, key)) { + auto statement = make_uniq(); + statement->info = info.Copy(); +#if SQLCTX_NEW_IDENTIFIER_API + statement->info->SetQualifiedName(Identifier(target.catalog), Identifier(target.schema), Identifier(target.name)); +#else + statement->info->catalog = target.catalog; + statement->info->schema = target.schema; + statement->info->name = target.name; +#endif + return std::move(statement); + } + } + if (physical || !MeasureViewNamespace(context, catalog, schema)) return nullptr; + if (SqlctxIsSemanticView(context, name)) { + throw BinderException("'%s' is a semantic view. Use DROP SEMANTIC VIEW %s", name, QuoteName(name)); + } + if (!SqlctxIsMeasureView(context, name)) return nullptr; + if (info.cascade) throw BinderException("DROP VIEW CASCADE is not supported for SQLCtx measure views"); + auto data = make_uniq(); + data->operation = "drop_measure_view"; + data->content = "[" + JsonString(name) + "]"; + data->replace = info.if_not_found == OnEntryNotFound::RETURN_NULL; + return SqlctxStatement(std::move(data)); +} + +void CheckNativeViewCollision(ClientContext &context, const CreateInfo &info, StatementProperties &properties) { + if (info.type != CatalogType::VIEW_ENTRY) return; +#if SQLCTX_NEW_IDENTIFIER_API + auto catalog = SqlctxName(info.GetQualifiedName().Catalog()); + auto schema = SqlctxName(info.GetQualifiedName().Schema()); + auto name = SqlctxName(info.GetQualifiedName().Name()); +#else + auto &catalog = info.catalog; + auto &schema = info.schema; + auto &name = info.Cast().view_name; +#endif + if (!MeasureViewNamespace(context, catalog, schema)) return; + RegisterSqlctxCatalogRead(context, properties); + if (SqlctxIsMeasureView(context, name)) { + throw CatalogException("Cannot create ordinary view '%s': a SQLCtx measure view already exists; DROP VIEW first", name); + } +} + class SqlctxRoutingState : public ClientContextState { public: explicit SqlctxRoutingState(ClientContext &context) : context(context) {} @@ -1546,7 +2405,9 @@ class SqlctxRoutingState : public ClientContextState { probing = false; probe_error = false; if (own_probe) { - candidate = SemanticShowStatement(statement); + candidate = error.ExtraInfo().at(ROUTING_PROBE) == "measure" ? Candidate(statement) : SemanticShowStatement(statement); + // Discovery probes also see ordinary DESCRIBE statements. When + // there is no semantic candidate, retry their untouched AST once. return RebindQueryInfo::ATTEMPT_TO_REBIND; } if (error.Type() != ExceptionType::BINDER && error.Type() != ExceptionType::CATALOG) { @@ -1578,15 +2439,29 @@ class SqlctxRoutingState : public ClientContextState { } unique_ptr Candidate(SQLStatement &statement) { + if (SqlctxDefinitionStoreBypassed()) return nullptr; + if (auto view = RewriteViewWrapperWarnings(context, statement)) { + auto compiled = Candidate(*view); + return compiled ? std::move(compiled) : std::move(view); + } + if (auto stored = RewriteSqlctxStoredDDL(context, statement)) return stored; if (statement.type == StatementType::PREPARE_STATEMENT) { return Candidate(*statement.Cast().statement); } + if (statement.type == StatementType::DROP_STATEMENT) { + return MeasureViewDrop(context, *statement.Cast().info); + } if (auto show = SemanticShowStatement(statement)) return show; auto query = QueryInStatement(statement); - if (!query) return nullptr; + if (!query) { + auto rewritten = statement.Copy(); + bool changed = RewriteAuxiliaryQueries(*rewritten); + return changed ? std::move(rewritten) : nullptr; + } RoutingReferences refs; refs.Query(*query->node); if (!refs.Possible()) return nullptr; + if (!SqlctxDefinitionTable(context).empty() && refs.OnlyNativeTables(context)) return nullptr; SqlctxCatalogSnapshot snapshot; try { snapshot = ReadSqlctxCatalog(context); @@ -1608,7 +2483,9 @@ class SqlctxRoutingState : public ClientContextState { model_snapshot = snapshot.payload; models = std::move(replacement); } - if (!refs.Matches(models->list)) return nullptr; + bool measure_views = false; + for (idx_t i = 0; i < models->list.count; ++i) measure_views |= models->list.models[i].is_measure_view; + if (!refs.Matches(models->list) && !measure_views && !snapshot.definitions) return nullptr; return CompileSemanticStatement(context, statement, snapshot, false, &models->list); } @@ -1628,6 +2505,54 @@ class SqlctxRoutingState : public ClientContextState { bool probing = false; bool probe_error = false; private: + bool RewriteAuxiliaryQueries(SQLStatement &statement) { + if (statement.type == StatementType::EXPLAIN_STATEMENT) { + return RewriteAuxiliaryQueries(*statement.Cast().stmt); + } + auto rewrite = [&](SelectStatement &query) { + auto compiled = Candidate(query); + if (!compiled) return false; + query.node = std::move(compiled->Cast().node); + return true; + }; + if (statement.type == StatementType::COPY_STATEMENT) { + auto &node = statement.Cast().info->select_statement; + if (!node) return false; + SelectStatement query; + query.node = std::move(node); + bool changed = rewrite(query); + node = std::move(query.node); + return changed; + } +#if SQLCTX_NEW_IDENTIFIER_API + QueryNode *node = nullptr; + if (statement.type == StatementType::UPDATE_STATEMENT) node = statement.Cast().node.get(); + if (statement.type == StatementType::DELETE_STATEMENT) node = statement.Cast().node.get(); + if (!node) return false; + bool changed = false; + for (auto &entry : node->cte_map.map) { + SelectStatement query; + query.node = std::move(entry.second->query_node); + changed |= rewrite(query); + entry.second->query_node = std::move(query.node); + } + std::function &)> expression = [&](unique_ptr &expr) { + if (expr->GetExpressionClass() == ExpressionClass::SUBQUERY) { + changed |= rewrite(*expr->Cast().SubqueryMutable()); + return; + } + ParsedExpressionIterator::EnumerateChildren(*expr, expression); + }; + auto table = [&](TableRef &ref) { + if (ref.type == TableReferenceType::SUBQUERY) changed |= rewrite(*ref.Cast().subquery); + }; + ParsedExpressionIterator::EnumerateQueryNodeChildren(*node, expression, table); + return changed; +#else + return false; +#endif + } + ClientContext &context; string model_snapshot; unique_ptr models; @@ -1641,13 +2566,17 @@ unique_ptr BindQueryCarrier(ClientContext &context, TableFuncti #endif vector &names) { if (input.inputs[0].IsNull()) throw InvalidInputException("sqlctx query carrier cannot be NULL"); + auto function_name = FunctionName(*input.ref.function); + bool compatibility = function_name == "yardstick" || function_name == "yardstick_scoped" || + function_name == "sqlctx_query" || function_name == "sqlctx_query_scoped"; unique_ptr statement = PrivateCarrierQuery(input.ref); if (!statement) { if (input.inputs.size() > 1 && input.inputs[1].IsNull()) { throw InvalidInputException("sqlctx query carrier parser settings cannot be NULL"); } - statement = ParseCarrier(input.inputs[0].GetValue(), - input.inputs.size() > 1 ? input.inputs[1].GetValue() : ""); + statement = ParseCarrier(context, input.inputs[0].GetValue(), compatibility + ? CarrierParserSettings(SqlctxContextParserOptions(context)) + : (input.inputs.size() > 1 ? input.inputs[1].GetValue() : ""), !compatibility); } auto state = context.registered_state->GetOrCreate(ROUTING_STATE, context); auto compiled = state->Candidate(*statement); @@ -1655,15 +2584,22 @@ unique_ptr BindQueryCarrier(ClientContext &context, TableFuncti statement = std::move(compiled); if (input.binder) RegisterSqlctxCatalogRead(context, input.binder->GetStatementProperties()); } + if (compatibility && input.inputs.size() > 1 && !input.inputs[1].GetValue().empty()) { + Parser parser(SqlctxContextParserOptions(context)); + parser.ParseQuery(WrapSqlctxQueryWarnings(statement->ToString(), input.inputs[1].GetValue())); + statement = std::move(parser.statements[0]); + } if (!input.binder) throw InternalException("sqlctx query carrier requires a binder"); auto child = Binder::CreateBinder(context, input.binder.get()); child->SetCanContainNulls(true); auto bound = child->Bind(*statement); + if (compatibility) QueryResult::DeduplicateColumns(bound.names); input.binder->MergeCorrelatedColumns(child->correlated_columns); auto bindings = bound.plan->GetColumnBindings(); vector> expressions; for (idx_t i = 0; i < bound.names.size(); ++i) { - names.emplace_back("__sqlctx_column_" + to_string(i) + "_" + SqlctxName(bound.names[i])); + names.emplace_back(compatibility ? SqlctxName(bound.names[i]) : + "__sqlctx_column_" + to_string(i) + "_" + SqlctxName(bound.names[i])); expressions.push_back(make_uniq(bound.types[i], bindings[i])); } auto projection = make_uniq(bind_index, std::move(expressions)); @@ -1671,32 +2607,193 @@ unique_ptr BindQueryCarrier(ClientContext &context, TableFuncti return std::move(projection); } +bool IsSqlctxQueryCarrier(TableFunctionCatalogEntry &entry) { +#if SQLCTX_NEW_IDENTIFIER_API + return StringUtil::CIEquals(SqlctxName(entry.extension_name), "sqlctx"); +#else + if (entry.functions.functions.empty()) return false; + for (auto &overload : entry.functions.functions) { + if (overload.bind_operator != BindQueryCarrier) return false; + } + return true; +#endif +} + +void CheckPeerMeasureQuery(ClientContext &context, const string &sql) { + auto snapshot = ReadSqlctxCatalog(context); + ModelListOwner models(snapshot.payload); + vector measures; + for (idx_t i = 0; i < models.list.count; ++i) { + if (models.list.models[i].is_measure_view) measures.push_back(models.list.models[i]); + } + if (!measures.empty()) { + SqlctxModelList measure_models {measures.data(), measures.size(), nullptr}; + Parser parser(SqlctxBuiltinParserOptions()); + parser.ParseQuery(sql); + for (auto &statement : parser.statements) { + auto query = QueryInStatement(*statement); + if (!query) continue; + SemanticRelations relations(context, measure_models, snapshot); + relations.Query(*query->node); + unordered_set compiled; + SemanticReferences references(context, measure_models, snapshot, false, compiled); + if (relations.measure_bindings || references.Query(*query->node)) { + // Yardstick's parser may already have replaced the + // original AGGREGATE with ordinary SQL. Its private + // catalog cannot evaluate a SQLCtx-owned measure view; + // do not guess which aggregate the caller intended. + // INVALID is the host's terminal planning diagnostic: + // other operator extensions must not retry the already + // bound statement after its AST has been consumed. + throw Exception(ExceptionType::INVALID, + "Yardstick cannot evaluate SQLCtx measure views; select the measure " + "directly (for example SELECT aov FROM sales) without AGGREGATE"); + } + } + } +} + +#if SQLCTX_PRE_BIND +void CheckPeerMeasureCarriers(ClientContext &context, QueryNode &query) { + auto expression = [&](unique_ptr &) {}; + auto table = [&](TableRef &ref) { + if (ref.type != TableReferenceType::TABLE_FUNCTION) return; + auto &function = ref.Cast().function; + if (!function || function->GetExpressionClass() != ExpressionClass::FUNCTION) return; + auto name = FunctionName(*function); + if (name != "yardstick" && name != "yardstick_scoped") return; + auto &arguments = function->Cast().GetArgumentsMutable(); + if (arguments.empty()) return; + auto &query_sql = arguments[0].GetExpressionMutable(); + if (query_sql->GetExpressionClass() != ExpressionClass::CONSTANT) return; + auto value = query_sql->Cast().GetLiteral().ToValue(); + if (!value.IsNull() && value.type().id() == LogicalTypeId::VARCHAR) { + CheckPeerMeasureQuery(context, value.GetValue()); + } + }; + ParsedExpressionIterator::EnumerateQueryNodeChildren(query, expression, table); +} +#endif + #if SQLCTX_PRE_BIND void SqlctxPreBind(PlannerExtensionInput &input, SQLStatement &statement) { auto query = QueryInStatement(statement); - if (!query) return; - if (auto original = UnwrapQueryCarrier(*query)) query->node = std::move(original->node); + if (query) { + // Reject a peer's rewritten carrier before its binder can wrap our + // diagnostic and retry a consumed AST through operator extensions. + if (ExtensionManager::Get(*input.context.db).ExtensionIsLoaded("yardstick")) { + CheckPeerMeasureCarriers(input.context, *query->node); + } + if (auto original = UnwrapQueryCarrier(*query)) query->node = std::move(original->node); + } auto state = input.context.registered_state->GetOrCreate(ROUTING_STATE, input.context); auto compiled = state->Candidate(statement); if (!compiled) return; - if (compiled->type != statement.type) { + if (compiled->type != statement.type || !query) { state->candidate = std::move(compiled); return; } auto rewritten = QueryInStatement(*compiled); - if (!rewritten) return; + if (!rewritten) { + state->candidate = std::move(compiled); + return; + } query->node = std::move(rewritten->node); RegisterSqlctxCatalogRead(input.context, input.binder.GetStatementProperties()); } #endif +void CheckPeerMeasureEvaluation(ClientContext &context, LogicalOperator &plan) { + if (plan.type == LogicalOperatorType::LOGICAL_GET) { + auto &get = plan.Cast(); +#if SQLCTX_NEW_IDENTIFIER_API + auto name = SqlctxName(get.function.GetName()); +#else + auto &name = get.function.name; +#endif + if ((name == "yardstick" || name == "yardstick_scoped") && !get.parameters.empty() && + get.parameters[0].type().id() == LogicalTypeId::VARCHAR && !get.parameters[0].IsNull()) { + CheckPeerMeasureQuery(context, get.parameters[0].GetValue()); + } + } + for (auto &child : plan.children) CheckPeerMeasureEvaluation(context, *child); +} + void SqlctxPostBind(PlannerExtensionInput &input, BoundStatement &bound) { + if (bound.plan && ExtensionManager::Get(*input.context.db).ExtensionIsLoaded("yardstick")) { + CheckPeerMeasureEvaluation(input.context, *bound.plan); + } auto state = input.context.registered_state->Get(ROUTING_STATE); if (!state) return; if (state->candidate) { bound = state->BindCandidate(input.binder); return; } +#if !SQLCTX_PRE_BIND + if (state->probing && !state->probe_error) { + auto has_measure = [&](Binder &binder) { + for (auto &binding : binder.bind_context.GetBindingsList()) { + auto entry = binding->GetStandardEntry(); + if (entry && SqlctxIsNativeMeasureView(*entry)) return true; + } + return false; + }; + std::function child_measure = [&](BoundStatement &statement) { + for (auto &binder : statement.extra_info.child_binders) if (has_measure(*binder)) return true; + for (auto &child : statement.extra_info.bound_children) if (child_measure(child)) return true; + return false; + }; + bool measure_definition = false; + if (bound.plan && bound.plan->type == LogicalOperatorType::LOGICAL_CREATE_VIEW) { + auto &view = bound.plan->Cast().info->Cast(); + measure_definition = !ViewWrapperWarnings(input.context, *view.query->node, false).empty(); + RoutingReferences references; + references.Query(*view.query->node); + for (auto source : references.sources) { + SqlctxMeasureTarget target; + string key; + if (ResolveSqlctxMeasureView(input.context, source->catalog_name, source->schema_name, + source->table_name, target, key)) measure_definition = true; + } + } + if (measure_definition || has_measure(input.binder) || child_measure(bound)) { + // Legacy hosts can bind a physical measure view successfully, but + // have no pre-bind hook. Retry only these tagged catalog bindings + // using the pristine caller AST supplied by OnPlanningError. + state->probe_error = true; + throw Exception(unordered_map {{ROUTING_PROBE, "measure"}}, ExceptionType::INVALID, + "sqlctx requires the pristine measure-view query"); + } + } +#endif + if (bound.plan && bound.plan->type == LogicalOperatorType::LOGICAL_CREATE_VIEW) { + CheckNativeViewCollision(input.context, *bound.plan->Cast().info, + input.binder.GetStatementProperties()); + } + if (bound.plan && bound.plan->type == LogicalOperatorType::LOGICAL_DROP) { +#if SQLCTX_NEW_IDENTIFIER_API + auto &info = *bound.plan->Cast().info; +#else + auto &info = bound.plan->Cast().info->Cast(); + if (state->probing && !state->probe_error && info.type == CatalogType::VIEW_ENTRY) { + SqlctxMeasureTarget target; + string key; + if (ResolveSqlctxMeasureView(input.context, info.catalog, info.schema, info.name, target, key)) { + // The legacy binder has already filled in the resolved catalog, + // losing the distinction between main.name and an unqualified + // temporary shadow. Recover the authored DROP before routing it. + state->probe_error = true; + throw Exception(unordered_map {{ROUTING_PROBE, "measure"}}, ExceptionType::INVALID, + "sqlctx requires the pristine measure-view DROP"); + } + } +#endif + state->candidate = MeasureViewDrop(input.context, info); + if (state->candidate) { + bound = state->BindCandidate(input.binder); + return; + } + } // Only legacy SHOW needs the pristine client AST after a successful bind: // another parser can interpret SHOW MODELS as DESCRIBE a physical table. if (!state->probing || state->probe_error || bound.names.size() < 2 || @@ -1711,10 +2808,167 @@ class SqlctxConnectionCallback : public ExtensionCallback { void OnConnectionOpened(ClientContext &context) override { context.registered_state->GetOrCreate(ROUTING_STATE, context); } + + void OnBeginExtensionLoad(DatabaseInstance &db, const string &name) override { + if (name != "yardstick") return; + auto &catalog = Catalog::GetSystemCatalog(db); + auto transaction = CatalogTransaction::GetSystemTransaction(db); + auto &schema = catalog.GetSchema(transaction, SqlctxIdentifier(DEFAULT_SCHEMA)); + for (const string alias : {"yardstick", "yardstick_scoped"}) { +#if SQLCTX_NEW_IDENTIFIER_API + EntryLookupInfo lookup(CatalogType::TABLE_FUNCTION_ENTRY, QualifiedName(Identifier(alias))); +#else + EntryLookupInfo lookup(CatalogType::TABLE_FUNCTION_ENTRY, alias); +#endif + auto entry = schema.LookupEntry(transaction, lookup); + if (!entry) continue; + auto &function = entry->Cast(); + if (!IsSqlctxQueryCarrier(function)) continue; + auto restore = make_uniq(function.functions); + restore->descriptions = function.descriptions; +#if SQLCTX_NEW_IDENTIFIER_API + restore->extension_name = SqlctxIdentifier("sqlctx"); +#endif + restore->internal = function.internal; + restore->on_conflict = OnCreateConflict::IGNORE_ON_CONFLICT; + // These aliases are SQLCtx-owned compatibility entries. Release + // them before the explicitly loaded implementation registers its + // own signatures; unrelated user functions retain their owner. + if (entry->set->DropEntry(transaction, SqlctxIdentifier(alias), false, true)) { + released.push_back(std::move(restore)); + } + } + } + + void OnExtensionLoaded(DatabaseInstance &, const string &name) override { + if (name == "yardstick") released.clear(); + } + + void OnExtensionLoadFail(DatabaseInstance &db, const string &name, const ErrorData &) override { + if (name != "yardstick") return; + auto &catalog = Catalog::GetSystemCatalog(db); + auto transaction = CatalogTransaction::GetSystemTransaction(db); + for (auto &info : released) catalog.CreateFunction(transaction, *info); + released.clear(); + } +private: + vector> released; }; } // namespace +ParserOptions SqlctxContextParserOptions(ClientContext &context) { +#if SQLCTX_NEW_IDENTIFIER_API + auto options = SqlctxBuiltinParserOptions(); + options.identifier_case_mode = Settings::Get(context); + options.integer_division = Settings::Get(context); + options.regex_match_operator_semantics = Settings::Get(context); + options.max_expression_depth = Settings::Get(context); + options.parser_override_setting = Settings::Get(context); + options.compiled_grammar = CompiledGrammar::Get(context); + options.context = context; + return options; +#else + return WithoutOverrides(context.GetParserOptions()); +#endif +} + +SqlctxPublicQueryPlan PlanSqlctxPublicQuery(ClientContext &context, const string &sql, bool explain) { + if (sql.find('\0') != string::npos) throw InvalidInputException("sqlctx SQL contains a NUL byte"); + auto tokens = Tokens(sql); + bool explicit_semantic = Keyword(tokens, 0, "SEMANTIC"); + Parser parser(SqlctxContextParserOptions(context)); + parser.ParseQuery(explicit_semantic ? sql.substr(tokens[0].end) : sql); + if (parser.statements.size() != 1 || parser.statements[0]->type != StatementType::SELECT_STATEMENT) { + throw InvalidInputException("sqlctx query inspection expects one SELECT statement"); + } + 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()); + string error = result.error ? result.error : ""; + string compiled = result.sql ? result.sql : ""; + if (result.report) reports.emplace_back(result.report); + sqlctx_free_plan_explanation(result); + if (!error.empty()) throw InvalidInputException("sqlctx: %s", SqlctxErrorText(error)); + if (compiled.empty()) throw InternalException("sqlctx returned no explained SQL"); + return compiled; + } + auto result = sqlctx_snapshot_rewrite(snapshot.payload.c_str(), query.c_str()); + string error = result.error ? result.error : ""; + string compiled = result.sql ? result.sql : ""; + sqlctx_free_result(result); + if (!error.empty()) throw InvalidInputException("sqlctx: %s", SqlctxErrorText(error)); + if (compiled.empty()) throw InternalException("sqlctx returned no rewritten SQL"); + return compiled; + }; + auto snapshot = ReadSqlctxCatalog(context); + auto rewritten = CompileSemanticStatement(context, *parser.statements[0], snapshot, explicit_semantic, nullptr, + &compile); + SqlctxPublicQueryPlan result; + result.sql = (rewritten ? *rewritten : *parser.statements[0]).ToString(); + if (explain) { + auto combined = sqlctx_combine_plan_explanations(result.sql.c_str(), + ("[" + StringUtil::Join(reports, ",") + "]").c_str()); + string error = combined.error ? combined.error : ""; + if (combined.sql) result.explanation = combined.sql; + sqlctx_free_result(combined); + if (!error.empty()) throw InvalidInputException("sqlctx: %s", SqlctxErrorText(error)); + if (result.explanation.empty()) throw InternalException("sqlctx returned no explanation"); + } + return result; +} + +SqlctxMeasureTarget SqlctxMeasureViewTarget(const string &sql) { + auto clean = sql; + auto tokens = Tokens(sql); + auto syntax = FindMeasureFields(clean, tokens); + if (!syntax.body || syntax.body >= tokens.size()) throw ParserException("Expected a view definition"); + // Parse the header independently: IF NOT EXISTS must not probe or bind + // the replacement body when DuckDB already has the requested view. + Parser parser(SqlctxBuiltinParserOptions()); + parser.ParseQuery(sql.substr(0, tokens[syntax.body].start) + "SELECT 1"); + auto &info = parser.statements.at(0)->Cast().info->Cast(); + SqlctxMeasureTarget target; +#if SQLCTX_NEW_IDENTIFIER_API + target.catalog = SqlctxName(info.GetQualifiedName().Catalog()); + target.schema = SqlctxName(info.GetQualifiedName().Schema()); + target.name = SqlctxName(info.GetViewName()); +#else + target.catalog = info.catalog; + target.schema = info.schema; + target.name = info.view_name; +#endif + target.temporary = info.temporary; + target.replace = info.on_conflict == OnCreateConflict::REPLACE_ON_CONFLICT; + target.if_not_exists = info.on_conflict == OnCreateConflict::IGNORE_ON_CONFLICT; + return target; +} + +void CheckSqlctxMeasureScope(const string &sql) { + auto clean = sql; + auto tokens = Tokens(sql); + idx_t i = 0; + if (!Keyword(tokens, i++, "CREATE")) return; + if (Keyword(tokens, i, "OR") && Keyword(tokens, i + 1, "REPLACE")) i += 2; + if (Keyword(tokens, i, "TEMP") || Keyword(tokens, i, "TEMPORARY")) ++i; + if (Keyword(tokens, i, "VIEW")) FindMeasureFields(clean, tokens); +} + +SqlctxMeasureDefinition LowerSqlctxMeasureView(ClientContext &context, const string &sql, const string &model_key) { + return BuildMeasureDefinition(&context, sql, model_key); +} + +unique_ptr ParseSqlctxStoredDefinition(const string &sql, const string &model_key, + const string &old_catalog, const string &new_catalog) { + auto declaration = BuildMeasureDefinition(nullptr, sql, model_key, old_catalog, new_catalog); + if (declaration.content.empty()) return nullptr; + auto result = make_uniq(); + result->operation = "measure_view"; + result->content = std::move(declaration.content); + return result; +} + void RegisterSqlctxRouting(DatabaseInstance &db) { auto &config = DBConfig::GetConfig(db); auto callback = make_shared_ptr(); @@ -1738,6 +2992,32 @@ void RegisterSqlctxQueryCarrier(ExtensionLoader &loader) { carriers.AddFunction(carrier); } loader.RegisterFunction(carriers); + { + bool peer_loaded = ExtensionManager::Get(loader.GetDatabaseInstance()).ExtensionIsLoaded("yardstick"); + for (auto name : {"sqlctx_query", "sqlctx_query_scoped", "yardstick", "yardstick_scoped"}) { + if (peer_loaded && (string(name) == "yardstick" || string(name) == "yardstick_scoped")) continue; + TableFunctionSet functions {SqlctxIdentifier(name)}; + vector descriptions; + for (idx_t count = 1; count <= ((string(name) == "yardstick" || string(name) == "sqlctx_query") ? 2 : 1); ++count) { + TableFunction function(name, vector(count, LogicalType::VARCHAR), nullptr, nullptr); + function.bind_operator = BindQueryCarrier; +#if SQLCTX_GRAMMAR_EXTENSION + function.GetSignature().GetParameter(0).SetName(Identifier("sql")); + if (count == 2) function.GetSignature().GetParameter(1).SetName(Identifier("warnings")); +#endif + functions.AddFunction(function); + FunctionDescription description; + description.parameter_types = vector(count, LogicalType::VARCHAR); + description.parameter_names = count == 1 ? vector {"sql"} : vector {"sql", "warnings"}; + description.description = "Compile a measure-aware SELECT in the caller's transaction and session."; + description.examples = {string("SELECT * FROM ") + name + "('SELECT 1 AS value')"}; + descriptions.push_back(std::move(description)); + } + CreateTableFunctionInfo info(std::move(functions)); + info.descriptions = std::move(descriptions); + loader.RegisterFunction(std::move(info)); + } + } } unique_ptr SqlctxParseData::Copy() const { @@ -1746,6 +3026,8 @@ unique_ptr SqlctxParseData::Copy() const { copy->content = content; copy->replace = replace; copy->explicit_semantic = explicit_semantic; + copy->batch_temporary = batch_temporary; + copy->batch_remaining_queries = batch_remaining_queries; if (statement) copy->statement = statement->Copy(); return std::move(copy); } @@ -1777,11 +3059,13 @@ unique_ptr ParseSqlctxDefinition(const string &sql) { idx_t pos = Keyword(tokens, 0, "SEMANTIC") ? 1 : 0; if (Keyword(tokens, pos, "SHOW")) { ++pos; - if (Keyword(tokens, pos, "SEMANTIC")) ++pos; + bool semantic = Keyword(tokens, pos, "SEMANTIC"); + if (semantic) ++pos; string kind; for (auto name : {"MODELS", "METRICS", "DIMENSIONS", "SEGMENTS", "RELATIONSHIPS"}) { if (Keyword(tokens, pos, name)) kind = StringUtil::Lower(name); } + if (semantic && Keyword(tokens, pos, "VIEWS")) kind = "views"; if (kind.empty()) return nullptr; kind.pop_back(); ++pos; @@ -1789,20 +3073,19 @@ unique_ptr ParseSqlctxDefinition(const string &sql) { result->operation = "show_" + kind; if (Keyword(tokens, pos, "FOR") && kind == "dimension") { result->operation = "show_compatible_dimensions"; - result->content = QualifiedNameJson(tokens, pos + 1, 2); + result->content = DiscoveryName(tokens, pos + 1, 4); } else if (pos < tokens.size()) { - if (!Keyword(tokens, pos, "FROM") || pos + 2 != tokens.size()) { + if (!Keyword(tokens, pos, "FROM")) { throw ParserException("SHOW semantic definitions expects FROM model or DIMENSIONS FOR model.metric"); } - result->content = IdentifierText(tokens[pos + 1].text); + result->content = DiscoveryName(tokens, pos + 1, 3); } return result; } if ((Keyword(tokens, pos, "DESCRIBE") || Keyword(tokens, pos, "DESC")) && Keyword(tokens, pos + 1, "MODEL")) { - if (pos + 3 != tokens.size()) throw ParserException("DESCRIBE MODEL expects one model name"); auto result = make_uniq(); result->operation = "show_"; - result->content = IdentifierText(tokens[pos + 2].text); + result->content = DiscoveryName(tokens, pos + 2, 3); return result; } if ((Keyword(tokens, pos, "EXPORT") || Keyword(tokens, pos, "IMPORT")) && @@ -1845,6 +3128,15 @@ unique_ptr ParseSqlctxDefinition(const string &sql) { } } if (pos >= tokens.size()) return nullptr; + if (create && (Keyword(tokens, pos, "TEMP") || Keyword(tokens, pos, "TEMPORARY"))) ++pos; + if (create && Keyword(tokens, pos, "VIEW")) { + auto syntax = FindMeasureFields(clean, tokens); + if (syntax.measures.empty()) return nullptr; + auto result = make_uniq(); + result->operation = "declare_measure_view"; + result->content = Keyword(tokens, 0, "SEMANTIC") ? sql.substr(tokens[1].start) : sql; + return result; + } if (create && Keyword(tokens, pos, "SEMANTIC") && Keyword(tokens, pos + 1, "VIEW")) { pos += 2; if (pos + 2 >= tokens.size() || !Keyword(tokens, pos + 1, "AS")) { @@ -1948,6 +3240,11 @@ unique_ptr WrapSqlctxQuery(unique_ptr statement, boo data->statement = std::move(statement); data->explicit_semantic = explicit_semantic; return SqlctxStatement(std::move(data)); + } else if (statement->type == StatementType::DROP_STATEMENT && + statement->Cast().info->type == CatalogType::VIEW_ENTRY) { + // The ordinary DROP path resolves native and stored measure views in + // the caller's transaction, including earlier declarations in a batch. + return statement; } else if (explicit_semantic && statement->type != StatementType::EXTENSION_STATEMENT) { throw ParserException("SEMANTIC expects SELECT, CREATE VIEW, CREATE TABLE AS, INSERT SELECT or a semantic definition"); } @@ -1985,16 +3282,156 @@ static bool YardstickOwnsSyntax(ParserExtensionInfo *info, const string &query) return false; } +#if SQLCTX_NEW_IDENTIFIER_API +static void FlattenBatchStatements(vector> &statements) { + vector> flat; + std::function)> append = [&](unique_ptr statement) { + if (statement->type == StatementType::MULTI_STATEMENT) { + for (auto &child : statement->Cast().statements) append(std::move(child)); + } else flat.push_back(std::move(statement)); + }; + for (auto &statement : statements) append(std::move(statement)); + statements = std::move(flat); +} +#endif + +static SQLStatement &BatchStatement(SQLStatement &statement) { + if (statement.type == StatementType::EXTENSION_STATEMENT) { + auto &extension = statement.Cast(); + if (extension.extension.plan_function == sqlctx_plan) { + auto &data = static_cast(*extension.parse_data); + if (data.statement) return BatchStatement(*data.statement); + } + } + return statement; +} + +static bool BatchDropsTemporary(SQLStatement &statement, const string &name) { + auto &native = BatchStatement(statement); + if (native.type != StatementType::DROP_STATEMENT) return false; + auto &drop = *native.Cast().info; +#if SQLCTX_NEW_IDENTIFIER_API + auto &target = drop.GetQualifiedName(); + auto target_name = SqlctxName(target.Name()); + auto catalog = SqlctxName(target.Catalog()); + auto schema = SqlctxName(target.Schema()); +#else + auto &target_name = drop.name; + auto &catalog = drop.catalog; + auto &schema = drop.schema; +#endif + return drop.type == CatalogType::VIEW_ENTRY && + StringUtil::CIEquals(target_name, name) && + (catalog.empty() || StringUtil::CIEquals(catalog, "temp")) && + (schema.empty() || StringUtil::CIEquals(schema, "temp")); +} + +static bool BatchReadsTemporary(SQLStatement &statement, const string &name) { + auto &native = BatchStatement(statement); +#if SQLCTX_NEW_IDENTIFIER_API + if (native.type == StatementType::MULTI_STATEMENT) { + bool found = false; + for (auto &child : native.Cast().statements) found |= BatchReadsTemporary(*child, name); + return found; + } +#endif + auto query = QueryInStatement(native, true); + if (!query) return false; + auto original = UnwrapQueryCarrier(*query); + if (original) query = original.get(); + RoutingReferences references; + references.Query(*query->node); + if (!references.aggregate) return false; + bool found = false; + for (auto source : references.sources) { +#if SQLCTX_NEW_IDENTIFIER_API + auto &target = source->GetQualifiedName(); + if (StringUtil::CIEquals(SqlctxName(target.Name()), name) && target.Catalog().empty() && + target.Schema().empty()) found = true; +#else + if (StringUtil::CIEquals(source->table_name, name) && source->catalog_name.empty() && + source->schema_name.empty()) found = true; +#endif + } + if (found && native.type == StatementType::SELECT_STATEMENT) { + throw ParserException("TEMPORARY AS MEASURE views cannot be returned directly from a statement batch"); + } + return found; +} + +static bool PrepareTemporaryMeasureBatch(vector> &statements, + const ParserOptions &options) { + bool batch_temporary = false; + for (idx_t index = 0; index < statements.size(); ++index) { + auto &statement = *statements[index]; + if (statement.type != StatementType::EXTENSION_STATEMENT) continue; + auto &extension = statement.Cast(); + if (extension.extension.plan_function != sqlctx_plan) continue; + auto &data = static_cast(*extension.parse_data); + if (data.operation != "declare_measure_view") continue; + auto target = SqlctxMeasureViewTarget(data.content); + if (!target.temporary) continue; + // Header aliases require live schema binding and define session-local + // views. Simple declarations retain the upstream statement-batch scope. + auto tokens = Tokens(data.content); + auto clean = data.content; + auto syntax = FindMeasureFields(clean, tokens); + Parser header(WithoutOverrides(options)); + header.ParseQuery(clean.substr(0, tokens.at(syntax.body).start) + "SELECT 1"); + auto &view = header.statements.at(0)->Cast().info->Cast(); + if (!view.aliases.empty()) continue; + bool used = false; + for (idx_t consumer = index + 1; consumer < statements.size(); ++consumer) { + if (BatchDropsTemporary(*statements[consumer], target.name)) { + used = true; + break; + } + used |= BatchReadsTemporary(*statements[consumer], target.name); + } + if (!used) { + throw ParserException("TEMPORARY AS MEASURE views must be used in the same statement batch as AGGREGATE()"); + } + data.batch_temporary = true; +#if !SQLCTX_NEW_IDENTIFIER_API + data.batch_remaining_queries = statements.size() - index; +#endif + batch_temporary = true; + } + return batch_temporary; +} + ParserOverrideResult sqlctx_parser_override(ParserExtensionInfo *info, const string &query, ParserOptions &options) { + auto tokens = Tokens(query); + if (Keyword(tokens, 0, "SET") && Keyword(tokens, 1, "active_grammar_extensions")) { + for (auto &token : tokens) { + if (!token.text.empty() && token.text.front() == '\'' && + StringUtil::CIEquals(IdentifierText(token.text), "yardstick")) EnsureSqlctxGrammarAlias(info); + } + } // A composed PEG grammar shares syntax, not another extension's private // transformer state. Let Yardstick establish its capture scope for measure // syntax before parsing it. The lexer excludes comments and quoted text. if (YardstickOwnsSyntax(info, query)) return ParserOverrideResult(); vector> statements; if (ParseSqlctxGrammar(info, query, options, statements)) { +#if SQLCTX_NEW_IDENTIFIER_API + FlattenBatchStatements(statements); + bool batch_temporary = PrepareTemporaryMeasureBatch(statements, options); +#endif for (auto &statement : statements) statement = WrapSqlctxQuery(std::move(statement), false, "", &options); +#if SQLCTX_NEW_IDENTIFIER_API + if (batch_temporary) { + // Native expansion preserves statement order, while its query-end + // callback restores batch-local views on success and on failure. + auto batch = make_uniq(); + batch->query = query; + batch->statements = std::move(statements); + statements.push_back(std::move(batch)); + } +#endif } else { ParseCompatibility(query, options, statements); + PrepareTemporaryMeasureBatch(statements, options); } return ParserOverrideResult(std::move(statements)); } @@ -2016,6 +3453,10 @@ ParserExtensionParseResult sqlctx_parse(ParserExtensionInfo *, const string &que ParserExtensionPlanResult sqlctx_plan(ParserExtensionInfo *, ClientContext &context, unique_ptr parsed) { auto &data = static_cast(*parsed); + if (data.operation == "stored_ddl") return PlanSqlctxStoredDDL(context, data.content); + if (data.operation == "declare_measure_view") { + return PlanSqlctxMeasureView(context, data.content, data.batch_temporary, data.batch_remaining_queries); + } if (data.operation == "export") return PlanSqlctxCatalog("export", "", ""); if (data.operation == "show_compatible_dimensions") return PlanSqlctxCatalog("dimension", "", data.content); if (StringUtil::StartsWith(data.operation, "show_")) { diff --git a/sqlctx-duckdb/src/sqlctx_semantic_input.cpp b/sqlctx-duckdb/src/sqlctx_semantic_input.cpp index 22da9fd36..46755f500 100644 --- a/sqlctx-duckdb/src/sqlctx_semantic_input.cpp +++ b/sqlctx-duckdb/src/sqlctx_semantic_input.cpp @@ -1,5 +1,7 @@ #include "sqlctx_semantic_input.hpp" +#include "sqlctx_catalog.hpp" #include "sqlctx_compat.hpp" +#include "sqlctx_function_metadata.hpp" #include "sqlctx.h" #include "duckdb/common/vector_operations/binary_executor.hpp" @@ -26,7 +28,7 @@ static string SemanticInputSQL(SqlctxRewriteResult compiled) { if (compiled.error) { string message(compiled.error); sqlctx_free_result(compiled); - throw InvalidInputException("SemanticInput failed: %s", message); + throw InvalidInputException("SemanticInput failed: %s", SqlctxErrorText(message)); } if (!compiled.sql) { sqlctx_free_result(compiled); @@ -87,16 +89,22 @@ void RegisterSqlctxSemanticInput(ExtensionLoader &loader) { auto compile_input = ScalarFunction("sqlctx_compile_semantic_input", {LogicalType::VARCHAR, LogicalType::VARCHAR}, LogicalType::VARCHAR, SqlctxCompileSemanticInputFunction); compile_input.SetFallible(); - loader.RegisterFunction(compile_input); + RegisterSqlctxFunction(loader, std::move(compile_input), {"input_json", "query_json"}, + "Compile a SemanticInput JSON model and semantic query JSON into SQL while retaining input policies.", + "sqlctx_compile_semantic_input(input_json, query_json)"); auto rewrite_input = ScalarFunction("sqlctx_rewrite_semantic_input", {LogicalType::VARCHAR, LogicalType::VARCHAR, LogicalType::VARCHAR}, LogicalType::VARCHAR, SqlctxRewriteSemanticInputFunction); rewrite_input.SetFallible(); - loader.RegisterFunction(rewrite_input); + RegisterSqlctxFunction(loader, std::move(rewrite_input), {"input_json", "sql", "context_json"}, + "Rewrite SQL against SemanticInput JSON with an explicit query context, retaining input policies.", + "sqlctx_rewrite_semantic_input(input_json, 'select revenue from sales', context_json)"); TableFunction query_input("sqlctx_query_semantic_input", {LogicalType::VARCHAR, LogicalType::VARCHAR}, nullptr, nullptr); query_input.bind_replace = SqlctxQuerySemanticInputBindReplace; - loader.RegisterFunction(query_input); + RegisterSqlctxFunction(loader, std::move(query_input), {"input_json", "query_json"}, + "Execute a compiled SemanticInput query as a relation in the caller's transaction, retaining input policies.", + "sqlctx_query_semantic_input(input_json, query_json)"); } } // namespace duckdb diff --git a/sqlctx-duckdb/src/sqlctx_warnings.cpp b/sqlctx-duckdb/src/sqlctx_warnings.cpp new file mode 100644 index 000000000..c9d53984b --- /dev/null +++ b/sqlctx-duckdb/src/sqlctx_warnings.cpp @@ -0,0 +1,83 @@ +#include "sqlctx_warnings.hpp" +#include "sqlctx_parser.hpp" +#include "sqlctx.h" + +#include "duckdb/common/vector_operations/unary_executor.hpp" +#include "duckdb/execution/expression_executor_state.hpp" +#include "duckdb/function/scalar_function.hpp" +#include "duckdb/logging/logger.hpp" +#include "duckdb/main/extension/extension_loader.hpp" +#include "duckdb/parser/parsed_data/create_scalar_function_info.hpp" +#include "duckdb/parser/statement/select_statement.hpp" + +namespace duckdb { + +void HandleSqlctxWarnings(ClientContext &context, const string &warnings) { + if (warnings.empty()) return; + Value setting; + if (context.TryGetCurrentSetting("warnings_as_errors", setting) && !setting.IsNull() && setting.GetValue()) { + throw InvalidInputException("%s", warnings); + } + DUCKDB_LOG_WARNING(context, "%s", warnings.c_str()); +} + +string WrapSqlctxQueryWarnings(const string &query_sql, const string &warnings) { + if (warnings.empty()) return query_sql; + // This helper operates on the query inside a native statement container. + // Let DuckDB remove trailing delimiters and validate that boundary. + Parser parser(SqlctxBuiltinParserOptions()); + parser.ParseQuery(query_sql); + if (parser.statements.size() != 1 || parser.statements[0]->type != StatementType::SELECT_STATEMENT) { + throw BinderException("sqlctx warning wrapper expects one compiled SELECT query"); + } + auto query = parser.statements[0]->Cast().node->ToString(); + string prefix = "__sqlctx_warning"; + auto lower_query = StringUtil::Lower(query); + while (lower_query.find(prefix) != string::npos) prefix += "_"; + auto message = StringUtil::Replace(warnings, "'", "''"); + return "WITH " + prefix + " AS MATERIALIZED (SELECT sqlctx_warning('" + message + "') AS ok), " + + prefix + "_query AS MATERIALIZED (" + query + ") SELECT " + prefix + "_query.* FROM " + + prefix + " CROSS JOIN " + prefix + "_query WHERE " + prefix + ".ok"; +} + +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()); + string compiled = result.sql ? result.sql : ""; + string warnings = result.warnings ? result.warnings : ""; + string error = result.error ? result.error : ""; + sqlctx_free_diagnostics_result(result); + if (!error.empty()) throw BinderException("sqlctx: %s", SqlctxErrorText(error)); + if (compiled.empty()) throw InternalException("sqlctx returned no rewritten SQL"); + if (collected_warnings) *collected_warnings = warnings; + return wrap_runtime_warnings ? WrapSqlctxQueryWarnings(compiled, warnings) : compiled; +} + +static void WarningFunction(DataChunk &args, ExpressionState &state, Vector &result) { + UnaryExecutor::Execute(args.data[0], result, args.size(), [&](string_t message) { + HandleSqlctxWarnings(state.GetContext(), message.GetString()); + return true; + }); +} + +void RegisterSqlctxWarnings(ExtensionLoader &loader) { + for (auto name : {"sqlctx_warning", "yardstick_warning"}) { + ScalarFunction function(name, {LogicalType::VARCHAR}, LogicalType::BOOLEAN, WarningFunction); + function.SetStability(FunctionStability::VOLATILE); + function.SetFallible(); + #if SQLCTX_GRAMMAR_EXTENSION + function.GetSignature().GetParameter(0).SetName(Identifier("message")); + #endif + CreateScalarFunctionInfo info(std::move(function)); + info.on_conflict = OnCreateConflict::ALTER_ON_CONFLICT; + FunctionDescription description; + description.parameter_names = {"message"}; + description.description = "Report a semantic rewrite warning and return true, or fail when warnings_as_errors is enabled."; + description.examples = {string(name) + "('')"}; + description.categories = {"utility"}; + info.descriptions.push_back(std::move(description)); + loader.RegisterFunction(std::move(info)); + } +} + +} // namespace duckdb diff --git a/sqlctx-duckdb/test/sql/sqlctx.test b/sqlctx-duckdb/test/sql/sqlctx.test index fb3027674..08db1edee 100644 --- a/sqlctx-duckdb/test/sql/sqlctx.test +++ b/sqlctx-duckdb/test/sql/sqlctx.test @@ -28,9 +28,9 @@ SELECT * FROM sqlctx_models(); ---- orders -# Test manual rewrite function - should contain SUM +# Test manual rewrite function - aggregate function names are case-insensitive query I -SELECT sqlctx_rewrite_sql('SELECT orders.revenue FROM orders') LIKE '%SUM%'; +SELECT sqlctx_rewrite_sql('SELECT orders.revenue FROM orders') ILIKE '%SUM(%'; ---- true diff --git a/sqlctx-duckdb/test/test_catalog_host.py b/sqlctx-duckdb/test/test_catalog_host.py index 3aeca4dc0..55bfb10bc 100644 --- a/sqlctx-duckdb/test/test_catalog_host.py +++ b/sqlctx-duckdb/test/test_catalog_host.py @@ -71,7 +71,7 @@ def literal(value): """ -def execute(sql, *, setup=SETUP, database=":memory:", readonly=False, error=None): +def execute(sql, *, setup=SETUP, database=":memory:", readonly=False, error=None, error_excludes=()): binary = Path(os.environ["SQLCTX_DUCKDB_BINARY"]).resolve() extension = Path(os.environ["SQLCTX_DUCKDB_EXTENSION"]).resolve() args = [str(binary), "-unsigned", "-no-init", "-json", "-bail"] @@ -89,6 +89,8 @@ def execute(sql, *, setup=SETUP, database=":memory:", readonly=False, error=None assert result.returncode != 0, result.stdout assert "INTERNAL Error" not in result.stderr, result.stderr assert error in result.stderr, result.stderr + for excluded in error_excludes: + assert excluded not in result.stderr, result.stderr return [] assert result.returncode == 0, result.stderr decoder = json.JSONDecoder() @@ -238,6 +240,57 @@ def test_prefixless_physical_collision_and_prepared_catalog_changes(): assert totals == [40, 2, 40] +@pytest.mark.parametrize("formula", ["revenue / order_count", "o2.revenue / o2.order_count"]) +def test_derived_metrics_bind_to_the_declaring_model(formula): + results = execute( + f""" + select aov from o2; + MODEL o3 FROM other_orders ( + sum(other_amount) AS revenue + count(*) AS order_count + ); + select aov from o2; + METRIC o2.standalone (type derived, sql '{formula}'); + select standalone as aov from o2; + METRIC o2.shorthand AS o2.revenue / o2.order_count; + select shorthand as aov from o2; + """, + setup=f""" + create table orders(id integer, amount integer); + insert into orders values (1, 10), (2, 30), (3, 80); + create table other_orders(id integer, other_amount integer); + insert into other_orders values (1, 900); + MODEL o2 FROM orders ( + sum(amount) AS revenue + count(*) AS order_count + {formula} AS aov + ); + """, + ) + assert [rows for rows in results if rows and "aov" in rows[0]] == [[{"aov": 40.0}]] * 4 + + +def test_derived_metric_ddl_rejects_missing_semantic_dependencies(): + setup = """ + create table orders(id integer, amount integer); + MODEL o2 FROM orders ( + sum(amount) AS revenue + ); + """ + execute( + "METRIC o2.invalid (type derived, sql 'o2.missing / o2.revenue');", + setup=setup, + error="Unknown metric 'o2.missing'", + ) + execute( + """ + METRIC o2.raw_amount AS o2.amount * 2; + METRIC o2.aggregate_input (type derived, sql 'SUM(o2.amount) * 2'); + """, + setup=setup, + ) + + def test_standard_catalog_discovery(): tables, columns, attributes, schema, rows, stars = execute(""" select table_name, table_type from information_schema.tables diff --git a/sqlctx-duckdb/test/test_explain_host.py b/sqlctx-duckdb/test/test_explain_host.py index 933a1e865..f2ee0e39d 100644 --- a/sqlctx-duckdb/test/test_explain_host.py +++ b/sqlctx-duckdb/test/test_explain_host.py @@ -5,9 +5,17 @@ import json +import pytest from test_catalog_host import execute, literal from test_semantic_views_host import SETUP as VIEW_SETUP +MEASURE_SETUP = """ +create table raw_sales(region varchar, amount integer); +insert into raw_sales values ('west', 10), ('west', 30), ('east', 80); +create schema analytics; +create view analytics.sales as select region, avg(amount) as measure aov from raw_sales; +""" + def test_explain_matches_rewrite_and_reports_selected_join_population(): sql = "select customers.country, orders.revenue from orders where customers.country = 'US'" @@ -41,12 +49,108 @@ def test_explain_invalid_query_errors_instead_of_guessing(): def test_explain_view_expands_filtered_ratio_and_aliases_like_rewrite(): - sql = "select country, aov, paid from sales" + sql = "select country, aov, paid from sales order by country" + setup = VIEW_SETUP.replace("numerator: revenue", "numerator: paid") rows = execute( - f"select sqlctx_explain({literal(sql)}) as report, sqlctx_rewrite_sql({literal(sql)}) as sql", - setup=VIEW_SETUP.replace("numerator: revenue", "numerator: paid"), + f"select sqlctx_explain({literal(sql)}) as report, sqlctx_rewrite_sql({literal(sql)}) as sql; {sql};", + setup=setup, ) report = json.loads(rows[0][0]["report"]) assert report["sql"] == rows[0][0]["sql"] - assert "NULLIF" in report["sql"] and "CASE WHEN" in report["sql"] + compiled = execute(report["sql"], setup=setup)[0] + assert compiled == rows[1] + assert [{**row, "paid": int(row["paid"])} for row in compiled] == [ + {"country": "CA", "aov": 80, "paid": 80}, + {"country": "US", "aov": 5, "paid": 10}, + ] assert report["events"] + + +@pytest.mark.parametrize( + "sql", + [ + "select aov from analytics.sales", + "select s.region, aggregate(s.aov) as mean_amount from analytics.sales s group by s.region order by s.region", + "select region, aov from analytics.sales order by region", + ], +) +def test_public_helpers_use_native_measure_view_routing(sql): + results = execute( + f"{sql}; select sqlctx_explain({literal(sql)}) as report, sqlctx_rewrite_sql({literal(sql)}) as sql;", + setup=MEASURE_SETUP, + ) + actual, inspection = results + report = json.loads(inspection[0]["report"]) + assert report["sql"] == inspection[0]["sql"] + assert execute(report["sql"], setup=MEASURE_SETUP) == [actual] + assert "avg(" in report["sql"].lower() + + +def test_public_helpers_respect_temporary_physical_shadow_and_explicit_schema(): + setup = ( + MEASURE_SETUP + + """ + create view sales as select region, avg(amount) as measure aov from raw_sales; + create temp table sales as select 7 as aov; + """ + ) + results = execute( + """ + select sqlctx_explain('select aov from sales') as report; + select sqlctx_explain('select aov from main.sales') as report; + """, + setup=setup, + ) + reports = [json.loads(rows[0]["report"]) for rows in results] + assert reports[0]["events"] == [] + assert execute(reports[0]["sql"], setup=setup) == [[{"aov": 7}]] + assert execute(reports[1]["sql"], setup=setup) == [[{"aov": 40}]] + + +def test_public_helpers_resolve_attached_measure_view_alias(): + setup = """ + attach ':memory:' as warehouse; + create table warehouse.main.raw_sales(region varchar, amount integer); + insert into warehouse.main.raw_sales values ('west', 10), ('west', 30), ('east', 80); + create view warehouse.main.sales as + select region, avg(amount) as measure aov from warehouse.main.raw_sales; + """ + sql = "select s.region, aggregate(s.aov) as aov from warehouse.main.sales s group by s.region order by s.region" + results = execute( + f"{sql}; select sqlctx_explain({literal(sql)}) as report, sqlctx_rewrite_sql({literal(sql)}) as sql;", + setup=setup, + ) + actual, inspection = results + report = json.loads(inspection[0]["report"]) + assert report["sql"] == inspection[0]["sql"] + assert execute(report["sql"], setup=setup) == [actual] + + +def test_public_function_metadata_names_arguments_and_documents_behavior(): + parameters = { + "sqlctx_load": ["yaml"], + "sqlctx_load_file": ["path"], + "sqlctx_models": [], + "sqlctx_rewrite_sql": ["sql"], + "sqlctx_explain": ["sql"], + "sqlctx_compile_semantic_input": ["input_json", "query_json"], + "sqlctx_rewrite_semantic_input": ["input_json", "sql", "context_json"], + "sqlctx_query_semantic_input": ["input_json", "query_json"], + } + expected = ", ".join( + f"({literal(name)}, [{', '.join(literal(parameter) for parameter in names)}]::varchar[])" + for name, names in parameters.items() + ) + # Hosts built without the JSON extension emit LIST columns using DuckDB's + # SQL display syntax in -json mode. Compare the complete lists in SQL. + rows = execute( + f"select function_name, actual.parameters = expected.parameters as parameters_match, " + f"description, len(examples) as example_count from duckdb_functions() actual " + f"join (values {expected}) expected(name, parameters) on function_name = expected.name " + f"order by function_name", + setup="", + )[0] + assert {row["function_name"] for row in rows} == set(parameters) + for row in rows: + assert row["parameters_match"], row["function_name"] + assert row["description"] and row["example_count"] > 0 diff --git a/sqlctx-duckdb/test/test_measure_declaration_host.py b/sqlctx-duckdb/test/test_measure_declaration_host.py new file mode 100644 index 000000000..2758b343f --- /dev/null +++ b/sqlctx-duckdb/test/test_measure_declaration_host.py @@ -0,0 +1,267 @@ +"""Define measures from physical rows with SQLCtx as the only loaded extension.""" + +import pytest +from test_catalog_host import execute + +ORDERS = """ +create table orders(id integer, region varchar, amount integer); +insert into orders values (1, 'west', 10), (2, 'west', 30), (3, 'east', 80); +""" + + +@pytest.mark.parametrize("native_grammar", [False, True]) +def test_measure_declaration_recomputes_average(native_grammar): + if native_grammar and not execute("select version() as v", setup="")[0][0]["v"].startswith("v2"): + pytest.skip("Native grammar requires DuckDB 2") + grammar = ( + "set active_grammar_extensions=['sqlctx']; set allow_parser_override_extension='default';" + if native_grammar + else "" + ) + results = execute( + """ + select region, aggregate(aov) as value from yard_sales order by region; + select aggregate(aov) as value from yard_sales; + select region, aov from yard_sales order by region; + select aov from yard_sales; + show metrics from yard_sales; + """, + setup=ORDERS + grammar + "create view yard_sales as select region, avg(amount) as measure aov from orders;", + ) + assert results[0] == [{"region": "east", "value": 80}, {"region": "west", "value": 20}] + assert results[1] == [{"value": 40}] + assert results[2] == [{"region": "east", "aov": 80}, {"region": "west", "aov": 20}] + assert results[3] == [{"aov": 40}] + assert any("aov" in row.values() for row in results[4]) + + +def test_measure_inputs_keep_join_qualifiers_and_filters(): + results = execute( + """ + select bucket, weighted from priced order by bucket; + select aggregate(weighted) as total from priced; + """, + setup=ORDERS + + """ + create table adjustments as select * from (values (1, 3), (2, 4), (3, 2)) a(id, amount); + create view priced as + select upper(o.region) as bucket, avg(o.amount * a.amount) as /* marker */ measure weighted + from orders o join adjustments a on o.id = a.id where o.id > 1; + """, + ) + assert results[0] == [{"bucket": "EAST", "weighted": 160}, {"bucket": "WEST", "weighted": 120}] + assert results[1] == [{"total": 140}] + + +def test_count_star_and_ordinary_measure_aliases(): + results = execute( + """ + select n from counted; + select measure, "a/*b" as words from ordinary; + select aggregate([1,2,3], 'sum')::bigint as total; + """, + setup=ORDERS + + """ + create view counted as select count(*) as measure n from orders; + create view ordinary as select 'AS MEASURE n' as "a/*b", 5 as measure, from (values (1)) t(i); + """, + ) + assert results == [[{"n": 3}], [{"measure": 5, "words": "AS MEASURE n"}], [{"total": 6}]] + + +def test_distinct_and_filtered_measures_share_live_source(): + results = execute( + """ + select regions, west from summary; + insert into orders values (4, 'west', 20); + select regions, west from summary; + """, + setup=ORDERS + + """ + create view summary as select count(distinct region) as measure regions, + sum(amount) filter (where region = 'west') as measure west from orders; + """, + ) + assert [[int(row["regions"]), int(row["west"])] for rows in results for row in rows] == [[2, 40], [2, 60]] + + +def test_formula_can_reference_other_measures(): + results = execute( + "select aggregate(aov) as value from sales;", + setup=ORDERS + + """ + create view sales as select sum(amount) as measure amount, count(*) as measure orders, + amount / nullif(orders, 0) as measure aov from orders; + """, + ) + assert results == [[{"value": 40}]] + + +def test_grouped_measure_declaration_preserves_its_grain(): + results = execute( + "select region, aggregate(aov) as value from grouped order by region;", + setup=ORDERS + "create view grouped as select region, avg(amount) as measure aov from orders group by region;", + ) + assert results == [[{"region": "east", "value": 80}, {"region": "west", "value": 20}]] + + +def test_star_preserves_interleaved_view_fields(): + rows = execute( + "select * from summary order by region;", + setup=ORDERS + + """ + create view summary as select avg(amount) as measure aov, region, count(*) as measure n from orders; + """, + )[0] + assert list(rows[0]) == ["aov", "region", "n"] + assert rows == [{"aov": 80, "region": "east", "n": 1}, {"aov": 20, "region": "west", "n": 2}] + + +@pytest.mark.parametrize( + ("projection", "expected"), + [ + ( + "o.*", + [ + {"id": 1, "region": "west", "amount": 10}, + {"id": 2, "region": "west", "amount": 30}, + {"id": 3, "region": "east", "amount": 80}, + ], + ), + ( + "o.* replace (upper(o.region) as region)", + [ + {"id": 1, "region": "WEST", "amount": 10}, + {"id": 2, "region": "WEST", "amount": 30}, + {"id": 3, "region": "EAST", "amount": 80}, + ], + ), + ( + "o.* rename (region as area)", + [ + {"id": 1, "area": "west", "amount": 10}, + {"id": 2, "area": "west", "amount": 30}, + {"id": 3, "area": "east", "amount": 80}, + ], + ), + ], +) +@pytest.mark.parametrize("joined", [False, True]) +def test_declaration_wildcards_preserve_expressions_and_qualifiers(tmp_path, projection, expected, joined): + database = tmp_path / "wildcards.duckdb" + columns = ", ".join(expected[0]) + query = f"select {columns} from summary order by id; select aov, n from summary;" + source = "orders o join adjustments a on o.id = a.id" if joined else "orders o" + results = execute( + query, + database=database, + setup=ORDERS + + f""" + create table adjustments as select id, 999 as amount from orders; + create view summary as select avg(o.amount) as measure aov, {projection}, count(*) as measure n + from {source}; + """, + ) + assert results == [expected, [{"aov": 40, "n": 3}]] + # Expanded expressions, aliases and measure positions must also survive storage. + assert execute(query, setup="", database=database, readonly=True) == results + + +def test_bi_sum_recomputes_additive_measure_at_requested_grain(): + results = execute( + """ + select region, sum(revenue) as total from sales group by region order by region; + select sum(revenue) as total from sales; + select region, sum(revenue) as total from sales where region='west' group by region; + select region, sum(revenue) as total from sales group by rollup(region) order by region nulls last; + select sum(revenue)/sum(units) as average from sales; + """, + setup=ORDERS + + "create view sales as select region, sum(amount) as measure revenue, sum(1) as measure units from orders;", + ) + for rows in results: + for row in rows: + if "total" in row: + row["total"] = int(row["total"]) + assert results == [ + [{"region": "east", "total": 80}, {"region": "west", "total": 40}], + [{"total": 120}], + [{"region": "west", "total": 40}], + [{"region": "east", "total": 80}, {"region": "west", "total": 40}, {"region": None, "total": 120}], + [{"average": 40}], + ] + + +@pytest.mark.parametrize( + "expression", + [ + "sum(aov)", + "avg(revenue)", + "count(revenue)", + "sum(distinct revenue)", + "sum(revenue + 1)", + "sum(aggregate(revenue))", + "sum(revenue) over ()", + "sum(revenue) filter (where region='west')", + ], +) +def test_ambiguous_measure_reaggregation_has_actionable_error(expression): + execute( + f"select {expression} from sales;", + setup=ORDERS + + "create view sales as select region, sum(amount) as measure revenue, avg(amount) as measure aov from orders;", + error="Use AGGREGATE(", + ) + + +def test_ordinary_aggregates_over_explicit_result_grain_remain_composable(): + results = execute( + """ + select sum(total) as total from (select region, aggregate(revenue) as total from sales group by region); + select avg(value) as average_of_regions from (select region, aggregate(aov) as value from sales group by region); + select sum(revenue) as total from regional_sales; + select sum(amount) as total from orders; + """, + setup=ORDERS + + """ + create view sales as select region, sum(amount) as measure revenue, avg(amount) as measure aov from orders; + create view regional_sales as select region, sum(amount) as measure revenue from orders group by region; + """, + ) + for rows in results: + for row in rows: + if "total" in row: + row["total"] = int(row["total"]) + assert results == [[{"total": 120}], [{"average_of_regions": 50}], [{"total": 120}], [{"total": 120}]] + + +SEMANTIC_ORDERS = ( + ORDERS + + """ +MODEL order_model FROM orders ( + primary key(id) + region + sum(amount) AS revenue + count(*) AS n + revenue / n AS aov +); +""" +) + + +@pytest.mark.parametrize("grouping", ["region", "1", "grouping sets ((1))"]) +def test_semantic_ratio_reaggregation_accepts_one_row_per_group(grouping): + rows = execute( + f"select region, sum(aov) as average from semantic.order_model group by {grouping} order by region;", + setup=SEMANTIC_ORDERS, + )[0] + assert rows == [{"region": "east", "average": 80}, {"region": "west", "average": 20}] + + +@pytest.mark.parametrize("grouping", ["rollup(region)", "rollup(1)", "grouping sets ((1), ())"]) +def test_semantic_ratio_reaggregation_rejects_grain_reducing_groups(grouping): + execute( + f"select region, sum(aov) as average from semantic.order_model group by {grouping};", + setup=SEMANTIC_ORDERS, + error="re-aggregates metric", + ) diff --git a/sqlctx-duckdb/test/test_measure_metadata_host.py b/sqlctx-duckdb/test/test_measure_metadata_host.py new file mode 100644 index 000000000..8a308c3e5 --- /dev/null +++ b/sqlctx-duckdb/test/test_measure_metadata_host.py @@ -0,0 +1,141 @@ +"""Native catalog metadata and unloaded readers must not misrepresent measures.""" + +import re + +import duckdb +import pytest +from test_catalog_host import execute + +SETUP = """ +create table raw_sales(region varchar, amount integer); +insert into raw_sales values ('west', 10), ('west', 30), ('east', 80); +create view sales as select region, avg(amount) as measure aov, + sum(amount) as measure revenue, count(*) as measure orders from raw_sales; +create view distinct_sales as select region, count(distinct amount) as measure amounts + from raw_sales group by region; +""" + + +def without_extension(database, sql, *, error=None): + # CI's shell statically links SQLCtx, and DuckDB 1.5 loads linked extensions + # at startup. The matching Python wheel provides a genuinely unloaded host. + with duckdb.connect( + str(database), config={"autoload_known_extensions": "false", "autoinstall_known_extensions": "false"} + ) as connection: + assert connection.execute( + "select count(*) from duckdb_extensions() where extension_name = 'sqlctx' and loaded" + ).fetchone() == (0,) + if error: + with pytest.raises(duckdb.Error, match=re.escape(error)): + connection.execute(sql).fetchall() + return None + result = connection.execute(sql) + names = [column[0] for column in result.description] + return [dict(zip(names, row)) for row in result.fetchall()] + + +def test_native_measure_column_types_match_describe_and_survive_reopen(tmp_path): + database = tmp_path / "types.duckdb" + query = """ + select column_name, data_type from information_schema.columns + where table_name = 'sales' order by ordinal_position; + """ + types, described = execute(query + "describe sales;", setup=SETUP, database=database) + expected = [ + {"column_name": "region", "data_type": "VARCHAR"}, + {"column_name": "aov", "data_type": "DOUBLE"}, + {"column_name": "revenue", "data_type": "HUGEINT"}, + {"column_name": "orders", "data_type": "BIGINT"}, + ] + assert types == expected + assert [(row["column_name"], row["column_type"]) for row in described] == [ + (row["column_name"], row["data_type"]) for row in expected + ] + assert without_extension(database, query) == expected + assert execute(query, setup="", database=database) == [expected] + + +def test_unloaded_virtual_measure_fails_and_materialized_measure_stays_readable(tmp_path): + database = tmp_path / "readers.duckdb" + execute("select aov from sales;", setup=SETUP, database=database) + without_extension(database, "select aov from sales;", error="requires LOAD sqlctx") + assert without_extension(database, "select region from sales order by region;") == [ + {"region": "east"}, + {"region": "west"}, + {"region": "west"}, + ] + assert without_extension(database, "select region, amounts from distinct_sales order by region;") == [ + {"region": "east", "amounts": 1}, + {"region": "west", "amounts": 2}, + ] + assert execute("select aov from sales;", setup="", database=database) == [[{"aov": 40}]] + + +def test_loaded_star_preserves_semantic_projection_and_cardinality(): + rows = execute("select * from sales order by region;", setup=SETUP)[0] + assert [(row["region"], row["aov"], int(row["revenue"]), row["orders"]) for row in rows] == [ + ("east", 80, 80, 1), + ("west", 20, 40, 2), + ] + + +def test_native_measure_metadata_replacement_rolls_back(tmp_path): + database = tmp_path / "rollback.duckdb" + execute( + """ + begin; + create or replace view sales as select min(region) as measure first_region from raw_sales; + rollback; + """, + setup=SETUP, + database=database, + ) + assert without_extension( + database, + "select data_type from information_schema.columns where table_name='sales' and column_name='aov';", + ) == [{"data_type": "DOUBLE"}] + without_extension(database, "select aov from sales;", error="requires LOAD sqlctx") + + +def test_attached_measure_metadata_and_loaded_reads(tmp_path): + database = tmp_path / "original.duckdb" + execute("select aov from sales;", setup=SETUP, database=database) + path = str(database).replace("'", "''") + metadata, values = execute( + f""" + attach '{path}' as renamed; + select data_type from information_schema.columns + where table_catalog='renamed' and table_name='sales' and column_name='aov'; + select aov from renamed.main.sales; + """, + setup="", + ) + assert metadata == [{"data_type": "DOUBLE"}] + assert values == [{"aov": 40}] + without_extension( + ":memory:", + f"attach '{path}' as renamed; select aov from renamed.main.sales;", + error="requires LOAD sqlctx", + ) + + +def test_measure_metadata_rebinds_after_source_type_changes(): + ordinary, semantic, metadata = execute( + """ + alter table raw_sales alter amount type decimal(12,2); + describe ordinary_sum; + describe semantic_sum; + select table_name, data_type from information_schema.columns + where table_name in ('ordinary_sum', 'semantic_sum') order by table_name; + """, + setup=SETUP + + """ + create view ordinary_sum as select sum(amount) as revenue from raw_sales; + create view semantic_sum as select sum(amount) as measure revenue from raw_sales; + """, + ) + assert ordinary[0]["column_type"] == semantic[0]["column_type"] == "DECIMAL(38,2)" + assert metadata == [ + {"table_name": "ordinary_sum", "data_type": "DECIMAL(38,2)"}, + {"table_name": "semantic_sum", "data_type": "DECIMAL(38,2)"}, + ] diff --git a/sqlctx-duckdb/test/test_measure_namespace_host.py b/sqlctx-duckdb/test/test_measure_namespace_host.py new file mode 100644 index 000000000..84d92b32a --- /dev/null +++ b/sqlctx-duckdb/test/test_measure_namespace_host.py @@ -0,0 +1,194 @@ +"""Native measure views obey DuckDB's catalog, schema and session lifetime.""" + +import os +from pathlib import Path + +import pytest +from test_catalog_host import execute + +ROWS = """ +create table raw_sales(id integer, amount integer); +insert into raw_sales values (1, 10), (2, 30); +create view sales as select sum(amount) as measure revenue from raw_sales; +""" + + +def test_temporary_measure_shadowing_qualified_lookup_and_rollback(): + results = execute( + """ + begin; + create temp view sales(revenue) as select sum(amount * 10) as measure revenue from raw_sales; + select aggregate(revenue) as total from sales; + select aggregate(revenue) as total from main.sales; + select count(*) as views, count(*) filter (where temporary) as temps + from duckdb_views() where view_name = 'sales'; + rollback; + select aggregate(revenue) as total from sales; + select count(*) as views from duckdb_views() where view_name = 'sales'; + """, + setup=ROWS, + ) + assert [int(rows[0]["total"]) for rows in results if "total" in rows[0]] == [400, 40, 40] + assert [{"views": 2, "temps": 1}] in results + assert results[-1] == [{"views": 1}] + + +def test_temporary_plain_replacement_and_drop_reveal_permanent_measure(): + results = execute( + """ + create temp view sales(revenue) as select sum(amount * 10) as measure revenue from raw_sales; + create or replace temp view sales as select 17 as revenue; + select revenue from sales; + select aggregate(revenue) as revenue from main.sales; + drop view sales; + select aggregate(revenue) as revenue from sales; + select count(*) as temps from duckdb_views() where view_name = 'sales' and temporary; + """, + setup=ROWS, + ) + assert [{"revenue": 17}] in results + assert [int(rows[0]["revenue"]) for rows in results if "revenue" in rows[0]] == [17, 40, 40] + assert results[-1] == [{"temps": 0}] + + +def test_explicit_main_drop_leaves_temporary_measure_view(): + results = execute( + """ + create temp view sales(revenue) as select sum(amount * 10) as measure revenue from raw_sales; + begin; + drop view main.sales; + select aggregate(revenue) as total from sales; + select count(*) as persistent from duckdb_views() where view_name = 'sales' and not temporary; + rollback; + select aggregate(revenue) as total from main.sales; + select aggregate(revenue) as total from temp.main.sales; + """, + setup=ROWS, + ) + assert [int(rows[0]["total"]) for rows in results if "total" in rows[0]] == [400, 40, 400] + assert [{"persistent": 0}] in results + + +def test_schema_search_path_and_qualified_discovery(): + results = execute( + """ + create schema first; + create schema second; + create view first.sales as select sum(amount * 2) as measure double_revenue from raw_sales; + create view second.sales as select sum(amount * 3) as measure triple_revenue from raw_sales; + set search_path = 'second,first,main'; + select aggregate(triple_revenue) as total from sales; + select aggregate(double_revenue) as total from first.sales; + show metrics from first.sales; + describe model second.sales; + drop view sales; + select aggregate(double_revenue) as total from sales; + """, + setup=ROWS, + ) + assert [int(rows[0]["total"]) for rows in results if "total" in rows[0]] == [120, 80, 80] + assert any(any(row.get("name") == "double_revenue" for row in rows) for rows in results) + assert any(any(row.get("name") == "triple_revenue" for row in rows) for rows in results) + + +def test_ignored_measure_declaration_does_not_bind_body(): + results = execute( + """ + create view if not exists sales as select sum(missing) as measure revenue from missing_table; + select aggregate(revenue) as total from sales; + """, + setup=ROWS, + ) + assert int(results[-1][0]["total"]) == 40 + + +def test_native_measure_metadata_never_leaks_into_ordinary_model_snapshot(tmp_path): + database = tmp_path / "catalog.duckdb" + execute( + """ + create temp view ephemeral(revenue) as select sum(amount * 10) as measure revenue from raw_sales; + model (name ordinary, table raw_sales, primary_key id); + dimension (name amount, type categorical); + create or replace view sales as select 17 as revenue; + """, + setup=ROWS, + database=database, + ) + rows, models, views = execute( + """ + select revenue from sales; + select model_name from sqlctx_models() order by model_name; + select count(*) as views from duckdb_views() where view_name = 'ephemeral'; + """, + setup="", + database=database, + ) + assert rows == [{"revenue": 17}] + assert models == [{"model_name": "ordinary"}] + assert views == [{"views": 0}] + + +def test_native_temporary_measure_view_is_connection_local(tmp_path): + duckdb = pytest.importorskip("duckdb") + extension = str(Path(os.environ["SQLCTX_DUCKDB_EXTENSION"]).resolve()).replace("'", "''") + database = str(tmp_path / "sessions.duckdb") + with duckdb.connect(database, config={"allow_unsigned_extensions": "true", "threads": "2"}) as first: + first.execute(f"load '{extension}'") + first.execute(ROWS) + with first.cursor() as second: + first.execute( + "create temp view sales(revenue) as select sum(amount * 10) as measure revenue from raw_sales" + ) + assert first.sql("select aggregate(revenue) from sales").fetchall() == [(400,)] + assert second.sql("select aggregate(revenue) from sales").fetchall() == [(40,)] + first.execute("drop view sales") + assert first.sql("select aggregate(revenue) from sales").fetchall() == [(40,)] + + +def test_failed_temporary_batch_does_not_leave_shadowing_metadata(): + duckdb = pytest.importorskip("duckdb") + extension = str(Path(os.environ["SQLCTX_DUCKDB_EXTENSION"]).resolve()).replace("'", "''") + with duckdb.connect(config={"allow_unsigned_extensions": "true", "threads": "2"}) as connection: + connection.execute(f"load '{extension}'") + connection.execute(ROWS) + with pytest.raises(duckdb.Error, match="missing_column"): + connection.execute(""" + create temp view sales as select sum(amount * 10) as measure revenue from raw_sales; + create table failed_result as select aggregate(revenue), missing_column from sales; + """) + assert connection.sql("select aggregate(revenue) from sales").fetchall() == [(40,)] + assert connection.sql( + "select count(*) from duckdb_views() where view_name = 'sales' and temporary" + ).fetchall() == [(0,)] + + +def test_temporary_batch_materializes_then_restores_permanent_view(): + duckdb = pytest.importorskip("duckdb") + extension = str(Path(os.environ["SQLCTX_DUCKDB_EXTENSION"]).resolve()).replace("'", "''") + with duckdb.connect(config={"allow_unsigned_extensions": "true", "threads": "2"}) as connection: + connection.execute(f"load '{extension}'") + connection.execute(ROWS) + connection.execute(""" + create temp view sales as select sum(amount * 10) as measure revenue from raw_sales; + create table batch_result as select aggregate(revenue) as revenue from sales; + """) + assert connection.sql("select revenue from batch_result").fetchall() == [(400,)] + assert connection.sql("select aggregate(revenue) from sales").fetchall() == [(40,)] + + +def test_native_measure_relocates_when_database_is_attached_under_another_name(tmp_path): + database = tmp_path / "original.duckdb" + execute("select aggregate(revenue) from sales;", setup=ROWS, database=database) + path = str(database).replace("'", "''") + results = execute( + f""" + attach '{path}' as renamed; + select aggregate(revenue) as revenue from renamed.main.sales; + use renamed; + select aggregate(revenue) as revenue from sales; + show metrics from renamed.main.sales; + """, + setup="", + ) + assert [int(rows[0]["revenue"]) for rows in results[:2]] == [40, 40] + assert any(row.get("name") == "revenue" for row in results[2]) diff --git a/sqlctx-duckdb/test/test_measure_view_lifecycle_host.py b/sqlctx-duckdb/test/test_measure_view_lifecycle_host.py new file mode 100644 index 000000000..eeeade34d --- /dev/null +++ b/sqlctx-duckdb/test/test_measure_view_lifecycle_host.py @@ -0,0 +1,220 @@ +"""Native VIEW lifecycle for models declared with standalone AS MEASURE.""" + +import pytest +from test_catalog_host import execute + +ROWS = """ +create table raw_sales(id integer, region varchar, amount integer); +insert into raw_sales values (1, 'west', 10), (2, 'west', 30), (3, 'east', 80); +""" +VIEW = "create view sales as select region, avg(amount) as measure aov from raw_sales;" +SETUP = ROWS + VIEW + + +def test_measure_view_aggregate_routing(): + grouped, total, direct, native = execute( + """ + select region, aggregate(aov) as aov from sales group by region order by region; + select aggregate(aov) as aov from sales; + select aov from sales; + select aggregate([1, 2, 3], 'sum') as total; + """, + setup=SETUP, + ) + assert grouped == [{"region": "east", "aov": 80}, {"region": "west", "aov": 20}] + assert total == direct == [{"aov": 40}] + assert int(native[0]["total"]) == 6 + + +def test_explicit_measure_view_aggregate_routing(): + grouped, total = execute( + """ + select region, aggregate(aov) as aov from semantic.sales order by region; + select aggregate(aov) as aov from semantic.sales; + """, + setup=SETUP, + ) + assert grouped == [{"region": "east", "aov": 80}, {"region": "west", "aov": 20}] + assert total == [{"aov": 40}] + + +def test_direct_measure_survives_prepare_and_ordinary_view_reopen(tmp_path): + database = tmp_path / "direct-view.duckdb" + assert execute( + """ + prepare mean_sales as select aov from sales; + execute mean_sales; + create view totals as select aov from sales; + select * from totals; + """, + setup=SETUP, + database=database, + ) == [[{"aov": 40}], [{"aov": 40}]] + assert execute("select * from totals;", setup="", database=database) == [[{"aov": 40}]] + + +@pytest.mark.parametrize("reference", ["aov", "plain.aov"]) +def test_ordinary_view_cannot_recompute_a_projected_measure(reference): + execute( + f"select aggregate({reference}) from sales_rows plain;", + setup=SETUP + "create view sales_rows as select * from sales;", + error="is read through plain, which does not define it", + ) + + +@pytest.mark.parametrize("drop", ["drop view sales", "drop view if exists sales", "drop view main.sales"]) +def test_measure_view_drop_rollback(drop): + results = execute( + f""" + begin; + {drop}; + select count(*) as models from sqlctx_models() where model_name = 'sales'; + rollback; + select aov from sales; + {drop}; + drop view if exists sales; + select count(*) as models from sqlctx_models() where model_name = 'sales'; + """, + setup=SETUP, + ) + assert results[-1] == [{"models": 0}] + assert [{"models": 0}] in results + assert [{"aov": 40}] in results + + +def test_measure_view_replace_then_drop(): + results = execute( + """ + select aov from sales; + create or replace view sales as select region, sum(amount) as measure revenue from raw_sales; + select revenue from sales; + drop view sales; + select count(*) as models from sqlctx_models() where model_name = 'sales'; + """, + setup=SETUP, + ) + assert [{"aov": 40}] in results + assert any("revenue" in rows[0] and int(rows[0]["revenue"]) == 120 for rows in results if rows) + assert results[-1] == [{"models": 0}] + + +@pytest.mark.parametrize("replace", ["", "or replace "]) +def test_measure_view_rejects_physical_table_collision(replace, tmp_path): + database = tmp_path / "collision.duckdb" + execute("select 1;", setup=ROWS + "create table sales as select 7 as amount;", database=database) + execute( + f"create {replace}view sales as select avg(amount) as measure aov from raw_sales;", + setup="", + database=database, + error="physical table already exists", + ) + assert execute("select amount from sales;", setup="", database=database) == [[{"amount": 7}]] + + +def test_ordinary_view_rejects_measure_collision_without_replace(tmp_path): + database = tmp_path / "measure.duckdb" + execute("select aov from sales;", setup=SETUP, database=database) + execute( + "create view sales as select 7 as amount;", + setup="", + database=database, + error="already exists", + ) + assert execute("select aov from sales;", setup="", database=database) == [[{"aov": 40}]] + + +def test_measure_and_ordinary_views_replace_each_other_transactionally(): + results = execute( + """ + begin; + create or replace view sales as select 7 as amount; + select amount from sales; + rollback; + select aggregate(aov) as aov from sales; + create or replace view sales as select 9 as amount; + select amount from sales; + create or replace view sales as select avg(amount) as measure aov from raw_sales; + select aggregate(aov) as aov from sales; + """, + setup=SETUP, + ) + assert [{"amount": 7}] in results + assert [{"amount": 9}] in results + assert results.count([{"aov": 40}]) == 2 + + +def test_failed_plain_replacement_preserves_measure_metadata(tmp_path): + database = tmp_path / "replace.duckdb" + execute("select aov from sales;", setup=SETUP, database=database) + execute( + "create or replace view sales as select missing_column;", setup="", database=database, error="missing_column" + ) + assert execute("select aggregate(aov) as aov from sales;", setup="", database=database) == [[{"aov": 40}]] + + +def test_prepared_measure_creation_rechecks_physical_collision(tmp_path): + database = tmp_path / "prepared.duckdb" + execute( + """ + prepare define_sales as create view sales as select avg(amount) as measure aov from raw_sales; + create table sales as select 7 as amount; + execute define_sales; + """, + setup=ROWS, + database=database, + error="physical table already exists", + ) + rows, models = execute( + "select amount from sales; select count(*) as models from sqlctx_models() where model_name = 'sales';", + setup="", + database=database, + ) + assert rows == [{"amount": 7}] + assert models == [{"models": 0}] + + +def test_native_views_and_models_keep_their_drop_semantics(): + results = execute( + """ + create view ordinary as select 7 as amount; + create or replace view ordinary as select 9 as amount; + select amount from ordinary; + drop view ordinary; + model (name facts, table raw_sales, primary_key id); + drop view if exists facts; + select model_name as name from sqlctx_models() where model_name = 'facts'; + """, + setup=ROWS, + ) + assert [{"amount": 9}] in results + assert results[-1] == [{"name": "facts"}] + + +def test_physical_table_shadow_does_not_drop_measure_model(tmp_path): + database = tmp_path / "shadow.duckdb" + execute( + "create temp table sales as select 7 as aov; drop view sales;", + setup=SETUP, + database=database, + error="sales", + ) + rows, models = execute( + "select aov from sales; select model_name as name from sqlctx_models() where model_name = 'sales';", + setup="", + database=database, + ) + assert rows == [{"aov": 40}] + assert models == [{"name": "sales"}] + + +def test_measure_view_reopens_and_readonly_drop_is_rejected(tmp_path): + database = tmp_path / "persistent.duckdb" + execute("select aov from sales;", setup=SETUP, database=database) + assert execute("select aov from sales;", setup="", database=database) == [[{"aov": 40}]] + execute("drop view sales;", setup="", database=database, readonly=True, error="read-only") + results = execute( + "drop view sales; select count(*) as models from sqlctx_models() where model_name = 'sales';", + setup="", + database=database, + ) + assert results[-1] == [{"models": 0}] diff --git a/sqlctx-duckdb/test/test_semantic_input_host.py b/sqlctx-duckdb/test/test_semantic_input_host.py index c9137822d..251b4e476 100644 --- a/sqlctx-duckdb/test/test_semantic_input_host.py +++ b/sqlctx-duckdb/test/test_semantic_input_host.py @@ -65,6 +65,16 @@ def relation(query=None, source=None): return f"sqlctx_query_semantic_input({input_json}, {query_json})" +def test_omitted_input_dialect_uses_duckdb_in_all_three_sql_functions(): + source = copy.deepcopy(SOURCE) + del source["input_dialect"] + assert call(source=source) == call() + query = "select orders.revenue from orders" + assert call(source=source, sql=query) == call(sql=query) + assert execute(f"select * from {relation(source=source)}") == execute(f"select * from {relation()}") + assert "supported semantic input version" in call(source={**source, "version": 99}, error=True) + + @pytest.mark.parametrize("expression", [False, True]) def test_graph_window_identity_shadows_same_named_local_aggregate(expression): source = { diff --git a/sqlctx-duckdb/test/test_semantic_views_host.py b/sqlctx-duckdb/test/test_semantic_views_host.py index 7e5940e64..6a466fd49 100644 --- a/sqlctx-duckdb/test/test_semantic_views_host.py +++ b/sqlctx-duckdb/test/test_semantic_views_host.py @@ -82,6 +82,99 @@ def test_named_view_nested_selection_and_star(): assert rows[-1] == [{"gross": 7}] +def test_bare_stars_route_models_and_views_without_a_named_field(): + rows = execute( + """ + select * from orders; + select * from semantic.orders; + select * from sales; + select * from semantic.sales; + select s.* from sales s; + with sales as (select 7 as marker) select * from sales; + create table sales as select 9 as marker; + select * from sales; + select * from semantic.sales; + """, + setup=SETUP, + ) + + def ordered(result): + return sorted(result, key=lambda row: tuple(str(value) for value in row.values())) + + assert ordered(rows[0]) == ordered(rows[1]) + assert ordered(rows[2]) == ordered(rows[3]) == ordered(rows[4]) == ordered(rows[7]) + assert rows[5] == [{"marker": 7}] + assert rows[6] == [{"marker": 9}] + assert ordered(rows[2]) == [ + {"country": "CA", "gross": 80, "paid": 80, "aov": 80}, + {"country": "US", "gross": 40, "paid": 10, "aov": 20}, + ] + + +def test_semantic_view_discovery_and_lifecycle_labels(tmp_path): + database = tmp_path / "discovery.duckdb" + rows = execute( + """ + create semantic view report as select country, gross from sales; + show semantic views; + create or replace semantic view report as select country, aov from sales; + prepare views as show semantic views; + begin; + drop semantic view report; + execute views; + rollback; + execute views; + """, + setup=SETUP, + database=database, + ) + assert rows[0] == [{"result": "Created semantic view report"}] + assert [(row["kind"], row["name"]) for row in rows[1]] == [("view", "report"), ("view", "sales")] + assert rows[1][0]["sql"].lower() == "select country, gross from sales" + assert rows[2] == [{"result": "Replaced semantic view report"}] + assert rows[3] == [{"result": "Dropped semantic view report"}] + assert [row["name"] for row in rows[4]] == ["sales"] + assert [row["name"] for row in rows[5]] == ["report", "sales"] + reopened = execute("show semantic views;", setup="", database=database)[0] + assert [(row["kind"], row["name"]) for row in reopened] == [("view", "report"), ("view", "sales")] + execute("drop semantic view sales;", setup="", database=database, error="RESTRICT") + execute("drop view report;", setup="", database=database, error="DROP SEMANTIC VIEW") + execute("drop view if exists report;", setup="", database=database, error="DROP SEMANTIC VIEW") + physical, semantic = execute( + """ + create view report as select 7 as marker; + select * from report; + drop view report; + select aov from report; + """, + setup="", + database=database, + ) + assert physical == [{"marker": 7}] + assert semantic == [{"aov": 40}] + + +def test_semantic_create_ordinary_view_persists_replayable_sql(tmp_path): + database = tmp_path / "ordinary-view.duckdb" + rows = execute( + """ + semantic create view persisted as select gross from sales; + select sql from duckdb_views() where view_name = 'persisted'; + """, + setup=SETUP, + database=database, + ) + sql = rows[0][0]["sql"] + assert sql and "raw_orders" in sql.lower() + assert execute("select * from persisted;", setup="", database=database) == [[{"gross": 120}]] + replayed = execute( + f"drop view persisted; drop semantic view sales; drop model orders; {sql} select * from persisted;", + setup="", + database=database, + ) + assert replayed[-1] == [{"gross": 120}] + + def test_view_aliases_keep_the_grain_and_bind_in_scalar_subqueries(): rows = execute( """ diff --git a/sqlctx-duckdb/test/test_yardstick_host.py b/sqlctx-duckdb/test/test_yardstick_host.py index 8a7287482..4aaa2eecd 100644 --- a/sqlctx-duckdb/test/test_yardstick_host.py +++ b/sqlctx-duckdb/test/test_yardstick_host.py @@ -53,6 +53,8 @@ def test_measure_views_with_yardstick(tmp_path, first): "select aggregate(list(amount), 'sum') from facts", 'select "aggregate"([1,2,3], \'sum\')', "semantic select sales.revenue from sales", + "select * from sqlctx_query('select revenue from report')", + "select * from sqlctx_query_scoped('select revenue from report')", ] print(json.dumps([con.execute(query).fetchall() for query in queries])) ''' @@ -76,4 +78,67 @@ def test_measure_views_with_yardstick(tmp_path, first): [[120]], [[6]], [[120]], + [[120]], + [[120]], ] + + +@pytest.mark.parametrize("first", ["sqlctx", "yardstick"]) +def test_yardstick_does_not_reinterpret_sqlctx_measures(tmp_path, first): + if not os.environ.get("YARDSTICK_EXTENSION"): + pytest.skip("Set YARDSTICK_EXTENSION to a Yardstick binary built for this host") + paths = { + "yardstick": str(Path(os.environ["YARDSTICK_EXTENSION"]).resolve()), + "sqlctx": str(Path(os.environ["SQLCTX_DUCKDB_EXTENSION"]).resolve()), + } + second = "sqlctx" if first == "yardstick" else "yardstick" + script = r""" +import duckdb +import json +import sys + +paths = json.loads(sys.argv[1]) +def load(con, path): + con.execute("load '" + path.replace("'", "''") + "'") + +con = duckdb.connect("measures.duckdb", config={"allow_unsigned_extensions": True}) +load(con, sys.argv[2]) +con.execute("create table facts(region varchar, amount int)") +con.execute("insert into facts values ('west',10), ('west',30), ('east',80)") +con.execute("create view ours as select region, avg(amount) as measure aov from facts") +con.close() +con = duckdb.connect("measures.duckdb", config={"allow_unsigned_extensions": True}) +for path in paths: + load(con, path) +if duckdb.__version__.startswith("2."): + con.execute("set active_grammar_extensions=['sqlctx','yardstick']") +assert con.execute("select aov from ours").fetchall() == [(40.0,)] +for run in (con.sql, con.execute, con.sql): + try: + run("select aggregate(aov) from ours").fetchall() + except duckdb.Error as error: + message = str(error) + assert ( + "Yardstick cannot evaluate SQLCtx measure views" in message + or 'Cannot safely reaggregate measure "aov"' in message + ), message + else: + raise AssertionError("Yardstick silently changed SQLCtx AVG semantics") +try: + con.execute("select missing_column from facts") +except duckdb.BinderException: + pass +else: + raise AssertionError("Ordinary SQL did not preserve its binder diagnostic") +assert con.execute("select aov from ours").fetchall() == [(40.0,)] +print("ok") +""" + result = subprocess.run( + [sys.executable, "-c", script, json.dumps([paths[first], paths[second]]), paths["sqlctx"]], + cwd=tmp_path, + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == "ok"