From d48eea2a9e3ceae703782967e15281fbda0cddf8 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:33:53 +0000 Subject: [PATCH 1/3] fix(convert): slice non-ASCII Snowflake source once per parse The Snowflake parser sliced its source by character offsets by walking the whole text from the start on every call once the text held any non-ASCII character, so parsing such a statement cost its length times the number of slices. It now builds the character-to-byte offsets once per parse, which also takes 2.6% off the strict-parsing instruction count; the baseline records the gain. Synthetic tests guard set-operator chains: their converted SQL nests no deeper and grows by the same bytes for each further branch, and chains over a multi-byte character return Snowflake's rows. --- coverage/instruction-counts.toml | 4 +- .../src/parser/_helpers/statements/entry.rs | 4 + .../src/parser/_helpers/types/data_types.rs | 24 +++- .../src/parser/models.rs | 2 + crates/sqlquack/tests/cli.rs | 2 + crates/sqlquack/tests/cli/helpers.rs | 11 ++ crates/sqlquack/tests/cli/test_set_chains.rs | 128 ++++++++++++++++++ crates/sqlquack/tests/cli/test_types.rs | 26 ++++ 8 files changed, 193 insertions(+), 8 deletions(-) create mode 100644 crates/sqlquack/tests/cli/test_set_chains.rs diff --git a/coverage/instruction-counts.toml b/coverage/instruction-counts.toml index bead8e03d..ce67def94 100644 --- a/coverage/instruction-counts.toml +++ b/coverage/instruction-counts.toml @@ -15,5 +15,5 @@ rustc = "rustc 1.99.1 (58cf8f9c3 2026-10-13)" tolerance_percent = 2 [counts] -analysis = 182168067 -parse = 252986430 +analysis = 182110245 +parse = 246355409 diff --git a/crates/sqlquack-syntax-snowflake/src/parser/_helpers/statements/entry.rs b/crates/sqlquack-syntax-snowflake/src/parser/_helpers/statements/entry.rs index 29703692b..97d67d4de 100644 --- a/crates/sqlquack-syntax-snowflake/src/parser/_helpers/statements/entry.rs +++ b/crates/sqlquack-syntax-snowflake/src/parser/_helpers/statements/entry.rs @@ -66,6 +66,7 @@ impl Parser { guards_checked: false, token_guard_stats: None, if_expr_ruled_out: HashSet::new(), + source_char_bytes: std::cell::OnceCell::new(), parsing_duckdb_json_path: false, faithful_calls: HashMap::new(), recursion: Arc::default(), @@ -87,6 +88,7 @@ impl Parser { guards_checked: false, token_guard_stats: None, if_expr_ruled_out: HashSet::new(), + source_char_bytes: std::cell::OnceCell::new(), parsing_duckdb_json_path: false, faithful_calls: HashMap::new(), recursion: Arc::default(), @@ -109,6 +111,7 @@ impl Parser { guards_checked: false, token_guard_stats: None, if_expr_ruled_out: HashSet::new(), + source_char_bytes: std::cell::OnceCell::new(), parsing_duckdb_json_path: false, faithful_calls: HashMap::new(), recursion: Arc::default(), @@ -134,6 +137,7 @@ impl Parser { guards_checked: false, token_guard_stats: Some(token_guard_stats), if_expr_ruled_out: HashSet::new(), + source_char_bytes: std::cell::OnceCell::new(), parsing_duckdb_json_path: false, faithful_calls: HashMap::new(), recursion: Arc::default(), diff --git a/crates/sqlquack-syntax-snowflake/src/parser/_helpers/types/data_types.rs b/crates/sqlquack-syntax-snowflake/src/parser/_helpers/types/data_types.rs index e6f9f2ad0..29b717ec3 100644 --- a/crates/sqlquack-syntax-snowflake/src/parser/_helpers/types/data_types.rs +++ b/crates/sqlquack-syntax-snowflake/src/parser/_helpers/types/data_types.rs @@ -1415,14 +1415,26 @@ impl Parser { return String::new(); }; - if source.is_ascii() { - source + let offsets: &Option> = self.source_char_bytes.get_or_init(|| { + (!source.is_ascii()).then(|| { + source + .char_indices() + .map(|(byte, _)| byte) + .chain([source.len()]) + .collect() + }) + }); + let Some(offsets) = offsets else { + return source .get(start..end) .map(ToString::to_string) - .unwrap_or_default() - } else { - source.chars().skip(start).take(end - start).collect() - } + .unwrap_or_default(); + }; + let byte = |offset: usize| offsets.get(offset).copied().unwrap_or(source.len()); + source + .get(byte(start)..byte(end.max(start))) + .map(ToString::to_string) + .unwrap_or_default() } /// Keeps a ClickHouse `(EXPLAIN ... SELECT ...)` subquery as command text. diff --git a/crates/sqlquack-syntax-snowflake/src/parser/models.rs b/crates/sqlquack-syntax-snowflake/src/parser/models.rs index 3ec917b6c..a5794ab5a 100644 --- a/crates/sqlquack-syntax-snowflake/src/parser/models.rs +++ b/crates/sqlquack-syntax-snowflake/src/parser/models.rs @@ -443,6 +443,8 @@ pub(crate) struct Parser { pub(crate) eof_followed_by: Option<(TokenType, Span)>, /// Positions where `IF` was rejected as an if-expression, so retries stay linear. pub(crate) if_expr_ruled_out: HashSet, + /// Each character's byte offset in a non-ASCII `source`, built once, so slicing never rewalks it. + pub(crate) source_char_bytes: std::cell::OnceCell>>, pub(crate) parsing_duckdb_json_path: bool, pub(crate) recursion: Arc, /// SQLQuack: faithful calls parsed so far, by argument start token, with the token after them. diff --git a/crates/sqlquack/tests/cli.rs b/crates/sqlquack/tests/cli.rs index 909d7ae52..640befe0c 100644 --- a/crates/sqlquack/tests/cli.rs +++ b/crates/sqlquack/tests/cli.rs @@ -38,6 +38,8 @@ mod test_review; mod test_row_limits; #[path = "cli/test_run.rs"] mod test_run; +#[path = "cli/test_set_chains.rs"] +mod test_set_chains; #[path = "cli/test_set_quantifier.rs"] mod test_set_quantifier; #[path = "cli/test_types.rs"] diff --git a/crates/sqlquack/tests/cli/helpers.rs b/crates/sqlquack/tests/cli/helpers.rs index 3db46e46a..fdf04a45f 100644 --- a/crates/sqlquack/tests/cli/helpers.rs +++ b/crates/sqlquack/tests/cli/helpers.rs @@ -1353,3 +1353,14 @@ fn project_folder(files: &[ProjectFile], folder: &str, sql: &str) -> tempfile::T std::fs::write(directory.path().join("query.sql"), sql).expect("query written"); directory } + +/// The deepest bracket nesting of `sql`, which must hold no brackets in quoted text. +pub(crate) fn bracket_depth(sql: &str) -> i64 { + sql.chars() + .scan(0_i64, |depth, character| { + *depth += i64::from(character == '(') - i64::from(character == ')'); + Some(*depth) + }) + .max() + .unwrap_or_default() +} diff --git a/crates/sqlquack/tests/cli/test_set_chains.rs b/crates/sqlquack/tests/cli/test_set_chains.rs new file mode 100644 index 000000000..70ac6fb9b --- /dev/null +++ b/crates/sqlquack/tests/cli/test_set_chains.rs @@ -0,0 +1,128 @@ +use crate::helpers::{bracket_depth, convert_streams, converted_first_value}; +use crate::test_types::{ChainGrowthTestCase, ChainValueTestCase, SetChainTestCase}; + +#[test] +fn given_a_chain_of_one_set_operator_when_converting_then_its_output_nests_no_deeper_with_more_branches() + { + let test_cases = [ + SetChainTestCase { + description: "four UNION ALL branches", + operator: " UNION ALL ", + branch: "SELECT 1 AS a", + branches: 4, + expected_depth: 4, + }, + SetChainTestCase { + description: "sixty-four UNION ALL branches nest as deep as four", + operator: " UNION ALL ", + branch: "SELECT 1 AS a", + branches: 64, + expected_depth: 4, + }, + SetChainTestCase { + description: "sixty-four UNION branches nest three deep", + operator: " UNION ", + branch: "SELECT 1 AS a", + branches: 64, + expected_depth: 3, + }, + SetChainTestCase { + description: "sixty-four EXCEPT branches nest three deep", + operator: " EXCEPT ", + branch: "SELECT 1 AS a", + branches: 64, + expected_depth: 3, + }, + ]; + for test_case in test_cases { + let sql = format!( + "WITH orders AS ({}) SELECT a FROM orders", + vec![test_case.branch; test_case.branches].join(test_case.operator) + ); + + let (converted, _) = convert_streams(&sql, &["--no-config", "--compact"]); + + assert_eq!( + bracket_depth(&converted), + test_case.expected_depth, + "{}: {converted}", + test_case.description + ); + } +} + +#[test] +fn given_longer_chains_of_one_set_operator_when_converting_then_each_branch_adds_the_same_output() { + let test_cases = [ + ChainGrowthTestCase { + description: "UNION ALL", + operator: " UNION ALL ", + branch: "SELECT 1 AS a", + expected_bytes_per_branch: 35, + }, + ChainGrowthTestCase { + description: "UNION", + operator: " UNION ", + branch: "SELECT 1 AS a", + expected_bytes_per_branch: 46, + }, + ]; + for test_case in test_cases { + let printed = |branches: usize| { + let sql = format!( + "WITH orders AS ({}) SELECT a FROM orders", + vec![test_case.branch; branches].join(test_case.operator) + ); + convert_streams(&sql, &["--no-config"]).0.len() + }; + + let (short, middle, long) = (printed(4), printed(16), printed(64)); + + // Laid-out text grows with nesting, so a chain nested a level per branch grows + // quadratically, and every pass over it with it; a flat chain grows linearly. + assert_eq!( + ((middle - short) / 12, (long - middle) / 48), + ( + test_case.expected_bytes_per_branch, + test_case.expected_bytes_per_branch + ), + "{}: {short}, {middle} and {long} bytes for 4, 16 and 64 branches", + test_case.description + ); + } +} + +#[test] +fn given_set_operator_chains_when_converting_then_duckdb_returns_snowflakes_rows() { + let test_cases = [ + ChainValueTestCase { + description: "a UNION ALL chain keeps every row", + sql: "SELECT CAST(COUNT(*) AS VARCHAR) AS n FROM (SELECT 1 AS a UNION ALL SELECT 1 \ + UNION ALL SELECT 1 UNION ALL SELECT 2)", + expected_value: "4", + }, + ChainValueTestCase { + description: "a UNION between UNION ALLs still removes the duplicates before it only", + sql: "SELECT CAST(COUNT(*) AS VARCHAR) AS n FROM (SELECT 1 AS a UNION ALL SELECT 1 \ + UNION SELECT 1 UNION ALL SELECT 1)", + expected_value: "2", + }, + ChainValueTestCase { + description: "an EXCEPT chain removes left to right", + sql: "SELECT CAST(COUNT(*) AS VARCHAR) AS n FROM (SELECT 1 AS a UNION ALL SELECT 2 \ + UNION ALL SELECT 3 EXCEPT SELECT 2 EXCEPT SELECT 3)", + expected_value: "1", + }, + ChainValueTestCase { + description: "text around a multi-byte character keeps its aliases in a chain", + sql: "SELECT MIN(a || b) AS n FROM (SELECT 'caf\u{e9}' AS a, 'x' as b UNION ALL \ + SELECT 'na\u{ef}ve' AS a, 'y' as b)", + expected_value: "caf\u{e9}x", + }, + ]; + for test_case in test_cases { + let value = converted_first_value(test_case.sql); + + assert_eq!(value, test_case.expected_value, "{}", test_case.description); + } +} diff --git a/crates/sqlquack/tests/cli/test_types.rs b/crates/sqlquack/tests/cli/test_types.rs index b8ff54fec..4fdd28e5a 100644 --- a/crates/sqlquack/tests/cli/test_types.rs +++ b/crates/sqlquack/tests/cli/test_types.rs @@ -414,3 +414,29 @@ pub(crate) struct SetQuantifierTestCase { pub(crate) expected_same_as: &'static str, pub(crate) expected_unlike: &'static str, } + +/// A chain of `branches` copies of `branch` joined by one set operator, and how deep its output nests. +pub(crate) struct SetChainTestCase { + pub(crate) description: &'static str, + pub(crate) operator: &'static str, + pub(crate) branch: &'static str, + pub(crate) branches: usize, + /// The deepest bracket nesting of the compact converted SQL, which must not grow with `branches`. + pub(crate) expected_depth: i64, +} + +/// A statement whose converted SQL returns one text value on DuckDB. +pub(crate) struct ChainValueTestCase { + pub(crate) description: &'static str, + pub(crate) sql: &'static str, + pub(crate) expected_value: &'static str, +} + +/// A set operator whose chains of `branch` must cost the same output for every branch added. +pub(crate) struct ChainGrowthTestCase { + pub(crate) description: &'static str, + pub(crate) operator: &'static str, + pub(crate) branch: &'static str, + /// The bytes of laid-out SQL each further branch adds, the same from 4 to 16 as from 16 to 64. + pub(crate) expected_bytes_per_branch: usize, +} From 3e732762494c7273a27b145f693bb0af76b72132 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:46:34 +0000 Subject: [PATCH 2/3] feat(convert): let callers skip DuckDB's bind check of the converted SQL `sqlquack convert --no-bind-check` and `ConvertOptions(bind_check=False)` skip DuckDB's parse and bind of the emitted statement and of SQL function bodies, for callers that run the converted SQL and handle DuckDB's errors. The bind only catches converted SQL DuckDB cannot bind, a SQLQuack bug, and is often the larger part of the conversion time. The lexical checks (one statement, no lambda parameter read with a dot) still run, every other refusal is unchanged, and the default keeps the check. --- .../src/checking/main/check_printed.rs | 25 +------- .../src/checking/main/check_unbound.rs | 28 +++++++++ .../sqlquack-blocks/src/checking/main/mod.rs | 1 + crates/sqlquack-blocks/src/checking/tests.rs | 2 + .../src/checking/tests/test_check_unbound.rs | 42 ++++++++++++++ .../_helpers/queries/function_body.rs | 14 ++++- .../conversion/main/_convert_function_body.rs | 2 +- .../conversion/main/convert_statement.rs | 7 ++- .../src/snowflake/conversion/models.rs | 2 + .../src/bindings/_helpers/convert_json.rs | 1 + crates/sqlquack-python/src/bindings/models.rs | 2 + crates/sqlquack/src/analysis/tests/helpers.rs | 1 + .../src/cli/_helpers/convert_command.rs | 6 +- crates/sqlquack/src/cli/models.rs | 3 + crates/sqlquack/tests/cli.rs | 2 + crates/sqlquack/tests/cli/test_bind_check.rs | 39 +++++++++++++ crates/sqlquack/tests/cli/test_types.rs | 8 +++ python/src/sqlquack/api/main/convert.py | 1 + python/src/sqlquack/api/models.py | 1 + .../src/sqlquack/api/main/_test_types.py | 7 +++ .../src/sqlquack/api/main/test_convert.py | 57 +++++++++++++++++++ website/src/content/docs/docs/cli/convert.mdx | 1 + website/src/content/docs/docs/python.mdx | 7 ++- 23 files changed, 229 insertions(+), 30 deletions(-) create mode 100644 crates/sqlquack-blocks/src/checking/main/check_unbound.rs create mode 100644 crates/sqlquack-blocks/src/checking/tests/test_check_unbound.rs create mode 100644 crates/sqlquack/tests/cli/test_bind_check.rs diff --git a/crates/sqlquack-blocks/src/checking/main/check_printed.rs b/crates/sqlquack-blocks/src/checking/main/check_printed.rs index fada83cc5..ce4ea62b2 100644 --- a/crates/sqlquack-blocks/src/checking/main/check_printed.rs +++ b/crates/sqlquack-blocks/src/checking/main/check_printed.rs @@ -1,9 +1,8 @@ //! `check_printed`: DuckDB parses printed SQL as one statement and binds it. use crate::checking::_helpers::binding::bound; -use crate::checking::_helpers::dotted_parameters::dotted_parameters; -use crate::checking::_helpers::lexing::lexed; -use crate::checking::errors::{CheckStage, PrintedSqlFailure}; +use crate::checking::errors::PrintedSqlFailure; +use crate::checking::main::check_unbound::check_unbound; use crate::checking::types::{FunctionLookup, RelationLookup}; /// Succeeds when DuckDB parses `sql` as one statement and binds it over the relations and functions. @@ -11,24 +10,6 @@ pub fn check_printed( sql: &str, (lookup, functions): (RelationLookup<'_>, FunctionLookup<'_>), ) -> Result<(), PrintedSqlFailure> { - let dotted = dotted_parameters(sql); - if !dotted.is_empty() { - return Err(failure( - CheckStage::CapturedParameter, - format!("{} read with a dot", dotted.join(", ")), - )); - } - let lexed = lexed(sql); - if lexed.statements != 1 { - return Err(failure( - CheckStage::StatementCount, - format!("{} statements", lexed.statements), - )); - } - let names: Vec = lexed.names.into_iter().collect(); + let names: Vec = check_unbound(sql)?; bound(sql, &names, (lookup, functions)) } - -fn failure(stage: CheckStage, message: String) -> PrintedSqlFailure { - PrintedSqlFailure { stage, message } -} diff --git a/crates/sqlquack-blocks/src/checking/main/check_unbound.rs b/crates/sqlquack-blocks/src/checking/main/check_unbound.rs new file mode 100644 index 000000000..9b7b9d3a3 --- /dev/null +++ b/crates/sqlquack-blocks/src/checking/main/check_unbound.rs @@ -0,0 +1,28 @@ +//! `check_unbound`: printed SQL is one statement with no lambda parameter read with a dot. + +use crate::checking::_helpers::dotted_parameters::dotted_parameters; +use crate::checking::_helpers::lexing::lexed; +use crate::checking::errors::{CheckStage, PrintedSqlFailure}; + +/// The names `sql` reads, when it is one statement reading no lambda parameter with a dot. +pub fn check_unbound(sql: &str) -> Result, PrintedSqlFailure> { + let dotted = dotted_parameters(sql); + if !dotted.is_empty() { + return Err(failure( + CheckStage::CapturedParameter, + format!("{} read with a dot", dotted.join(", ")), + )); + } + let lexed = lexed(sql); + if lexed.statements != 1 { + return Err(failure( + CheckStage::StatementCount, + format!("{} statements", lexed.statements), + )); + } + Ok(lexed.names.into_iter().collect()) +} + +fn failure(stage: CheckStage, message: String) -> PrintedSqlFailure { + PrintedSqlFailure { stage, message } +} diff --git a/crates/sqlquack-blocks/src/checking/main/mod.rs b/crates/sqlquack-blocks/src/checking/main/mod.rs index 5502bcb0c..52a0a06bd 100644 --- a/crates/sqlquack-blocks/src/checking/main/mod.rs +++ b/crates/sqlquack-blocks/src/checking/main/mod.rs @@ -2,5 +2,6 @@ pub mod bound_outside_lambdas; pub mod check_printed; +pub mod check_unbound; pub mod create_table; pub mod quoted_relation; diff --git a/crates/sqlquack-blocks/src/checking/tests.rs b/crates/sqlquack-blocks/src/checking/tests.rs index 4e9b80cb6..31e2659b2 100644 --- a/crates/sqlquack-blocks/src/checking/tests.rs +++ b/crates/sqlquack-blocks/src/checking/tests.rs @@ -4,5 +4,7 @@ mod helpers; mod test_bound_outside_lambdas; #[path = "tests/test_check_printed.rs"] mod test_check_printed; +#[path = "tests/test_check_unbound.rs"] +mod test_check_unbound; #[path = "tests/test_types.rs"] mod test_types; diff --git a/crates/sqlquack-blocks/src/checking/tests/test_check_unbound.rs b/crates/sqlquack-blocks/src/checking/tests/test_check_unbound.rs new file mode 100644 index 000000000..a83030dd8 --- /dev/null +++ b/crates/sqlquack-blocks/src/checking/tests/test_check_unbound.rs @@ -0,0 +1,42 @@ +use crate::checking::errors::CheckStage; +use crate::checking::main::check_unbound::check_unbound; +use crate::checking::tests::test_types::CheckTestCase; + +#[test] +fn given_printed_sql_when_checked_without_binding_then_only_its_lexical_failures_refuse() { + let test_cases = [ + CheckTestCase { + description: "an unknown column is left to the caller that runs the SQL", + sql: "SELECT \"MISSING\" FROM \"ORDERS\"".to_owned(), + expected_stage: None, + }, + CheckTestCase { + description: "an unknown relation is left to the caller that runs the SQL", + sql: "SELECT 1 FROM \"CUSTOMERS\"".to_owned(), + expected_stage: None, + }, + CheckTestCase { + description: "a type error is left to the caller that runs the SQL", + sql: "SELECT date_trunc('day', \"ID\") FROM \"ORDERS\"".to_owned(), + expected_stage: None, + }, + CheckTestCase { + description: "a lambda parameter read with a dot is still refused", + sql: "SELECT list_transform([struct_pack(l := 1)], lambda p: p.l) FROM \"ORDERS\" AS p" + .to_owned(), + expected_stage: Some(CheckStage::CapturedParameter), + }, + CheckTestCase { + description: "two statements are still refused", + sql: "SELECT 1; SELECT 2".to_owned(), + expected_stage: Some(CheckStage::StatementCount), + }, + ]; + for test_case in test_cases { + let stage = check_unbound(&test_case.sql) + .err() + .map(|failure| failure.stage); + + assert_eq!(stage, test_case.expected_stage, "{}", test_case.description); + } +} diff --git a/crates/sqlquack-convert/src/snowflake/conversion/_helpers/queries/function_body.rs b/crates/sqlquack-convert/src/snowflake/conversion/_helpers/queries/function_body.rs index 5845701b8..4aef144a0 100644 --- a/crates/sqlquack-convert/src/snowflake/conversion/_helpers/queries/function_body.rs +++ b/crates/sqlquack-convert/src/snowflake/conversion/_helpers/queries/function_body.rs @@ -3,6 +3,7 @@ use crate::snowflake::conversion::_helpers::support::typed_leaves::checked; use sqlquack_blocks::blocks::main::quoted_identifier::quoted_identifier; use sqlquack_blocks::checking::main::check_printed::check_printed; +use sqlquack_blocks::checking::main::check_unbound::check_unbound; use sqlquack_blocks::checking::models::{FunctionStub, StubReturns}; use sqlquack_diagnostics::provenance::models::ProvenanceLog; use sqlquack_diagnostics::refusals::main::missing::missing; @@ -92,8 +93,11 @@ pub(crate) fn parameters_joined( ) } -/// DuckDB parses and binds the body over NULL parameters and the schema's relations. -pub(crate) fn check_body(checked: &str, schema: &Schema) -> Result<(), Refusal> { +/// DuckDB parses and binds the body over NULL parameters and the schema's relations, unless `skip_bind`. +pub(crate) fn check_body( + checked: &str, + (schema, skip_bind): (&Schema, bool), +) -> Result<(), Refusal> { let relation = |name: &str| -> Option> { Some( schema @@ -104,7 +108,11 @@ pub(crate) fn check_body(checked: &str, schema: &Schema) -> Result<(), Refusal> .collect(), ) }; - check_printed(checked, (&relation, &|name| function_stub(schema, name))).map_err(|failure| { + match skip_bind { + true => check_unbound(checked).map(drop), + false => check_printed(checked, (&relation, &|name| function_stub(schema, name))), + } + .map_err(|failure| { missing( node_construct("function_body"), format!("the emitted DuckDB SQL fails DuckDB's check: {failure}"), diff --git a/crates/sqlquack-convert/src/snowflake/conversion/main/_convert_function_body.rs b/crates/sqlquack-convert/src/snowflake/conversion/main/_convert_function_body.rs index c7c7095c2..5c194541b 100644 --- a/crates/sqlquack-convert/src/snowflake/conversion/main/_convert_function_body.rs +++ b/crates/sqlquack-convert/src/snowflake/conversion/main/_convert_function_body.rs @@ -62,7 +62,7 @@ pub(in crate::snowflake) fn convert_function_body( "SELECT {selected} FROM {}", joined(&vec!["NULL".to_owned(); held.len()]) ), - schema, + (schema, options.skip_bind_check), )?; let body = match &spec.returns { FunctionReturns::Scalar(_) => format!("(SELECT {selected} FROM {})", joined(&names)), diff --git a/crates/sqlquack-convert/src/snowflake/conversion/main/convert_statement.rs b/crates/sqlquack-convert/src/snowflake/conversion/main/convert_statement.rs index d42ed4338..c0af45cdc 100644 --- a/crates/sqlquack-convert/src/snowflake/conversion/main/convert_statement.rs +++ b/crates/sqlquack-convert/src/snowflake/conversion/main/convert_statement.rs @@ -3,6 +3,7 @@ use crate::snowflake::conversion::_helpers::support::typed_leaves::checked; use sqlquack_blocks::blocks::main::quoted_identifier::quoted_identifier; use sqlquack_blocks::checking::main::check_printed::check_printed; +use sqlquack_blocks::checking::main::check_unbound::check_unbound; use sqlquack_blocks::held::main::variant_written::variant_written; use sqlquack_blocks::semi_structured::main::json_output::json_output; use sqlquack_diagnostics::provenance::models::ProvenanceLog; @@ -66,7 +67,11 @@ pub fn convert_statement( }; let function = |name: &str| function_stub(schema, name).or_else(|| override_stub(options, name)); - check_printed(&sql, (&relation, &function)).map_err(|failure| { + match options.skip_bind_check { + true => check_unbound(&sql).map(drop), + false => check_printed(&sql, (&relation, &function)), + } + .map_err(|failure| { let refusal = missing( node_construct("statement"), format!("the emitted DuckDB SQL fails DuckDB's check: {failure}"), diff --git a/crates/sqlquack-convert/src/snowflake/conversion/models.rs b/crates/sqlquack-convert/src/snowflake/conversion/models.rs index 85741552b..21760a114 100644 --- a/crates/sqlquack-convert/src/snowflake/conversion/models.rs +++ b/crates/sqlquack-convert/src/snowflake/conversion/models.rs @@ -48,6 +48,8 @@ pub struct ConversionOptions { pub verified_overrides: BTreeMap, /// Function calls nested deeper than this are a parse error; the parser's default when absent. pub max_call_depth: Option, + /// Skip DuckDB's parse-and-bind of the emitted SQL, for a caller that runs it and reports errors. + pub skip_bind_check: bool, } /// A user's DuckDB SQL standing in for a Snowflake function, written in SQLBuild's FUNCTION() format. diff --git a/crates/sqlquack-python/src/bindings/_helpers/convert_json.rs b/crates/sqlquack-python/src/bindings/_helpers/convert_json.rs index 7853ea325..f0591c3df 100644 --- a/crates/sqlquack-python/src/bindings/_helpers/convert_json.rs +++ b/crates/sqlquack-python/src/bindings/_helpers/convert_json.rs @@ -39,6 +39,7 @@ pub(crate) fn convert_json(sql: &str, request: &str, path: &str) -> PyResult, /// `--compact`. pub compact: bool, + /// `--no-bind-check`. + pub no_bind_check: bool, /// `--max-call-depth`; the default when absent. pub max_call_depth: Option, } diff --git a/crates/sqlquack/src/analysis/tests/helpers.rs b/crates/sqlquack/src/analysis/tests/helpers.rs index 8a6a55c66..cd26ecb81 100644 --- a/crates/sqlquack/src/analysis/tests/helpers.rs +++ b/crates/sqlquack/src/analysis/tests/helpers.rs @@ -1002,6 +1002,7 @@ fn everyday_arguments(root: &std::path::Path, no_config: bool) -> ConvertArgumen verified_overrides: Vec::new(), session: Vec::new(), compact: true, + no_bind_check: false, verbose: false, output: OutputArguments { format: OutputFormat::Json, diff --git a/crates/sqlquack/src/cli/_helpers/convert_command.rs b/crates/sqlquack/src/cli/_helpers/convert_command.rs index 3556e6a49..a13e4485d 100644 --- a/crates/sqlquack/src/cli/_helpers/convert_command.rs +++ b/crates/sqlquack/src/cli/_helpers/convert_command.rs @@ -152,6 +152,7 @@ fn run_printed(arguments: &RunArguments, palette: &Palette) -> RunPrinted { verified_overrides: arguments.verified_overrides.clone(), session: arguments.session.clone(), compact: true, + no_bind_check: false, verbose: false, output: OutputArguments { format: OutputFormat::Text, @@ -569,7 +570,10 @@ pub(crate) fn chosen_options( options: ConversionOptions, ) -> Result { with_overrides( - options, + ConversionOptions { + skip_bind_check: arguments.no_bind_check, + ..options + }, ( arguments.overrides.as_deref(), &arguments.verified_overrides, diff --git a/crates/sqlquack/src/cli/models.rs b/crates/sqlquack/src/cli/models.rs index 02e8750d3..a35ce0e34 100644 --- a/crates/sqlquack/src/cli/models.rs +++ b/crates/sqlquack/src/cli/models.rs @@ -127,6 +127,9 @@ pub struct ConvertArguments { /// Print each converted statement on one line instead of one clause per line, in `--json` too. #[arg(long)] pub compact: bool, + /// Skip DuckDB's parse and bind of the converted SQL, for callers that run it and handle its errors. + #[arg(long)] + pub no_bind_check: bool, /// Print a warning for each use of a known difference: where it is and what allows it. #[arg(long)] pub verbose: bool, diff --git a/crates/sqlquack/tests/cli.rs b/crates/sqlquack/tests/cli.rs index 640befe0c..5a164eda1 100644 --- a/crates/sqlquack/tests/cli.rs +++ b/crates/sqlquack/tests/cli.rs @@ -1,5 +1,7 @@ #[path = "cli/helpers.rs"] mod helpers; +#[path = "cli/test_bind_check.rs"] +mod test_bind_check; #[path = "cli/test_builtin_policy.rs"] mod test_builtin_policy; #[path = "cli/test_bundled.rs"] diff --git a/crates/sqlquack/tests/cli/test_bind_check.rs b/crates/sqlquack/tests/cli/test_bind_check.rs new file mode 100644 index 000000000..1ab535714 --- /dev/null +++ b/crates/sqlquack/tests/cli/test_bind_check.rs @@ -0,0 +1,39 @@ +use crate::helpers::convert_streams; +use crate::test_types::BindCheckTestCase; + +#[test] +fn given_the_bind_check_off_when_converting_then_the_output_is_the_same() { + let test_cases = [ + BindCheckTestCase { + description: "a converted query", + sql: "WITH orders AS (SELECT 1 AS a UNION ALL SELECT 2) SELECT a + 1 AS b FROM orders", + expected_converted: true, + }, + BindCheckTestCase { + description: "a query refused for an undeclared relation", + sql: "SELECT a FROM customers", + expected_converted: false, + }, + BindCheckTestCase { + description: "a query refused for a function SQLQuack cannot convert", + sql: "SELECT DATE_PART('epoch_second', 'x') AS a", + expected_converted: false, + }, + ]; + for test_case in test_cases { + let checked = convert_streams(test_case.sql, &["--no-config", "--compact"]); + + let unchecked = convert_streams( + test_case.sql, + &["--no-config", "--compact", "--no-bind-check"], + ); + + assert_eq!(unchecked, checked, "{}", test_case.description); + assert_eq!( + !checked.0.trim().is_empty(), + test_case.expected_converted, + "{}: {checked:?}", + test_case.description + ); + } +} diff --git a/crates/sqlquack/tests/cli/test_types.rs b/crates/sqlquack/tests/cli/test_types.rs index 4fdd28e5a..84a18ba41 100644 --- a/crates/sqlquack/tests/cli/test_types.rs +++ b/crates/sqlquack/tests/cli/test_types.rs @@ -440,3 +440,11 @@ pub(crate) struct ChainGrowthTestCase { /// The bytes of laid-out SQL each further branch adds, the same from 4 to 16 as from 16 to 64. pub(crate) expected_bytes_per_branch: usize, } + +/// A statement whose conversion must not depend on DuckDB's bind check. +pub(crate) struct BindCheckTestCase { + pub(crate) description: &'static str, + pub(crate) sql: &'static str, + /// Whether it converts, printing SQL on standard output. + pub(crate) expected_converted: bool, +} diff --git a/python/src/sqlquack/api/main/convert.py b/python/src/sqlquack/api/main/convert.py index be7c39979..c3afa3a06 100644 --- a/python/src/sqlquack/api/main/convert.py +++ b/python/src/sqlquack/api/main/convert.py @@ -28,6 +28,7 @@ def convert( "verified_overrides": dict(chosen.verified_overrides), "compact": chosen.compact, "max_call_depth": chosen.max_call_depth, + "no_bind_check": not chosen.bind_check, } result: dict[str, Any] = loaded(lambda: convert_json(sql, json.dumps(request), path)) report: dict[str, Any] = result["report"] diff --git a/python/src/sqlquack/api/models.py b/python/src/sqlquack/api/models.py index d27afe15a..189988e74 100644 --- a/python/src/sqlquack/api/models.py +++ b/python/src/sqlquack/api/models.py @@ -76,3 +76,4 @@ class ConvertOptions: verified_overrides: Mapping[str, str] = field(default_factory=dict) compact: bool = False max_call_depth: int | None = None + bind_check: bool = True diff --git a/tests/unit/python/src/sqlquack/api/main/_test_types.py b/tests/unit/python/src/sqlquack/api/main/_test_types.py index 11a3d2958..4b5048542 100644 --- a/tests/unit/python/src/sqlquack/api/main/_test_types.py +++ b/tests/unit/python/src/sqlquack/api/main/_test_types.py @@ -82,3 +82,10 @@ class ProjectTestCase: session: dict[str, str] arguments: tuple[str, ...] expected_notes: int + + +@dataclass(frozen=True) +class BindCheckTestCase: + description: str + sql: str + expected_converted: bool diff --git a/tests/unit/python/src/sqlquack/api/main/test_convert.py b/tests/unit/python/src/sqlquack/api/main/test_convert.py index 704e0eae6..9141055ef 100644 --- a/tests/unit/python/src/sqlquack/api/main/test_convert.py +++ b/tests/unit/python/src/sqlquack/api/main/test_convert.py @@ -9,6 +9,7 @@ import sqlquack from sqlquack import Conversion, ConvertOptions, Diagnostic from tests.unit.python.src.sqlquack.api.main._test_types import ( + BindCheckTestCase, CommandLineTestCase, DeepChainTestCase, FailureTestCase, @@ -43,6 +44,20 @@ options=ConvertOptions(no_config=True, schema=SCHEMA, compact=True), expected_converted=True, ), + CommandLineTestCase( + description="a converted query without DuckDB's bind check", + sql="SELECT order_id, price * 2 AS doubled FROM orders", + arguments=("--no-config", "--no-bind-check"), + options=ConvertOptions(no_config=True, schema=SCHEMA, bind_check=False), + expected_converted=True, + ), + CommandLineTestCase( + description="a refused query without DuckDB's bind check", + sql="SELECT a FROM customers", + arguments=("--no-config", "--no-bind-check"), + options=ConvertOptions(no_config=True, schema=SCHEMA, bind_check=False), + expected_converted=False, + ), CommandLineTestCase( description="no --config and no sqlquack.toml: the defaults", sql="SELECT order_id, price * 2 AS doubled FROM orders", @@ -102,6 +117,48 @@ def test_given_the_same_options_when_converting_then_the_report_is_the_command_l assert conversion.divergence_failures == conversion.report["divergence_failures"] +@pytest.mark.parametrize( + "test_case", + ( + BindCheckTestCase( + description="a converted query", + sql="SELECT order_id, price * 2 AS doubled FROM orders", + expected_converted=True, + ), + BindCheckTestCase( + description="a query refused for an undeclared relation", + sql="SELECT a FROM customers", + expected_converted=False, + ), + BindCheckTestCase( + description="HASH refused by the configuration", + sql=HASHED, + expected_converted=False, + ), + BindCheckTestCase( + description="CURRENT_DATE converted with the differences it relies on", + sql=DATED, + expected_converted=True, + ), + ), + ids=lambda case: case.description, +) +def test_given_the_bind_check_off_when_converting_then_the_report_is_the_same( + test_case: BindCheckTestCase, +) -> None: + checked: Conversion = sqlquack.convert( + sql=test_case.sql, options=ConvertOptions(config=CONFIG, schema=SCHEMA) + ) + + unchecked: Conversion = sqlquack.convert( + sql=test_case.sql, + options=ConvertOptions(config=CONFIG, schema=SCHEMA, bind_check=False), + ) + + assert unchecked.report == checked.report + assert unchecked.converted is test_case.expected_converted + + @pytest.mark.parametrize( "test_case", ( diff --git a/website/src/content/docs/docs/cli/convert.mdx b/website/src/content/docs/docs/cli/convert.mdx index c9a397033..2a0730269 100644 --- a/website/src/content/docs/docs/cli/convert.mdx +++ b/website/src/content/docs/docs/cli/convert.mdx @@ -64,6 +64,7 @@ SQL that does not parse, or that Snowflake rejects, is refused with the same cod | `--overrides ` | [Replacements](/docs/policy/#replace): a `FUNCTION()` file, or a directory of them, each with `replaces` and `dialect duckdb`. Replaces the project's `overrides/` folder. | | `--verified-override NAME=SHA256` | An override verified for the body with that hash, as `convert --json` reports. | | `--compact` | Print each statement on one line instead, in the JSON report too. | +| `--no-bind-check` | Skip DuckDB's parse and bind of the converted SQL, often the larger part of the conversion time, for callers that run the SQL and handle DuckDB's errors. The check only catches SQLQuack bugs, converted SQL that DuckDB cannot bind; without it, such SQL is reported as converted and fails when run. The other checks and refusals are unchanged. | | `--max-call-depth ` | Refuse function calls nested more than `n` deep, as for [`check`](/docs/cli/check/#options). Default `256`, at most `512`. `run`, `function` and `census` take it too. | | `--format text\|json`, `--json` | Print the report as text or JSON. | | `--color auto\|always\|never` | Highlight the SQL and colour diagnostics, as for [`check`](/docs/cli/check/#options). JSON is never coloured. | diff --git a/website/src/content/docs/docs/python.mdx b/website/src/content/docs/docs/python.mdx index a190b7c9d..6de02a186 100644 --- a/website/src/content/docs/docs/python.mdx +++ b/website/src/content/docs/docs/python.mdx @@ -77,10 +77,13 @@ default and at most `512`. It returns a `CheckResult`: `ConvertOptions` has one field per [`convert`](/docs/cli/convert/) flag, with the same defaults: `project`, `config`, `no_config`, `session`, `strict`, `python_runtime`, `overrides`, -`verified_overrides`, `compact` and `max_call_depth`. `project`, `config` and `overrides` take a path (`str` or -`os.PathLike`), not the parsed contents. `session` and `verified_overrides` take a mapping, such as +`verified_overrides`, `compact`, `max_call_depth` and `bind_check`. `project`, `config` and +`overrides` take a path (`str` or `os.PathLike`), not the parsed contents. `session` and `verified_overrides` take a mapping, such as `session={"TIMEZONE": "UTC"}`, not a list of `NAME=VALUE` strings. +`bind_check=False` is `--no-bind-check`: conversion skips DuckDB's parse and bind of its output, +for callers that run the SQL themselves and handle DuckDB's errors. It defaults to `True`. + `schema` declares tables in memory, beside the project's, as a mapping of table names to `[column, Snowflake type]` pairs: From d3b3bc4d6449cb1444019685674c66f7cdbd254a Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 25 Nov 2026 05:48:05 +0000 Subject: [PATCH 3/3] fix(convert): bind a simple CASE's computed operand once in DuckDB A simple CASE over a computed operand binds the operand once in a lambda that returns the first equal WHEN's position, then chose the result with a simple CASE over that position. DuckDB repeats a simple CASE's operand in every WHEN, so the whole lambda, and everything in the operand, was bound once per WHEN: binding grew with the WHENs times the operand's size. When every result and the ELSE are a column or a literal, they are now packed beside the operand and chosen inside the lambda, so DuckDB parses the operand once. Each result is still cast only where it is chosen. Other CASEs keep the position form. --- .../_helpers/expressions/conditionals.rs | 104 ++++++++++++++---- crates/sqlquack/tests/cli.rs | 2 + crates/sqlquack/tests/cli/helpers.rs | 11 ++ .../sqlquack/tests/cli/test_case_subject.rs | 91 +++++++++++++++ crates/sqlquack/tests/cli/test_types.rs | 10 ++ 5 files changed, 198 insertions(+), 20 deletions(-) create mode 100644 crates/sqlquack/tests/cli/test_case_subject.rs diff --git a/crates/sqlquack-convert/src/snowflake/conversion/_helpers/expressions/conditionals.rs b/crates/sqlquack-convert/src/snowflake/conversion/_helpers/expressions/conditionals.rs index 12a557aca..8f489e869 100644 --- a/crates/sqlquack-convert/src/snowflake/conversion/_helpers/expressions/conditionals.rs +++ b/crates/sqlquack-convert/src/snowflake/conversion/_helpers/expressions/conditionals.rs @@ -280,11 +280,27 @@ pub(crate) fn case_expression(payload: &Value, site: Site<'_>) -> Result> = None; let (subject, conditions, mut branches) = match operand_node { Some(node) if !plain(node) && whens.iter().all(|when| when.get(0).is_some_and(plain)) => { - let (subject, results) = bound_whens(node, whens, site)?; - let positions = (1..=results.len()).map(|position| position.to_string()); - (format!(" {subject}"), positions.collect(), results) + let carry = whens.iter().all(|when| when.get(1).is_some_and(plain)) + && otherwise_node.is_none_or(plain); + let bound = bound_whens(node, whens, carry, site)?; + match carry { + true => { + carried = Some(bound.packed); + (String::new(), bound.tests, bound.results) + } + false => { + let positions = (1..=bound.results.len()).map(|position| position.to_string()); + ( + format!(" {}", bound.subject()), + positions.collect(), + bound.results, + ) + } + } } Some(node) => { let operand = convert_expression(node, site)?; @@ -296,8 +312,12 @@ pub(crate) fn case_expression(payload: &Value, site: Site<'_>) -> Result Some(convert_expression(otherwise, site)?), + let otherwise = match otherwise_node { + Some(otherwise) => Some(carried_branch( + convert_expression(otherwise, site)?, + "e", + carried.as_mut(), + )), None => None, }; branches.extend(otherwise.iter().cloned()); @@ -310,6 +330,9 @@ pub(crate) fn case_expression(payload: &Value, site: Site<'_>) -> Result bool { } } -/// A simple CASE's operand bound once beside its WHEN values: the first equal WHEN's position. +/// A simple CASE's operand packed once, as DuckDB repeats a simple CASE's operand in every WHEN. +struct BoundWhens { + /// The `struct_pack` fields: the operand, the WHEN values and any carried results. + packed: Vec, + /// Each WHEN's test of the packed operand against its packed value. + tests: Vec, + /// The results, read from the pack when carried. + results: Vec, +} + +impl BoundWhens { + /// The first equal WHEN's position, for a CASE over the positions choosing uncarried results. + fn subject(&self) -> String { + let tests: Vec = self + .tests + .iter() + .enumerate() + .map(|(position, test)| format!(" WHEN {test} THEN {}", position + 1)) + .collect(); + bound_subject(&self.packed, &format!("CASE{} END", tests.concat())) + } +} + +/// `body` over the packed fields, read through the lambda parameter once per row. +fn bound_subject(packed: &[String], body: &str) -> String { + format!( + "list_transform([struct_pack({})], lambda {CASE_SUBJECT}: {body})[1]", + packed.join(", ") + ) +} + +/// `branch` read from the pack as `field` when the results are carried in it. +fn carried_branch(branch: Emitted, field: &str, packed: Option<&mut Vec>) -> Emitted { + let Some(packed) = packed else { + return branch; + }; + packed.push(format!("{field} := {}", branch.sql)); + Emitted { + sql: format!("{CASE_SUBJECT}['{field}']"), + ..branch + } +} + +/// A simple CASE's operand packed once with its WHEN values and, when `carry`, its plain results. fn bound_whens( operand: &Value, whens: &[Value], + carry: bool, site: Site<'_>, -) -> Result<(String, Vec), Refusal> { +) -> Result { let construct = node_construct("case"); let operand = convert_expression(operand, site)?; let mut packed = vec![format!("o := {}", operand.sql)]; @@ -367,25 +434,22 @@ fn bound_whens( ..value }; let (left, right) = comparable(subject.clone(), value, &construct, site.context)?; - tests.push(format!( - " WHEN {} = {} THEN {}", - left.sql, - right.sql, - position + 1 + tests.push(format!("{} = {}", left.sql, right.sql)); + let result = convert_expression(result, site)?; + results.push(carried_branch( + result, + &format!("r{position}"), + carry.then_some(&mut packed), )); - results.push(convert_expression(result, site)?); } if tests.is_empty() { return Err(missing(construct, "CASE without WHEN".to_owned())); } - Ok(( - format!( - "list_transform([struct_pack({})], lambda {CASE_SUBJECT}: CASE{} END)[1]", - packed.join(", "), - tests.concat() - ), + Ok(BoundWhens { + packed, + tests, results, - )) + }) } fn case_whens( diff --git a/crates/sqlquack/tests/cli.rs b/crates/sqlquack/tests/cli.rs index 5a164eda1..79b8f163f 100644 --- a/crates/sqlquack/tests/cli.rs +++ b/crates/sqlquack/tests/cli.rs @@ -6,6 +6,8 @@ mod test_bind_check; mod test_builtin_policy; #[path = "cli/test_bundled.rs"] mod test_bundled; +#[path = "cli/test_case_subject.rs"] +mod test_case_subject; #[path = "cli/test_check.rs"] mod test_check; #[path = "cli/test_compare.rs"] diff --git a/crates/sqlquack/tests/cli/helpers.rs b/crates/sqlquack/tests/cli/helpers.rs index fdf04a45f..dcb7e3e87 100644 --- a/crates/sqlquack/tests/cli/helpers.rs +++ b/crates/sqlquack/tests/cli/helpers.rs @@ -1364,3 +1364,14 @@ pub(crate) fn bracket_depth(sql: &str) -> i64 { .max() .unwrap_or_default() } + +/// How many times `marker` appears in DuckDB's parse of the converted `sql`, what DuckDB binds. +pub(crate) fn parsed_copies(sql: &str, marker: &str) -> usize { + let (converted, _) = convert_streams(sql, &["--no-config", "--compact"]); + let connection = duckdb::Connection::open_in_memory().expect("DuckDB opens"); + let query = after_setup(&connection, &converted); + let parsed: String = connection + .query_row("SELECT json_serialize_sql(?)", [query], |row| row.get(0)) + .expect("DuckDB parses the converted statement"); + parsed.matches(marker).count() +} diff --git a/crates/sqlquack/tests/cli/test_case_subject.rs b/crates/sqlquack/tests/cli/test_case_subject.rs new file mode 100644 index 000000000..0f72aa81b --- /dev/null +++ b/crates/sqlquack/tests/cli/test_case_subject.rs @@ -0,0 +1,91 @@ +use crate::helpers::{converted_first_value, parsed_copies}; +use crate::test_types::{CaseSubjectTestCase, ChainValueTestCase}; + +#[test] +fn given_a_simple_case_over_a_computed_operand_when_converting_then_duckdb_binds_the_operand_once() +{ + let test_cases = [ + CaseSubjectTestCase { + description: "two WHENs with literal results", + branches: 2, + result: "'v{i}'", + expected_copies: 1, + }, + CaseSubjectTestCase { + description: "thirty-two WHENs with literal results", + branches: 32, + result: "'v{i}'", + expected_copies: 1, + }, + CaseSubjectTestCase { + description: "thirty-two WHENs with column results", + branches: 32, + result: "b", + expected_copies: 1, + }, + ]; + for test_case in test_cases { + let whens: Vec = (0..test_case.branches) + .map(|i| { + format!( + "WHEN 'W{i}' THEN {}", + test_case.result.replace("{i}", &i.to_string()) + ) + }) + .collect(); + let sql = format!( + "SELECT CASE UPPER(a || 'operand_marker') {} ELSE NULL END AS c \ + FROM (SELECT 'x' AS a, 'y' AS b)", + whens.join(" ") + ); + + let copies = parsed_copies(&sql, "operand_marker"); + + assert_eq!( + copies, test_case.expected_copies, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_a_simple_case_with_plain_results_when_converting_then_duckdb_returns_snowflakes_value() { + let test_cases = [ + ChainValueTestCase { + description: "the first equal WHEN's literal result", + sql: "SELECT CASE UPPER(a) WHEN 'X' THEN 'first' WHEN 'X' THEN 'second' END AS c \ + FROM (SELECT 'x' AS a)", + expected_value: "first", + }, + ChainValueTestCase { + description: "a column result", + sql: "SELECT CASE UPPER(a) WHEN 'Y' THEN 'no' WHEN 'X' THEN b END AS c \ + FROM (SELECT 'x' AS a, 'from b' AS b)", + expected_value: "from b", + }, + ChainValueTestCase { + description: "ELSE when no WHEN equals the operand", + sql: "SELECT CASE UPPER(a) WHEN 'Y' THEN 'no' ELSE b END AS c \ + FROM (SELECT 'x' AS a, 'else' AS b)", + expected_value: "else", + }, + ChainValueTestCase { + description: "a NULL operand equals no WHEN", + sql: "SELECT CASE UPPER(a) WHEN 'X' THEN 'no' ELSE 'null operand' END AS c \ + FROM (SELECT CAST(NULL AS VARCHAR) AS a)", + expected_value: "null operand", + }, + ChainValueTestCase { + description: "a number result cast to the CASE's type only where chosen", + sql: "SELECT CAST(CASE a + 1 WHEN 2 THEN 1.5 WHEN 3 THEN n END AS VARCHAR) AS c \ + FROM (SELECT 1 AS a, 7 AS n)", + expected_value: "1.5", + }, + ]; + for test_case in test_cases { + let value = converted_first_value(test_case.sql); + + assert_eq!(value, test_case.expected_value, "{}", test_case.description); + } +} diff --git a/crates/sqlquack/tests/cli/test_types.rs b/crates/sqlquack/tests/cli/test_types.rs index 84a18ba41..89bff7ed8 100644 --- a/crates/sqlquack/tests/cli/test_types.rs +++ b/crates/sqlquack/tests/cli/test_types.rs @@ -448,3 +448,13 @@ pub(crate) struct BindCheckTestCase { /// Whether it converts, printing SQL on standard output. pub(crate) expected_converted: bool, } + +/// A simple CASE over a computed operand, with `branches` WHENs choosing `result`. +pub(crate) struct CaseSubjectTestCase { + pub(crate) description: &'static str, + pub(crate) branches: usize, + /// One WHEN's result, `{i}` replaced by its position. + pub(crate) result: &'static str, + /// How many copies of the operand DuckDB parses, whatever the number of WHENs. + pub(crate) expected_copies: usize, +}