From 108e19ce4956329577e8054fb01e09c4fb1e2d24 Mon Sep 17 00:00:00 2001 From: Nico Ritschel Date: Thu, 5 Nov 2026 23:09:34 +0000 Subject: [PATCH 1/3] Complete Ossie window queries and preserve dialect execution semantics --- docs/compatibility/ossie.md | 18 +- sidemantic-rs/src/adapters/ossie.rs | 4 +- sidemantic-rs/src/semantic_input.rs | 47 + sidemantic-rs/src/semantic_input/dialects.rs | 109 ++ sidemantic-rs/src/sql/generator/ossie_wide.rs | 93 +- .../src/sql/rewriter/ossie_relational.rs | 1100 ++++++++++++++++- sidemantic/sql/ossie_relational.py | 326 ++++- sidemantic/sql/ossie_views.py | 38 +- sidemantic/sql/ossie_wide.py | 27 +- .../ossie/test_implicit_seed_source.py | 91 ++ .../ossie/test_qualify_complete.py | 140 +++ .../ossie/test_qualify_dialect_routes.py | 56 + .../ossie/test_quoted_wildcard_rename.py | 87 ++ .../interchange/ossie/test_review_qualify.py | 9 +- .../test_review_relational_boundaries.py | 16 +- .../ossie/test_review_wide_adapter.py | 5 +- 16 files changed, 2048 insertions(+), 118 deletions(-) create mode 100644 tests/interchange/ossie/test_implicit_seed_source.py create mode 100644 tests/interchange/ossie/test_qualify_complete.py create mode 100644 tests/interchange/ossie/test_qualify_dialect_routes.py create mode 100644 tests/interchange/ossie/test_quoted_wildcard_rename.py diff --git a/docs/compatibility/ossie.md b/docs/compatibility/ossie.md index 9b19c57b6..4d1af75e1 100644 --- a/docs/compatibility/ossie.md +++ b/docs/compatibility/ossie.md @@ -260,11 +260,19 @@ population. The provisional measure-definition spellings are `TO_MEASURE(expr)` and `expr TO MEASURE`. Set operations and DISTINCT reject unevaluated measures; ordinary scalar results after `AGG()` retain normal SQL behavior. Using a measure as a scalar, filter predicate, join key, or grouping key fails during binding. -Unaggregated inline-window `QUALIFY` preserves aliases and clause ordering; -combined aggregation or named-window `QUALIFY` shapes reject explicitly. -Wildcard `EXCLUDE`, `REPLACE`, and `RENAME` retain their projection semantics. -Native Rust rejects quoted wildcard `RENAME` operands because its pinned parser -loses their quoted-name identity; ordinary aliases remain supported. +`QUALIFY` supports both unaggregated and grouped relations, including named +windows, inherited window definitions, aggregate aliases, grouping sets, and +window frame expressions. Aggregation and HAVING run before windows and QUALIFY; +DISTINCT, ordering, and pagination run afterward. Hidden measure inputs retain +their source-row identity through the window stage. +Wildcard `EXCLUDE`, `REPLACE`, and `RENAME` retain their projection semantics, +including quoted rename operands, escaped quotes, and schema-qualified stars in +native Rust. Authored SQL uses the layer's SQL dialect, including its identifier +quoting syntax (for example, backticks for BigQuery). + +ClickHouse semantic queries include query-local settings for NULL-preserving +joins, SQL empty-aggregate results, and all matching join rows. They do not depend +on the server's default join or aggregate settings. `DESCRIBE` and `information_schema.columns` identify measure columns using a `MEASURE` type marker. The metadata overlay includes semantic relations while diff --git a/sidemantic-rs/src/adapters/ossie.rs b/sidemantic-rs/src/adapters/ossie.rs index 947b5a1d4..c37239b48 100644 --- a/sidemantic-rs/src/adapters/ossie.rs +++ b/sidemantic-rs/src/adapters/ossie.rs @@ -2783,7 +2783,9 @@ fn compile_scope( } fn classify_source(source: &str, target: OssieTarget) -> Option { - if let Ok(expressions) = polyglot_sql::parse(source, target.parser_dialect()) { + if let Ok(expressions) = + crate::semantic_input::dialects::parse_many(source, target.parser_dialect()) + { if expressions.len() != 1 { return None; } diff --git a/sidemantic-rs/src/semantic_input.rs b/sidemantic-rs/src/semantic_input.rs index f3884ad23..b2d58d21f 100644 --- a/sidemantic-rs/src/semantic_input.rs +++ b/sidemantic-rs/src/semantic_input.rs @@ -2044,6 +2044,53 @@ mod tests { assert_eq!(model.get_segment("unused").unwrap().sql, "{% if missing"); } + #[test] + fn latest_ossie_structured_ordering_preserves_direction_and_nulls() { + let mut source = input(); + source["models"][0]["metadata"] = + json!({"ossie_schema_revision":"172a3e566f2fc9c0a733ebbb470e97c33d2bd8b1"}); + source["models"][0]["dimensions"] = + json!([{"name":"amount", "type":"numeric", "sql":"amount"}]); + source["models"][0]["metrics"] = + json!([{"name":"revenue", "type":"derived", "sql":"SUM(amount)"}]); + for (order, alias, expected) in [ + ( + "orders.revenue DESC NULLS FIRST", + None, + "\"orders.revenue\" DESC NULLS FIRST", + ), + ( + "orders.revenue asc nulls last", + None, + "\"orders.revenue\" ASC NULLS LAST", + ), + ( + "orders.revenue NULLS FIRST", + None, + "\"orders.revenue\" NULLS FIRST", + ), + ( + "Sort DESC NULLS FIRST", + Some("Sort DESC NULLS FIRST"), + "\"Sort DESC NULLS FIRST\"", + ), + ( + "Sort DESC NULLS FIRST ASC NULLS LAST", + Some("Sort DESC NULLS FIRST"), + "\"Sort DESC NULLS FIRST\" ASC NULLS LAST", + ), + ] { + let mut request = + json!({"metrics":["orders.revenue"], "dialect":"postgres", "order_by":[order]}); + if let Some(alias) = alias { + request["aliases"] = json!({"orders.revenue":alias}); + } + let sql = + compile_with_semantic_input(&source.to_string(), &request.to_string()).unwrap(); + assert!(sql.ends_with(&format!("ORDER BY {expected}")), "{sql}"); + } + } + #[test] fn selected_order_names_remain_canonical_before_sql_rendering() { let mut source = input(); diff --git a/sidemantic-rs/src/semantic_input/dialects.rs b/sidemantic-rs/src/semantic_input/dialects.rs index 43774e6b1..d2b5bd9cc 100644 --- a/sidemantic-rs/src/semantic_input/dialects.rs +++ b/sidemantic-rs/src/semantic_input/dialects.rs @@ -290,6 +290,7 @@ pub(crate) fn generate_preserving_null_order( fn transpile(sql: &str, source: DialectType, target: DialectType) -> Result { let sql = super::literals::source_sql(sql, source)?; + let sql = explicit_seed_aliases(&sql, source)?; #[cfg(target_arch = "wasm32")] crate::wasm_sql_guard::check(&sql, source)?; let mut statements = Dialect::get(source) @@ -305,6 +306,7 @@ fn transpile(sql: &str, source: DialectType, target: DialectType) -> Result Result { let sql = super::literals::source_sql(sql, source)?; + let sql = explicit_seed_aliases(&sql, source)?; #[cfg(target_arch = "wasm32")] crate::wasm_sql_guard::check(&sql, source)?; let mut statements = parse_many(&sql, source)?; @@ -316,6 +318,63 @@ pub(crate) fn parse(sql: &str, source: DialectType) -> Result { Ok(statements.remove(0)) } +/// The pinned parser treats SEED after a derived table as a sampling clause, +/// even where the warehouse accepts it as an implicit alias. Insert only the +/// optional AS token in that exact lexer-confirmed relation context. Strings, +/// quoted identifiers, comments, and actual sampling clauses remain untouched. +fn explicit_seed_aliases(sql: &str, dialect: DialectType) -> Result { + use polyglot_sql::tokens::TokenType; + if !sql.to_ascii_uppercase().contains("SEED") { + return Ok(sql.to_owned()); + } + let tokens = Dialect::get(dialect) + .tokenize(sql) + .map_err(|error| SidemanticError::SqlParse(error.to_string()))?; + let offsets = sql + .char_indices() + .map(|(index, _)| index) + .chain([sql.len()]) + .collect::>(); + let mut opens = Vec::new(); + let mut closes = HashMap::new(); + let mut insertions = Vec::new(); + for (index, token) in tokens.iter().enumerate() { + match token.token_type { + TokenType::LParen => opens.push(index), + TokenType::RParen => { + if let Some(open) = opens.pop() { + closes.insert(index, open); + } + } + TokenType::Seed if index > 0 => { + let Some(&open) = closes.get(&(index - 1)) else { + continue; + }; + if open == 0 { + continue; + } + let relation = matches!( + tokens[open - 1].token_type, + TokenType::From | TokenType::Join | TokenType::Comma | TokenType::Lateral + ); + let query = matches!( + tokens[open + 1].token_type, + TokenType::Select | TokenType::With | TokenType::Values + ); + if relation && query { + insertions.push(offsets[token.span.start]); + } + } + _ => {} + } + } + let mut output = sql.to_owned(); + for offset in insertions.into_iter().rev() { + output.insert_str(offset, "AS "); + } + Ok(output) +} + /// QUANTILE_CONT/DISC are absent from the pinned parser's aggregate registry. /// Parse their argument lists with its generic aggregate grammar, then restore /// the actual name in the AST. ORDER BY, DISTINCT, FILTER and window clauses @@ -395,6 +454,7 @@ pub(crate) fn parse_many(sql: &str, dialect: DialectType) -> Result Result { return Ok(sql.to_owned()); } let sql = super::literals::source_sql(sql, source)?; + let sql = explicit_seed_aliases(&sql, source)?; #[cfg(target_arch = "wasm32")] crate::wasm_sql_guard::check(&sql, source)?; Dialect::get(source) @@ -782,6 +843,54 @@ pub(super) fn normalize( mod tests { use super::*; + #[test] + fn source_transpilation_keeps_seed_alias_and_empty_predicate() { + let source = "SELECT amount FROM (SELECT 1 AS amount) seed WHERE FALSE"; + for dialect in [ + DialectType::DuckDB, + DialectType::PostgreSQL, + DialectType::Snowflake, + DialectType::ClickHouse, + DialectType::BigQuery, + ] { + for sql in [ + query(source, dialect).unwrap(), + query_batch(source, dialect).unwrap(), + ] { + let Expression::Select(select) = parse(&sql, DialectType::DuckDB).unwrap() else { + panic!("expected SELECT"); + }; + assert!(select.where_clause.is_some(), "{dialect:?}: {sql}"); + assert!(sql.contains("FALSE"), "{dialect:?}: {sql}"); + } + } + } + + #[test] + fn derived_seed_aliases_do_not_rewrite_sampling_or_quoted_text() { + for sql in [ + "SELECT amount FROM (SELECT 1 AS amount) seed WHERE FALSE", + "SELECT seed.amount FROM (SELECT 1 AS amount) /* é seed */ seed", + "WITH x AS (SELECT 1 AS amount) SELECT amount FROM (SELECT * FROM x) seed", + "SELECT seed.amount FROM (VALUES (1)) seed(amount)", + ] { + let rewritten = explicit_seed_aliases(sql, DialectType::DuckDB).unwrap(); + assert!(rewritten.contains("AS seed"), "{rewritten}"); + assert!(parse_many(sql, DialectType::DuckDB).is_ok(), "{sql}"); + } + for sql in [ + "SELECT 'seed' FROM (SELECT 1) AS seed", + "SELECT * FROM (SELECT 1) \"seed\"", + "SELECT * FROM t USING SAMPLE 10 PERCENT (bernoulli, 42)", + "SELECT * FROM t TABLESAMPLE BERNOULLI (10) SEED (42)", + ] { + assert_eq!( + explicit_seed_aliases(sql, DialectType::DuckDB).unwrap(), + sql + ); + } + } + #[test] fn ossie_physical_and_expression_dialects_normalize_independently_once() { for (physical, expression, query, field_sql) in [ diff --git a/sidemantic-rs/src/sql/generator/ossie_wide.rs b/sidemantic-rs/src/sql/generator/ossie_wide.rs index d5868a176..da826a1cc 100644 --- a/sidemantic-rs/src/sql/generator/ossie_wide.rs +++ b/sidemantic-rs/src/sql/generator/ossie_wide.rs @@ -171,6 +171,17 @@ struct Planner<'a, 'g> { impl SqlGenerator<'_> { /// Strict JSON binding for Apache Ossie Layer 3 (wide-table semantics §3.7). pub fn generate_ossie_wide(&self, query: &Value) -> Result { + self.compile_ossie_wide(query) + .map(|sql| self.finish_ossie_wide(sql)) + } + fn finish_ossie_wide(&self, sql: String) -> String { + if self.dialect == DialectType::ClickHouse { + format!("{sql} SETTINGS join_use_nulls = 1, aggregate_functions_null_for_empty = 1, join_default_strictness = 'ALL'") + } else { + sql + } + } + fn compile_ossie_wide(&self, query: &Value) -> Result { if !self.uses_latest_ossie() { return Err(fail( "E_INVALID_QUERY", @@ -245,15 +256,18 @@ impl SqlGenerator<'_> { .join(" AND ") .into(); } - let mut sql = self.generate_ossie_wide(&request)?; + let mut sql = self.compile_ossie_wide(&request)?; if !query.order_by.is_empty() { let mut orders = vec![]; + let known_names = query + .metrics + .iter() + .chain(&query.dimensions) + .chain(query.aliases.values()) + .map(String::as_str) + .collect::>(); for order in &query.order_by { - let (name, direction) = order - .strip_suffix(" DESC") - .map(|n| (n, " DESC")) - .or_else(|| order.strip_suffix(" ASC").map(|n| (n, " ASC"))) - .unwrap_or((order.as_str(), "")); + let (name, suffix) = crate::sql::split_order_field(order, &known_names); let selected = query .metrics @@ -270,7 +284,12 @@ impl SqlGenerator<'_> { } }); let output = output_name(selected.map(String::as_str).unwrap_or(name)); - orders.push(format!("{}{direction}", self.quote_identifier(&output))); + let rendered = self.quote_identifier(&output); + orders.push(if suffix.is_empty() { + rendered + } else { + format!("{rendered} {suffix}") + }); } sql.push_str(&format!(" ORDER BY {}", orders.join(", "))); } @@ -280,7 +299,7 @@ impl SqlGenerator<'_> { if let Some(offset) = query.offset { sql.push_str(&format!(" OFFSET {offset}")); } - Ok(sql) + Ok(self.finish_ossie_wide(sql)) } } impl<'a, 'g> Planner<'a, 'g> { @@ -909,11 +928,23 @@ impl<'a, 'g> Planner<'a, 'g> { paths } fn rebind(&self, sql: &str, alias: &str) -> Result { + self.rebind_inputs(sql, alias, &HashMap::new()) + } + fn rebind_inputs( + &self, + sql: &str, + alias: &str, + fields: &HashMap, + ) -> Result { let mut replacements = HashMap::new(); for c in semantic_column_references(sql)? { replacements.insert( (c.model, c.field.clone()), - format!("{}.{}", self.q(alias), self.q(&c.field)), + format!( + "{}.{}", + self.q(alias), + self.q(fields.get(&c.field).unwrap_or(&c.field)) + ), ); } self.emit_final(replace_semantic_columns( @@ -1186,6 +1217,30 @@ impl<'a, 'g> Planner<'a, 'g> { self.q(home), row_ids[home] )); + // Carry measure inputs with their identity through the population. A + // second source scan cannot join by ROW_NUMBER: nonmaterialized CTEs + // can assign different numbers to the same physical rows. + let mut home_fields = inputs + .get(home) + .into_iter() + .flatten() + .cloned() + .collect::>(); + home_fields.sort(); + let carried = home_fields + .into_iter() + .enumerate() + .map(|(index, field)| { + let slot = format!("__ossie_input{index}"); + fields.push(format!( + "{}.{} AS {}", + self.q(home), + self.q(&field), + self.q(&slot) + )); + (field, slot) + }) + .collect::>(); ctes.push(format!( "__ossie_population{branch} AS (SELECT DISTINCT {} FROM {relation}{where_sql})", fields.join(", ") @@ -1193,7 +1248,11 @@ impl<'a, 'g> Planner<'a, 'g> { let keys = (0..dimensions.len()) .map(|i| format!("p.__ossie_d{i}")) .collect::>(); - let mut selections = keys.clone(); + let mut selections = keys + .iter() + .enumerate() + .map(|(i, key)| format!("{key} AS __ossie_d{i}")) + .collect::>(); selections.push("1 AS __ossie_present".into()); for (index, component) in self .components @@ -1203,7 +1262,7 @@ impl<'a, 'g> Planner<'a, 'g> { { selections.push(format!( "{} AS __ossie_c{index}", - self.rebind(&component.sql, "h")? + self.rebind_inputs(&component.sql, "p", &carried)? )); } let group = if keys.is_empty() { @@ -1211,7 +1270,10 @@ impl<'a, 'g> Planner<'a, 'g> { } else { format!(" GROUP BY {}", keys.join(", ")) }; - ctes.push(format!("__ossie_branch{branch} AS (SELECT {} FROM __ossie_population{branch} p JOIN {} h ON p.__ossie_row_id = h.{}{group})",selections.join(", "),source_names[home], row_ids[home])); + ctes.push(format!( + "__ossie_branch{branch} AS (SELECT {} FROM __ossie_population{branch} p{group})", + selections.join(", ") + )); branches.push(format!("__ossie_branch{branch}")); } let keys = (0..dimensions.len()) @@ -1226,10 +1288,13 @@ impl<'a, 'g> Planner<'a, 'g> { .iter() .map(|b| format!("SELECT {} FROM {b}", keys.join(", "))) .collect::>() - .join(" UNION ") + .join(" UNION DISTINCT ") )); } - let mut combined = keys.iter().map(|k| format!("k.{k}")).collect::>(); + let mut combined = keys + .iter() + .map(|key| format!("k.{key} AS {key}")) + .collect::>(); let mut relation = "__ossie_keys k".to_owned(); for (branch, home) in homes.iter().enumerate() { let condition = if keys.is_empty() { diff --git a/sidemantic-rs/src/sql/rewriter/ossie_relational.rs b/sidemantic-rs/src/sql/rewriter/ossie_relational.rs index 6711f50a3..0dfc322d7 100644 --- a/sidemantic-rs/src/sql/rewriter/ossie_relational.rs +++ b/sidemantic-rs/src/sql/rewriter/ossie_relational.rs @@ -37,6 +37,172 @@ fn declared(name: &str) -> Identifier { fn sql(expr: &Expression) -> Result { crate::semantic_input::dialects::emit(expr.clone(), DialectType::DuckDB, DialectType::DuckDB) } +/// Lower a bound window filter after window evaluation and before DISTINCT, +/// ordering and pagination. Every visible projection already has a stable slot. +fn lower_bound_qualify(mut expression: Expression) -> Result { + let mut sequence = 0; + loop { + let mut changed = false; + expression = binding::transform_nodes(expression, &mut |node| { + let Expression::Select(select) = node else { + return Ok(None); + }; + let Some(qualify) = &select.qualify else { + return Ok(None); + }; + changed = true; + sequence += 1; + let predicate_slot = format!("__ossie_qualify_predicate_{sequence}"); + let mut inner = select.as_ref().clone(); + inner.qualify = None; + let mut aliases = HashMap::new(); + let mut visible = Vec::new(); + for projection in &inner.expressions { + match projection { + Expression::Alias(alias) => { + aliases.insert(key(&alias.alias), alias.this.clone()); + visible.push(column(&alias.alias.name)); + } + Expression::Column(value) => visible.push(column(&value.name.name)), + _ => { + return Err(error( + "bound QUALIFY projection requires a stable output slot", + )) + } + } + } + let predicate = binding::transform_nodes(qualify.this.clone(), &mut |node| { + if let Expression::Column(value) = node { + if value.table.is_none() { + return Ok(aliases.get(&key(&value.name)).cloned()); + } + } + Ok(None) + })?; + inner.expressions.push(Expression::Alias(Box::new( + polyglot_sql::expressions::Alias::new( + predicate, + Identifier::quoted(&predicate_slot), + ), + ))); + let Expression::Select(mut outer) = + parse("SELECT 1 FROM (SELECT 1) AS __ossie_qualified")? + else { + unreachable!() + }; + outer.expressions = visible; + outer.distinct = inner.distinct; + inner.distinct = false; + outer.limit = inner.limit.take(); + outer.offset = inner.offset.take(); + outer.order_by = inner.order_by.take(); + if let Some(order) = &mut outer.order_by { + for (index, ordered) in order.expressions.iter_mut().enumerate() { + if matches!(&ordered.this, Expression::Literal(Literal::Number(_))) { + continue; + } + let existing = inner.expressions.iter().find_map(|projection| match projection { + Expression::Alias(alias) if alias.this == ordered.this || matches!(&ordered.this, Expression::Column(value) if value.table.is_none() && key(&value.name) == key(&alias.alias)) => Some(alias.alias.name.clone()), + _ => None, + }); + let slot = existing + .unwrap_or_else(|| format!("__ossie_qualify_order_{sequence}_{index}")); + if !inner.expressions.iter().any(|projection| matches!(projection, Expression::Alias(alias) if alias.alias.name == slot)) { + inner.expressions.push(Expression::Alias(Box::new(polyglot_sql::expressions::Alias::new(ordered.this.clone(), Identifier::quoted(&slot))))); + } + ordered.this = column(&slot); + } + } + outer.where_clause = Some(polyglot_sql::expressions::Where { + this: column(&predicate_slot), + }); + let Expression::Subquery(relation) = &mut outer.from.as_mut().unwrap().expressions[0] + else { + unreachable!() + }; + relation.this = Expression::Select(Box::new(inner)); + Ok(Some(Expression::Select(outer))) + })?; + if !changed { + return Ok(expression); + } + } +} + +fn inline_declared_windows(mut expression: Expression) -> Result { + loop { + let mut changed = false; + expression = binding::transform_nodes(expression, &mut |node| { + if let Expression::Select(select) = node { + if select + .windows + .as_ref() + .is_some_and(|windows| !windows.is_empty()) + { + changed = true; + return Ok(Some(Expression::Select(Box::new(inline_named_windows( + select.as_ref().clone(), + )?)))); + } + } + Ok(None) + })?; + if !changed { + return Ok(expression); + } + } +} + +fn emit_relational(mut expression: Expression, output: DialectType) -> Result { + if output == DialectType::PostgreSQL { + expression = lower_bound_qualify(expression)?; + } + if !matches!( + output, + DialectType::DuckDB | DialectType::PostgreSQL | DialectType::SQLite + ) { + fn clear_materialized(value: &mut Value) { + match value { + Value::Object(fields) => { + if fields.contains_key("materialized") + && fields.contains_key("alias") + && fields.contains_key("this") + { + fields.insert("materialized".into(), Value::Null); + } + for child in fields.values_mut() { + clear_materialized(child); + } + } + Value::Array(values) => values.iter_mut().for_each(clear_materialized), + _ => {} + } + } + let mut value = serde_json::to_value(expression).map_err(|err| error(err.to_string()))?; + clear_materialized(&mut value); + expression = serde_json::from_value(value).map_err(|err| error(err.to_string()))?; + } + if output == DialectType::ClickHouse { + expression = binding::transform_nodes(expression, &mut |node| { + if let Expression::NullSafeEq(comparison) = node { + return Ok(Some(expr(&format!( + "(({} = {}) OR ({} IS NULL AND {} IS NULL))", + sql(&comparison.left)?, + sql(&comparison.right)?, + sql(&comparison.left)?, + sql(&comparison.right)? + ))?)); + } + Ok(None) + })?; + } + let mut rendered = + crate::semantic_input::dialects::emit(expression, DialectType::DuckDB, output)?; + if output == DialectType::ClickHouse { + rendered.push_str(" SETTINGS join_use_nulls=1, aggregate_functions_null_for_empty=1, join_default_strictness='ALL'"); + } + Ok(rendered) +} fn parse(sql: &str) -> Result { parse_sql_with_dialect(sql, DialectType::DuckDB)? .into_iter() @@ -55,7 +221,11 @@ fn expr(sql: &str) -> Result { fn ossie_input(source: &str, dialect: DialectType) -> Result> { // A target generator may quote a keyword (rows -> "rows") even when the // author did not. Preserve identifier identity until Ossie name binding. - let mut originals = HashMap::::new(); + let ProtectedWildcards { + source, + mut originals, + qualified_stars, + } = protect_wildcard_identifiers(source, dialect)?; fn protect(value: &mut Value, originals: &mut HashMap) { match value { Value::Object(fields) => { @@ -122,7 +292,7 @@ fn ossie_input(source: &str, dialect: DialectType) -> Result> { } } let normalized = if dialect == DialectType::DuckDB { - parse_rewrite_input(source, dialect)? + parse_rewrite_input(&source, dialect)? } else { let authored = source.to_owned(); let parsed = run_parser(move || { @@ -131,21 +301,50 @@ fn ossie_input(source: &str, dialect: DialectType) -> Result> { )?]) })? .remove(0); + // Snowflake's generator omits WINDOW declarations. Resolve them in + // their authored SELECT scope before any dialect generation can lose them. + let parsed = inline_declared_windows(parsed)?; let mut value = serde_json::to_value(parsed).map_err(|err| error(err.to_string()))?; + restore(&mut value, &originals); + originals.clear(); protect(&mut value, &mut originals); let parsed = serde_json::from_value(value).map_err(|err| error(err.to_string()))?; - let protected = polyglot_sql::Dialect::get(dialect) - .generate(&parsed) - .map_err(|err| error(err.to_string()))?; + let protected = crate::semantic_input::dialects::generate_preserving_null_order( + &parsed, dialect, dialect, + )?; parse_rewrite_input(&protected, dialect)? }; + // The intermediate DuckDB emitter omits NULLS LAST as its default. + // Restore that resolved choice before later target emission (Snowflake + // otherwise interprets an absent DESC modifier as NULLS FIRST). + fn restore_intermediate_null_order(value: &mut Value) { + match value { + Value::Object(fields) => { + if fields.contains_key("this") + && fields.contains_key("desc") + && fields.get("nulls_first").is_some_and(Value::is_null) + { + fields.insert("nulls_first".into(), Value::Bool(false)); + } + for child in fields.values_mut() { + restore_intermediate_null_order(child); + } + } + Value::Array(children) => children + .iter_mut() + .for_each(restore_intermediate_null_order), + _ => {} + } + } normalized .into_iter() .map(|expression| { let mut value = serde_json::to_value(expression).map_err(|err| error(err.to_string()))?; restore(&mut value, &originals); + restore_intermediate_null_order(&mut value); let expression = serde_json::from_value(value).map_err(|err| error(err.to_string()))?; + let expression = restore_qualified_stars(expression, &qualified_stars)?; crate::semantic_input::dialects::ossie_index_offsets( expression, dialect, @@ -201,10 +400,26 @@ fn aggregate(node: &Expression) -> bool { fn has_aggregate(expression: &Expression) -> Result { let mut found = false; binding::transform_nodes(expression.clone(), &mut |node| { - if matches!( - node, - Expression::Subquery(_) | Expression::Select(_) | Expression::WindowFunction(_) - ) || is_call(node, "TO_MEASURE") + if let Expression::WindowFunction(window) = node { + let mut root = true; + binding::transform_nodes(window.this.clone(), &mut |child| { + if root { + root = false; + return Ok(None); + } + found |= has_aggregate(child)?; + Ok(Some(child.clone())) + })?; + for child in &window.over.partition_by { + found |= has_aggregate(child)?; + } + for ordered in &window.over.order_by { + found |= has_aggregate(&ordered.this)?; + } + return Ok(Some(node.clone())); + } + if matches!(node, Expression::Subquery(_) | Expression::Select(_)) + || is_call(node, "TO_MEASURE") { return Ok(Some(node.clone())); } @@ -216,6 +431,153 @@ fn has_aggregate(expression: &Expression) -> Result { })?; Ok(found) } + +fn has_window(expression: &Expression) -> Result { + let mut found = false; + binding::transform_nodes(expression.clone(), &mut |node| { + if matches!(node, Expression::Subquery(_) | Expression::Select(_)) { + return Ok(Some(node.clone())); + } + if matches!(node, Expression::WindowFunction(_)) { + found = true; + return Ok(Some(node.clone())); + } + Ok(None) + })?; + Ok(found) +} + +fn bind_window_frame( + frame: &mut Option, + transform: &mut impl FnMut(&Expression) -> Result, +) -> Result<()> { + use polyglot_sql::expressions::WindowFrameBound; + if let Some(frame) = frame { + for bound in std::iter::once(&mut frame.start).chain(frame.end.iter_mut()) { + if let WindowFrameBound::Preceding(value) + | WindowFrameBound::Following(value) + | WindowFrameBound::Value(value) = bound + { + **value = transform(value)?; + } + } + } + Ok(()) +} + +fn inline_named_windows(mut select: Select) -> Result