From 13731e2ab60721c80d29c3bcb5d64ff3da47bc66 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:42:42 +0000 Subject: [PATCH 1/8] perf(convert): bind a computed SPLIT operand once in DuckDB SPLIT named its text three times: in the NULL test, in the empty-separator branch and in string_split. A long computed operand, such as an UPPER with full case mapping, was pasted and bound three times. A long operand now reaches the expression once through a lambda parameter, as other text conversions do. --- .../src/variants/main/json_split.rs | 18 ++- crates/sqlquack/tests/cli.rs | 2 + .../sqlquack/tests/cli/test_case_mapping.rs | 110 ++++++++++++++++++ crates/sqlquack/tests/cli/test_types.rs | 7 ++ 4 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 crates/sqlquack/tests/cli/test_case_mapping.rs diff --git a/crates/sqlquack-blocks/src/variants/main/json_split.rs b/crates/sqlquack-blocks/src/variants/main/json_split.rs index 355b0f306..dbcd89f97 100644 --- a/crates/sqlquack-blocks/src/variants/main/json_split.rs +++ b/crates/sqlquack-blocks/src/variants/main/json_split.rs @@ -2,14 +2,22 @@ use sqlquack_diagnostics::provenance::models::ProvenanceLog; +use crate::blocks::constants::INLINE_ARGUMENT_LIMIT; use crate::semi_structured::constants::JSON_SPLIT; +use crate::variants::_helpers::objects::bound; /// The parts of `text` between occurrences of `separator`; an empty separator keeps the text whole. pub fn json_split((text, separator): (&str, &str), log: &ProvenanceLog) -> String { log.building_block(JSON_SPLIT); - format!( - "(CASE WHEN {text} IS NULL OR {separator} IS NULL THEN NULL \ - WHEN {separator} = '' THEN CAST(to_json([{text}]) AS JSON) \ - ELSE CAST(to_json(string_split({text}, {separator})) AS JSON) END)" - ) + let split = |text: &str| { + format!( + "(CASE WHEN {text} IS NULL OR {separator} IS NULL THEN NULL \ + WHEN {separator} = '' THEN CAST(to_json([{text}]) AS JSON) \ + ELSE CAST(to_json(string_split({text}, {separator})) AS JSON) END)" + ) + }; + match text.len() > INLINE_ARGUMENT_LIMIT { + true => bound(text, "split_text", &split("split_text")), + false => split(text), + } } diff --git a/crates/sqlquack/tests/cli.rs b/crates/sqlquack/tests/cli.rs index 79b8f163f..0f270bd4d 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_mapping.rs"] +mod test_case_mapping; #[path = "cli/test_case_subject.rs"] mod test_case_subject; #[path = "cli/test_check.rs"] diff --git a/crates/sqlquack/tests/cli/test_case_mapping.rs b/crates/sqlquack/tests/cli/test_case_mapping.rs new file mode 100644 index 000000000..f92d71991 --- /dev/null +++ b/crates/sqlquack/tests/cli/test_case_mapping.rs @@ -0,0 +1,110 @@ +use crate::helpers::{converted_first_value, parsed_copies}; +use crate::test_types::{ChainValueTestCase, OperandCopiesTestCase}; + +#[test] +fn given_split_over_a_computed_operand_when_converting_then_duckdb_parses_the_operand_once() { + let test_cases = [ + OperandCopiesTestCase { + description: "an UPPER operand", + sql: "SELECT SPLIT(UPPER(a || 'operand_marker'), ' ') AS c FROM (SELECT 'x y' AS a)", + expected_copies: 1, + }, + OperandCopiesTestCase { + description: "an UPPER operand and an empty separator", + sql: "SELECT SPLIT(UPPER(a || 'operand_marker'), '') AS c FROM (SELECT 'x y' AS a)", + expected_copies: 1, + }, + ]; + for test_case in test_cases { + let copies = parsed_copies(test_case.sql, "operand_marker"); + + assert_eq!( + copies, test_case.expected_copies, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_split_over_a_computed_operand_when_converting_then_duckdb_returns_snowflakes_value() { + let test_cases = [ + ChainValueTestCase { + description: "the parts of the upper-cased text", + sql: "SELECT TO_VARCHAR(SPLIT(UPPER(a), ' ')) AS c FROM (SELECT 'x straße' AS a)", + expected_value: "[\"X\",\"STRASSE\"]", + }, + ChainValueTestCase { + description: "an empty separator keeps the text whole", + sql: "SELECT TO_VARCHAR(SPLIT(UPPER(a), '')) AS c FROM (SELECT 'x y' AS a)", + expected_value: "[\"X Y\"]", + }, + ChainValueTestCase { + description: "a NULL operand", + sql: "SELECT COALESCE(TO_VARCHAR(SPLIT(UPPER(a), ' ')), 'none') AS c \ + FROM (SELECT CAST(NULL AS VARCHAR) AS a)", + expected_value: "none", + }, + ]; + for test_case in test_cases { + let value = converted_first_value(test_case.sql); + + assert_eq!(value, test_case.expected_value, "{}", test_case.description); + } +} + +#[test] +fn given_lower_when_converting_then_duckdb_parses_no_lambda() { + let test_cases = [ + OperandCopiesTestCase { + description: "LOWER over a column", + sql: "SELECT LOWER(a) AS c FROM (SELECT 'X' AS a)", + expected_copies: 0, + }, + OperandCopiesTestCase { + description: "LOWER over a computed operand", + sql: "SELECT LOWER(a || 'Y') AS c FROM (SELECT 'X' AS a)", + expected_copies: 0, + }, + ]; + for test_case in test_cases { + let copies = parsed_copies(test_case.sql, "\"LAMBDA\""); + + assert_eq!( + copies, test_case.expected_copies, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_lower_when_converting_then_duckdb_returns_snowflakes_value() { + let test_cases = [ + ChainValueTestCase { + description: "a dotted capital I becomes i and a combining dot", + sql: "SELECT LOWER(a) AS c FROM (SELECT '\u{130}' AS a)", + expected_value: "i\u{307}", + }, + ChainValueTestCase { + description: "the mapping among other characters", + sql: "SELECT LOWER(a) AS c FROM (SELECT 'A\u{130}B\u{130}\u{c9}' AS a)", + expected_value: "ai\u{307}bi\u{307}\u{e9}", + }, + ChainValueTestCase { + description: "text without the mapped character", + sql: "SELECT LOWER(a) AS c FROM (SELECT 'Stra\u{df}e' AS a)", + expected_value: "stra\u{df}e", + }, + ChainValueTestCase { + description: "a NULL operand", + sql: "SELECT COALESCE(LOWER(a), 'none') AS c FROM (SELECT CAST(NULL AS VARCHAR) AS a)", + expected_value: "none", + }, + ]; + 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 89bff7ed8..8c8d9db65 100644 --- a/crates/sqlquack/tests/cli/test_types.rs +++ b/crates/sqlquack/tests/cli/test_types.rs @@ -458,3 +458,10 @@ pub(crate) struct CaseSubjectTestCase { /// How many copies of the operand DuckDB parses, whatever the number of WHENs. pub(crate) expected_copies: usize, } + +/// A statement whose marked operand DuckDB must parse `expected_copies` times after conversion. +pub(crate) struct OperandCopiesTestCase { + pub(crate) description: &'static str, + pub(crate) sql: &'static str, + pub(crate) expected_copies: usize, +} From 6b0a2046de74d735a0c2464c903cbb45edd10e6b Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:42:44 +0000 Subject: [PATCH 2/8] perf(convert): emit LOWER as DuckDB's lower over one replace LOWER has a single multi-character mapping (U+0130). It now converts to lower(replace(text, U+0130, 'i' U+0307)) instead of a per-character lambda lookup, so DuckDB binds no lambda for it. Results are unchanged. --- crates/sqlquack-blocks/src/blocks/_helpers/text.rs | 11 +++++++++++ .../src/blocks/main/full_case_lower.rs | 4 ++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/crates/sqlquack-blocks/src/blocks/_helpers/text.rs b/crates/sqlquack-blocks/src/blocks/_helpers/text.rs index eafbbcfff..a7cc5bfef 100644 --- a/crates/sqlquack-blocks/src/blocks/_helpers/text.rs +++ b/crates/sqlquack-blocks/src/blocks/_helpers/text.rs @@ -14,6 +14,17 @@ use crate::blocks::main::string_literal::string_literal; use crate::blocks::models::TextFailure; use crate::raises::main::raised::raised; +/// `sql` with each key of `expansions` replaced by its text, one `replace` per key. +pub(crate) fn replaced(sql: &str, expansions: &[(&str, &str)], log: &ProvenanceLog) -> String { + expansions.iter().fold(sql.to_owned(), |text, (from, to)| { + format!( + "replace({text}, {}, {})", + string_literal(from, log), + string_literal(to, log) + ) + }) +} + /// `sql` with each one-character key of `expansions` spelled as its text, by a single lookup. pub(crate) fn expanded(sql: &str, expansions: &[(&str, &str)], log: &ProvenanceLog) -> String { let class: String = expansions diff --git a/crates/sqlquack-blocks/src/blocks/main/full_case_lower.rs b/crates/sqlquack-blocks/src/blocks/main/full_case_lower.rs index 6a6b76064..eab7d8d0d 100644 --- a/crates/sqlquack-blocks/src/blocks/main/full_case_lower.rs +++ b/crates/sqlquack-blocks/src/blocks/main/full_case_lower.rs @@ -2,11 +2,11 @@ use sqlquack_diagnostics::provenance::models::ProvenanceLog; -use crate::blocks::_helpers::text::expanded; +use crate::blocks::_helpers::text::replaced; use crate::blocks::constants::{FULL_CASE_MAPPING, LOWERCASE_EXPANSIONS}; /// LOWER with full Unicode case mapping: multi-character mappings first, then DuckDB's lower. pub fn full_case_lower(sql: &str, log: &ProvenanceLog) -> String { log.building_block(FULL_CASE_MAPPING); - format!("lower({})", expanded(sql, LOWERCASE_EXPANSIONS, log)) + format!("lower({})", replaced(sql, LOWERCASE_EXPANSIONS, log)) } From 0690304f9ce459205cf434fcbd1a67446d869a46 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 25 Nov 2026 15:52:14 +0000 Subject: [PATCH 3/8] perf(convert): look up UPPER's multi-character mappings in two strings UPPER with full case mapping looked each character up with list_position over two 102-item list literals, which DuckDB binds at every call. Text holding a mapped character now finds its mapping by instr in one string of keys and one split of the mapped texts; other text goes straight to DuckDB's upper. A long operand is still bound once. Results are unchanged, and binding one call takes about a quarter of the time it did. --- .../src/blocks/_helpers/text.rs | 32 ++--- .../sqlquack-blocks/src/blocks/constants.rs | 2 + .../sqlquack/tests/cli/test_case_mapping.rs | 130 +++++++++++++++++- .../sqlquack/tests/cli/test_case_subject.rs | 7 +- crates/sqlquack/tests/cli/test_types.rs | 15 ++ 5 files changed, 162 insertions(+), 24 deletions(-) diff --git a/crates/sqlquack-blocks/src/blocks/_helpers/text.rs b/crates/sqlquack-blocks/src/blocks/_helpers/text.rs index a7cc5bfef..c127a9201 100644 --- a/crates/sqlquack-blocks/src/blocks/_helpers/text.rs +++ b/crates/sqlquack-blocks/src/blocks/_helpers/text.rs @@ -8,7 +8,8 @@ use sqlquack_diagnostics::failures::models::SnowflakeCode; use sqlquack_diagnostics::provenance::models::ProvenanceLog; use crate::blocks::constants::{ - CONVERSION_WHITESPACE, INLINE_ARGUMENT_LIMIT, NUMBER_RANGE_MESSAGE, VARIANT_CAST_MESSAGE, + CONVERSION_WHITESPACE, EXPANSION_SEPARATOR, INLINE_ARGUMENT_LIMIT, NUMBER_RANGE_MESSAGE, + VARIANT_CAST_MESSAGE, }; use crate::blocks::main::string_literal::string_literal; use crate::blocks::models::TextFailure; @@ -32,21 +33,20 @@ pub(crate) fn expanded(sql: &str, expansions: &[(&str, &str)], log: &ProvenanceL .flat_map(|(from, _)| from.chars()) .map(|character| format!("\\x{{{:x}}}", u32::from(character))) .collect(); - let list = |texts: Vec<&str>| { - texts - .into_iter() - .map(|text| string_literal(text, log)) - .collect::>() - .join(", ") - }; - let keys = list(expansions.iter().map(|(from, _)| *from).collect()); - let values = list(expansions.iter().map(|(_, to)| *to).collect()); - format!( - "list_transform([{sql}], lambda case_text: CASE WHEN regexp_matches(case_text, '[{class}]') \ - THEN array_to_string(list_transform(string_split(case_text, ''), lambda case_character: \ - coalesce([{values}][list_position([{keys}], case_character)], case_character)), '') \ - ELSE case_text END)[1]" - ) + let keys = string_literal( + &expansions.iter().map(|(from, _)| *from).collect::(), + log, + ); + let targets = expansions.iter().map(|(_, to)| *to).collect::>(); + let targets = string_literal(&targets.join(EXPANSION_SEPARATOR), log); + once_bound(sql, "case_text", |text| { + format!( + "CASE WHEN regexp_matches({text}, '[{class}]') \ + THEN array_to_string(list_transform(string_split({text}, ''), lambda case_character: \ + coalesce(string_split({targets}, chr(31))[instr({keys}, case_character)], case_character)), '') \ + ELSE {text} END" + ) + }) } /// What a failed conversion yields: NULL when trying, else text's error `code` or a VARIANT's. diff --git a/crates/sqlquack-blocks/src/blocks/constants.rs b/crates/sqlquack-blocks/src/blocks/constants.rs index 9505c9206..ac4d6b612 100644 --- a/crates/sqlquack-blocks/src/blocks/constants.rs +++ b/crates/sqlquack-blocks/src/blocks/constants.rs @@ -172,6 +172,8 @@ pub const TRUE_WORDS: &[&str] = &["true", "t", "yes", "y", "on", "1"]; pub const FALSE_WORDS: &[&str] = &["false", "f", "no", "n", "off", "0"]; /// DuckDB's largest DECIMAL precision. pub const MAX_DECIMAL_PRECISION: u8 = 38; +/// What separates the mapped texts in an expansion lookup; `chr(31)` in the emitted SQL. +pub const EXPANSION_SEPARATOR: &str = "\u{1f}"; /// Characters whose full uppercase mapping has several characters. pub const UPPERCASE_EXPANSIONS: &[(&str, &str)] = &[ ("\u{df}", "SS"), diff --git a/crates/sqlquack/tests/cli/test_case_mapping.rs b/crates/sqlquack/tests/cli/test_case_mapping.rs index f92d71991..870130e0d 100644 --- a/crates/sqlquack/tests/cli/test_case_mapping.rs +++ b/crates/sqlquack/tests/cli/test_case_mapping.rs @@ -1,22 +1,31 @@ +use sqlquack_blocks::blocks::constants::UPPERCASE_EXPANSIONS; + use crate::helpers::{converted_first_value, parsed_copies}; -use crate::test_types::{ChainValueTestCase, OperandCopiesTestCase}; +use crate::test_types::{ + ChainValueTestCase, FullCaseMappingTestCase, OperandCopiesTestCase, PatternCopiesTestCase, +}; + +/// Text only an UPPER lookup holds: the uppercase mapping of U+0587. +const UPPER_LOOKUP_MARKER: &str = "\u{535}\u{552}"; #[test] fn given_split_over_a_computed_operand_when_converting_then_duckdb_parses_the_operand_once() { let test_cases = [ - OperandCopiesTestCase { + PatternCopiesTestCase { description: "an UPPER operand", - sql: "SELECT SPLIT(UPPER(a || 'operand_marker'), ' ') AS c FROM (SELECT 'x y' AS a)", + sql: "SELECT SPLIT(UPPER(a), ' ') AS c FROM (SELECT 'x y' AS a)", + pattern: UPPER_LOOKUP_MARKER, expected_copies: 1, }, - OperandCopiesTestCase { + PatternCopiesTestCase { description: "an UPPER operand and an empty separator", - sql: "SELECT SPLIT(UPPER(a || 'operand_marker'), '') AS c FROM (SELECT 'x y' AS a)", + sql: "SELECT SPLIT(UPPER(a), '') AS c FROM (SELECT 'x y' AS a)", + pattern: UPPER_LOOKUP_MARKER, expected_copies: 1, }, ]; for test_case in test_cases { - let copies = parsed_copies(test_case.sql, "operand_marker"); + let copies = parsed_copies(test_case.sql, test_case.pattern); assert_eq!( copies, test_case.expected_copies, @@ -108,3 +117,112 @@ fn given_lower_when_converting_then_duckdb_returns_snowflakes_value() { assert_eq!(value, test_case.expected_value, "{}", test_case.description); } } + +#[test] +fn given_upper_when_converting_then_duckdb_parses_one_lookup_and_no_list_position() { + let test_cases = [ + PatternCopiesTestCase { + description: "no list_position", + sql: "SELECT UPPER(a) AS c FROM (SELECT 'x' AS a)", + pattern: "\"function_name\":\"list_position\"", + expected_copies: 0, + }, + PatternCopiesTestCase { + description: "the mapped texts parsed once", + sql: "SELECT UPPER(a) AS c FROM (SELECT 'x' AS a)", + pattern: UPPER_LOOKUP_MARKER, + expected_copies: 1, + }, + PatternCopiesTestCase { + description: "one lookup string_split beside the one that splits the text", + sql: "SELECT UPPER(a) AS c FROM (SELECT 'x' AS a)", + pattern: "\"function_name\":\"string_split\"", + expected_copies: 2, + }, + PatternCopiesTestCase { + description: "one lookup per UPPER call", + sql: "SELECT UPPER(a) AS c, UPPER(a || 'y') AS d FROM (SELECT 'x' AS a)", + pattern: UPPER_LOOKUP_MARKER, + expected_copies: 2, + }, + ]; + for test_case in test_cases { + let copies = parsed_copies(test_case.sql, test_case.pattern); + + assert_eq!( + copies, test_case.expected_copies, + "{}", + test_case.description + ); + } +} + +#[test] +fn given_upper_over_every_multi_character_mapping_when_converting_then_duckdb_returns_full_case_mapping() + { + let test_cases = [ + FullCaseMappingTestCase { + description: "each mapped character between plain letters", + between: "a", + expected_mappings: 102, + }, + FullCaseMappingTestCase { + description: "the mapped characters side by side", + between: "", + expected_mappings: 102, + }, + ]; + for test_case in test_cases { + let text: String = UPPERCASE_EXPANSIONS + .iter() + .map(|(from, _)| format!("{}{from}", test_case.between)) + .collect(); + let sql = format!("SELECT UPPER(a) AS c FROM (SELECT '{text}' AS a)"); + + let value = converted_first_value(&sql); + + assert_eq!( + UPPERCASE_EXPANSIONS.len(), + test_case.expected_mappings, + "{}", + test_case.description + ); + assert_eq!(value, text.to_uppercase(), "{}", test_case.description); + } +} + +#[test] +fn given_upper_when_converting_then_duckdb_returns_snowflakes_value() { + let test_cases = [ + ChainValueTestCase { + description: "text without a multi-character mapping", + sql: "SELECT UPPER(a) AS c FROM (SELECT 'abc \u{e9}' AS a)", + expected_value: "ABC \u{c9}", + }, + ChainValueTestCase { + description: "a sharp s among other characters", + sql: "SELECT UPPER(a) AS c FROM (SELECT 'stra\u{df}e' AS a)", + expected_value: "STRASSE", + }, + ChainValueTestCase { + description: "a computed operand", + sql: "SELECT UPPER(a || '\u{fb03}') AS c FROM (SELECT 'x' AS a)", + expected_value: "XFFI", + }, + ChainValueTestCase { + description: "an empty text", + sql: "SELECT '[' || UPPER(a) || ']' AS c FROM (SELECT '' AS a)", + expected_value: "[]", + }, + ChainValueTestCase { + description: "a NULL operand", + sql: "SELECT COALESCE(UPPER(a), 'none') AS c FROM (SELECT CAST(NULL AS VARCHAR) AS a)", + expected_value: "none", + }, + ]; + 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_case_subject.rs b/crates/sqlquack/tests/cli/test_case_subject.rs index 0f72aa81b..64dd82c97 100644 --- a/crates/sqlquack/tests/cli/test_case_subject.rs +++ b/crates/sqlquack/tests/cli/test_case_subject.rs @@ -1,6 +1,9 @@ use crate::helpers::{converted_first_value, parsed_copies}; use crate::test_types::{CaseSubjectTestCase, ChainValueTestCase}; +/// Text only an UPPER expansion holds, so its count is the copies of the CASE operand. +const UPPER_LOOKUP_MARKER: &str = "\u{535}\u{552}"; + #[test] fn given_a_simple_case_over_a_computed_operand_when_converting_then_duckdb_binds_the_operand_once() { @@ -34,12 +37,12 @@ fn given_a_simple_case_over_a_computed_operand_when_converting_then_duckdb_binds }) .collect(); let sql = format!( - "SELECT CASE UPPER(a || 'operand_marker') {} ELSE NULL END AS c \ + "SELECT CASE UPPER(a || 'operand') {} ELSE NULL END AS c \ FROM (SELECT 'x' AS a, 'y' AS b)", whens.join(" ") ); - let copies = parsed_copies(&sql, "operand_marker"); + let copies = parsed_copies(&sql, UPPER_LOOKUP_MARKER); assert_eq!( copies, test_case.expected_copies, diff --git a/crates/sqlquack/tests/cli/test_types.rs b/crates/sqlquack/tests/cli/test_types.rs index 8c8d9db65..558f791de 100644 --- a/crates/sqlquack/tests/cli/test_types.rs +++ b/crates/sqlquack/tests/cli/test_types.rs @@ -465,3 +465,18 @@ pub(crate) struct OperandCopiesTestCase { pub(crate) sql: &'static str, pub(crate) expected_copies: usize, } + +/// A statement whose conversion DuckDB must parse with `pattern` appearing `expected_copies` times. +pub(crate) struct PatternCopiesTestCase { + pub(crate) description: &'static str, + pub(crate) sql: &'static str, + pub(crate) pattern: &'static str, + pub(crate) expected_copies: usize, +} + +/// Every multi-character uppercase mapping, each after `between`, upper-cased in one statement. +pub(crate) struct FullCaseMappingTestCase { + pub(crate) description: &'static str, + pub(crate) between: &'static str, + pub(crate) expected_mappings: usize, +} From e3d9cdc98f545743038b60ab766dee789fc3435c Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:43:15 +0000 Subject: [PATCH 4/8] docs(website): show real sqlquack output in every example, and check it in CI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The homepage still showed the division output from before 0.23.2, and other examples had drifted from what sqlquack prints: the HASH refusal was wrapped by hand, the census coverage report named an old category, the helper-macros page listed macros convert no longer emits alone, and several blocks left out a final status line. Each example now shows real output, cut down only where marked … website/examples holds every example's input files. make website-examples, part of make check-ci, runs the commands each marked block shows with the built sqlquack and fails where the page shows anything else, or where a terminal or console block names no example. website/examples/README.md describes the markers and the few ways a page may shorten output. --- Makefile | 11 +- scripts/check_website_examples.py | 14 ++ scripts/website_examples/__init__.py | 1 + scripts/website_examples/_helpers/__init__.py | 0 scripts/website_examples/_helpers/blocks.py | 49 +++++ .../website_examples/_helpers/comparison.py | 36 ++++ scripts/website_examples/_helpers/running.py | 173 ++++++++++++++++++ scripts/website_examples/constants.py | 30 +++ scripts/website_examples/main/__init__.py | 1 + scripts/website_examples/main/examples.py | 34 ++++ scripts/website_examples/models.py | 16 ++ scripts/website_examples/types.py | 7 + .../unit/scripts/website_examples/__init__.py | 1 + .../scripts/website_examples/_test_types.py | 15 ++ .../unit/scripts/website_examples/helpers.py | 34 ++++ .../scripts/website_examples/test_examples.py | 156 ++++++++++++++++ website/README.md | 3 + website/examples/README.md | 34 ++++ .../models/marts/customer_report.sql | 1 + .../models/marts/customer_sounds.sql | 4 + .../models/staging/stg_customers.sql | 1 + .../models/staging/stg_orders.sql | 1 + .../examples/census-chained/sources/shop.yml | 21 +++ .../models/marts/customer_report.sql | 1 + .../models/marts/customer_sounds.sql | 4 + .../models/staging/stg_customers.sql | 1 + .../models/staging/stg_orders.sql | 1 + .../examples/census-report/sources/shop.yml | 15 ++ .../census/models/marts/customer_sounds.sql | 4 + .../census/models/staging/stg_customers.sql | 1 + .../census/models/staging/stg_orders.sql | 1 + website/examples/census/sources/shop.yml | 15 ++ website/examples/division/div.sql | 1 + website/examples/division/sources/orders.yml | 13 ++ website/examples/hash-policy/due.sql | 3 + .../examples/hash-policy/sources/orders.yml | 13 ++ website/examples/hash-policy/sqlquack.toml | 2 + .../examples/helper-macros/sources/events.yml | 5 + website/examples/helper-macros/staging.sql | 1 + website/examples/intersect/query.sql | 1 + website/examples/no-sources/revenue.sql | 4 + website/examples/project-untyped/revenue.sql | 3 + .../examples/project-untyped/sources/more.yml | 6 + .../examples/project-untyped/sources/shop.yml | 9 + website/examples/project/revenue.sql | 3 + website/examples/project/sources/shop.yml | 9 + website/examples/quickstart/orders.sql | 5 + website/examples/quickstart/revenue.sql | 4 + .../examples/quickstart/sources/orders.yml | 13 ++ website/examples/run/data/orders.csv | 3 + website/examples/run/doubled.sql | 3 + website/examples/run/sources/orders.yml | 7 + website/examples/sessions/orders.sql | 1 + website/examples/sessions/sources/orders.yml | 13 ++ website/public/index.html | 55 +++--- website/src/content/docs/docs/cli/census.mdx | 14 +- website/src/content/docs/docs/cli/check.mdx | 1 + website/src/content/docs/docs/cli/convert.mdx | 2 + website/src/content/docs/docs/cli/run.mdx | 7 + .../src/content/docs/docs/helper-macros.mdx | 12 +- website/src/content/docs/docs/index.mdx | 3 + website/src/content/docs/docs/policy.mdx | 3 + website/src/content/docs/docs/project.mdx | 6 + website/src/content/docs/docs/python.mdx | 1 + website/src/content/docs/docs/quickstart.mdx | 4 + website/src/content/docs/docs/sessions.mdx | 1 + 66 files changed, 877 insertions(+), 40 deletions(-) create mode 100644 scripts/check_website_examples.py create mode 100644 scripts/website_examples/__init__.py create mode 100644 scripts/website_examples/_helpers/__init__.py create mode 100644 scripts/website_examples/_helpers/blocks.py create mode 100644 scripts/website_examples/_helpers/comparison.py create mode 100644 scripts/website_examples/_helpers/running.py create mode 100644 scripts/website_examples/constants.py create mode 100644 scripts/website_examples/main/__init__.py create mode 100644 scripts/website_examples/main/examples.py create mode 100644 scripts/website_examples/models.py create mode 100644 scripts/website_examples/types.py create mode 100644 tests/unit/scripts/website_examples/__init__.py create mode 100644 tests/unit/scripts/website_examples/_test_types.py create mode 100644 tests/unit/scripts/website_examples/helpers.py create mode 100644 tests/unit/scripts/website_examples/test_examples.py create mode 100644 website/examples/README.md create mode 100644 website/examples/census-chained/models/marts/customer_report.sql create mode 100644 website/examples/census-chained/models/marts/customer_sounds.sql create mode 100644 website/examples/census-chained/models/staging/stg_customers.sql create mode 100644 website/examples/census-chained/models/staging/stg_orders.sql create mode 100644 website/examples/census-chained/sources/shop.yml create mode 100644 website/examples/census-report/models/marts/customer_report.sql create mode 100644 website/examples/census-report/models/marts/customer_sounds.sql create mode 100644 website/examples/census-report/models/staging/stg_customers.sql create mode 100644 website/examples/census-report/models/staging/stg_orders.sql create mode 100644 website/examples/census-report/sources/shop.yml create mode 100644 website/examples/census/models/marts/customer_sounds.sql create mode 100644 website/examples/census/models/staging/stg_customers.sql create mode 100644 website/examples/census/models/staging/stg_orders.sql create mode 100644 website/examples/census/sources/shop.yml create mode 100644 website/examples/division/div.sql create mode 100644 website/examples/division/sources/orders.yml create mode 100644 website/examples/hash-policy/due.sql create mode 100644 website/examples/hash-policy/sources/orders.yml create mode 100644 website/examples/hash-policy/sqlquack.toml create mode 100644 website/examples/helper-macros/sources/events.yml create mode 100644 website/examples/helper-macros/staging.sql create mode 100644 website/examples/intersect/query.sql create mode 100644 website/examples/no-sources/revenue.sql create mode 100644 website/examples/project-untyped/revenue.sql create mode 100644 website/examples/project-untyped/sources/more.yml create mode 100644 website/examples/project-untyped/sources/shop.yml create mode 100644 website/examples/project/revenue.sql create mode 100644 website/examples/project/sources/shop.yml create mode 100644 website/examples/quickstart/orders.sql create mode 100644 website/examples/quickstart/revenue.sql create mode 100644 website/examples/quickstart/sources/orders.yml create mode 100644 website/examples/run/data/orders.csv create mode 100644 website/examples/run/doubled.sql create mode 100644 website/examples/run/sources/orders.yml create mode 100644 website/examples/sessions/orders.sql create mode 100644 website/examples/sessions/sources/orders.yml diff --git a/Makefile b/Makefile index 3ee356d87..f971990cc 100644 --- a/Makefile +++ b/Makefile @@ -30,7 +30,7 @@ PYTHON_TYPED := scripts tests/unit/scripts python/src $(PYTHON_API_TESTS) PYTHON_TESTS := tests/unit/scripts $(PYTHON_API_TESTS) endif -.PHONY: distribution-notices format rust-lint python-check fensu syntax-coverage website-figures website-figures-update depth-probe depth-probe-debug instruction-counts instruction-baseline gate-build engine-free bundled-extensions dialect-builds generate-cases generated-cases generate-syntax-cases syntax-obligations syntax-cases dialect-cases dialect-validate corpus-rerecord corpus-verdicts corpus-verdicts-baseline generate-referee-cases referee-cases referee-pending translation-files translation-results help pending check-syntax record-syntax check-convert record-convert sql-sizes sql-size-baseline sql-benchmark check-ci check-merge test test-rust test-python python-build python-module python-api python-wheel verify-recorded verify-changed replay-scope test-crate check-pr-metadata evidence-clone evidence-refresh evidence-pin evidence-pin-check clutter-guard census-duckshop fuzz-smoke gate gate-parallel census duckshop-compiled duckshop-measure +.PHONY: distribution-notices format rust-lint python-check fensu syntax-coverage website-figures website-figures-update website-examples depth-probe depth-probe-debug instruction-counts instruction-baseline gate-build engine-free bundled-extensions dialect-builds generate-cases generated-cases generate-syntax-cases syntax-obligations syntax-cases dialect-cases dialect-validate corpus-rerecord corpus-verdicts corpus-verdicts-baseline generate-referee-cases referee-cases referee-pending translation-files translation-results help pending check-syntax record-syntax check-convert record-convert sql-sizes sql-size-baseline sql-benchmark check-ci check-merge test test-rust test-python python-build python-module python-api python-wheel verify-recorded verify-changed replay-scope test-crate check-pr-metadata evidence-clone evidence-refresh evidence-pin evidence-pin-check clutter-guard census-duckshop fuzz-smoke gate gate-parallel census duckshop-compiled duckshop-measure format: cargo fmt --all @@ -76,6 +76,13 @@ website-figures website-figures-update: gate-build $(GATE_DIR)/syntax-coverage summary --evidence $(call syntax_evidence_dir,snowflake) --json > $(SYNTAX_SUMMARY_FILE) uv run python -m scripts.check_website_figures $(if $(filter website-figures-update,$@),write,check) $(SYNTAX_SUMMARY_FILE) +# Fails when an example the website shows (homepage terminals and docs blocks marked as examples) +# differs from what the built sqlquack prints for its inputs in website/examples, or when a +# terminal or console block names no example. +website-examples: gate-build python-module + PYTHONPATH=$(abspath python/src) LD_LIBRARY_PATH=$(abspath $(PYTHON_PACKAGE)) \ + uv run python -m scripts.check_website_examples $(GATE_DIR)/sqlquack + # Fails when a native parser crashes, panics or hangs on deeply nested SQL on a 2 MiB thread and # coverage/deep-nesting.toml does not list it, or when a listed failure no longer happens. depth-probe: gate-build @@ -249,7 +256,7 @@ referee-pending: uv run python -m scripts.write_referee_pending $(REFEREE_ARGS) # The static gate, the first step of `gate`, and the Python API's tests. -check-ci: rust-lint python-check fensu syntax-coverage website-figures depth-probe instruction-counts corpus-verdicts evidence-pin-check clutter-guard engine-free bundled-extensions dialect-builds generated-cases syntax-obligations syntax-cases dialect-cases dialect-validate referee-cases translation-files python-api distribution-notices replay-scope ## The static gate CI runs. +check-ci: rust-lint python-check fensu syntax-coverage website-figures website-examples depth-probe instruction-counts corpus-verdicts evidence-pin-check clutter-guard engine-free bundled-extensions dialect-builds generated-cases syntax-obligations syntax-cases dialect-cases dialect-validate referee-cases translation-files python-api distribution-notices replay-scope ## The static gate CI runs. # Each distribution ships the licence and third-party notices; its copies must match the root files. distribution-notices: diff --git a/scripts/check_website_examples.py b/scripts/check_website_examples.py new file mode 100644 index 000000000..05090de4f --- /dev/null +++ b/scripts/check_website_examples.py @@ -0,0 +1,14 @@ +"""Direct wrapper for the website examples.""" + +from __future__ import annotations + +from scripts.website_examples.main.examples import run_examples + + +def main(argv: list[str] | None = None) -> int: + """Check the website's examples against the real output of the built `sqlquack`.""" + return run_examples(argv) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/website_examples/__init__.py b/scripts/website_examples/__init__.py new file mode 100644 index 000000000..97c7dabfe --- /dev/null +++ b/scripts/website_examples/__init__.py @@ -0,0 +1 @@ +"""The website's examples, run with the built `sqlquack` and checked against what the pages show.""" diff --git a/scripts/website_examples/_helpers/__init__.py b/scripts/website_examples/_helpers/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/scripts/website_examples/_helpers/blocks.py b/scripts/website_examples/_helpers/blocks.py new file mode 100644 index 000000000..faf2876fd --- /dev/null +++ b/scripts/website_examples/_helpers/blocks.py @@ -0,0 +1,49 @@ +"""The example blocks the homepage and the docs pages show, and the blocks no marker names.""" + +from __future__ import annotations + +import html +from pathlib import Path + +from scripts.website_examples.constants import ( + COMMAND_SPAN, + DOCS_DIR, + HOMEPAGE, + MDX_BLOCK, + MDX_TRANSCRIPT_LANGUAGE, + PROMPT, + TAG, + TERMINAL_BLOCK, +) +from scripts.website_examples.models import ShownBlock + + +def shown_blocks(root: Path) -> tuple[list[ShownBlock], list[str]]: + """Every marked example block, and a problem for each terminal or console block unmarked.""" + found: list[ShownBlock] = [] + homepage: str = (root / HOMEPAGE).read_text(encoding="utf-8") + for match in TERMINAL_BLOCK.finditer(homepage): + line: int = homepage.count("\n", 0, match.start()) + 1 + text: str = html.unescape(TAG.sub("", COMMAND_SPAN.sub(PROMPT + r"\1", match["body"]))) + found.append(ShownBlock(HOMEPAGE, line, *_named(match["spec"]), text)) + for path in sorted((root / DOCS_DIR).rglob("*.mdx")): + page: str = path.relative_to(root).as_posix() + source: str = path.read_text(encoding="utf-8") + for match in MDX_BLOCK.finditer(source): + if match["spec"] is None and match["language"] != MDX_TRANSCRIPT_LANGUAGE: + continue + line = source.count("\n", 0, match.start()) + 1 + text = match["body"].removesuffix("\n") + found.append(ShownBlock(page, line, *_named(match["spec"]), text)) + unmarked: list[str] = [ + f"{block.page}:{block.line}: the block names no example" + for block in found + if not block.example + ] + return [block for block in found if block.example], unmarked + + +def _named(spec: str | None) -> tuple[str, str]: + """The example a marker names and the rest of its specification; empty without a marker.""" + name, _, rest = (spec or "").partition(" ") + return name, rest diff --git a/scripts/website_examples/_helpers/comparison.py b/scripts/website_examples/_helpers/comparison.py new file mode 100644 index 000000000..06a933663 --- /dev/null +++ b/scripts/website_examples/_helpers/comparison.py @@ -0,0 +1,36 @@ +"""Whether shown text matches real output, `…` standing for what the page leaves out.""" + +from __future__ import annotations + +import difflib +import re +from collections.abc import Iterator + +from scripts.website_examples.constants import ELISION, PROGRESS_LINE + + +def shows(*, shown: str, actual: str) -> bool: + """Whether `shown` is `actual`, a line of only `…` for lines and `…` in a line for its text.""" + pieces: list[str] = [] + for line in shown.split("\n"): + if line.strip() == ELISION: + pieces.append(r"[^\n]*(?:\n[^\n]*)*?") + continue + pieces.append(r"[^\n]*".join(re.escape(part) for part in line.split(ELISION))) + return re.fullmatch("\n".join(pieces), actual) is not None + + +def without_progress(*, shown: str, actual: str) -> str: + """`actual` without its leading progress line when `shown` leaves that line out.""" + first, _, rest = actual.partition("\n") + if PROGRESS_LINE.fullmatch(first) and not PROGRESS_LINE.fullmatch(shown.partition("\n")[0]): + return rest + return actual + + +def difference(*, shown: str, actual: str) -> str: + """The shown text against the real output, as a unified diff.""" + lines: Iterator[str] = difflib.unified_diff( + shown.split("\n"), actual.split("\n"), "shown on the page", "real output", lineterm="" + ) + return "\n".join(lines) diff --git a/scripts/website_examples/_helpers/running.py b/scripts/website_examples/_helpers/running.py new file mode 100644 index 000000000..21f1ffec5 --- /dev/null +++ b/scripts/website_examples/_helpers/running.py @@ -0,0 +1,173 @@ +"""Running one shown example in a copy of its input files and finding where the page differs.""" + +from __future__ import annotations + +import ast +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + +from scripts.website_examples._helpers.comparison import difference, shows, without_progress +from scripts.website_examples.constants import ( + COMMAND_TIMEOUT_SECONDS, + EXAMPLES_DIR, + FILE_KEY, + NO_INPUTS, + OUTPUT_KEY, + PREAMBLE_KEY, + PROMPT, + PYTHON_KIND, + RESULT_COMMENT, + SKIPPED_COMMANDS, +) +from scripts.website_examples.models import ShownBlock +from scripts.website_examples.types import Place + + +def block_problems(*, block: ShownBlock, root: Path, sqlquack: Path) -> list[str]: + """Where `block` differs from its example run with `sqlquack`, or why it cannot be checked.""" + inputs: Path = root / EXAMPLES_DIR / block.example + where: str = f"{block.page}:{block.line}: example {block.example}" + if block.example != NO_INPUTS and not inputs.is_dir(): + return [f"{where}: {EXAMPLES_DIR}/{block.example} does not exist"] + with tempfile.TemporaryDirectory() as directory: + work: Path = Path(directory) / "example" + if block.example == NO_INPUTS: + work.mkdir() + else: + shutil.copytree(inputs, work) + place: Place = (work, _environment(sqlquack=sqlquack, directory=Path(directory))) + if block.spec.startswith(FILE_KEY): + name: str = block.spec.removeprefix(FILE_KEY) + return _file_problems(text=block.text, file=(work, name), where=where) + if block.spec == PYTHON_KIND: + return _python_problems(text=block.text, place=place, where=where) + if block.spec.startswith(OUTPUT_KEY): + command: str = block.spec.removeprefix(OUTPUT_KEY) + actual: str = _run(command=command, place=place, merged=False) + return _output_problems(shown=block.text, actual=actual, where=f"{where}: `{command}`") + if block.spec and not block.spec.startswith(PREAMBLE_KEY): + return [f"{where}: unknown example kind {block.spec!r}"] + return _transcript_problems(block=block, place=place, where=where) + + +def _environment(*, sqlquack: Path, directory: Path) -> dict[str, str]: + """The environment examples run in: the built `sqlquack` first on PATH and a scratch home.""" + home: Path = directory / "home" + home.mkdir() + path: str = os.pathsep.join((str(sqlquack.resolve().parent), os.environ.get("PATH", ""))) + return {**os.environ, "PATH": path, "HOME": str(home), "NO_COLOR": "1", "TERM": "dumb"} + + +def _run(*, command: str, place: Place, merged: bool) -> str: + """What `command` prints in the shell: standard output, with standard error when `merged`.""" + work, environment = place + finished: subprocess.CompletedProcess[str] = subprocess.run( + ["sh", "-c", command], + cwd=work, + env=environment, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT if merged else subprocess.DEVNULL, + text=True, + timeout=COMMAND_TIMEOUT_SECONDS, + check=False, + ) + return finished.stdout.removesuffix("\n") + + +def _unlabelled(*, text: str, name: str) -> str: + """`text` without a first-line comment that labels it as the file `name`.""" + first, _, rest = text.partition("\n") + labels: tuple[str, ...] = (f"-- {name}", f"# {name}") + return rest if first.startswith(labels) else text + + +def _file_problems(*, text: str, file: tuple[Path, str], where: str) -> list[str]: + """Where the shown text differs from the example's file.""" + work, name = file + if not (work / name).is_file(): + return [f"{where}: the example has no file {name}"] + actual: str = (work / name).read_text(encoding="utf-8").removesuffix("\n") + shown: str = _unlabelled(text=text, name=name) + if shown == actual: + return [] + return [f"{where}: {name} differs from the page\n{difference(shown=shown, actual=actual)}"] + + +def _output_problems(*, shown: str, actual: str, where: str) -> list[str]: + """Where the shown output differs from what the command printed.""" + printed: str = without_progress(shown=shown, actual=actual) + if shows(shown=shown, actual=printed): + return [] + return [f"{where} prints something else\n{difference(shown=shown, actual=printed)}"] + + +def _transcript_problems(*, block: ShownBlock, place: Place, where: str) -> list[str]: + """Where a shown session of `$` commands differs from running them in order.""" + lines: list[str] = block.text.split("\n") + starts: list[int] = [index for index, line in enumerate(lines) if line.startswith(PROMPT)] + if not starts: + return [f"{where}: the block shows no `{PROMPT.strip()}` command"] + problems: list[str] = [] + preamble: str = "\n".join(lines[: starts[0]]).strip("\n") + if block.spec.startswith(PREAMBLE_KEY): + shown_file: tuple[Path, str] = (place[0], block.spec.removeprefix(PREAMBLE_KEY)) + problems += _file_problems(text=preamble, file=shown_file, where=where) + elif preamble: + problems.append(f"{where}: lines before the first command need a preamble= file") + for start, end in zip(starts, [*starts[1:], len(lines)], strict=True): + command: str = lines[start].removeprefix(PROMPT) + shown: str = "\n".join(lines[start + 1 : end]).strip("\n") + if command in SKIPPED_COMMANDS: + continue + actual: str = _run(command=command, place=place, merged=True) + problems += _output_problems(shown=shown, actual=actual, where=f"{where}: `{command}`") + return problems + + +def _python_problems(*, text: str, place: Place, where: str) -> list[str]: + """Where a value a Python block shows in a `# value` comment differs from the one it gives.""" + work, environment = place + script: list[str] = ["_shown = []"] + expected: dict[int, object] = {} + for number, line in enumerate(text.split("\n"), start=1): + found: re.Match[str] | None = RESULT_COMMENT.match(line) + value: object = _literal(found["value"]) if found else None + if found is None or value is None: + script.append(line) + continue + expected[number] = value + script.append(f"_shown.append(({number}, repr({found['expression']})))") + script.append("import json\nprint(json.dumps(_shown))") + finished: subprocess.CompletedProcess[str] = subprocess.run( + [sys.executable, "-c", "\n".join(script)], + cwd=work, + env=environment, + capture_output=True, + text=True, + timeout=COMMAND_TIMEOUT_SECONDS, + check=False, + ) + if finished.returncode != 0: + return [f"{where}: the Python block fails\n{finished.stderr.strip()}"] + given: dict[int, object] = { + line: ast.literal_eval(shown) for line, shown in json.loads(finished.stdout) + } + return [ + f"{where}: line {line} shows {value!r}, but gives {given[line]!r}" + for line, value in expected.items() + if given[line] != value + ] + + +def _literal(text: str) -> object: + """The Python literal a result comment shows, or None when it shows none.""" + try: + return ast.literal_eval(text) + except (SyntaxError, ValueError): + return None diff --git a/scripts/website_examples/constants.py b/scripts/website_examples/constants.py new file mode 100644 index 000000000..04349226a --- /dev/null +++ b/scripts/website_examples/constants.py @@ -0,0 +1,30 @@ +"""Where the website shows examples, how a page marks them, and how a shown block reads.""" + +from __future__ import annotations + +import re + +HOMEPAGE: str = "website/public/index.html" +DOCS_DIR: str = "website/src/content/docs/docs" +EXAMPLES_DIR: str = "website/examples" +NO_INPUTS: str = "no-inputs" +ELISION: str = "…" +PROMPT: str = "$ " +PYTHON_KIND: str = "python" +FILE_KEY: str = "file=" +PREAMBLE_KEY: str = "preamble=" +OUTPUT_KEY: str = "output: " +SKIPPED_COMMANDS: tuple[str, ...] = ("pip install sqlquack",) +COMMAND_TIMEOUT_SECONDS: int = 60 +MDX_BLOCK: re.Pattern[str] = re.compile( + r"^(?:\{/\* example: (?P[^*\n]+?) \*/\}\n)?```(?P\w*)[^\n]*\n(?P.*?)^```", + re.MULTILINE | re.DOTALL, +) +MDX_TRANSCRIPT_LANGUAGE: str = "console" +TERMINAL_BLOCK: re.Pattern[str] = re.compile( + r'
(?P.*?)
', re.DOTALL +) +COMMAND_SPAN: re.Pattern[str] = re.compile(r'(.*?)', re.DOTALL) +TAG: re.Pattern[str] = re.compile(r"<[^>]+>") +PROGRESS_LINE: re.Pattern[str] = re.compile(r"sqlquack \w+: \w+ing\b[^\n]*…") +RESULT_COMMENT: re.Pattern[str] = re.compile(r"^(?P\S.*?)\s+# (?P.+)$") diff --git a/scripts/website_examples/main/__init__.py b/scripts/website_examples/main/__init__.py new file mode 100644 index 000000000..d81105aaa --- /dev/null +++ b/scripts/website_examples/main/__init__.py @@ -0,0 +1 @@ +"""Entry points for the website examples.""" diff --git a/scripts/website_examples/main/examples.py b/scripts/website_examples/main/examples.py new file mode 100644 index 000000000..13376ea47 --- /dev/null +++ b/scripts/website_examples/main/examples.py @@ -0,0 +1,34 @@ +"""Run every example the website shows and fail where a page differs from the real output.""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +from scripts.website_examples._helpers.blocks import shown_blocks +from scripts.website_examples._helpers.running import block_problems +from scripts.website_examples.constants import EXAMPLES_DIR + + +def run_examples(argv: list[str] | None = None) -> int: + """Check each marked example block against its example's real output; 1 when any differs.""" + parser: argparse.ArgumentParser = argparse.ArgumentParser(description=run_examples.__doc__) + parser.add_argument("sqlquack", type=Path, help="the built sqlquack binary") + parser.add_argument("--root", type=Path, default=Path()) + arguments: argparse.Namespace = parser.parse_args(argv) + blocks, unmarked = shown_blocks(arguments.root) + problems: list[str] = list(unmarked) + for block in blocks: + problems += block_problems(block=block, root=arguments.root, sqlquack=arguments.sqlquack) + for problem in problems: + print(f"website examples: {problem}", file=sys.stderr) + if problems: + print( + f"website examples: update the page to the real output, or the inputs in " + f"{EXAMPLES_DIR}/, then run `make website-examples`", + file=sys.stderr, + ) + return 1 + print(f"website examples: passed, {len(blocks)} blocks") + return 0 diff --git a/scripts/website_examples/models.py b/scripts/website_examples/models.py new file mode 100644 index 000000000..6785cf594 --- /dev/null +++ b/scripts/website_examples/models.py @@ -0,0 +1,16 @@ +"""A block a website page shows as an example.""" + +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class ShownBlock: + """A block's page and line, the example it shows, how to read it, and its text.""" + + page: str + line: int + example: str + spec: str + text: str diff --git a/scripts/website_examples/types.py b/scripts/website_examples/types.py new file mode 100644 index 000000000..756dabca0 --- /dev/null +++ b/scripts/website_examples/types.py @@ -0,0 +1,7 @@ +"""Type aliases of the website examples.""" + +from __future__ import annotations + +from pathlib import Path + +type Place = tuple[Path, dict[str, str]] diff --git a/tests/unit/scripts/website_examples/__init__.py b/tests/unit/scripts/website_examples/__init__.py new file mode 100644 index 000000000..fb0b208fc --- /dev/null +++ b/tests/unit/scripts/website_examples/__init__.py @@ -0,0 +1 @@ +"""Tests for checking the website's examples against real output.""" diff --git a/tests/unit/scripts/website_examples/_test_types.py b/tests/unit/scripts/website_examples/_test_types.py new file mode 100644 index 000000000..bebd46067 --- /dev/null +++ b/tests/unit/scripts/website_examples/_test_types.py @@ -0,0 +1,15 @@ +"""Test types for the website examples.""" + +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class ExampleCheckTestCase: + description: str + page: str + homepage: str + printed: str + expected_return_code: int + expected_fragment: str diff --git a/tests/unit/scripts/website_examples/helpers.py b/tests/unit/scripts/website_examples/helpers.py new file mode 100644 index 000000000..6948c06dc --- /dev/null +++ b/tests/unit/scripts/website_examples/helpers.py @@ -0,0 +1,34 @@ +"""A small website, one example's inputs and a stand-in sqlquack, written into a directory.""" + +from __future__ import annotations + +import io +from contextlib import redirect_stderr, redirect_stdout +from pathlib import Path + +from scripts.website_examples.main.examples import run_examples + +STAND_IN: str = '#!/bin/sh\ncat "$(dirname "$0")/printed.txt"\n' + + +def checked_site(*, tmp_path: Path, pages: tuple[str, str], printed: str) -> tuple[int, str]: + """The check's return code and messages for a docs page and a homepage over `printed`.""" + page, homepage = pages + docs: Path = tmp_path / "website/src/content/docs/docs" + docs.mkdir(parents=True) + (docs / "page.mdx").write_text(page, encoding="utf-8") + (tmp_path / "website/public").mkdir(parents=True) + (tmp_path / "website/public/index.html").write_text(homepage, encoding="utf-8") + example: Path = tmp_path / "website/examples/orders" + example.mkdir(parents=True) + (example / "query.sql").write_text("SELECT a\nFROM t\n", encoding="utf-8") + tools: Path = tmp_path / "bin" + tools.mkdir() + (tools / "printed.txt").write_text(printed, encoding="utf-8") + sqlquack: Path = tools / "sqlquack" + sqlquack.write_text(STAND_IN) + sqlquack.chmod(0o755) + messages: io.StringIO = io.StringIO() + with redirect_stderr(messages), redirect_stdout(messages): + code: int = run_examples([str(sqlquack), "--root", str(tmp_path)]) + return code, messages.getvalue() diff --git a/tests/unit/scripts/website_examples/test_examples.py b/tests/unit/scripts/website_examples/test_examples.py new file mode 100644 index 000000000..aa9041451 --- /dev/null +++ b/tests/unit/scripts/website_examples/test_examples.py @@ -0,0 +1,156 @@ +"""Checking the blocks a website page marks as examples against what the commands print.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from tests.unit.scripts.website_examples._test_types import ExampleCheckTestCase +from tests.unit.scripts.website_examples.helpers import checked_site + +TRANSCRIPT: str = ( + "{/* example: orders */}\n```console\n$ sqlquack convert query.sql\nSELECT 1\n" + "sqlquack convert: done, converted\n```\n" +) +PRINTED: str = "SELECT 1\nsqlquack convert: done, converted\n" + + +@pytest.mark.parametrize( + "test_case", + ( + ExampleCheckTestCase( + description="a transcript showing the real output passes", + page=TRANSCRIPT, + homepage="", + printed=PRINTED, + expected_return_code=0, + expected_fragment="passed, 1 blocks", + ), + ExampleCheckTestCase( + description="a leading progress line the page leaves out passes", + page=TRANSCRIPT, + homepage="", + printed="sqlquack convert: converting…\n" + PRINTED, + expected_return_code=0, + expected_fragment="passed", + ), + ExampleCheckTestCase( + description="a line of only an ellipsis stands for several lines", + page="{/* example: orders */}\n```console\n$ sqlquack convert query.sql\n…\n" + "sqlquack convert: done, converted\n```\n", + homepage="", + printed="SELECT\n 1\n" + "sqlquack convert: done, converted\n", + expected_return_code=0, + expected_fragment="passed", + ), + ExampleCheckTestCase( + description="an ellipsis in a line stands for the rest of its text", + page="{/* example: orders */}\n```console\n$ sqlquack convert query.sql\nSELECT 1\n" + "sqlquack convert: done, …\n```\n", + homepage="", + printed=PRINTED, + expected_return_code=0, + expected_fragment="passed", + ), + ExampleCheckTestCase( + description="a file shown under its label comment passes", + page="{/* example: orders file=query.sql */}\n```sql\n-- query.sql\nSELECT a\nFROM t\n```\n", + homepage="", + printed="", + expected_return_code=0, + expected_fragment="passed", + ), + ExampleCheckTestCase( + description="a homepage terminal reads its command spans and entities", + page="", + homepage='
'
+            'sqlquack convert query.sql\n'
+            "SELECT "A"
", + printed='SELECT "A"\n', + expected_return_code=0, + expected_fragment="passed", + ), + ExampleCheckTestCase( + description="a value a Python block shows in its result comment passes", + page="{/* example: no-inputs python */}\n```python\ntotal = 1 + 1\ntotal # 2\n```\n", + homepage="", + printed="", + expected_return_code=0, + expected_fragment="passed", + ), + ), + ids=lambda case: case.description, +) +def test_given_pages_showing_real_output_when_checking_then_the_check_passes( + test_case: ExampleCheckTestCase, tmp_path: Path +) -> None: + code, messages = checked_site( + tmp_path=tmp_path, pages=(test_case.page, test_case.homepage), printed=test_case.printed + ) + assert code == test_case.expected_return_code, messages + assert test_case.expected_fragment in messages + + +@pytest.mark.parametrize( + "test_case", + ( + ExampleCheckTestCase( + description="output that changed fails with the difference", + page=TRANSCRIPT, + homepage="", + printed="SELECT 2\nsqlquack convert: done, converted\n", + expected_return_code=1, + expected_fragment="+SELECT 2", + ), + ExampleCheckTestCase( + description="a console block that names no example fails", + page="```console\n$ sqlquack convert query.sql\nSELECT 1\n```\n", + homepage="", + printed=PRINTED, + expected_return_code=1, + expected_fragment="page.mdx:1: the block names no example", + ), + ExampleCheckTestCase( + description="a homepage terminal that names no example fails", + page="", + homepage='
sqlquack check
', + printed="", + expected_return_code=1, + expected_fragment="index.html:1: the block names no example", + ), + ExampleCheckTestCase( + description="an example without inputs fails", + page="{/* example: missing */}\n```console\n$ sqlquack convert query.sql\n```\n", + homepage="", + printed="", + expected_return_code=1, + expected_fragment="website/examples/missing does not exist", + ), + ExampleCheckTestCase( + description="a shown file that differs from the example's fails", + page="{/* example: orders file=query.sql */}\n```sql\nSELECT b\nFROM t\n```\n", + homepage="", + printed="", + expected_return_code=1, + expected_fragment="query.sql differs from the page", + ), + ExampleCheckTestCase( + description="a Python result comment that differs fails", + page="{/* example: no-inputs python */}\n```python\n1 + 1 # 3\n```\n", + homepage="", + printed="", + expected_return_code=1, + expected_fragment="line 1 shows 3, but gives 2", + ), + ), + ids=lambda case: case.description, +) +def test_given_pages_that_differ_from_real_output_when_checking_then_the_check_fails( + test_case: ExampleCheckTestCase, tmp_path: Path +) -> None: + code, messages = checked_site( + tmp_path=tmp_path, pages=(test_case.page, test_case.homepage), printed=test_case.printed + ) + assert code == test_case.expected_return_code, messages + assert test_case.expected_fragment in messages diff --git a/website/README.md b/website/README.md index 8a05a57cf..2224da61d 100644 --- a/website/README.md +++ b/website/README.md @@ -6,6 +6,9 @@ structure, styling and components with the SQLClean and SQLBuild websites. - `public/index.html` and `public/styles.css`: the homepage, plain static HTML and CSS. Its terminal examples are real `sqlquack` output on a small orders example, trimmed where marked `…`. +- `examples/`: the inputs of every example the site shows, one folder each. `make website-examples` + (part of `make check-ci`) runs each one with the built `sqlquack` and fails where a page shows + anything else, so an output change can't leave a stale example. See `examples/README.md`. - `src/content/docs/docs/`: the documentation pages (MDX). `src/sidebar.json` holds the sidebar and `src/navigation.mjs` the redirects. `STYLE.md` is the style guide for these pages. - `src/content/docs/docs/diagnostics/reference.mdx` is generated from diff --git a/website/examples/README.md b/website/examples/README.md new file mode 100644 index 000000000..c62d8c561 --- /dev/null +++ b/website/examples/README.md @@ -0,0 +1,34 @@ +# Website examples + +Each folder holds the input files of one example the website shows: SQL files, `sources/*.yml` +and `sqlquack.toml`. `make website-examples` copies the folder to a scratch directory, runs the +commands a page shows there with the built `sqlquack` first on `PATH`, and fails where the page +shows anything other than the real output. It also fails on any homepage terminal or docs +`console` block that names no example. + +A page names the example a block shows: + +- On the homepage, on the `
`: `
`.
+- In a docs page, on the line before the block: `{/* example: quickstart */}`.
+
+After the name, the marker says how to read the block:
+
+| Marker | The block shows |
+|--------|-----------------|
+| `name` | A session: each `$ command` line, then what it prints (standard output and error). |
+| `name preamble=FILE` | The same, after the contents of `FILE`. |
+| `name file=FILE` | The contents of `FILE`. |
+| `name output: COMMAND` | What `COMMAND` prints on standard output. |
+| `name python` | Python code: each `expression  # value` line shows the value it gives. |
+
+`no-inputs` is the name for an example that needs no files, such as `echo "…" | sqlquack check`.
+
+The page may shorten what it shows:
+
+- A line of only `…` stands for one or more lines.
+- `…` within a line stands for any text on that line.
+- A first line that comments the file's name (`-- div.sql, …` or `# sources/orders.yml`) labels the
+  file and is not part of it.
+- A command's leading progress line, such as `sqlquack convert: converting…`, may be left out.
+
+`pip install sqlquack` is shown but not run.
diff --git a/website/examples/census-chained/models/marts/customer_report.sql b/website/examples/census-chained/models/marts/customer_report.sql
new file mode 100644
index 000000000..74858da30
--- /dev/null
+++ b/website/examples/census-chained/models/marts/customer_report.sql
@@ -0,0 +1 @@
+SELECT customer_id, UPPER(name_sound) AS name_sound FROM __ref("customer_sounds")
diff --git a/website/examples/census-chained/models/marts/customer_sounds.sql b/website/examples/census-chained/models/marts/customer_sounds.sql
new file mode 100644
index 000000000..eda983ab4
--- /dev/null
+++ b/website/examples/census-chained/models/marts/customer_sounds.sql
@@ -0,0 +1,4 @@
+SELECT
+    customer_id,
+    SOUNDEX(name) AS name_sound
+FROM __ref("stg_customers")
diff --git a/website/examples/census-chained/models/staging/stg_customers.sql b/website/examples/census-chained/models/staging/stg_customers.sql
new file mode 100644
index 000000000..39689a69f
--- /dev/null
+++ b/website/examples/census-chained/models/staging/stg_customers.sql
@@ -0,0 +1 @@
+SELECT customer_id, name FROM customers
diff --git a/website/examples/census-chained/models/staging/stg_orders.sql b/website/examples/census-chained/models/staging/stg_orders.sql
new file mode 100644
index 000000000..221fe14c3
--- /dev/null
+++ b/website/examples/census-chained/models/staging/stg_orders.sql
@@ -0,0 +1 @@
+SELECT order_id, customer_id, WEEKISO(ordered_at) AS order_week FROM orders
diff --git a/website/examples/census-chained/sources/shop.yml b/website/examples/census-chained/sources/shop.yml
new file mode 100644
index 000000000..d41e4a794
--- /dev/null
+++ b/website/examples/census-chained/sources/shop.yml
@@ -0,0 +1,21 @@
+sources:
+  - name: orders
+    columns:
+      - name: order_id
+        type: NUMBER(38,0)
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: ordered_at
+        type: TIMESTAMP_NTZ
+  - name: customers
+    columns:
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: name
+        type: VARCHAR
+  - name: __sqlquack_relation__customer_sounds
+    columns:
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: name_sound
+        type: VARCHAR
diff --git a/website/examples/census-report/models/marts/customer_report.sql b/website/examples/census-report/models/marts/customer_report.sql
new file mode 100644
index 000000000..74858da30
--- /dev/null
+++ b/website/examples/census-report/models/marts/customer_report.sql
@@ -0,0 +1 @@
+SELECT customer_id, UPPER(name_sound) AS name_sound FROM __ref("customer_sounds")
diff --git a/website/examples/census-report/models/marts/customer_sounds.sql b/website/examples/census-report/models/marts/customer_sounds.sql
new file mode 100644
index 000000000..eda983ab4
--- /dev/null
+++ b/website/examples/census-report/models/marts/customer_sounds.sql
@@ -0,0 +1,4 @@
+SELECT
+    customer_id,
+    SOUNDEX(name) AS name_sound
+FROM __ref("stg_customers")
diff --git a/website/examples/census-report/models/staging/stg_customers.sql b/website/examples/census-report/models/staging/stg_customers.sql
new file mode 100644
index 000000000..39689a69f
--- /dev/null
+++ b/website/examples/census-report/models/staging/stg_customers.sql
@@ -0,0 +1 @@
+SELECT customer_id, name FROM customers
diff --git a/website/examples/census-report/models/staging/stg_orders.sql b/website/examples/census-report/models/staging/stg_orders.sql
new file mode 100644
index 000000000..221fe14c3
--- /dev/null
+++ b/website/examples/census-report/models/staging/stg_orders.sql
@@ -0,0 +1 @@
+SELECT order_id, customer_id, WEEKISO(ordered_at) AS order_week FROM orders
diff --git a/website/examples/census-report/sources/shop.yml b/website/examples/census-report/sources/shop.yml
new file mode 100644
index 000000000..81befbb19
--- /dev/null
+++ b/website/examples/census-report/sources/shop.yml
@@ -0,0 +1,15 @@
+sources:
+  - name: orders
+    columns:
+      - name: order_id
+        type: NUMBER(38,0)
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: ordered_at
+        type: TIMESTAMP_NTZ
+  - name: customers
+    columns:
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: name
+        type: VARCHAR
diff --git a/website/examples/census/models/marts/customer_sounds.sql b/website/examples/census/models/marts/customer_sounds.sql
new file mode 100644
index 000000000..eda983ab4
--- /dev/null
+++ b/website/examples/census/models/marts/customer_sounds.sql
@@ -0,0 +1,4 @@
+SELECT
+    customer_id,
+    SOUNDEX(name) AS name_sound
+FROM __ref("stg_customers")
diff --git a/website/examples/census/models/staging/stg_customers.sql b/website/examples/census/models/staging/stg_customers.sql
new file mode 100644
index 000000000..39689a69f
--- /dev/null
+++ b/website/examples/census/models/staging/stg_customers.sql
@@ -0,0 +1 @@
+SELECT customer_id, name FROM customers
diff --git a/website/examples/census/models/staging/stg_orders.sql b/website/examples/census/models/staging/stg_orders.sql
new file mode 100644
index 000000000..221fe14c3
--- /dev/null
+++ b/website/examples/census/models/staging/stg_orders.sql
@@ -0,0 +1 @@
+SELECT order_id, customer_id, WEEKISO(ordered_at) AS order_week FROM orders
diff --git a/website/examples/census/sources/shop.yml b/website/examples/census/sources/shop.yml
new file mode 100644
index 000000000..81befbb19
--- /dev/null
+++ b/website/examples/census/sources/shop.yml
@@ -0,0 +1,15 @@
+sources:
+  - name: orders
+    columns:
+      - name: order_id
+        type: NUMBER(38,0)
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: ordered_at
+        type: TIMESTAMP_NTZ
+  - name: customers
+    columns:
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: name
+        type: VARCHAR
diff --git a/website/examples/division/div.sql b/website/examples/division/div.sql
new file mode 100644
index 000000000..9a4e23d7e
--- /dev/null
+++ b/website/examples/division/div.sql
@@ -0,0 +1 @@
+SELECT order_id, total / 3 AS third FROM orders
diff --git a/website/examples/division/sources/orders.yml b/website/examples/division/sources/orders.yml
new file mode 100644
index 000000000..e495c99b4
--- /dev/null
+++ b/website/examples/division/sources/orders.yml
@@ -0,0 +1,13 @@
+sources:
+  - name: orders
+    columns:
+      - name: order_id
+        type: NUMBER(38,0)
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: status
+        type: VARCHAR
+      - name: total
+        type: NUMBER(12,2)
+      - name: ordered_at
+        type: TIMESTAMP_NTZ
diff --git a/website/examples/hash-policy/due.sql b/website/examples/hash-policy/due.sql
new file mode 100644
index 000000000..c3bd2bdf6
--- /dev/null
+++ b/website/examples/hash-policy/due.sql
@@ -0,0 +1,3 @@
+SELECT order_id,
+       HASH(customer_id) AS bucket
+FROM orders
diff --git a/website/examples/hash-policy/sources/orders.yml b/website/examples/hash-policy/sources/orders.yml
new file mode 100644
index 000000000..e495c99b4
--- /dev/null
+++ b/website/examples/hash-policy/sources/orders.yml
@@ -0,0 +1,13 @@
+sources:
+  - name: orders
+    columns:
+      - name: order_id
+        type: NUMBER(38,0)
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: status
+        type: VARCHAR
+      - name: total
+        type: NUMBER(12,2)
+      - name: ordered_at
+        type: TIMESTAMP_NTZ
diff --git a/website/examples/hash-policy/sqlquack.toml b/website/examples/hash-policy/sqlquack.toml
new file mode 100644
index 000000000..2da95b2ad
--- /dev/null
+++ b/website/examples/hash-policy/sqlquack.toml
@@ -0,0 +1,2 @@
+[allow]
+hash = true
diff --git a/website/examples/helper-macros/sources/events.yml b/website/examples/helper-macros/sources/events.yml
new file mode 100644
index 000000000..f7ab8332d
--- /dev/null
+++ b/website/examples/helper-macros/sources/events.yml
@@ -0,0 +1,5 @@
+sources:
+  - name: events
+    columns:
+      - name: payload
+        type: VARIANT
diff --git a/website/examples/helper-macros/staging.sql b/website/examples/helper-macros/staging.sql
new file mode 100644
index 000000000..5ec5f75f5
--- /dev/null
+++ b/website/examples/helper-macros/staging.sql
@@ -0,0 +1 @@
+SELECT payload:customer_id::VARCHAR AS customer_id FROM events
diff --git a/website/examples/intersect/query.sql b/website/examples/intersect/query.sql
new file mode 100644
index 000000000..974207083
--- /dev/null
+++ b/website/examples/intersect/query.sql
@@ -0,0 +1 @@
+SELECT order_id FROM orders INTERSECT ALL SELECT order_id FROM orders
diff --git a/website/examples/no-sources/revenue.sql b/website/examples/no-sources/revenue.sql
new file mode 100644
index 000000000..71536cae3
--- /dev/null
+++ b/website/examples/no-sources/revenue.sql
@@ -0,0 +1,4 @@
+SELECT customer_id, SUM(total) AS revenue
+FROM orders
+WHERE status = 'shipped'
+GROUP BY customer_id
diff --git a/website/examples/project-untyped/revenue.sql b/website/examples/project-untyped/revenue.sql
new file mode 100644
index 000000000..efebd2926
--- /dev/null
+++ b/website/examples/project-untyped/revenue.sql
@@ -0,0 +1,3 @@
+SELECT status, SUM(total) AS revenue
+FROM orders
+GROUP BY status
diff --git a/website/examples/project-untyped/sources/more.yml b/website/examples/project-untyped/sources/more.yml
new file mode 100644
index 000000000..f17750aa7
--- /dev/null
+++ b/website/examples/project-untyped/sources/more.yml
@@ -0,0 +1,6 @@
+sources:
+  - name: customers
+    columns:
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: email
diff --git a/website/examples/project-untyped/sources/shop.yml b/website/examples/project-untyped/sources/shop.yml
new file mode 100644
index 000000000..b21c15746
--- /dev/null
+++ b/website/examples/project-untyped/sources/shop.yml
@@ -0,0 +1,9 @@
+sources:
+  - name: orders
+    columns:
+      - name: order_id
+        type: NUMBER(38,0)
+      - name: status
+        type: VARCHAR
+      - name: total
+        type: NUMBER(12,2)
diff --git a/website/examples/project/revenue.sql b/website/examples/project/revenue.sql
new file mode 100644
index 000000000..efebd2926
--- /dev/null
+++ b/website/examples/project/revenue.sql
@@ -0,0 +1,3 @@
+SELECT status, SUM(total) AS revenue
+FROM orders
+GROUP BY status
diff --git a/website/examples/project/sources/shop.yml b/website/examples/project/sources/shop.yml
new file mode 100644
index 000000000..b21c15746
--- /dev/null
+++ b/website/examples/project/sources/shop.yml
@@ -0,0 +1,9 @@
+sources:
+  - name: orders
+    columns:
+      - name: order_id
+        type: NUMBER(38,0)
+      - name: status
+        type: VARCHAR
+      - name: total
+        type: NUMBER(12,2)
diff --git a/website/examples/quickstart/orders.sql b/website/examples/quickstart/orders.sql
new file mode 100644
index 000000000..f7f3993af
--- /dev/null
+++ b/website/examples/quickstart/orders.sql
@@ -0,0 +1,5 @@
+SELECT customer_id, SUM(total) AS revenue
+FROM orders
+WHERE status = 'shipped'
+GROUP BY customer_id
+QUALIFY revenue > 100
diff --git a/website/examples/quickstart/revenue.sql b/website/examples/quickstart/revenue.sql
new file mode 100644
index 000000000..71536cae3
--- /dev/null
+++ b/website/examples/quickstart/revenue.sql
@@ -0,0 +1,4 @@
+SELECT customer_id, SUM(total) AS revenue
+FROM orders
+WHERE status = 'shipped'
+GROUP BY customer_id
diff --git a/website/examples/quickstart/sources/orders.yml b/website/examples/quickstart/sources/orders.yml
new file mode 100644
index 000000000..e495c99b4
--- /dev/null
+++ b/website/examples/quickstart/sources/orders.yml
@@ -0,0 +1,13 @@
+sources:
+  - name: orders
+    columns:
+      - name: order_id
+        type: NUMBER(38,0)
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: status
+        type: VARCHAR
+      - name: total
+        type: NUMBER(12,2)
+      - name: ordered_at
+        type: TIMESTAMP_NTZ
diff --git a/website/examples/run/data/orders.csv b/website/examples/run/data/orders.csv
new file mode 100644
index 000000000..66d9c8188
--- /dev/null
+++ b/website/examples/run/data/orders.csv
@@ -0,0 +1,3 @@
+id,amount
+1,2.5
+2,4
diff --git a/website/examples/run/doubled.sql b/website/examples/run/doubled.sql
new file mode 100644
index 000000000..2b4c56535
--- /dev/null
+++ b/website/examples/run/doubled.sql
@@ -0,0 +1,3 @@
+SELECT id, amount * 2 AS doubled
+FROM orders
+ORDER BY id
diff --git a/website/examples/run/sources/orders.yml b/website/examples/run/sources/orders.yml
new file mode 100644
index 000000000..66db708f8
--- /dev/null
+++ b/website/examples/run/sources/orders.yml
@@ -0,0 +1,7 @@
+sources:
+  - name: orders
+    columns:
+      - name: id
+        type: INTEGER
+      - name: amount
+        type: NUMBER(10,2)
diff --git a/website/examples/sessions/orders.sql b/website/examples/sessions/orders.sql
new file mode 100644
index 000000000..f77103028
--- /dev/null
+++ b/website/examples/sessions/orders.sql
@@ -0,0 +1 @@
+SELECT order_id FROM orders
diff --git a/website/examples/sessions/sources/orders.yml b/website/examples/sessions/sources/orders.yml
new file mode 100644
index 000000000..e495c99b4
--- /dev/null
+++ b/website/examples/sessions/sources/orders.yml
@@ -0,0 +1,13 @@
+sources:
+  - name: orders
+    columns:
+      - name: order_id
+        type: NUMBER(38,0)
+      - name: customer_id
+        type: NUMBER(38,0)
+      - name: status
+        type: VARCHAR
+      - name: total
+        type: NUMBER(12,2)
+      - name: ordered_at
+        type: TIMESTAMP_NTZ
diff --git a/website/public/index.html b/website/public/index.html
index 3a076457c..f8b48696e 100644
--- a/website/public/index.html
+++ b/website/public/index.html
@@ -139,14 +139,15 @@ 

Catch what the warehouse would reject

Snowflake today: parses Snowflake SQL and reports the syntax Snowflake would reject. No schema needed. Each error has a code and the exact span; rejections also come with a fix.

How checking works →

-
sqlquack check
+
sqlquack check query.sql
 error[SQ0201]: Snowflake does not support INTERSECT, EXCEPT or MINUS with ALL
- --> <stdin>:1:29
+ --> query.sql:1:29
   |
 1 | SELECT order_id FROM orders INTERSECT ALL SELECT order_id FROM orders
   |                             ^^^^^^^^^^^^^ Snowflake does not support INTERSECT with ALL
   |
-  = help: drop ALL to compare distinct rows; only UNION accepts ALL in Snowflake
+ = help: drop ALL to compare distinct rows; only UNION accepts ALL in Snowflake +sqlquack check: found 1 problem
@@ -156,7 +157,7 @@

DuckDB SQL that keeps Snowflake's meaning

Uses your sources' types and only verified rules. NUMBER(12,2) / 3 keeps Snowflake's 8 decimal places.

How conversion works →

-
-- div.sql, with TOTAL as NUMBER(12,2) in sources/orders.yml
+
-- div.sql, with TOTAL as NUMBER(12,2) in sources/orders.yml
 SELECT order_id, total / 3 AS third FROM orders
 
 sqlquack convert div.sql --no-config
@@ -165,20 +166,12 @@ 

DuckDB SQL that keeps Snowflake's meaning

CAST( CAST( ( - sign(CAST(CAST("ORDERS"."TOTAL" AS DECIMAL(38, 2)) * 100000000 AS HUGEINT)) - * ( - ( - 2 - * abs(CAST(CAST("ORDERS"."TOTAL" AS DECIMAL(38, 2)) * 100000000 AS HUGEINT)) - + 3 - ) - // 6 - ) + (CAST(CAST("ORDERS"."TOTAL" AS DECIMAL(38, 2)) * 100000000 AS HUGEINT) * 10) // 3 ) AS DECIMAL(38, 0) ) - * 0.00000001 AS DECIMAL(18, 8) + * 0.000000001 AS DECIMAL(18, 8) ) AS "THIRD" -FROM "ORDERS" AS "ORDERS" +FROM "ORDERS" sqlquack convert: done, converted
@@ -189,21 +182,17 @@

A refusal you can act on

No verified rule, no conversion. The refusal underlines the construct and says what to change.

Every diagnostic code →

-
sqlquack convert due.sql --no-config
+
sqlquack convert due.sql --no-config
 error[SQ0008]: HASH gives a different value in DuckDB
  --> due.sql:2:8
   |
 2 |        HASH(customer_id) AS bucket
-  |        ^^^^^^^^^^^^^^^^^ DuckDB computes its own hash,
-  |          never Snowflake's
+  |        ^^^^^^^^^^^^^^^^^ DuckDB computes its own hash, never Snowflake's
   |
   = note: Equal inputs still get equal hashes within one run.
-  = note: fine when: Joins, grouping, removing duplicates and
-          spotting changed rows by hash.
-  = note: wrong when: Storing, comparing or sorting by the hash
-          value itself: it differs, with no error.
-  = help: allow it in a sqlquack.toml …;
-          `sqlquack explain hash` says when it is safe
+  = note: fine when: Joins, grouping, removing duplicates …
+  = note: wrong when: Storing, comparing or sorting by the hash …
+  = help: allow it with hash = true under [allow] …
 sqlquack convert: refused, 1 refusal
@@ -214,17 +203,18 @@

Known differences are your call

Some Snowflake behaviour has no exact match in DuckDB, like HASH. Each known difference says when it's fine and when it gives a wrong result. You refuse it, allow it or replace it with your own SQL.

Refuse, allow or replace →

-
# sqlquack.toml
+
# sqlquack.toml
 [allow]
 hash = true
 
 sqlquack convert due.sql
 SELECT
     "ORDERS"."ORDER_ID" AS "ORDER_ID",
-    … AS "BUCKET"
+    CAST(
+        …
+    ) AS "BUCKET"
 FROM "ORDERS"
-sqlquack convert: done, converted (1 known difference
-  allowed: hash — sqlquack explain hash)
+sqlquack convert: done, converted (1 known difference allowed: hash …)
@@ -234,7 +224,7 @@

See what a whole project needs

Point it at a folder of compiled SQL, such as dbt's target/compiled. It shows a diagnostic for each file that doesn't convert, and how many do. It exits 1 when any file is blocked, so CI can track it.

Run a census →

-
sqlquack census models --no-config --chain-models
+
sqlquack census models --no-config --chain-models
 error[SQ0002]: SQLQuack can't convert SOUNDEX yet
  --> models/marts/customer_sounds.sql:3:5
   |
@@ -246,7 +236,8 @@ 

See what a whole project needs

… Converted 1 of 3 files (33%) -Blocked: 2 files, 2 causes (SQ0002 SOUNDEX, SQ0002 WEEKISO)
+Blocked: 2 files, 2 causes (SQ0002 SOUNDEX, SQ0002 WEEKISO) +sqlquack census: done, 3 files in … s
@@ -256,7 +247,7 @@

The same engine, as a library

The same engine as the CLI, with typed results and diagnostics.

Python API →

-
import sqlquack
+
import sqlquack
 
 result = sqlquack.check(sql="SELECT 1 QUALIFY TRUE")
 result.diagnostics[0].code   # "SQ0203"
@@ -315,7 +306,7 @@ 

Start in a minute

  • Free and open source, Apache-2.0.
  • -
    pip install sqlquack
    +
    pip install sqlquack
     echo "SELECT 1 QUALIFY TRUE" | sqlquack check
     error[SQ0203]: QUALIFY needs a window function
     …
    diff --git a/website/src/content/docs/docs/cli/census.mdx b/website/src/content/docs/docs/cli/census.mdx
    index f1d9e325c..5ea06e22a 100644
    --- a/website/src/content/docs/docs/cli/census.mdx
    +++ b/website/src/content/docs/docs/cli/census.mdx
    @@ -27,6 +27,7 @@ recognised. A directory is searched for `.sql` files. The tables they read come
     `database.schema.table`; see [Projects](/docs/project/#naming-tables) for how
     they resolve.
     
    +{/* example: census */}
     ```console
     $ sqlquack census models --no-config
     error[SQ0004]: SQLQuack doesn't know this name
    @@ -45,6 +46,7 @@ error[SQ0002]: SQLQuack can't convert WEEKISO yet
     
     Converted 1 of 3 files (33%)
     Blocked: 2 files, 2 causes (SQ0002 WEEKISO, SQ0004 STG_CUSTOMERS)
    +sqlquack census: done, 3 files in … s
     ```
     
     Each diagnostic has the same code, message and help that [`convert`](/docs/cli/convert/) gives
    @@ -60,6 +62,7 @@ the [project](/docs/project/) declares that model's columns. When the model it r
     convert either, its diagnostic carries a note naming that model, and it isn't counted as a separate
     cause:
     
    +{/* example: census-report output: sqlquack census models --no-config */}
     ```text
     error[SQ0004]: SQLQuack doesn't know this name
      --> models/marts/customer_report.sql:1:58
    @@ -69,7 +72,7 @@ error[SQ0004]: SQLQuack doesn't know this name
       |
       = note: reads `customer_sounds`, which doesn't convert
       = help: declare the relation and its columns in a source file of the project (`sources/*.yml`)
    -...
    +…
     Converted 1 of 4 files (25%)
     Blocked: 3 files, 2 causes (SQ0002 WEEKISO, SQ0004 STG_CUSTOMERS)
     ```
    @@ -79,7 +82,9 @@ name references, read by any qualifier as dbt writes it, and the files reading i
     those columns. With `--chain-models`, census also warns about each file that converts while reading
     a model that doesn't, which happens when the project already types that model:
     
    +{/* example: census-chained output: sqlquack census models --no-config --chain-models */}
     ```text
    +…
     warning: models/marts/customer_report.sql converts, but reads customer_sounds, which doesn't
      --> models/marts/customer_report.sql
     
    @@ -109,18 +114,21 @@ refusals by category and construct, and what blocks files through the model grap
     - `--anonymous` holds counts and construct names only, never SQL text or file, model or relation
       names, so you can share it. With both flags, the report stays anonymous.
     
    +{/* example: census */}
     ```console
     $ sqlquack census models --no-config --anonymous
     Census of 3 snowflake SQL files
       parsed 3 (3 statements), unparsed 0, empty 0
       distinct constructs 6 (2 fn, 4 node)
    -  files refused: missing rule 2, outside type conditions 0, unresolved name 0, not expressible 0, parse fidelity 0, conversion budget 0, divergence refused 0
    +  files refused: missing rule 1, outside type conditions 0, unresolved name 1, not expressible 0, parse fidelity 0, conversion budget 0, known difference not allowed 0
       convertible: strict 1 (every model upstream converts too), unit-testable 1 (the file's own SQL converts; 0 with an upstream model refused or not scanned)
       with no named assumption: strict 1, unit-testable 1 (relying on one: none)
     
     Refusals by category and construct (top 50)
    -       1  missing rule: fn:SOUNDEX
            1  missing rule: fn:WEEKISO
    +       1  unresolved name: statement
    +…
    +sqlquack census: done, 3 files in … s
     ```
     
     | Count | Meaning |
    diff --git a/website/src/content/docs/docs/cli/check.mdx b/website/src/content/docs/docs/cli/check.mdx
    index b6c47ee8e..57413d4b1 100644
    --- a/website/src/content/docs/docs/cli/check.mdx
    +++ b/website/src/content/docs/docs/cli/check.mdx
    @@ -21,6 +21,7 @@ echo "SELECT 1 QUALIFY TRUE" | sqlquack check --json
     
     `PATH` is a SQL file. Without one, or with `-`, `check` reads standard input.
     
    +{/* example: intersect */}
     ```console
     $ sqlquack check query.sql
     error[SQ0201]: Snowflake does not support INTERSECT, EXCEPT or MINUS with ALL
    diff --git a/website/src/content/docs/docs/cli/convert.mdx b/website/src/content/docs/docs/cli/convert.mdx
    index 2a0730269..6b35e9c93 100644
    --- a/website/src/content/docs/docs/cli/convert.mdx
    +++ b/website/src/content/docs/docs/cli/convert.mdx
    @@ -25,6 +25,7 @@ to standard output, laid out with each clause on its own line, select items one
     nested queries and long `CASE` expressions indented; short statements stay on one line. Progress,
     the known differences and assumptions it relies on, and refusals go to standard error.
     
    +{/* example: quickstart */}
     ```console
     $ sqlquack convert revenue.sql --no-config
     SELECT
    @@ -76,6 +77,7 @@ SQL that does not parse, or that Snowflake rejects, is refused with the same cod
     
     With `--json`, `convert` prints one object:
     
    +{/* example: no-inputs output: echo "SELECT 1 AS total" | sqlquack convert --no-config --json */}
     ```json
     {
       "converted": true,
    diff --git a/website/src/content/docs/docs/cli/run.mdx b/website/src/content/docs/docs/cli/run.mdx
    index 8fd081e31..4e4cb6793 100644
    --- a/website/src/content/docs/docs/cli/run.mdx
    +++ b/website/src/content/docs/docs/cli/run.mdx
    @@ -13,6 +13,7 @@ test. DuckDB comes with `sqlquack`, so there is nothing else to install.
     
     Take a [project](/docs/project/) with one source:
     
    +{/* example: run file=sources/orders.yml */}
     ```yaml
     # sources/orders.yml
     sources:
    @@ -26,6 +27,7 @@ sources:
     
     and a query in `doubled.sql`:
     
    +{/* example: run file=doubled.sql */}
     ```sql
     SELECT id, amount * 2 AS doubled
     FROM orders
    @@ -34,6 +36,7 @@ ORDER BY id
     
     Give `orders` two rows and run it:
     
    +{/* example: run */}
     ```console
     $ sqlquack run doubled.sql --fixture 'orders=[[1, 2.5], [2, 4]]'
     ID  DOUBLED
    @@ -53,6 +56,7 @@ its whole `database.schema.table` name when two sources share a name. Case does
     Rows are a JSON list. A row is either a list of values in column order, or an object naming the
     columns it sets, the rest NULL:
     
    +{/* example: run */}
     ```console
     $ sqlquack run doubled.sql --fixture 'orders=[{"id": 1, "amount": 2.5}, {"id": 2}]'
     ID  DOUBLED
    @@ -64,6 +68,7 @@ sqlquack run: done, 2 rows
     A value that contains a `/` is a file instead: a CSV file with a header row, or a Parquet file.
     Its columns fill the table's columns of the same name.
     
    +{/* example: run */}
     ```console
     $ cat data/orders.csv
     id,amount
    @@ -83,6 +88,7 @@ Write `./orders.csv` rather than `orders.csv`, so the value holds a `/`.
     `--expect` gives the rows the result must hold, written the same way as fixture rows. Each value
     is cast to the result column's type before comparing, so `5` matches `5.00`:
     
    +{/* example: run */}
     ```console
     $ sqlquack run doubled.sql --fixture 'orders=[[1, 2.5], [2, 4]]' --expect '[[1, 5], [2, 8]]'
     ID  DOUBLED
    @@ -94,6 +100,7 @@ sqlquack run: done, 2 rows as expected
     When the query has an `ORDER BY`, the rows must come in the same order. Otherwise they may come
     in any order. A difference exits 1 and shows where:
     
    +{/* example: run */}
     ```console
     $ sqlquack run doubled.sql --fixture 'orders=[[1, 2.5], [2, 4]]' --expect '[[1, 5], [2, 9]]'
     ID  DOUBLED
    diff --git a/website/src/content/docs/docs/helper-macros.mdx b/website/src/content/docs/docs/helper-macros.mdx
    index 3299527aa..2af22b032 100644
    --- a/website/src/content/docs/docs/helper-macros.mdx
    +++ b/website/src/content/docs/docs/helper-macros.mdx
    @@ -8,17 +8,23 @@ Converted SQL that reads a VARIANT or date and time text, or divides wide decima
     `convert` prints the statements creating the macros a query calls ahead of the query, so its
     output runs as it is in any DuckDB session:
     
    +{/* example: helper-macros */}
     ```console
     $ sqlquack convert staging.sql --no-config
     CREATE SCHEMA IF NOT EXISTS sqlquack;
    -CREATE OR REPLACE MACRO sqlquack.json_escaped_v1(quack_text) AS ...;
    -CREATE OR REPLACE MACRO sqlquack.variant_text_v1(quack_site, quack_value) AS ...;
    +CREATE OR REPLACE MACRO sqlquack.json_read_v1(
    +…
    +CREATE OR REPLACE MACRO sqlquack.variant_text_v1(quack_site, quack_value) AS list_transform(
    +…
     SELECT
         sqlquack.variant_text_v1(
             '#0d01742fedea',
             json_extract("EVENTS"."PAYLOAD", '$."customer_id"')
         ) AS "CUSTOMER_ID"
    -FROM ...
    +FROM (
    +…
    +) AS "EVENTS"
    +sqlquack convert: done, converted (1 known difference allowed: json_fidelity — sqlquack explain json_fidelity)
     ```
     
     A query that calls no helper macro prints no setup statements.
    diff --git a/website/src/content/docs/docs/index.mdx b/website/src/content/docs/docs/index.mdx
    index aa7096ade..c5e245f33 100644
    --- a/website/src/content/docs/docs/index.mdx
    +++ b/website/src/content/docs/docs/index.mdx
    @@ -13,6 +13,7 @@ against results recorded on Snowflake. Anything no rule covers is refused with a
     span and a reason. Other dialects have parsers but don't convert yet; see
     [Dialects](/docs/coverage/#dialects).
     
    +{/* example: no-sources */}
     ```console
     $ sqlquack convert revenue.sql --no-config
     error[SQ0004]: SQLQuack doesn't know this name
    @@ -22,10 +23,12 @@ error[SQ0004]: SQLQuack doesn't know this name
       |      ^^^^^^ relation `ORDERS` has no known columns
       |
       = help: declare the relation and its columns in a source file of the project (`sources/*.yml`)
    +sqlquack convert: refused, 1 refusal
     ```
     
     Once `sources/orders.yml` declares `ORDERS`, the same file converts:
     
    +{/* example: quickstart */}
     ```console
     $ sqlquack convert revenue.sql --no-config
     SELECT
    diff --git a/website/src/content/docs/docs/policy.mdx b/website/src/content/docs/docs/policy.mdx
    index ff6cc7fbf..bc8fd829f 100644
    --- a/website/src/content/docs/docs/policy.mdx
    +++ b/website/src/content/docs/docs/policy.mdx
    @@ -30,6 +30,7 @@ that runs in UTC, and the `TIMESTAMP_TZ` offsets the schema declares.
     
     A refused known difference stops the statement at the construct that needs it:
     
    +{/* example: hash-policy */}
     ```console
     $ sqlquack convert due.sql --no-config
     error[SQ0008]: HASH gives a different value in DuckDB
    @@ -71,6 +72,7 @@ Allowing a known difference is a decision about your data, so read its entry fir
     the converted SQL gives Snowflake's result and when it doesn't. List it under `[allow]` in
     `sqlquack.toml`, `true` to allow it and `false` to refuse it:
     
    +{/* example: hash-policy file=sqlquack.toml */}
     ```toml
     [allow]
     hash = true
    @@ -100,6 +102,7 @@ current_time = false
     A conversion that relies on an allowed known difference names it in its last line on standard
     error, and `--verbose` adds a warning at each use:
     
    +{/* example: hash-policy */}
     ```console
     $ sqlquack convert due.sql
     SELECT
    diff --git a/website/src/content/docs/docs/project.mdx b/website/src/content/docs/docs/project.mdx
    index 34e9bdf63..5ca687dba 100644
    --- a/website/src/content/docs/docs/project.mdx
    +++ b/website/src/content/docs/docs/project.mdx
    @@ -8,6 +8,7 @@ it. You declare them once in a project folder, and every command run there reads
     
     A project is a folder holding a `sources/` folder of YAML files. Here is one:
     
    +{/* example: project file=sources/shop.yml */}
     ```yaml
     # sources/shop.yml
     sources:
    @@ -23,6 +24,7 @@ sources:
     
     Run `convert` in the folder and the query's table is known:
     
    +{/* example: project */}
     ```console
     $ sqlquack convert revenue.sql
     sqlquack convert: converting…
    @@ -48,8 +50,12 @@ A source with an `expression` is a query rather than a table, and is skipped.
     A source with a column that has no `type`, or a type SQLQuack can't read, is left out whole, so a
     `SELECT *` never misses a column. SQLQuack warns about it:
     
    +{/* example: project-untyped */}
     ```console
    +$ sqlquack convert revenue.sql
    +…
     sqlquack convert: warning: ./sources/more.yml: the source customers is left out, because its column email has no type
    +sqlquack convert: done, converted
     ```
     
     A table declared in two files is an error naming both.
    diff --git a/website/src/content/docs/docs/python.mdx b/website/src/content/docs/docs/python.mdx
    index 6de02a186..92e31d6f9 100644
    --- a/website/src/content/docs/docs/python.mdx
    +++ b/website/src/content/docs/docs/python.mdx
    @@ -7,6 +7,7 @@ The `sqlquack` Python package runs the same code as the command line. `check` an
     frozen results with typed diagnostics, the text the command line renders, and, for `convert`, its
     exact `--json` report.
     
    +{/* example: no-inputs python */}
     ```python
     import sqlquack
     
    diff --git a/website/src/content/docs/docs/quickstart.mdx b/website/src/content/docs/docs/quickstart.mdx
    index 72d61ae55..3a9a5f657 100644
    --- a/website/src/content/docs/docs/quickstart.mdx
    +++ b/website/src/content/docs/docs/quickstart.mdx
    @@ -44,6 +44,7 @@ Use `DYLD_LIBRARY_PATH` on macOS and `PATH` on Windows.
     
     `check` needs no schema. It parses the SQL and reports what Snowflake would reject.
     
    +{/* example: quickstart file=orders.sql */}
     ```sql
     -- orders.sql
     SELECT customer_id, SUM(total) AS revenue
    @@ -53,6 +54,7 @@ GROUP BY customer_id
     QUALIFY revenue > 100
     ```
     
    +{/* example: quickstart */}
     ```console
     $ sqlquack check orders.sql
     error[SQ0203]: QUALIFY needs a window function
    @@ -73,6 +75,7 @@ Conversion types every expression, so it needs the columns and Snowflake types o
     statement reads. Declare them in a source file under `sources/` in the folder you run `sqlquack`
     from (see [Projects](/docs/project/)):
     
    +{/* example: quickstart file=sources/orders.yml */}
     ```yaml
     # sources/orders.yml
     sources:
    @@ -90,6 +93,7 @@ sources:
             type: TIMESTAMP_NTZ
     ```
     
    +{/* example: quickstart */}
     ```console
     $ sqlquack convert revenue.sql --no-config
     SELECT
    diff --git a/website/src/content/docs/docs/sessions.mdx b/website/src/content/docs/docs/sessions.mdx
    index ff0dee1b9..bd5aaef7f 100644
    --- a/website/src/content/docs/docs/sessions.mdx
    +++ b/website/src/content/docs/docs/sessions.mdx
    @@ -37,6 +37,7 @@ session without `TIMEZONE`, or with `TIMEZONE = "UTC"`, says. The defaults allow
     
     A `TIMEZONE` other than UTC refuses them, in every mode, and a note says so:
     
    +{/* example: sessions */}
     ```console
     $ sqlquack convert orders.sql --session TIMEZONE=Europe/London
     SELECT "ORDERS"."ORDER_ID" AS "ORDER_ID"
    
    From 6418ba4d8970e3559710ab3c5dd8ca25a160cda5 Mon Sep 17 00:00:00 2001
    From: Kevin Longe <273747162+kvlonge@users.noreply.github.com>
    Date: Wed, 25 Nov 2026 17:17:55 +0000
    Subject: [PATCH 5/8] perf(convert): write VARIANT text through version-2
     macros that escape once
    
    variant_text_v1 and variant_json_text_v1 called json_escaped_v1 on each text
    they might write, and DuckDB pastes a macro's body in at every call, so every
    VARIANT written as text bound the escaping twice. variant_text_v2 and
    variant_json_text_v2 choose the text first and escape it once. A number or
    boolean, which escaping never changes, is written as it is. Results are
    those of version 1, which stays for SQL converted by earlier releases; both
    new definitions are pinned.
    ---
     .../src/macros/_helpers/registry.rs           |  24 ++-
     .../src/macros/_helpers/writing.rs            |  53 +++++-
     .../sqlquack-blocks/src/macros/constants.rs   |   4 +
     crates/sqlquack-blocks/src/macros/tests.rs    |   4 +
     .../src/macros/tests/helpers.rs               |  57 +++++++
     .../macros/tests/test_helper_statements.rs    |  10 ++
     .../src/macros/tests/test_types.rs            |  17 ++
     .../src/macros/tests/test_variant_text.rs     | 156 ++++++++++++++++++
     .../src/semi_structured/_helpers/writing.rs   |   6 +-
     .../src/content/docs/docs/helper-macros.mdx   |  18 +-
     10 files changed, 328 insertions(+), 21 deletions(-)
     create mode 100644 crates/sqlquack-blocks/src/macros/tests/helpers.rs
     create mode 100644 crates/sqlquack-blocks/src/macros/tests/test_variant_text.rs
    
    diff --git a/crates/sqlquack-blocks/src/macros/_helpers/registry.rs b/crates/sqlquack-blocks/src/macros/_helpers/registry.rs
    index 76303dc7f..25a9580ff 100644
    --- a/crates/sqlquack-blocks/src/macros/_helpers/registry.rs
    +++ b/crates/sqlquack-blocks/src/macros/_helpers/registry.rs
    @@ -10,7 +10,7 @@ use crate::macros::_helpers::temporal::{
         timestamp_body, utc_zoned_body, zone_name_body, zoned_body,
     };
     use crate::macros::_helpers::writing::{
    -    escaped_body, held_written_body, json_text_body, text_body,
    +    escaped_body, held_written_body, json_text_body, json_text_body_v2, text_body, text_body_v2,
     };
     use crate::macros::constants::{
         DATE_TEXT_V1, DECIMAL_QUOTIENT_V1, DIVIDEND_PARAMETER, DIVISOR_PARAMETER, HELPER_CALL_PREFIX,
    @@ -19,13 +19,13 @@ use crate::macros::constants::{
         TEXT_PARAMETER, TIME_ZONE_V1, TIMESTAMP_TEXT_V1, TRY_DATE_TEXT_V1, TRY_TIMESTAMP_TEXT_V1,
         TRY_UTC_ZONED_TEXT_V1, TRY_ZONED_TEXT_V1, TRYING_PARAMETER, UTC_ZONED_TEXT_V1, VALUE_PARAMETER,
         VALUES_PARAMETER, VARIANT_BOOLEAN_V1, VARIANT_DATE_V1, VARIANT_FLOAT_V1, VARIANT_JSON_TEXT_V1,
    -    VARIANT_NUMBER_V1, VARIANT_TEXT_V1, VARIANT_TIMESTAMP_NTZ_V1, VARIANT_WRITTEN_V1,
    -    ZONED_TEXT_V1,
    +    VARIANT_JSON_TEXT_V2, VARIANT_NUMBER_V1, VARIANT_TEXT_V1, VARIANT_TEXT_V2,
    +    VARIANT_TIMESTAMP_NTZ_V1, VARIANT_WRITTEN_V1, ZONED_TEXT_V1,
     };
     use crate::macros::models::HelperMacro;
     
     /// The helper macros, dependencies first.
    -pub(crate) fn helper_macros() -> [HelperMacro; 21] {
    +pub(crate) fn helper_macros() -> [HelperMacro; 23] {
         [
             HelperMacro {
                 name: TIME_ZONE_V1,
    @@ -158,6 +158,22 @@ pub(crate) fn helper_macros() -> [HelperMacro; 21] {
                           object's keys in byte order at every depth. Raises json_fidelity where \
                           DuckDB could sort the keys only by rewriting a number.",
             },
    +        HelperMacro {
    +            name: VARIANT_TEXT_V2,
    +            parameters: &[SITE_PARAMETER, VALUE_PARAMETER],
    +            body: text_body_v2,
    +            explain: "variant_text_v1's result. A number or boolean is written as it is, and \
    +                      the text chosen takes Snowflake's escapes once, so DuckDB binds the escape \
    +                      once a call, not twice.",
    +        },
    +        HelperMacro {
    +            name: VARIANT_JSON_TEXT_V2,
    +            parameters: &[SITE_PARAMETER, VALUE_PARAMETER],
    +            body: json_text_body_v2,
    +            explain: "variant_json_text_v1's result. A number, boolean or null is written as it \
    +                      is, and the text chosen takes Snowflake's escapes once, so DuckDB binds \
    +                      the escape once a call, not twice.",
    +        },
             HelperMacro {
                 name: VARIANT_NUMBER_V1,
                 parameters: &[
    diff --git a/crates/sqlquack-blocks/src/macros/_helpers/writing.rs b/crates/sqlquack-blocks/src/macros/_helpers/writing.rs
    index c18f3562f..e16a39cbf 100644
    --- a/crates/sqlquack-blocks/src/macros/_helpers/writing.rs
    +++ b/crates/sqlquack-blocks/src/macros/_helpers/writing.rs
    @@ -11,6 +11,15 @@ use crate::semi_structured::constants::{
     };
     use crate::semi_structured::main::json_escaped::json_escaped;
     
    +/// Where the written text takes Snowflake's escapes.
    +#[derive(Clone, Copy)]
    +enum Escape {
    +    /// On each text that may be chosen, as the released version-1 macros do.
    +    EachText,
    +    /// Once, on the text chosen: DuckDB pastes the escape's body in at every use.
    +    Chosen,
    +}
    +
     /// The text of `json_value` with every object's keys in byte order, from DuckDB's `VARIANT`.
     const RESORTED: &str = "CAST(CAST(CAST(json_value AS VARIANT) AS JSON) AS VARCHAR)";
     
    @@ -20,7 +29,7 @@ pub(crate) fn text_body() -> String {
             "(CASE WHEN json_value IS NULL OR json_type(json_value) = 'NULL' THEN NULL \
              WHEN json_type(json_value) = 'VARCHAR' THEN json_extract_string(json_value, '$') \
              ELSE {} END)",
    -        sorted()
    +        sorted(Escape::EachText)
         ))
     }
     
    @@ -28,7 +37,28 @@ pub(crate) fn text_body() -> String {
     pub(crate) fn json_text_body() -> String {
         written(&format!(
             "(CASE WHEN json_value IS NULL THEN NULL ELSE {} END)",
    -        sorted()
    +        sorted(Escape::EachText)
    +    ))
    +}
    +
    +/// variant_text_v1's result, a number or boolean written as it is and other values escaped once.
    +pub(crate) fn text_body_v2() -> String {
    +    written(&format!(
    +        "(CASE WHEN json_value IS NULL OR json_type(json_value) = 'NULL' THEN NULL \
    +         WHEN json_type(json_value) = 'VARCHAR' THEN json_extract_string(json_value, '$') \
    +         WHEN json_type(json_value) NOT IN ('OBJECT', 'ARRAY') THEN CAST(json_value AS VARCHAR) \
    +         ELSE {} END)",
    +        sorted(Escape::Chosen)
    +    ))
    +}
    +
    +/// variant_json_text_v1's result, a number, boolean or null written as it is, others escaped once.
    +pub(crate) fn json_text_body_v2() -> String {
    +    written(&format!(
    +        "(CASE WHEN json_value IS NULL THEN NULL \
    +         WHEN json_type(json_value) NOT IN ('OBJECT', 'ARRAY', 'VARCHAR') \
    +         THEN CAST(json_value AS VARCHAR) ELSE {} END)",
    +        sorted(Escape::Chosen)
         ))
     }
     
    @@ -60,8 +90,11 @@ fn written(body: &str) -> String {
     }
     
     /// The JSON text of `json_value`, its objects' keys resorted through DuckDB's VARIANT if needed.
    -fn sorted() -> String {
    -    let escaped = |sql: &str| helper_call(JSON_ESCAPED_V1, &[sql]);
    +fn sorted(escape: Escape) -> String {
    +    let escaped = |sql: &str| match escape {
    +        Escape::EachText => helper_call(JSON_ESCAPED_V1, &[sql]),
    +        Escape::Chosen => sql.to_owned(),
    +    };
         let resorted = bound(
             RESORTED,
             "json_resorted",
    @@ -75,7 +108,7 @@ fn sorted() -> String {
                 escaped("json_resorted"),
             ),
         );
    -    bound(
    +    let chosen = bound(
             &format!(
                 "struct_pack(text := CAST(json_value AS VARCHAR), unsorted := {})",
                 keys_unsorted("json_value")
    @@ -85,7 +118,15 @@ fn sorted() -> String {
                 "(CASE WHEN NOT json_written['unsorted'] THEN {} ELSE {resorted} END)",
                 escaped("json_written['text']"),
             ),
    -    )
    +    );
    +    match escape {
    +        Escape::EachText => chosen,
    +        Escape::Chosen => bound(
    +            &chosen,
    +            "json_chosen",
    +            &helper_call(JSON_ESCAPED_V1, &["json_chosen"]),
    +        ),
    +    }
     }
     
     /// The numbers of the JSON text `sql`, outside strings, in byte order.
    diff --git a/crates/sqlquack-blocks/src/macros/constants.rs b/crates/sqlquack-blocks/src/macros/constants.rs
    index b12fcad8e..c3242c608 100644
    --- a/crates/sqlquack-blocks/src/macros/constants.rs
    +++ b/crates/sqlquack-blocks/src/macros/constants.rs
    @@ -12,6 +12,10 @@ pub const JSON_ESCAPED_V1: &str = "json_escaped_v1";
     pub const VARIANT_TEXT_V1: &str = "variant_text_v1";
     /// A VARIANT as JSON text, as Snowflake writes it.
     pub const VARIANT_JSON_TEXT_V1: &str = "variant_json_text_v1";
    +/// A VARIANT cast to VARCHAR as variant_text_v1 writes it, with one escape a call.
    +pub const VARIANT_TEXT_V2: &str = "variant_text_v2";
    +/// A VARIANT as JSON text as variant_json_text_v1 writes it, with one escape a call.
    +pub const VARIANT_JSON_TEXT_V2: &str = "variant_json_text_v2";
     /// A VARIANT cast to a NUMBER.
     pub const VARIANT_NUMBER_V1: &str = "variant_number_v1";
     /// A VARIANT cast to FLOAT.
    diff --git a/crates/sqlquack-blocks/src/macros/tests.rs b/crates/sqlquack-blocks/src/macros/tests.rs
    index 2ce882b7e..c13f3e61a 100644
    --- a/crates/sqlquack-blocks/src/macros/tests.rs
    +++ b/crates/sqlquack-blocks/src/macros/tests.rs
    @@ -1,4 +1,8 @@
    +#[path = "tests/helpers.rs"]
    +mod helpers;
     #[path = "tests/test_helper_statements.rs"]
     mod test_helper_statements;
     #[path = "tests/test_types.rs"]
     mod test_types;
    +#[path = "tests/test_variant_text.rs"]
    +mod test_variant_text;
    diff --git a/crates/sqlquack-blocks/src/macros/tests/helpers.rs b/crates/sqlquack-blocks/src/macros/tests/helpers.rs
    new file mode 100644
    index 000000000..178165c0e
    --- /dev/null
    +++ b/crates/sqlquack-blocks/src/macros/tests/helpers.rs
    @@ -0,0 +1,57 @@
    +use crate::macros::main::all_helper_statements::all_helper_statements;
    +
    +/// Every helper macro, created on a fresh DuckDB connection.
    +pub(crate) fn helpers() -> duckdb::Connection {
    +    let connection = duckdb::Connection::open_in_memory().expect("DuckDB opens");
    +    for statement in all_helper_statements() {
    +        connection
    +            .execute_batch(&statement)
    +            .expect("the helper is created");
    +    }
    +    connection
    +}
    +
    +/// What a helper wrote, or the tagged message it raised.
    +pub(crate) type Outcome = Result, String>;
    +
    +/// Each outcome with borrowed text, to compare with expected values.
    +pub(crate) fn shown(outcomes: &[Outcome]) -> Vec, &str>> {
    +    outcomes
    +        .iter()
    +        .map(|outcome| {
    +            outcome
    +                .as_ref()
    +                .map(Option::as_deref)
    +                .map_err(String::as_str)
    +        })
    +        .collect()
    +}
    +
    +/// What the helper `name` writes for the JSON text `value`, or the tagged message it raises.
    +pub(crate) fn written(
    +    connection: &duckdb::Connection,
    +    (name, value): (&str, Option<&str>),
    +) -> Outcome {
    +    connection
    +        .query_row(
    +            &format!("SELECT sqlquack.{name}('#s', CAST(? AS JSON))"),
    +            [value],
    +            |row| row.get::<_, Option>(0),
    +        )
    +        .map_err(|error| {
    +            let message = error.to_string();
    +            message
    +                .split_once("string '")
    +                .and_then(|(_, rest)| rest.split_once("' to "))
    +                .map_or(message.clone(), |(tagged, _)| tagged.to_owned())
    +        })
    +}
    +
    +/// How many times the definition of the helper `name` calls `callee`.
    +pub(crate) fn calls_in_definition(name: &str, callee: &str) -> Option {
    +    let opening = format!("CREATE OR REPLACE MACRO sqlquack.{name}(");
    +    all_helper_statements()
    +        .into_iter()
    +        .find(|statement| statement.starts_with(&opening))
    +        .map(|statement| statement.matches(&format!("sqlquack.{callee}(")).count())
    +}
    diff --git a/crates/sqlquack-blocks/src/macros/tests/test_helper_statements.rs b/crates/sqlquack-blocks/src/macros/tests/test_helper_statements.rs
    index 5d9d7b06f..6e2c7ca46 100644
    --- a/crates/sqlquack-blocks/src/macros/tests/test_helper_statements.rs
    +++ b/crates/sqlquack-blocks/src/macros/tests/test_helper_statements.rs
    @@ -170,6 +170,16 @@ fn given_a_released_helper_when_defined_then_its_definition_is_unchanged() {
                 name: "variant_json_text_v1",
                 expected_md5: Some("7c2319469ba632f57dfa5dbc4e09577a"),
             },
    +        PinnedDefinitionTestCase {
    +            description: "variant_text_v2's released definition is unchanged; a change takes a new version",
    +            name: "variant_text_v2",
    +            expected_md5: Some("657d35684ebccf15038b2125eb5ac7d2"),
    +        },
    +        PinnedDefinitionTestCase {
    +            description: "variant_json_text_v2's released definition is unchanged; a change takes a new version",
    +            name: "variant_json_text_v2",
    +            expected_md5: Some("7d0d6a068917cdfc44d84174e0db7fa7"),
    +        },
             PinnedDefinitionTestCase {
                 description: "variant_number_v1's released definition is unchanged; a change takes a new version",
                 name: "variant_number_v1",
    diff --git a/crates/sqlquack-blocks/src/macros/tests/test_types.rs b/crates/sqlquack-blocks/src/macros/tests/test_types.rs
    index 235115083..4608c5890 100644
    --- a/crates/sqlquack-blocks/src/macros/tests/test_types.rs
    +++ b/crates/sqlquack-blocks/src/macros/tests/test_types.rs
    @@ -27,3 +27,20 @@ pub(crate) struct PinnedDefinitionTestCase {
         pub(crate) name: &'static str,
         pub(crate) expected_md5: Option<&'static str>,
     }
    +
    +/// A VARIANT's JSON text and what both versions of each writing helper give for it.
    +pub(crate) struct VariantTextTestCase {
    +    pub(crate) description: &'static str,
    +    pub(crate) value: Option<&'static str>,
    +    /// variant_text's result, or a fragment of the error it raises.
    +    pub(crate) expected_text: Result, &'static str>,
    +    /// variant_json_text's result, or a fragment of the error it raises.
    +    pub(crate) expected_json_text: Result, &'static str>,
    +}
    +
    +/// A writing helper and how many times its definition calls json_escaped_v1.
    +pub(crate) struct EscapeCallsTestCase {
    +    pub(crate) description: &'static str,
    +    pub(crate) name: &'static str,
    +    pub(crate) expected_calls: usize,
    +}
    diff --git a/crates/sqlquack-blocks/src/macros/tests/test_variant_text.rs b/crates/sqlquack-blocks/src/macros/tests/test_variant_text.rs
    new file mode 100644
    index 000000000..64f9d6afb
    --- /dev/null
    +++ b/crates/sqlquack-blocks/src/macros/tests/test_variant_text.rs
    @@ -0,0 +1,156 @@
    +use crate::macros::tests::helpers::{Outcome, calls_in_definition, helpers, shown, written};
    +use crate::macros::tests::test_types::{EscapeCallsTestCase, VariantTextTestCase};
    +
    +#[test]
    +fn given_variant_values_when_writing_them_then_version_2_writes_what_version_1_writes() {
    +    let test_cases = [
    +        VariantTextTestCase {
    +            description: "SQL NULL",
    +            value: None,
    +            expected_text: Ok(None),
    +            expected_json_text: Ok(None),
    +        },
    +        VariantTextTestCase {
    +            description: "JSON null",
    +            value: Some("null"),
    +            expected_text: Ok(None),
    +            expected_json_text: Ok(Some("null")),
    +        },
    +        VariantTextTestCase {
    +            description: "a boolean",
    +            value: Some("true"),
    +            expected_text: Ok(Some("true")),
    +            expected_json_text: Ok(Some("true")),
    +        },
    +        VariantTextTestCase {
    +            description: "a negative integer",
    +            value: Some("-12"),
    +            expected_text: Ok(Some("-12")),
    +            expected_json_text: Ok(Some("-12")),
    +        },
    +        VariantTextTestCase {
    +            description: "a number with an exponent",
    +            value: Some("1e5"),
    +            expected_text: Ok(Some("1e5")),
    +            expected_json_text: Ok(Some("1e5")),
    +        },
    +        VariantTextTestCase {
    +            description: "a string with escapes",
    +            value: Some(r#""tab\tq\"x""#),
    +            expected_text: Ok(Some("tab\tq\"x")),
    +            expected_json_text: Ok(Some(r#""tab\tq\"x""#)),
    +        },
    +        VariantTextTestCase {
    +            description: "a string with control characters",
    +            value: Some(r#""\u001F\u007F""#),
    +            expected_text: Ok(Some("\u{1f}\u{7f}")),
    +            expected_json_text: Ok(Some(r#""\u001f\u007F""#)),
    +        },
    +        VariantTextTestCase {
    +            description: "an empty object",
    +            value: Some("{}"),
    +            expected_text: Ok(Some("{}")),
    +            expected_json_text: Ok(Some("{}")),
    +        },
    +        VariantTextTestCase {
    +            description: "an array of a number and a string",
    +            value: Some(r#"[1,2.5,"x"]"#),
    +            expected_text: Ok(Some(r#"[1,2.5,"x"]"#)),
    +            expected_json_text: Ok(Some(r#"[1,2.5,"x"]"#)),
    +        },
    +        VariantTextTestCase {
    +            description: "an array holding an escaped control character",
    +            value: Some(r#"["\u001F"]"#),
    +            expected_text: Ok(Some(r#"["\u001f"]"#)),
    +            expected_json_text: Ok(Some(r#"["\u001f"]"#)),
    +        },
    +        VariantTextTestCase {
    +            description: "an object whose keys are in byte order",
    +            value: Some(r#"{"a":1,"b":[true,null]}"#),
    +            expected_text: Ok(Some(r#"{"a":1,"b":[true,null]}"#)),
    +            expected_json_text: Ok(Some(r#"{"a":1,"b":[true,null]}"#)),
    +        },
    +        VariantTextTestCase {
    +            description: "an object whose keys are not",
    +            value: Some(r#"{"b":1,"a":2}"#),
    +            expected_text: Ok(Some(r#"{"a":2,"b":1}"#)),
    +            expected_json_text: Ok(Some(r#"{"a":2,"b":1}"#)),
    +        },
    +        VariantTextTestCase {
    +            description: "unsorted keys at every depth, beside an escape",
    +            value: Some(r#"{"b":{"d":1,"c":[{"z":0,"y":"\u001B"}]},"a":null}"#),
    +            expected_text: Ok(Some(r#"{"a":null,"b":{"c":[{"y":"\u001b","z":0}],"d":1}}"#)),
    +            expected_json_text: Ok(Some(r#"{"a":null,"b":{"c":[{"y":"\u001b","z":0}],"d":1}}"#)),
    +        },
    +        VariantTextTestCase {
    +            description: "unsorted keys DuckDB could sort only by rewriting a number",
    +            value: Some(r#"{"b":1.50,"a":2}"#),
    +            expected_text: Err(
    +                "json_fidelity#s: an object whose keys DuckDB could sort only by rewriting a number",
    +            ),
    +            expected_json_text: Err(
    +                "json_fidelity#s: an object whose keys DuckDB could sort only by rewriting a number",
    +            ),
    +        },
    +    ];
    +    let connection = helpers();
    +    for test_case in test_cases {
    +        let texts: Vec = ["variant_text_v1", "variant_text_v2"]
    +            .into_iter()
    +            .map(|name| written(&connection, (name, test_case.value)))
    +            .collect();
    +        let json_texts: Vec = ["variant_json_text_v1", "variant_json_text_v2"]
    +            .into_iter()
    +            .map(|name| written(&connection, (name, test_case.value)))
    +            .collect();
    +
    +        assert_eq!(
    +            shown(&texts),
    +            [test_case.expected_text; 2],
    +            "{}",
    +            test_case.description
    +        );
    +        assert_eq!(
    +            shown(&json_texts),
    +            [test_case.expected_json_text; 2],
    +            "{}",
    +            test_case.description
    +        );
    +    }
    +}
    +
    +#[test]
    +fn given_the_variant_text_helpers_when_defined_then_version_2_calls_the_escape_once() {
    +    let test_cases = [
    +        EscapeCallsTestCase {
    +            description: "variant_text_v1 escapes each text it may write",
    +            name: "variant_text_v1",
    +            expected_calls: 2,
    +        },
    +        EscapeCallsTestCase {
    +            description: "variant_text_v2 escapes the text it writes once",
    +            name: "variant_text_v2",
    +            expected_calls: 1,
    +        },
    +        EscapeCallsTestCase {
    +            description: "variant_json_text_v1 escapes each text it may write",
    +            name: "variant_json_text_v1",
    +            expected_calls: 2,
    +        },
    +        EscapeCallsTestCase {
    +            description: "variant_json_text_v2 escapes the text it writes once",
    +            name: "variant_json_text_v2",
    +            expected_calls: 1,
    +        },
    +    ];
    +    for test_case in test_cases {
    +        let calls = calls_in_definition(test_case.name, "json_escaped_v1");
    +
    +        assert_eq!(
    +            calls,
    +            Some(test_case.expected_calls),
    +            "{}",
    +            test_case.description
    +        );
    +    }
    +}
    diff --git a/crates/sqlquack-blocks/src/semi_structured/_helpers/writing.rs b/crates/sqlquack-blocks/src/semi_structured/_helpers/writing.rs
    index 8b767943e..81d0e79db 100644
    --- a/crates/sqlquack-blocks/src/semi_structured/_helpers/writing.rs
    +++ b/crates/sqlquack-blocks/src/semi_structured/_helpers/writing.rs
    @@ -1,6 +1,6 @@
     //! JSON text as Snowflake writes it, through the helper macros that write it.
     
    -use crate::macros::constants::{JSON_ESCAPED_V1, VARIANT_JSON_TEXT_V1, VARIANT_TEXT_V1};
    +use crate::macros::constants::{JSON_ESCAPED_V1, VARIANT_JSON_TEXT_V2, VARIANT_TEXT_V2};
     use crate::macros::main::helper_call::helper_call;
     use crate::raises::constants::UNIDENTIFIED_SITE;
     
    @@ -16,8 +16,8 @@ pub(crate) enum Root {
     /// The VARIANT `sql` as Snowflake writes it, through its helper macro.
     pub(crate) fn sorted_text(sql: &str, root: Root) -> String {
         let name = match root {
    -        Root::Json => VARIANT_JSON_TEXT_V1,
    -        Root::Text => VARIANT_TEXT_V1,
    +        Root::Json => VARIANT_JSON_TEXT_V2,
    +        Root::Text => VARIANT_TEXT_V2,
         };
         helper_call(name, &[UNIDENTIFIED_SITE, sql])
     }
    diff --git a/website/src/content/docs/docs/helper-macros.mdx b/website/src/content/docs/docs/helper-macros.mdx
    index 2af22b032..3448cf824 100644
    --- a/website/src/content/docs/docs/helper-macros.mdx
    +++ b/website/src/content/docs/docs/helper-macros.mdx
    @@ -4,7 +4,7 @@ description: "The versioned DuckDB macros converted SQL calls, and how to create
     ---
     
     Converted SQL that reads a VARIANT or date and time text, or divides wide decimals, calls small DuckDB macros in a `sqlquack` schema, such as
    -`sqlquack.variant_text_v1`, instead of repeating the same long expression at every use.
    +`sqlquack.variant_text_v2`, instead of repeating the same long expression at every use.
     `convert` prints the statements creating the macros a query calls ahead of the query, so its
     output runs as it is in any DuckDB session:
     
    @@ -14,11 +14,11 @@ $ sqlquack convert staging.sql --no-config
     CREATE SCHEMA IF NOT EXISTS sqlquack;
     CREATE OR REPLACE MACRO sqlquack.json_read_v1(
     …
    -CREATE OR REPLACE MACRO sqlquack.variant_text_v1(quack_site, quack_value) AS list_transform(
    +CREATE OR REPLACE MACRO sqlquack.variant_text_v2(quack_site, quack_value) AS list_transform(
     …
     SELECT
    -    sqlquack.variant_text_v1(
    -        '#0d01742fedea',
    +    sqlquack.variant_text_v2(
    +        '#4e58bb5a4ce8',
             json_extract("EVENTS"."PAYLOAD", '$."customer_id"')
         ) AS "CUSTOMER_ID"
     FROM (
    @@ -53,7 +53,7 @@ changed macro gets a new version and a new name.
     `sqlquack explain ` prints a macro's arguments, what it computes and its definition:
     
     ```bash
    -sqlquack explain variant_text_v1
    +sqlquack explain variant_text_v2
     ```
     
     | Macro | What it computes |
    @@ -61,8 +61,10 @@ sqlquack explain variant_text_v1
     | `json_read_v1` | JSON text read as a VARIANT, raising `json_fidelity` where DuckDB might read it differently from Snowflake. |
     | `json_checked_v1` | The same read, faster: plain JSON is read as it is, anything else goes through `json_read_v1`. |
     | `json_escaped_v1` | JSON text with Snowflake's escapes. |
    -| `variant_text_v1` | A VARIANT cast to `VARCHAR`, as Snowflake writes it. |
    -| `variant_json_text_v1` | A VARIANT as Snowflake writes it as JSON text. |
    +| `variant_text_v2` | A VARIANT cast to `VARCHAR`, as Snowflake writes it. |
    +| `variant_json_text_v2` | A VARIANT as Snowflake writes it as JSON text. |
    +| `variant_text_v1` | What `variant_text_v2` computes, from a larger definition. Kept for SQL converted by 0.24.0 and earlier. |
    +| `variant_json_text_v1` | What `variant_json_text_v2` computes, from a larger definition. Kept for SQL converted by 0.24.0 and earlier. |
     | `variant_written_v1` | A FLOAT held in a VARIANT, or a value built around one, as Snowflake writes it as JSON text. |
     | `variant_number_v1` | A VARIANT cast to `NUMBER(p, s)`, with Snowflake's errors. |
     | `variant_float_v1` | A VARIANT cast to `FLOAT`, with Snowflake's errors. |
    @@ -80,5 +82,5 @@ sqlquack explain variant_text_v1
     | `time_zone_v1` | A time zone name passed through when NULL or a name Snowflake was recorded accepting, case included; raises `time_zone_spelling` for any other name. |
     | `decimal_quotient_v1` | The exact quotient of two unscaled decimals at the result scale, rounded half away from zero or truncated; raises Snowflake's division by zero error and `numeric_range` where the quotient needs more than 128 bits. |
     
    -A raising macro takes the raise site first, such as `'#0d01742fedea'`, so its error names the
    +A raising macro takes the raise site first, such as `'#4e58bb5a4ce8'`, so its error names the
     place in your SQL it came from, as an inline raise does.
    
    From 1654e9d31f1ccd07d84a01659a7014fa1c670f0a Mon Sep 17 00:00:00 2001
    From: Kevin Longe <273747162+kvlonge@users.noreply.github.com>
    Date: Wed, 25 Nov 2026 18:05:29 +0000
    Subject: [PATCH 6/8] perf(convert): read text as FLOAT with one literal for
     its whitespace, numbers first
    
    The inline text-to-FLOAT conversion trimmed with ' ' || chr(9) || chr(10),
    which DuckDB binds as three calls at every cast, and tested for NaN before the
    number pattern, so ordinary numbers ran two regular expressions. It now trims
    with the literal E' \t\n' and tests numbers first; the patterns are disjoint,
    so results are unchanged. Released macro bodies keep the original spelling, so
    their pinned definitions stay as they are.
    ---
     .../sqlquack-blocks/src/blocks/constants.rs   |   2 +
     .../src/blocks/main/text_to_float.rs          |  20 +-
     crates/sqlquack/tests/cli.rs                  |   2 +
     crates/sqlquack/tests/cli/test_text_float.rs  | 217 ++++++++++++++++++
     4 files changed, 232 insertions(+), 9 deletions(-)
     create mode 100644 crates/sqlquack/tests/cli/test_text_float.rs
    
    diff --git a/crates/sqlquack-blocks/src/blocks/constants.rs b/crates/sqlquack-blocks/src/blocks/constants.rs
    index ac4d6b612..d51cab46a 100644
    --- a/crates/sqlquack-blocks/src/blocks/constants.rs
    +++ b/crates/sqlquack-blocks/src/blocks/constants.rs
    @@ -154,6 +154,8 @@ pub const MANTISSA_FREE_PATTERN: &str = "[eE][+-]?[0-9]+";
     pub const INLINE_ARGUMENT_LIMIT: usize = 256;
     /// Whitespace conversions ignore around a value (space, tab, line feed; not no-break space).
     pub const CONVERSION_WHITESPACE: &str = "(' ' || chr(9) || chr(10))";
    +/// CONVERSION_WHITESPACE as one literal, binding no calls; pinned macro bodies keep the original.
    +pub const CONVERSION_WHITESPACE_LITERAL: &str = "E' \\t\\n'";
     /// The characters of CONVERSION_WHITESPACE, for trimming a literal at compile time.
     pub const CONVERSION_WHITESPACE_CHARS: [char; 3] = [' ', '\t', '\n'];
     /// Words Snowflake reads as a non-finite FLOAT, lower-cased, with their DuckDB spelling.
    diff --git a/crates/sqlquack-blocks/src/blocks/main/text_to_float.rs b/crates/sqlquack-blocks/src/blocks/main/text_to_float.rs
    index 907f4dc8d..59c8124fe 100644
    --- a/crates/sqlquack-blocks/src/blocks/main/text_to_float.rs
    +++ b/crates/sqlquack-blocks/src/blocks/main/text_to_float.rs
    @@ -4,7 +4,9 @@ use sqlquack_diagnostics::failures::constants::NUMBER_NOT_RECOGNIZED;
     use sqlquack_diagnostics::provenance::models::ProvenanceLog;
     
     use crate::blocks::_helpers::text::{conversion_failure, once_bound, space_trimmed};
    -use crate::blocks::constants::{DECIMAL_TEXT_PATTERN, NON_FINITE_FLOAT_WORDS, TEXT_TO_FLOAT};
    +use crate::blocks::constants::{
    +    CONVERSION_WHITESPACE_LITERAL, DECIMAL_TEXT_PATTERN, NON_FINITE_FLOAT_WORDS, TEXT_TO_FLOAT,
    +};
     use crate::blocks::models::TextFailure;
     
     /// Text to a double; special-value words in ASCII only; other unrecorded text fails, or is NULL trying.
    @@ -16,7 +18,7 @@ pub fn text_to_float(sql: &str, failure: TextFailure, log: &ProvenanceLog) -> St
         })
     }
     
    -/// The CASE reading the text `sql` as a double, its trimmed text bound once.
    +/// The CASE reading the text `sql` as a double, its trimmed text bound once; numbers tested first.
     fn read_float(sql: &str, failure: TextFailure) -> String {
         let trimmed = "float_trimmed";
         let unread = conversion_failure(
    @@ -26,9 +28,9 @@ fn read_float(sql: &str, failure: TextFailure) -> String {
         let infinite = "(?i:[+-]?inf|-?infinity)";
         let finite = match failure {
             TextFailure::Null | TextFailure::Variant => format!(
    -            "WHEN regexp_full_match({trimmed}, '{infinite}') THEN CAST({trimmed} AS DOUBLE) \
    -             WHEN regexp_full_match({trimmed}, '{DECIMAL_TEXT_PATTERN}') THEN \
    -             (CASE WHEN isinf(CAST({trimmed} AS DOUBLE)) THEN NULL ELSE CAST({trimmed} AS DOUBLE) END)"
    +            "WHEN regexp_full_match({trimmed}, '{DECIMAL_TEXT_PATTERN}') THEN \
    +             (CASE WHEN isinf(CAST({trimmed} AS DOUBLE)) THEN NULL ELSE CAST({trimmed} AS DOUBLE) END) \
    +             WHEN regexp_full_match({trimmed}, '{infinite}') THEN CAST({trimmed} AS DOUBLE)"
             ),
             TextFailure::Text => format!(
                 "WHEN regexp_full_match({trimmed}, '{DECIMAL_TEXT_PATTERN}|{infinite}') \
    @@ -36,10 +38,10 @@ fn read_float(sql: &str, failure: TextFailure) -> String {
             ),
         };
         format!(
    -        "(CASE WHEN {sql} IS NULL THEN NULL ELSE list_transform([{}], lambda {trimmed}: \
    -         CASE WHEN regexp_full_match({trimmed}, '(?i:-?nan)') THEN CAST('nan' AS DOUBLE) \
    -         {finite} ELSE {unread} END)[1] END)",
    -        space_trimmed(sql)
    +        "(CASE WHEN {sql} IS NULL THEN NULL ELSE list_transform([trim({sql}, \
    +         {CONVERSION_WHITESPACE_LITERAL})], lambda {trimmed}: CASE {finite} \
    +         WHEN regexp_full_match({trimmed}, '(?i:-?nan)') THEN CAST('nan' AS DOUBLE) \
    +         ELSE {unread} END)[1] END)"
         )
     }
     
    diff --git a/crates/sqlquack/tests/cli.rs b/crates/sqlquack/tests/cli.rs
    index 0f270bd4d..856896d33 100644
    --- a/crates/sqlquack/tests/cli.rs
    +++ b/crates/sqlquack/tests/cli.rs
    @@ -48,5 +48,7 @@ mod test_run;
     mod test_set_chains;
     #[path = "cli/test_set_quantifier.rs"]
     mod test_set_quantifier;
    +#[path = "cli/test_text_float.rs"]
    +mod test_text_float;
     #[path = "cli/test_types.rs"]
     mod test_types;
    diff --git a/crates/sqlquack/tests/cli/test_text_float.rs b/crates/sqlquack/tests/cli/test_text_float.rs
    new file mode 100644
    index 000000000..d30dec4fb
    --- /dev/null
    +++ b/crates/sqlquack/tests/cli/test_text_float.rs
    @@ -0,0 +1,217 @@
    +use crate::helpers::{converted_first_value, converted_run_error, parsed_copies};
    +use crate::test_types::{ChainValueTestCase, PatternCopiesTestCase, RunErrorTestCase};
    +
    +#[test]
    +fn given_text_cast_to_float_when_converting_then_duckdb_returns_snowflakes_value() {
    +    let test_cases = [
    +        ChainValueTestCase {
    +            description: "CAST: an integer",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '1' AS a)",
    +            expected_value: "1",
    +        },
    +        ChainValueTestCase {
    +            description: "CAST: a decimal between spaces",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT ' 2.5 ' AS a)",
    +            expected_value: "2.5",
    +        },
    +        ChainValueTestCase {
    +            description: "CAST: an exponent between a tab and a line feed",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '\t-1e3\n' AS a)",
    +            expected_value: "-1000",
    +        },
    +        ChainValueTestCase {
    +            description: "CAST: a decimal without a whole part",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '.5' AS a)",
    +            expected_value: "0.5",
    +        },
    +        ChainValueTestCase {
    +            description: "CAST: a decimal point without a fraction",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '5.' AS a)",
    +            expected_value: "5",
    +        },
    +        ChainValueTestCase {
    +            description: "CAST: NaN",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT 'nan' AS a)",
    +            expected_value: "NaN",
    +        },
    +        ChainValueTestCase {
    +            description: "CAST: a signed NaN in another case",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '-NaN' AS a)",
    +            expected_value: "NaN",
    +        },
    +        ChainValueTestCase {
    +            description: "CAST: infinity",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT 'inf' AS a)",
    +            expected_value: "inf",
    +        },
    +        ChainValueTestCase {
    +            description: "CAST: negative infinity spelled out",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '-Infinity' AS a)",
    +            expected_value: "-inf",
    +        },
    +        ChainValueTestCase {
    +            description: "CAST: signed infinity",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '+inf' AS a)",
    +            expected_value: "inf",
    +        },
    +        ChainValueTestCase {
    +            description: "CAST: a number beyond the double range",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '1e400' AS a)",
    +            expected_value: "inf",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: an integer",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '1' AS a)",
    +            expected_value: "1",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: a decimal between spaces",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT ' 2.5 ' AS a)",
    +            expected_value: "2.5",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: an exponent between a tab and a line feed",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '\t-1e3\n' AS a)",
    +            expected_value: "-1000",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: a decimal without a whole part",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '.5' AS a)",
    +            expected_value: "0.5",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: a decimal point without a fraction",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '5.' AS a)",
    +            expected_value: "5",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: NaN",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT 'nan' AS a)",
    +            expected_value: "NaN",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: a signed NaN in another case",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '-NaN' AS a)",
    +            expected_value: "NaN",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: infinity",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT 'inf' AS a)",
    +            expected_value: "inf",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: negative infinity spelled out",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '-Infinity' AS a)",
    +            expected_value: "-inf",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: signed infinity",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '+inf' AS a)",
    +            expected_value: "inf",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: a word",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT 'abc' AS a)",
    +            expected_value: "none",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: digits with an underscore",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '1_000' AS a)",
    +            expected_value: "none",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: hexadecimal",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '0x10' AS a)",
    +            expected_value: "none",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: a number beyond the double range",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '1e400' AS a)",
    +            expected_value: "none",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: empty text",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '' AS a)",
    +            expected_value: "none",
    +        },
    +        ChainValueTestCase {
    +            description: "TRY_CAST: an Arabic-Indic digit",
    +            sql: "SELECT COALESCE(TO_VARCHAR(TRY_CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '\u{661}' AS a)",
    +            expected_value: "none",
    +        },
    +    ];
    +    for test_case in test_cases {
    +        let value = converted_first_value(test_case.sql);
    +
    +        assert_eq!(value, test_case.expected_value, "{}", test_case.description);
    +    }
    +}
    +
    +#[test]
    +fn given_unrecognized_text_cast_to_float_when_running_then_duckdb_raises_snowflakes_error() {
    +    let test_cases = [
    +        RunErrorTestCase {
    +            description: "CAST: a word",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT 'abc' AS a)",
    +            expected_mention: "Numeric value is not recognized",
    +        },
    +        RunErrorTestCase {
    +            description: "CAST: digits with an underscore",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '1_000' AS a)",
    +            expected_mention: "Numeric value is not recognized",
    +        },
    +        RunErrorTestCase {
    +            description: "CAST: hexadecimal",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '0x10' AS a)",
    +            expected_mention: "Numeric value is not recognized",
    +        },
    +        RunErrorTestCase {
    +            description: "CAST: empty text",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '' AS a)",
    +            expected_mention: "Numeric value is not recognized",
    +        },
    +        RunErrorTestCase {
    +            description: "CAST: an Arabic-Indic digit",
    +            sql: "SELECT COALESCE(TO_VARCHAR(CAST(a AS FLOAT)), 'none') AS c FROM (SELECT '\u{661}' AS a)",
    +            expected_mention: "Numeric value is not recognized",
    +        },
    +    ];
    +    for test_case in test_cases {
    +        let error = converted_run_error(test_case.sql);
    +
    +        assert!(
    +            error
    +                .as_deref()
    +                .is_some_and(|error| error.contains(test_case.expected_mention)),
    +            "{}: {error:?}",
    +            test_case.description
    +        );
    +    }
    +}
    +
    +#[test]
    +fn given_text_cast_to_float_when_converting_then_duckdb_binds_no_chr_call() {
    +    let test_cases = [
    +        PatternCopiesTestCase {
    +            description: "CAST trims with one whitespace literal",
    +            sql: "SELECT CAST(a AS FLOAT) AS c FROM (SELECT '1' AS a)",
    +            pattern: "\"function_name\":\"chr\"",
    +            expected_copies: 0,
    +        },
    +        PatternCopiesTestCase {
    +            description: "TRY_CAST trims with one whitespace literal",
    +            sql: "SELECT TRY_CAST(a AS FLOAT) AS c FROM (SELECT '1' AS a)",
    +            pattern: "\"function_name\":\"chr\"",
    +            expected_copies: 0,
    +        },
    +    ];
    +    for test_case in test_cases {
    +        let copies = parsed_copies(test_case.sql, test_case.pattern);
    +
    +        assert_eq!(
    +            copies, test_case.expected_copies,
    +            "{}",
    +            test_case.description
    +        );
    +    }
    +}
    
    From b072581f183bb07fd3d0820c54859a332e367a5a Mon Sep 17 00:00:00 2001
    From: Kevin Longe <273747162+kvlonge@users.noreply.github.com>
    Date: Wed, 25 Nov 2026 18:24:31 +0000
    Subject: [PATCH 7/8] perf(convert): keep computed arguments out of DuckDB's
     repeating macros
    
    DuckDB defines nullif, array_to_string and split_part as SQL macros that paste
    an argument twice, so a computed argument was bound twice, and nested
    NULLIFZERO doubled at every level. NULLIFZERO now binds an operand once unless
    it is a column, a literal, or a window function over plain arguments, which
    DuckDB's window operator computes once however often it is written; so
    RATIO_TO_REPORT converts exactly as before. UPPER, INITCAP,
    JAROWINKLER_SIMILARITY, ARRAY_TO_STRING and arrays written as text join through
    list_aggr, which takes the list once; where a list may be empty, coalesce keeps
    array_to_string's ''. A literal SPLIT_PART part is read as 1 for 0 when
    converting, so the macro pastes an integer rather than a CASE. Results are
    unchanged.
    ---
     .../src/arrays/main/json_array_written.rs     |   8 +-
     .../src/blocks/_helpers/text.rs               |   6 +-
     .../src/blocks/main/split_text_part.rs        |  10 +-
     .../main/json_array_to_string.rs              |   4 +-
     .../src/text/main/character_similarity.rs     |   4 +-
     .../src/text/main/title_case.rs               |   4 +-
     .../_helpers/expressions/conditionals.rs      |  46 +++-
     .../_helpers/expressions/text_functions.rs    |  14 +-
     .../src/snowflake/conversion/constants.rs     |   2 +
     crates/sqlquack/tests/cli.rs                  |   2 +
     crates/sqlquack/tests/cli/helpers.rs          |  41 ++++
     .../sqlquack/tests/cli/test_duckdb_macros.rs  | 211 ++++++++++++++++++
     crates/sqlquack/tests/cli/test_types.rs       |   7 +
     13 files changed, 336 insertions(+), 23 deletions(-)
     create mode 100644 crates/sqlquack/tests/cli/test_duckdb_macros.rs
    
    diff --git a/crates/sqlquack-blocks/src/arrays/main/json_array_written.rs b/crates/sqlquack-blocks/src/arrays/main/json_array_written.rs
    index 1217ece24..eb2dc1b11 100644
    --- a/crates/sqlquack-blocks/src/arrays/main/json_array_written.rs
    +++ b/crates/sqlquack-blocks/src/arrays/main/json_array_written.rs
    @@ -20,16 +20,16 @@ pub fn json_array_written(
         log.building_block(JSON_ARRAY_WRITTEN);
         let body = match separator {
             None => format!(
    -            "('[' || array_to_string(list_transform(a, lambda e: CASE WHEN e IS NULL THEN \
    -             '{UNDEFINED_TEXT}' ELSE {} END), ',') || ']')",
    +            "('[' || coalesce(list_aggr(list_transform(a, lambda e: CASE WHEN e IS NULL THEN \
    +             '{UNDEFINED_TEXT}' ELSE {} END), 'string_agg', ','), '') || ']')",
                 json_serialized("e", log)
             ),
             Some(separator) => format!(
                 "(CASE WHEN {separator} IS NULL THEN NULL \
                  WHEN list_contains(list_transform(a, lambda e: json_type(e)), 'NULL') \
                  THEN CAST({} AS VARCHAR) \
    -             ELSE array_to_string(list_transform(a, lambda e: \
    -             CASE WHEN e IS NULL THEN '' ELSE {} END), {separator}) END)",
    +             ELSE coalesce(list_aggr(list_transform(a, lambda e: \
    +             CASE WHEN e IS NULL THEN '' ELSE {} END), 'string_agg', {separator}), '') END)",
                 raised(&tagged_message(
                     VARIANT_NOT_CAST,
                     ARRAY_ELEMENT_NOT_TEXT_MESSAGE
    diff --git a/crates/sqlquack-blocks/src/blocks/_helpers/text.rs b/crates/sqlquack-blocks/src/blocks/_helpers/text.rs
    index c127a9201..a4cb3eb3c 100644
    --- a/crates/sqlquack-blocks/src/blocks/_helpers/text.rs
    +++ b/crates/sqlquack-blocks/src/blocks/_helpers/text.rs
    @@ -26,7 +26,7 @@ pub(crate) fn replaced(sql: &str, expansions: &[(&str, &str)], log: &ProvenanceL
         })
     }
     
    -/// `sql` with each one-character key of `expansions` spelled as its text, by a single lookup.
    +/// `sql` with each key of `expansions` spelled out; list_aggr joins, as array_to_string pastes twice.
     pub(crate) fn expanded(sql: &str, expansions: &[(&str, &str)], log: &ProvenanceLog) -> String {
         let class: String = expansions
             .iter()
    @@ -42,8 +42,8 @@ pub(crate) fn expanded(sql: &str, expansions: &[(&str, &str)], log: &ProvenanceL
         once_bound(sql, "case_text", |text| {
             format!(
                 "CASE WHEN regexp_matches({text}, '[{class}]') \
    -             THEN array_to_string(list_transform(string_split({text}, ''), lambda case_character: \
    -             coalesce(string_split({targets}, chr(31))[instr({keys}, case_character)], case_character)), '') \
    +             THEN list_aggr(list_transform(string_split({text}, ''), lambda case_character: \
    +             coalesce(string_split({targets}, chr(31))[instr({keys}, case_character)], case_character)), 'string_agg', '') \
                  ELSE {text} END"
             )
         })
    diff --git a/crates/sqlquack-blocks/src/blocks/main/split_text_part.rs b/crates/sqlquack-blocks/src/blocks/main/split_text_part.rs
    index bd7160e01..119cf24aa 100644
    --- a/crates/sqlquack-blocks/src/blocks/main/split_text_part.rs
    +++ b/crates/sqlquack-blocks/src/blocks/main/split_text_part.rs
    @@ -5,11 +5,15 @@ use sqlquack_diagnostics::provenance::models::ProvenanceLog;
     use crate::blocks::_helpers::text::once_bound;
     use crate::blocks::constants::SPLIT_TEXT_PART;
     
    -/// The part at `part` (0 read as 1) of `text` split on `delimiter`; long text is bound with both.
    +/// The part at `part` (0 read as 1, a literal here) of `text` split on `delimiter`; long text bound.
     pub fn split_text_part(text: &str, (delimiter, part): (&str, &str), log: &ProvenanceLog) -> String {
         log.building_block(SPLIT_TEXT_PART);
    -    let split = |text: &str, delimiter: &str, part: &str| {
    -        format!("split_part({text}, {delimiter}, (CASE WHEN {part} = 0 THEN 1 ELSE {part} END))")
    +    let split = |text: &str, delimiter: &str, part: &str| match part.parse::() {
    +        Ok(0) => format!("split_part({text}, {delimiter}, 1)"),
    +        Ok(_) => format!("split_part({text}, {delimiter}, {part})"),
    +        Err(_) => format!(
    +            "split_part({text}, {delimiter}, (CASE WHEN {part} = 0 THEN 1 ELSE {part} END))"
    +        ),
         };
         let bound = once_bound(text, "part_text", |name| name.to_owned());
         match bound == text {
    diff --git a/crates/sqlquack-blocks/src/semi_structured/main/json_array_to_string.rs b/crates/sqlquack-blocks/src/semi_structured/main/json_array_to_string.rs
    index d44c1f63a..a4ca56edb 100644
    --- a/crates/sqlquack-blocks/src/semi_structured/main/json_array_to_string.rs
    +++ b/crates/sqlquack-blocks/src/semi_structured/main/json_array_to_string.rs
    @@ -23,9 +23,9 @@ pub fn json_array_to_string((sql, separator): (&str, &str), log: &ProvenanceLog)
                  WHEN json_type(a) <> 'ARRAY' THEN CAST({} AS VARCHAR) \
                  WHEN list_contains(list_transform({elements}, lambda e: json_type(e)), 'NULL') \
                  THEN CAST({} AS VARCHAR) \
    -             ELSE array_to_string(list_transform({elements}, lambda e: CASE \
    +             ELSE coalesce(list_aggr(list_transform({elements}, lambda e: CASE \
                  WHEN json_type(e) = 'VARCHAR' THEN json_extract_string(e, '$') \
    -             ELSE {written} END), {separator}) END)",
    +             ELSE {written} END), 'string_agg', {separator}), '') END)",
                 raised(&tagged_message(
                     NOT_AN_ARRAY_ARGUMENT,
                     NOT_AN_ARRAY_ARGUMENT_MESSAGE
    diff --git a/crates/sqlquack-blocks/src/text/main/character_similarity.rs b/crates/sqlquack-blocks/src/text/main/character_similarity.rs
    index 42a93a37f..de9924431 100644
    --- a/crates/sqlquack-blocks/src/text/main/character_similarity.rs
    +++ b/crates/sqlquack-blocks/src/text/main/character_similarity.rs
    @@ -22,8 +22,8 @@ pub fn character_similarity(left: &str, right: &str, log: &ProvenanceLog) -> Str
         };
         let encoded = |side: &str| {
             format!(
    -            "array_to_string(list_transform(string_split(lower(p['{side}']), ''), \
    -             lambda c: chr(list_position(a, c))), '')"
    +            "list_aggr(list_transform(string_split(lower(p['{side}']), ''), \
    +             lambda c: chr(list_position(a, c))), 'string_agg', '')"
             )
         };
         format!(
    diff --git a/crates/sqlquack-blocks/src/text/main/title_case.rs b/crates/sqlquack-blocks/src/text/main/title_case.rs
    index 3d60034ed..703f26904 100644
    --- a/crates/sqlquack-blocks/src/text/main/title_case.rs
    +++ b/crates/sqlquack-blocks/src/text/main/title_case.rs
    @@ -39,8 +39,8 @@ pub fn title_case(value: &str, delimiters: &str, log: &ProvenanceLog) -> String
         let body = format!(
             "(CASE WHEN {text} IS NULL THEN NULL WHEN regexp_matches({text}, {}) \
              THEN CAST({unproven} AS VARCHAR) \
    -         ELSE array_to_string(list_transform(string_split({text}, ''), lambda c, i: \
    -         CASE WHEN i = 1{after_delimiter} THEN upper(c) ELSE {} END), '') END)",
    +         ELSE coalesce(list_aggr(list_transform(string_split({text}, ''), lambda c, i: \
    +         CASE WHEN i = 1{after_delimiter} THEN upper(c) ELSE {} END), 'string_agg', ''), '') END)",
             string_literal(&unknown, log),
             full_case_lower("c", log)
         );
    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 8f489e869..562f72707 100644
    --- a/crates/sqlquack-convert/src/snowflake/conversion/_helpers/expressions/conditionals.rs
    +++ b/crates/sqlquack-convert/src/snowflake/conversion/_helpers/expressions/conditionals.rs
    @@ -24,7 +24,7 @@ use crate::snowflake::conversion::_helpers::support::tree::{
     };
     use crate::snowflake::conversion::constants::{
         CASE, CASE_SUBJECT, COALESCE, DECODE_RULE, DIV0_RULE, IFF, NULL_BRANCHES, NULL_IF_ZERO_RULE,
    -    NVL2_RULE, SEMI_STRUCTURED_HOLDING, TEXT_BRANCHES, ZERO_IF_NULL_RULE,
    +    NVL2_RULE, SEMI_STRUCTURED_HOLDING, TEXT_BRANCHES, ZERO_IF_NULL_RULE, ZERO_TESTED,
     };
     
     /// The branches cast to their unified type, and that type; text beside other types refuses.
    @@ -361,6 +361,34 @@ fn plain(node: &Value) -> bool {
         }
     }
     
    +/// Whether `node` is a window function over plain arguments, which DuckDB computes once however often written.
    +fn plain_window(node: &Value) -> bool {
    +    let Some(("window_function", payload)) = node_kind(node) else {
    +        return false;
    +    };
    +    let operands_plain = payload
    +        .get("this")
    +        .and_then(node_kind)
    +        .and_then(|(_, aggregate)| aggregate.as_object())
    +        .is_some_and(|fields| {
    +            fields.values().all(|operand| match operand {
    +                Value::Array(items) => items.iter().all(plain),
    +                Value::Object(_) => plain(operand),
    +                _ => true,
    +            })
    +        });
    +    let over = payload.get("over").and_then(Value::as_object);
    +    let ordered = |item: &Value| {
    +        node_kind(item).is_some_and(|(_, order)| order.get("this").is_some_and(plain))
    +    };
    +    operands_plain
    +        && over.is_some_and(|over| {
    +            list(over, "partition_by").iter().all(plain)
    +                && list(over, "order_by").iter().all(ordered)
    +                && over.get("frame").is_none_or(Value::is_null)
    +        })
    +}
    +
     /// 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.
    @@ -599,7 +627,7 @@ pub(crate) fn div0(
         ))
     }
     
    -/// NULLIFZERO of a NUMBER or FLOAT: NULL for zero, otherwise the value, of its type.
    +/// NULLIFZERO of a NUMBER or FLOAT: NULL for zero, otherwise the value; a computed one bound once.
     pub(crate) fn null_if_zero(
         arguments: &[Value],
         construct: &Construct,
    @@ -611,11 +639,17 @@ pub(crate) fn null_if_zero(
             return Err(refuse("NULLIFZERO with these arguments".to_owned()));
         };
         let operand = convert_expression(value, site)?;
    +    let sql = match plain(value) || plain_window(value) {
    +        true => format!("nullif({}, 0)", operand.sql),
    +        false => format!(
    +            "list_transform([{}], lambda {ZERO_TESTED}: nullif({ZERO_TESTED}, 0))[1]",
    +            operand.sql
    +        ),
    +    };
         match operand.data_type {
    -        SnowflakeType::Number { .. } | SnowflakeType::Float => Ok(Emitted::new(
    -            format!("nullif({}, 0)", operand.sql),
    -            operand.data_type,
    -        )),
    +        SnowflakeType::Number { .. } | SnowflakeType::Float => {
    +            Ok(Emitted::new(sql, operand.data_type))
    +        }
             other => Err(refuse(format!("NULLIFZERO of {other}"))),
         }
     }
    diff --git a/crates/sqlquack-convert/src/snowflake/conversion/_helpers/expressions/text_functions.rs b/crates/sqlquack-convert/src/snowflake/conversion/_helpers/expressions/text_functions.rs
    index 8855b7787..0c563026e 100644
    --- a/crates/sqlquack-convert/src/snowflake/conversion/_helpers/expressions/text_functions.rs
    +++ b/crates/sqlquack-convert/src/snowflake/conversion/_helpers/expressions/text_functions.rs
    @@ -251,7 +251,11 @@ pub(crate) fn split_part(
                 )),
             };
         }
    -    let part = integer_operand(part, construct, site)?;
    +    let literal = convert_expression(part, site)?.literal;
    +    let part = match literal.as_ref().map(literal_index) {
    +        Some(Ok(index)) => index.to_string(),
    +        _ => integer_operand(part, construct, site)?,
    +    };
         let delimiter = string_literal(&delimiter, site.context.log);
         Ok(Emitted::new(
             split_text_part(&text, (&delimiter, &part), site.context.log),
    @@ -259,6 +263,14 @@ pub(crate) fn split_part(
         ))
     }
     
    +/// The integer a SPLIT_PART part literal spells, or why it is not one.
    +fn literal_index(literal: &Literal) -> Result {
    +    match literal {
    +        Literal::Number(number) => number.parse::().map_err(|error| error.to_string()),
    +        Literal::Text(_) => Err("a text part".to_owned()),
    +    }
    +}
    +
     /// SPLIT_PART with a delimiter from a column: an empty delimiter leaves the text as its one part.
     fn split_part_by_column(
         (text, delimiter, part): (&str, &Value, &Value),
    diff --git a/crates/sqlquack-convert/src/snowflake/conversion/constants.rs b/crates/sqlquack-convert/src/snowflake/conversion/constants.rs
    index 3642895a4..c1cc5a240 100644
    --- a/crates/sqlquack-convert/src/snowflake/conversion/constants.rs
    +++ b/crates/sqlquack-convert/src/snowflake/conversion/constants.rs
    @@ -415,6 +415,8 @@ pub const TABLE_WRAPPER: &str = "TABLE";
     pub const SEMI_STRUCTURED_HOLDING: &str = "JSON";
     /// The lambda parameter a simple CASE binds its computed operand and WHEN values to.
     pub const CASE_SUBJECT: &str = "case_subject";
    +/// The lambda parameter NULLIFZERO binds a computed operand to: DuckDB's nullif pastes it twice.
    +pub const ZERO_TESTED: &str = "zero_tested";
     /// OBJECT_PICK.
     pub const OBJECT_PICK_RULE: &str = "rule.object_pick";
     /// OBJECT_KEYS.
    diff --git a/crates/sqlquack/tests/cli.rs b/crates/sqlquack/tests/cli.rs
    index 856896d33..56e6d6aeb 100644
    --- a/crates/sqlquack/tests/cli.rs
    +++ b/crates/sqlquack/tests/cli.rs
    @@ -22,6 +22,8 @@ mod test_coverage;
     mod test_divergence;
     #[path = "cli/test_division.rs"]
     mod test_division;
    +#[path = "cli/test_duckdb_macros.rs"]
    +mod test_duckdb_macros;
     #[path = "cli/test_error_check.rs"]
     mod test_error_check;
     #[path = "cli/test_evidence_commands.rs"]
    diff --git a/crates/sqlquack/tests/cli/helpers.rs b/crates/sqlquack/tests/cli/helpers.rs
    index dcb7e3e87..88b1f37c1 100644
    --- a/crates/sqlquack/tests/cli/helpers.rs
    +++ b/crates/sqlquack/tests/cli/helpers.rs
    @@ -1375,3 +1375,44 @@ pub(crate) fn parsed_copies(sql: &str, marker: &str) -> usize {
             .expect("DuckDB parses the converted statement");
         parsed.matches(marker).count()
     }
    +
    +/// DuckDB's built-in macros that paste an argument twice, so a computed argument is bound twice.
    +const REPEATING_MACROS: [&str; 3] = ["nullif", "array_to_string", "split_part"];
    +
    +/// How many arguments of DuckDB's repeating macros in converted `sql` are not a column or constant.
    +pub(crate) fn computed_macro_arguments(sql: &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");
    +    let tree: serde_json::Value = serde_json::from_str(&parsed).expect("the parse is JSON");
    +    computed_arguments(&tree)
    +}
    +
    +/// The computed arguments of repeating macros at and below `node`.
    +fn computed_arguments(node: &serde_json::Value) -> usize {
    +    let repeating = node
    +        .get("function_name")
    +        .and_then(serde_json::Value::as_str)
    +        .is_some_and(|name| REPEATING_MACROS.contains(&name));
    +    let own: usize = node
    +        .get("arguments")
    +        .and_then(serde_json::Value::as_array)
    +        .filter(|_| repeating)
    +        .map_or(0, |arguments| {
    +            arguments
    +                .iter()
    +                .filter_map(|argument| argument.pointer("/expression/class"))
    +                .filter(|class| !matches!(class.as_str(), Some("COLUMN_REF" | "CONSTANT")))
    +                .count()
    +        });
    +    let fields: usize = node
    +        .as_object()
    +        .map_or(0, |fields| fields.values().map(computed_arguments).sum());
    +    let items: usize = node
    +        .as_array()
    +        .map_or(0, |items| items.iter().map(computed_arguments).sum());
    +    own + fields + items
    +}
    diff --git a/crates/sqlquack/tests/cli/test_duckdb_macros.rs b/crates/sqlquack/tests/cli/test_duckdb_macros.rs
    new file mode 100644
    index 000000000..00c14f11c
    --- /dev/null
    +++ b/crates/sqlquack/tests/cli/test_duckdb_macros.rs
    @@ -0,0 +1,211 @@
    +use crate::helpers::{computed_macro_arguments, convert_streams, converted_first_value};
    +use crate::test_types::{ChainValueTestCase, ConvertedSqlTestCase, OperandCopiesTestCase};
    +
    +#[test]
    +fn given_emitters_over_duckdb_macros_when_converting_then_duckdb_returns_snowflakes_value() {
    +    let test_cases = [
    +        ChainValueTestCase {
    +            description: "NULLIFZERO of a computed zero",
    +            sql: "SELECT COALESCE(TO_VARCHAR(NULLIFZERO(a + 1)), 'none') AS c FROM (SELECT -1 AS a)",
    +            expected_value: "none",
    +        },
    +        ChainValueTestCase {
    +            description: "NULLIFZERO of a computed value",
    +            sql: "SELECT COALESCE(TO_VARCHAR(NULLIFZERO(a + 1)), 'none') AS c FROM (SELECT 1 AS a)",
    +            expected_value: "2",
    +        },
    +        ChainValueTestCase {
    +            description: "nested NULLIFZERO",
    +            sql: "SELECT COALESCE(TO_VARCHAR(NULLIFZERO(NULLIFZERO(a + 1) * 2)), 'none') AS c FROM (SELECT 2 AS a)",
    +            expected_value: "6",
    +        },
    +        ChainValueTestCase {
    +            description: "nested NULLIFZERO of zero",
    +            sql: "SELECT COALESCE(TO_VARCHAR(NULLIFZERO(NULLIFZERO(a + 1) * 2)), 'none') AS c FROM (SELECT -1 AS a)",
    +            expected_value: "none",
    +        },
    +        ChainValueTestCase {
    +            description: "NULLIFZERO of a FLOAT",
    +            sql: "SELECT COALESCE(TO_VARCHAR(NULLIFZERO(CAST(a AS FLOAT) - 0.5)), 'none') AS c FROM (SELECT 1 AS a)",
    +            expected_value: "0.5",
    +        },
    +        ChainValueTestCase {
    +            description: "INITCAP of words",
    +            sql: "SELECT INITCAP(a) AS c FROM (SELECT 'hello wORLD' AS a)",
    +            expected_value: "Hello World",
    +        },
    +        ChainValueTestCase {
    +            description: "INITCAP of empty text",
    +            sql: "SELECT '[' || INITCAP(a) || ']' AS c FROM (SELECT '' AS a)",
    +            expected_value: "[]",
    +        },
    +        ChainValueTestCase {
    +            description: "INITCAP of NULL",
    +            sql: "SELECT COALESCE(INITCAP(a), 'none') AS c FROM (SELECT CAST(NULL AS VARCHAR) AS a)",
    +            expected_value: "none",
    +        },
    +        ChainValueTestCase {
    +            description: "JAROWINKLER_SIMILARITY of two words",
    +            sql: "SELECT TO_VARCHAR(JAROWINKLER_SIMILARITY(a, b)) AS c FROM (SELECT 'martha' AS a, 'MARHTA' AS b)",
    +            expected_value: "96",
    +        },
    +        ChainValueTestCase {
    +            description: "JAROWINKLER_SIMILARITY with empty text",
    +            sql: "SELECT TO_VARCHAR(JAROWINKLER_SIMILARITY(a, b)) AS c FROM (SELECT '' AS a, 'x' AS b)",
    +            expected_value: "0",
    +        },
    +        ChainValueTestCase {
    +            description: "ARRAY_TO_STRING of a VARIANT array",
    +            sql: "SELECT ARRAY_TO_STRING(PARSE_JSON(a), '-') AS c FROM (SELECT '[1,\"a\",{\"b\":2,\"a\":1}]' AS a)",
    +            expected_value: "1-a-{\"a\":1,\"b\":2}",
    +        },
    +        ChainValueTestCase {
    +            description: "ARRAY_TO_STRING of an empty VARIANT array",
    +            sql: "SELECT '[' || ARRAY_TO_STRING(PARSE_JSON(a), '-') || ']' AS c FROM (SELECT '[]' AS a)",
    +            expected_value: "[]",
    +        },
    +        ChainValueTestCase {
    +            description: "ARRAY_TO_STRING of a constructed array",
    +            sql: "SELECT ARRAY_TO_STRING(ARRAY_CONSTRUCT(a, 'y'), ',') AS c FROM (SELECT 'x' AS a)",
    +            expected_value: "x,y",
    +        },
    +        ChainValueTestCase {
    +            description: "ARRAY_TO_STRING of an empty constructed array",
    +            sql: "SELECT '[' || ARRAY_TO_STRING(ARRAY_CONSTRUCT(), ',') || ']' AS c",
    +            expected_value: "[]",
    +        },
    +        ChainValueTestCase {
    +            description: "a constructed array as text",
    +            sql: "SELECT TO_VARCHAR(ARRAY_CONSTRUCT(a, 2)) AS c FROM (SELECT 1 AS a)",
    +            expected_value: "[1,2]",
    +        },
    +        ChainValueTestCase {
    +            description: "an empty constructed array as text",
    +            sql: "SELECT TO_VARCHAR(ARRAY_CONSTRUCT()) AS c",
    +            expected_value: "[]",
    +        },
    +        ChainValueTestCase {
    +            description: "SPLIT_PART at part 0",
    +            sql: "SELECT SPLIT_PART(a, ',', 0) AS c FROM (SELECT 'x,y,z' AS a)",
    +            expected_value: "x",
    +        },
    +        ChainValueTestCase {
    +            description: "SPLIT_PART at part 2",
    +            sql: "SELECT SPLIT_PART(a, ',', 2) AS c FROM (SELECT 'x,y,z' AS a)",
    +            expected_value: "y",
    +        },
    +        ChainValueTestCase {
    +            description: "SPLIT_PART at part -1",
    +            sql: "SELECT SPLIT_PART(a, ',', -1) AS c FROM (SELECT 'x,y,z' AS a)",
    +            expected_value: "z",
    +        },
    +        ChainValueTestCase {
    +            description: "SPLIT_PART beyond the parts",
    +            sql: "SELECT '[' || SPLIT_PART(a, ',', 5) || ']' AS c FROM (SELECT 'x,y,z' AS a)",
    +            expected_value: "[]",
    +        },
    +        ChainValueTestCase {
    +            description: "SPLIT_PART of NULL",
    +            sql: "SELECT COALESCE(SPLIT_PART(a, ',', 2), 'none') AS c FROM (SELECT CAST(NULL AS VARCHAR) AS a)",
    +            expected_value: "none",
    +        },
    +    ];
    +    for test_case in test_cases {
    +        let value = converted_first_value(test_case.sql);
    +
    +        assert_eq!(value, test_case.expected_value, "{}", test_case.description);
    +    }
    +}
    +
    +#[test]
    +fn given_emitters_over_duckdb_macros_when_converting_then_only_a_plain_window_reaches_a_repeating_macro()
    + {
    +    let test_cases = [
    +        OperandCopiesTestCase {
    +            description: "NULLIFZERO of a computed operand",
    +            sql: "SELECT NULLIFZERO(a + 1) AS c FROM (SELECT 1 AS a)",
    +            expected_copies: 0,
    +        },
    +        OperandCopiesTestCase {
    +            description: "NULLIFZERO nested three deep, which nullif doubled at each level",
    +            sql: "SELECT NULLIFZERO(NULLIFZERO(NULLIFZERO(a + 1) * 2) * 3) AS c FROM (SELECT 1 AS a)",
    +            expected_copies: 0,
    +        },
    +        OperandCopiesTestCase {
    +            description: "UPPER's per-character lookup",
    +            sql: "SELECT UPPER(a) AS c FROM (SELECT 'x' AS a)",
    +            expected_copies: 0,
    +        },
    +        OperandCopiesTestCase {
    +            description: "INITCAP's per-character casing",
    +            sql: "SELECT INITCAP(a) AS c FROM (SELECT 'x' AS a)",
    +            expected_copies: 0,
    +        },
    +        OperandCopiesTestCase {
    +            description: "JAROWINKLER_SIMILARITY's encoding of each side",
    +            sql: "SELECT JAROWINKLER_SIMILARITY(a, b) AS c FROM (SELECT 'x' AS a, 'y' AS b)",
    +            expected_copies: 0,
    +        },
    +        OperandCopiesTestCase {
    +            description: "ARRAY_TO_STRING's writing of each VARIANT element",
    +            sql: "SELECT ARRAY_TO_STRING(PARSE_JSON(a), ',') AS c FROM (SELECT '[1]' AS a)",
    +            expected_copies: 0,
    +        },
    +        OperandCopiesTestCase {
    +            description: "ARRAY_TO_STRING of a constructed array",
    +            sql: "SELECT ARRAY_TO_STRING(ARRAY_CONSTRUCT(a, 'y'), ',') AS c FROM (SELECT 'x' AS a)",
    +            expected_copies: 0,
    +        },
    +        OperandCopiesTestCase {
    +            description: "NULLIFZERO of a window function over a computed argument",
    +            sql: "SELECT NULLIFZERO(SUM(a + 1) OVER ()) AS c FROM (SELECT 1 AS a)",
    +            expected_copies: 0,
    +        },
    +        OperandCopiesTestCase {
    +            description: "NULLIFZERO of a window function over plain arguments, the one exception: \
    +                          DuckDB computes the window once however often nullif writes it",
    +            sql: "SELECT NULLIFZERO(SUM(a) OVER (PARTITION BY b)) AS c FROM (SELECT 1 AS a, 'x' AS b)",
    +            expected_copies: 1,
    +        },
    +        OperandCopiesTestCase {
    +            description: "SPLIT_PART at a literal part",
    +            sql: "SELECT SPLIT_PART(a, ',', 2) AS c FROM (SELECT 'x,y' AS a)",
    +            expected_copies: 0,
    +        },
    +    ];
    +    for test_case in test_cases {
    +        let copies = computed_macro_arguments(test_case.sql);
    +
    +        assert_eq!(
    +            copies, test_case.expected_copies,
    +            "{}",
    +            test_case.description
    +        );
    +    }
    +}
    +
    +#[test]
    +fn given_ratio_to_report_when_converting_then_the_sql_is_byte_identical_to_0_24_0() {
    +    let test_cases = [
    +        ConvertedSqlTestCase {
    +            description: "RATIO_TO_REPORT over a partition",
    +            sql: "SELECT RATIO_TO_REPORT(x) OVER (PARTITION BY g) AS r FROM (SELECT CAST(1.5 AS NUMBER(10,2)) AS x, 'a' AS g)",
    +            expected_sql: r#"SELECT (CASE WHEN "__SQLQUACK_SUBQUERY_0"."X" IS NULL OR nullif(CAST(sum("__SQLQUACK_SUBQUERY_0"."X") OVER (PARTITION BY "__SQLQUACK_SUBQUERY_0"."G") AS DECIMAL(22,2)), 0) IS NULL THEN NULL WHEN nullif(CAST(sum("__SQLQUACK_SUBQUERY_0"."X") OVER (PARTITION BY "__SQLQUACK_SUBQUERY_0"."G") AS DECIMAL(22,2)), 0) = 0 THEN CAST(CAST('sqlquack:100051#484e0d07a67e: Division by zero' AS INTEGER) AS "NULL") ELSE CAST(CAST(((CAST(CAST("__SQLQUACK_SUBQUERY_0"."X" AS DECIMAL(38,2)) * 10000000000 AS HUGEINT) * 10) // CAST(CAST(nullif(CAST(sum("__SQLQUACK_SUBQUERY_0"."X") OVER (PARTITION BY "__SQLQUACK_SUBQUERY_0"."G") AS DECIMAL(22,2)), 0) AS DECIMAL(38,2)) * 100 AS HUGEINT)) AS DECIMAL(38,0)) * 0.000000001 AS DECIMAL(18,8)) END) AS "R" FROM (SELECT CAST(1.5 AS DECIMAL(10,2)) AS "X", 'a' AS "G") AS "__SQLQUACK_SUBQUERY_0"("X", "G")"#,
    +        },
    +        ConvertedSqlTestCase {
    +            description: "RATIO_TO_REPORT over the whole result",
    +            sql: "SELECT RATIO_TO_REPORT(x) OVER () AS r FROM (SELECT CAST(1.5 AS NUMBER(10,2)) AS x)",
    +            expected_sql: r#"SELECT (CASE WHEN "__SQLQUACK_SUBQUERY_0"."X" IS NULL OR nullif(CAST(sum("__SQLQUACK_SUBQUERY_0"."X") OVER () AS DECIMAL(22,2)), 0) IS NULL THEN NULL WHEN nullif(CAST(sum("__SQLQUACK_SUBQUERY_0"."X") OVER () AS DECIMAL(22,2)), 0) = 0 THEN CAST(CAST('sqlquack:100051#35fe8ffca89c: Division by zero' AS INTEGER) AS "NULL") ELSE CAST(CAST(((CAST(CAST("__SQLQUACK_SUBQUERY_0"."X" AS DECIMAL(38,2)) * 10000000000 AS HUGEINT) * 10) // CAST(CAST(nullif(CAST(sum("__SQLQUACK_SUBQUERY_0"."X") OVER () AS DECIMAL(22,2)), 0) AS DECIMAL(38,2)) * 100 AS HUGEINT)) AS DECIMAL(38,0)) * 0.000000001 AS DECIMAL(18,8)) END) AS "R" FROM (SELECT CAST(1.5 AS DECIMAL(10,2)) AS "X") AS "__SQLQUACK_SUBQUERY_0"("X")"#,
    +        },
    +    ];
    +    for test_case in test_cases {
    +        let (converted, _) = convert_streams(test_case.sql, &["--no-config", "--compact"]);
    +
    +        assert_eq!(
    +            converted.trim_end(),
    +            test_case.expected_sql,
    +            "{}",
    +            test_case.description
    +        );
    +    }
    +}
    diff --git a/crates/sqlquack/tests/cli/test_types.rs b/crates/sqlquack/tests/cli/test_types.rs
    index 558f791de..0c5c63d8c 100644
    --- a/crates/sqlquack/tests/cli/test_types.rs
    +++ b/crates/sqlquack/tests/cli/test_types.rs
    @@ -480,3 +480,10 @@ pub(crate) struct FullCaseMappingTestCase {
         pub(crate) between: &'static str,
         pub(crate) expected_mappings: usize,
     }
    +
    +/// A statement and the exact compact SQL `convert` must print for it.
    +pub(crate) struct ConvertedSqlTestCase {
    +    pub(crate) description: &'static str,
    +    pub(crate) sql: &'static str,
    +    pub(crate) expected_sql: &'static str,
    +}
    
    From 9c5aaa2b8b5615250260273a88652f378a171d9b Mon Sep 17 00:00:00 2001
    From: Kevin Longe <273747162+kvlonge@users.noreply.github.com>
    Date: Wed, 25 Nov 2026 19:59:34 +0000
    Subject: [PATCH 8/8] test(coverage): re-record SQL sizes for the smaller
     DuckDB conversions
    
    168 recorded cases change size: 115 shrink with the case mapping, VARIANT
    text, FLOAT and SPLIT changes; 53 grow within the allowed growth, mostly
    ARRAY_TO_STRING, whose list_aggr spelling is longer but which DuckDB now
    expands once instead of twice. All 9,404 cases total 9,057,744 B, down from
    9,089,909 B.
    ---
     coverage/sql-size/baseline.json | 336 ++++++++++++++++----------------
     1 file changed, 168 insertions(+), 168 deletions(-)
    
    diff --git a/coverage/sql-size/baseline.json b/coverage/sql-size/baseline.json
    index b53c8ef21..6aeb8c759 100644
    --- a/coverage/sql-size/baseline.json
    +++ b/coverage/sql-size/baseline.json
    @@ -53,8 +53,8 @@
         "aggregate/array_agg_order_free.toml#order_free_removed_appended_flattened": 4715,
         "aggregate/array_agg_order_free.toml#order_free_set_sizes": 5351,
         "aggregate/array_agg_order_free.toml#order_free_sorted_and_extremes": 10736,
    -    "aggregate/array_agg_order_free.toml#order_observed_after_cte": 2190,
    -    "aggregate/array_agg_order_free.toml#order_observed_single_values": 2668,
    +    "aggregate/array_agg_order_free.toml#order_observed_after_cte": 2212,
    +    "aggregate/array_agg_order_free.toml#order_observed_single_values": 2690,
         "aggregate/array_agg_ties.toml#array_agg_ties_different_values": 1221,
         "aggregate/array_agg_ties.toml#array_agg_ties_equal_values": 2487,
         "aggregate/array_agg_ties.toml#array_agg_ties_null_keys": 1146,
    @@ -65,14 +65,14 @@
         "aggregate/float_min_max.toml#float_min_max_empty": 238,
         "aggregate/float_min_max.toml#float_min_max_groups": 764,
         "aggregate/group_by_all.toml#group_by_all_columns": 756,
    -    "aggregate/group_by_all.toml#group_by_all_expressions": 3378,
    +    "aggregate/group_by_all.toml#group_by_all_expressions": 2648,
         "aggregate/group_by_all.toml#group_by_all_no_rows": 279,
         "aggregate/group_by_all.toml#group_by_all_ordered": 567,
         "aggregate/grouped.toml#avg": 1033,
         "aggregate/grouped.toml#avg_integers": 630,
         "aggregate/grouped.toml#count_forms": 713,
         "aggregate/grouped.toml#empty_input": 1019,
    -    "aggregate/grouped.toml#group_by_position": 3241,
    +    "aggregate/grouped.toml#group_by_position": 2511,
         "aggregate/grouped.toml#grouped_empty_input": 630,
         "aggregate/grouped.toml#having": 669,
         "aggregate/grouped.toml#max_of_variant_distinct_values": 2816,
    @@ -82,31 +82,31 @@
         "aggregate/grouped.toml#sum_wide_in_range": 408,
         "aggregate/grouped.toml#text_min_max": 365,
         "aggregate/mode.toml#mode_all_null_no_group": 3480,
    -    "aggregate/mode.toml#mode_floats": 4603,
    +    "aggregate/mode.toml#mode_floats": 4477,
         "aggregate/mode.toml#mode_no_rows": 713,
         "aggregate/mode.toml#mode_no_rows_having": 1381,
         "aggregate/mode.toml#mode_no_rows_having_excluded": 1280,
         "aggregate/mode.toml#mode_no_rows_timestamp": 1567,
         "aggregate/mode.toml#mode_no_rows_types": 2808,
         "aggregate/mode.toml#mode_numbers": 1166,
    -    "aggregate/mode.toml#mode_signed_zero": 4037,
    +    "aggregate/mode.toml#mode_signed_zero": 3911,
         "aggregate/mode.toml#mode_ties": 698,
         "aggregate/mode.toml#mode_types": 1844,
         "aggregate/mode.toml#mode_values_no_group": 1316,
    -    "aggregate/next_swathe_aggregates.toml#array_agg_distinct_ordered": 8879,
    +    "aggregate/next_swathe_aggregates.toml#array_agg_distinct_ordered": 6743,
         "aggregate/next_swathe_aggregates.toml#array_agg_distinct_single": 930,
         "aggregate/next_swathe_aggregates.toml#max_by_ties": 1711,
         "aggregate/next_swathe_aggregates.toml#max_by_variant_path": 2140,
         "aggregate/next_swathe_aggregates.toml#sum_float_empty": 1022,
         "aggregate/next_swathe_aggregates.toml#sum_float_grouped": 1465,
    -    "aggregate/next_swathe_aggregates.toml#sum_float_of_text": 4661,
    +    "aggregate/next_swathe_aggregates.toml#sum_float_of_text": 4625,
         "aggregate/next_swathe_aggregates.toml#sum_float_window": 4501,
         "aggregate/signed_zero_ties.toml#any_value_one_zero_or_nan": 799,
         "aggregate/signed_zero_ties.toml#any_value_signed_zeros": 699,
         "aggregate/signed_zero_ties.toml#max_by_keys_of_both_zero_signs": 1696,
         "aggregate/signed_zero_ties.toml#max_by_ties_holding_one_zero_or_nan": 2113,
         "aggregate/signed_zero_ties.toml#max_by_ties_holding_signed_zeros": 1826,
    -    "aggregate/within_group.toml#array_agg_within_group": 2378,
    +    "aggregate/within_group.toml#array_agg_within_group": 2400,
         "aggregate/within_group.toml#listagg_distinct_within_group": 1046,
         "aggregate/within_group.toml#listagg_empty": 1395,
         "aggregate/within_group.toml#listagg_null_group": 1392,
    @@ -147,7 +147,7 @@
         "comparison/predicates_batch2.toml#coalesce_ntz_precisions": 543,
         "comparison/predicates_batch2.toml#coalesce_number_text": 3173,
         "comparison/predicates_batch2.toml#coalesce_number_text_invalid": 3008,
    -    "comparison/predicates_batch2.toml#coalesce_text_float": 1984,
    +    "comparison/predicates_batch2.toml#coalesce_text_float": 1930,
         "comparison/predicates_batch2.toml#coalesce_text_number": 3244,
         "comparison/predicates_batch2.toml#coalesce_tz_ntz": 715,
         "comparison/predicates_batch2.toml#compare_float_integer": 569,
    @@ -244,7 +244,7 @@
         "conversion/census_blockers.toml#try_to_number_texts": 1629,
         "conversion/census_blockers.toml#variant_to_bounded_varchar": 669,
         "conversion/census_blockers.toml#variant_to_bounded_varchar_overlong": 466,
    -    "conversion/float_text_magnitudes.toml#float_text_from_text": 1378,
    +    "conversion/float_text_magnitudes.toml#float_text_from_text": 1360,
         "conversion/float_text_magnitudes.toml#float_text_many_rows_band_edges": 2878,
         "conversion/float_text_magnitudes.toml#float_text_many_rows_negatives": 2786,
         "conversion/float_text_magnitudes.toml#float_text_many_rows_six_to_fifteen_whole_digits": 2941,
    @@ -257,7 +257,7 @@
         "conversion/float_text_magnitudes.toml#float_text_single_row_seven_whole_digits": 2364,
         "conversion/float_text_magnitudes.toml#float_text_single_row_small_fraction": 2366,
         "conversion/float_text_magnitudes.toml#float_text_single_row_two_whole_digits": 2364,
    -    "conversion/float_text_remaining.toml#float_concat_from_text": 1304,
    +    "conversion/float_text_remaining.toml#float_concat_from_text": 1286,
         "conversion/float_text_remaining.toml#float_concat_many_rows": 2743,
         "conversion/float_text_remaining.toml#float_concat_single_row": 2084,
         "conversion/float_text_remaining.toml#float_text_negative_zero_many_rows": 2612,
    @@ -288,11 +288,11 @@
         "conversion/to_date.toml#timestamp_to_date": 472,
         "conversion/to_float.toml#decimal_to_double": 339,
         "conversion/to_float.toml#number_to_float": 369,
    -    "conversion/to_float.toml#text_float_overflow": 634,
    -    "conversion/to_float.toml#text_float_spellings": 1021,
    -    "conversion/to_float.toml#text_to_float": 800,
    -    "conversion/to_float.toml#text_to_float_invalid": 632,
    -    "conversion/to_float.toml#text_to_float_lenient": 927,
    +    "conversion/to_float.toml#text_float_overflow": 616,
    +    "conversion/to_float.toml#text_float_spellings": 1003,
    +    "conversion/to_float.toml#text_to_float": 782,
    +    "conversion/to_float.toml#text_to_float_invalid": 614,
    +    "conversion/to_float.toml#text_to_float_lenient": 909,
         "conversion/to_number.toml#boolean_to_number": 345,
         "conversion/to_number.toml#default_number": 399,
         "conversion/to_number.toml#double_colon_int": 1152,
    @@ -405,9 +405,9 @@
         "fidelity/subscript_get.toml#subscript_index_text~canonical": 743,
         "fidelity/subscript_get.toml#subscript_key_column": 1067,
         "fidelity/subscript_get.toml#subscript_key_column~canonical": 1067,
    -    "fidelity/text_float_non_ascii.toml#cast_float_dotted_capital_i": 638,
    -    "fidelity/text_float_non_ascii.toml#to_double_dotted_capital_i": 633,
    -    "fidelity/text_float_non_ascii.toml#try_float_words_non_ascii": 1595,
    +    "fidelity/text_float_non_ascii.toml#cast_float_dotted_capital_i": 620,
    +    "fidelity/text_float_non_ascii.toml#to_double_dotted_capital_i": 615,
    +    "fidelity/text_float_non_ascii.toml#try_float_words_non_ascii": 1559,
         "fidelity/text_type.toml#string_from_date": 328,
         "fidelity/text_type.toml#string_from_date~canonical": 328,
         "fidelity/text_type.toml#string_from_number": 445,
    @@ -434,12 +434,12 @@
         "fidelity/timestampdiff.toml#timestampdiff_seconds~canonical": 1122,
         "fidelity/timestampdiff.toml#timestampdiff_timestamp_units": 2257,
         "fidelity/timestampdiff.toml#timestampdiff_timestamp_units~canonical": 2257,
    -    "fidelity/to_double.toml#to_double_invalid": 631,
    -    "fidelity/to_double.toml#to_double_invalid~canonical": 631,
    -    "fidelity/to_double.toml#to_double_text": 778,
    -    "fidelity/to_double.toml#to_double_text~canonical": 778,
    -    "fidelity/to_double.toml#try_to_double_text": 1047,
    -    "fidelity/to_double.toml#try_to_double_text~canonical": 1047,
    +    "fidelity/to_double.toml#to_double_invalid": 613,
    +    "fidelity/to_double.toml#to_double_invalid~canonical": 613,
    +    "fidelity/to_double.toml#to_double_text": 760,
    +    "fidelity/to_double.toml#to_double_text~canonical": 760,
    +    "fidelity/to_double.toml#try_to_double_text": 1029,
    +    "fidelity/to_double.toml#try_to_double_text~canonical": 1029,
         "fidelity/to_number.toml#to_number_invalid": 1042,
         "fidelity/to_number.toml#to_number_invalid~canonical": 1042,
         "fidelity/to_number.toml#to_number_text": 1185,
    @@ -540,8 +540,8 @@
         "generated/casts/from_varchar.toml#varchar_to_boolean_invalid": 533,
         "generated/casts/from_varchar.toml#varchar_to_date": 402,
         "generated/casts/from_varchar.toml#varchar_to_date_invalid": 207,
    -    "generated/casts/from_varchar.toml#varchar_to_float": 886,
    -    "generated/casts/from_varchar.toml#varchar_to_float_invalid": 632,
    +    "generated/casts/from_varchar.toml#varchar_to_float": 868,
    +    "generated/casts/from_varchar.toml#varchar_to_float_invalid": 614,
         "generated/casts/from_varchar.toml#varchar_to_ltz9": 621,
         "generated/casts/from_varchar.toml#varchar_to_ltz9_invalid": 477,
         "generated/casts/from_varchar.toml#varchar_to_n10_2": 1218,
    @@ -563,7 +563,7 @@
         "generated/casts/from_varchar.toml#varchar_to_varchar3_invalid": 318,
         "generated/casts/try_from_varchar.toml#varchar_try_cast_boolean": 765,
         "generated/casts/try_from_varchar.toml#varchar_try_cast_date": 439,
    -    "generated/casts/try_from_varchar.toml#varchar_try_cast_float": 964,
    +    "generated/casts/try_from_varchar.toml#varchar_try_cast_float": 946,
         "generated/casts/try_from_varchar.toml#varchar_try_cast_ltz9": 662,
         "generated/casts/try_from_varchar.toml#varchar_try_cast_n10_2": 979,
         "generated/casts/try_from_varchar.toml#varchar_try_cast_n38_0": 1043,
    @@ -861,22 +861,22 @@
         "generated/hazards/array_size__semi-structured-array.toml#fn_array_size_0_variant_large_numbers": 717,
         "generated/hazards/array_size__semi-structured-array.toml#fn_array_size_0_variant_number_spellings": 682,
         "generated/hazards/array_size__semi-structured-array.toml#fn_array_size_combination_0_variant": 349,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_0_variant_hazards": 1346,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_0_variant_large_numbers": 1271,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_0_variant_number_spellings": 1236,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_combination_0_variant_null_literal": 905,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_case_only": 3670,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_dollar_prefix": 1541,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_dots_brackets": 2242,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_empty": 840,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_non_ascii": 2951,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_null": 844,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_number_text": 3638,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_quotes_backslashes": 2258,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_slash_prefix": 1539,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_title_case_digraph": 2953,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_whitespace": 3630,
    -    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_combination_0_variant_text_literal": 903,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_0_variant_hazards": 1368,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_0_variant_large_numbers": 1293,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_0_variant_number_spellings": 1258,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_combination_0_variant_null_literal": 927,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_case_only": 3780,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_dollar_prefix": 1585,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_dots_brackets": 2308,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_empty": 862,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_non_ascii": 3039,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_null": 866,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_number_text": 3748,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_quotes_backslashes": 2324,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_slash_prefix": 1583,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_title_case_digraph": 3041,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_1_text_whitespace": 3740,
    +    "generated/hazards/array_to_string__semi-structured-array.toml#fn_array_to_string_combination_0_variant_text_literal": 925,
         "generated/hazards/average__aggregate.toml#node_avg_0_decimal_digits_38": 1266,
         "generated/hazards/average__aggregate.toml#node_avg_0_decimal_hazards": 1593,
         "generated/hazards/average__aggregate.toml#node_avg_0_integer_beyond_64_bits": 1227,
    @@ -992,9 +992,9 @@
         "generated/hazards/bitwise__numeric.toml#fn_bitand_combination_0_integer_integer": 553,
         "generated/hazards/bitwise__numeric.toml#fn_bitand_combination_1_integer_integer": 553,
         "generated/hazards/bitwise__numeric.toml#fn_bitand_combination_2_integer_integer": 555,
    -    "generated/hazards/case_mapping__string.toml#node_upper_0_text_hazards": 3803,
    -    "generated/hazards/case_mapping__string.toml#node_upper_combination_0_text": 2859,
    -    "generated/hazards/case_mapping__string.toml#node_upper_combination_1_text": 488,
    +    "generated/hazards/case_mapping__string.toml#node_upper_0_text_hazards": 3071,
    +    "generated/hazards/case_mapping__string.toml#node_upper_combination_0_text": 2127,
    +    "generated/hazards/case_mapping__string.toml#node_upper_combination_1_text": 235,
         "generated/hazards/cast_boolean__conversion.toml#node_cast_0_boolean_hazards": 218,
         "generated/hazards/cast_boolean__conversion.toml#node_cast_1_0_decimal_digits_38": 334,
         "generated/hazards/cast_boolean__conversion.toml#node_cast_1_0_decimal_hazards": 637,
    @@ -1037,11 +1037,11 @@
         "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_0_text": 824,
         "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_1_text": 1089,
         "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_2_text": 1090,
    -    "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_3_text": 679,
    +    "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_3_text": 661,
         "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_4_text": 579,
         "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_5_text": 246,
         "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_6_text": 823,
    -    "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_7_text": 731,
    +    "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_7_text": 713,
         "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_8_text": 487,
         "generated/hazards/cast_parsed_text__conversion.toml#node_cast_combination_9_text": 250,
         "generated/hazards/cast_same_type__conversion.toml#fn_to_date_21_0_date_extreme_years": 266,
    @@ -3407,10 +3407,10 @@
         "generated/hazards/percentile__window.toml#node_window_function_1_window_empty_input": 239,
         "generated/hazards/percentile__window.toml#node_window_function_1_window_null_beside_value": 433,
         "generated/hazards/percentile__window.toml#node_window_function_1_window_single_row": 289,
    -    "generated/hazards/reduce__semi-structured-array.toml#fn_reduce_0_variant_hazards": 2767,
    -    "generated/hazards/reduce__semi-structured-array.toml#fn_reduce_0_variant_large_numbers": 2692,
    -    "generated/hazards/reduce__semi-structured-array.toml#fn_reduce_0_variant_number_spellings": 2657,
    -    "generated/hazards/reduce__semi-structured-array.toml#fn_reduce_combination_0_variant": 2346,
    +    "generated/hazards/reduce__semi-structured-array.toml#fn_reduce_0_variant_hazards": 2731,
    +    "generated/hazards/reduce__semi-structured-array.toml#fn_reduce_0_variant_large_numbers": 2656,
    +    "generated/hazards/reduce__semi-structured-array.toml#fn_reduce_0_variant_number_spellings": 2621,
    +    "generated/hazards/reduce__semi-structured-array.toml#fn_reduce_combination_0_variant": 2310,
         "generated/hazards/regexp__string.toml#fn_regexp_like_0_text_hazards": 1176,
         "generated/hazards/regexp__string.toml#fn_regexp_like_1_0_text_hazards": 1181,
         "generated/hazards/regexp__string.toml#fn_regexp_like_1_combination_0_text_text_literal_text_literal": 237,
    @@ -3575,26 +3575,26 @@
         "generated/hazards/text_hex__string.toml#fn_hex_encode_combination_0_text": 211,
         "generated/hazards/text_hex_decode__string.toml#fn_try_hex_decode_string_0_text_hazards": 1294,
         "generated/hazards/text_hex_decode__string.toml#fn_try_hex_decode_string_combination_0_text": 350,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_dollar_prefix": 1273,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_dots_brackets": 1322,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_hazards": 1459,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_non_ascii": 1358,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_number_text": 1378,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_quotes_backslashes": 1330,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_slash_prefix": 1272,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_title_case_digraph": 1359,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_whitespace": 1374,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_dollar_prefix": 1261,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_dots_brackets": 1310,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_hazards": 1447,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_non_ascii": 1346,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_number_text": 1366,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_quotes_backslashes": 1318,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_slash_prefix": 1260,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_title_case_digraph": 1347,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_whitespace": 1362,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_1_combination_0_text_literal_text": 1259,
    -    "generated/hazards/text_initcap__string.toml#fn_initcap_combination_0_text": 1271,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_dollar_prefix": 1042,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_dots_brackets": 1091,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_hazards": 1228,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_non_ascii": 1127,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_number_text": 1147,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_quotes_backslashes": 1099,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_slash_prefix": 1041,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_title_case_digraph": 1128,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_0_text_whitespace": 1143,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_dollar_prefix": 1030,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_dots_brackets": 1079,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_hazards": 1216,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_non_ascii": 1115,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_number_text": 1135,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_quotes_backslashes": 1087,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_slash_prefix": 1029,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_title_case_digraph": 1116,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_1_1_text_whitespace": 1131,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_1_combination_0_text_literal_text": 1028,
    +    "generated/hazards/text_initcap__string.toml#fn_initcap_combination_0_text": 1040,
         "generated/hazards/text_number_comparison__comparison.toml#node_eq_0_text_hazards": 3611,
         "generated/hazards/text_number_comparison__comparison.toml#node_eq_0_text_number_text": 2257,
         "generated/hazards/text_number_comparison__comparison.toml#node_eq_1_decimal_digits_38": 1607,
    @@ -3647,8 +3647,8 @@
         "generated/hazards/text_replace__string.toml#fn_replace_1_combination_0_text_text_text": 377,
         "generated/hazards/text_replace__string.toml#fn_replace_1_text_hazards": 1360,
         "generated/hazards/text_replace__string.toml#fn_replace_combination_0_text_text": 338,
    -    "generated/hazards/text_replace__string.toml#fn_split_part_2_0_text_hazards": 1280,
    -    "generated/hazards/text_replace__string.toml#fn_split_part_2_combination_0_text_text_literal_integer_literal": 336,
    +    "generated/hazards/text_replace__string.toml#fn_split_part_2_0_text_hazards": 1170,
    +    "generated/hazards/text_replace__string.toml#fn_split_part_2_combination_0_text_text_literal_integer_literal": 226,
         "generated/hazards/text_to_time__temporal.toml#fn_to_time_0_text_dots_brackets": 1742,
         "generated/hazards/text_to_time__temporal.toml#fn_to_time_0_text_hazards": 2422,
         "generated/hazards/text_to_time__temporal.toml#fn_to_time_0_text_number_text": 1798,
    @@ -3783,11 +3783,11 @@
         "generated/hazards/unary_plus__numeric.toml#node_pos_0_integer_beyond_64_bits": 286,
         "generated/hazards/unary_plus__numeric.toml#node_pos_0_integer_digits_38": 323,
         "generated/hazards/unary_plus__numeric.toml#node_pos_0_integer_hazards": 445,
    -    "generated/hazards/unary_plus__numeric.toml#node_pos_0_text_hazards": 1623,
    +    "generated/hazards/unary_plus__numeric.toml#node_pos_0_text_hazards": 1605,
         "generated/hazards/unary_plus__numeric.toml#node_pos_combination_0_decimal": 255,
         "generated/hazards/unary_plus__numeric.toml#node_pos_combination_0_float": 239,
         "generated/hazards/unary_plus__numeric.toml#node_pos_combination_0_integer": 248,
    -    "generated/hazards/unary_plus__numeric.toml#node_pos_combination_0_text": 679,
    +    "generated/hazards/unary_plus__numeric.toml#node_pos_combination_0_text": 661,
         "generated/hazards/value_at_extreme_key__aggregate.toml#fn_max_by_0_boolean_hazards": 844,
         "generated/hazards/value_at_extreme_key__aggregate.toml#fn_max_by_0_date_extreme_years": 949,
         "generated/hazards/value_at_extreme_key__aggregate.toml#fn_max_by_0_date_hazards": 1130,
    @@ -6120,7 +6120,7 @@
         "imported/sqlglot_string.toml#rpad_default_pad": 452,
         "imported/sqlglot_string.toml#rpad_exact_length": 455,
         "imported/sqlglot_string.toml#rpad_with_pattern": 458,
    -    "imported/sqlglot_string.toml#split_part_middle": 275,
    +    "imported/sqlglot_string.toml#split_part_middle": 165,
         "imported/sqlglot_window.toml#lag_basic": 507,
         "imported/sqlglot_window.toml#lag_full_respect_nulls": 810,
         "imported/sqlglot_window.toml#lag_offset_ignore_nulls": 849,
    @@ -6215,7 +6215,7 @@
         "numeric/small_functions_batch3.toml#median_of_38_digit_integers": 2170,
         "numeric/small_functions_batch3.toml#median_values": 1713,
         "numeric/small_functions_batch3.toml#median_wide_numbers": 2632,
    -    "numeric/small_functions_batch3.toml#nullifzero_and_logs": 1503,
    +    "numeric/small_functions_batch3.toml#nullifzero_and_logs": 1557,
         "numeric/small_functions_batch3.toml#sqrt_of_negative": 327,
         "numeric/small_functions_batch3.toml#sqrt_values": 950,
         "numeric/small_functions_batch3.toml#substr_computed_lengths": 2404,
    @@ -6379,7 +6379,7 @@
         "relational/quoted_identifiers_ignore_case.toml#select_star_over_quoted_columns": 533,
         "relational/quoted_identifiers_ignore_case.toml#unquoted_variant_key_stays_case_sensitive": 754,
         "relational/set_operation_text_unification.toml#except_number_and_text": 2731,
    -    "relational/set_operation_text_unification.toml#union_float_and_text": 1805,
    +    "relational/set_operation_text_unification.toml#union_float_and_text": 1769,
         "relational/set_operations.toml#except": 782,
         "relational/set_operations.toml#except_empty": 782,
         "relational/set_operations.toml#minus": 782,
    @@ -6429,7 +6429,7 @@
         "relational/unaliased_name_comment_edges.toml#simple_case_and_dateadd": 1131,
         "relational/unaliased_name_comment_edges.toml#stacked_block_comments": 145,
         "relational/unaliased_output_names.toml#unaliased_aggregates": 934,
    -    "relational/unaliased_output_names.toml#unaliased_expressions": 4051,
    +    "relational/unaliased_output_names.toml#unaliased_expressions": 3064,
         "relational/unaliased_output_names.toml#unaliased_group_count": 326,
         "relational/unaliased_output_names.toml#unaliased_literals": 420,
         "relational/unaliased_output_names.toml#unaliased_over_no_rows": 262,
    @@ -6444,8 +6444,8 @@
         "relational/unaliased_round_current.toml#unaliased_current_time": 236,
         "relational/unaliased_round_current.toml#unaliased_round": 498,
         "relational/unaliased_round_current.toml#unaliased_round_no_rows": 285,
    -    "relational/unaliased_round_current.toml#unaliased_row_expressions": 1788,
    -    "relational/unaliased_round_current.toml#unaliased_row_expressions_no_rows": 1604,
    +    "relational/unaliased_round_current.toml#unaliased_row_expressions": 1535,
    +    "relational/unaliased_round_current.toml#unaliased_row_expressions_no_rows": 1351,
         "relational/unaliased_trailing_comments.toml#trailing_block_comment_integer": 152,
         "relational/unaliased_trailing_comments.toml#trailing_line_comment_boolean": 136,
         "relational/unaliased_trailing_comments.toml#trailing_line_comment_column": 263,
    @@ -6541,16 +6541,16 @@
         "semi-structured/array_sets_batch4.toml#array_remove_values": 3354,
         "semi-structured/array_sets_batch4.toml#array_sets_integers_and_strings": 3207,
         "semi-structured/array_sets_batch4.toml#array_sets_objects_reordered": 3064,
    -    "semi-structured/array_to_string_text.toml#array_to_string_control_array": 966,
    -    "semi-structured/array_to_string_text.toml#array_to_string_control_object": 954,
    -    "semi-structured/array_to_string_text.toml#array_to_string_control_strings": 961,
    -    "semi-structured/array_to_string_text.toml#array_to_string_long_decimal": 953,
    -    "semi-structured/array_to_string_text.toml#array_to_string_numbers": 995,
    -    "semi-structured/array_to_string_text.toml#array_to_string_numbers_in_objects": 965,
    -    "semi-structured/array_to_string_text.toml#array_to_string_sorted_elements": 1128,
    -    "semi-structured/array_to_string_text.toml#array_to_string_unsorted_keys_mixed": 965,
    -    "semi-structured/array_to_string_text.toml#array_to_string_unsorted_nested": 985,
    -    "semi-structured/array_to_string_text.toml#array_to_string_unsorted_object": 947,
    +    "semi-structured/array_to_string_text.toml#array_to_string_control_array": 988,
    +    "semi-structured/array_to_string_text.toml#array_to_string_control_object": 976,
    +    "semi-structured/array_to_string_text.toml#array_to_string_control_strings": 983,
    +    "semi-structured/array_to_string_text.toml#array_to_string_long_decimal": 975,
    +    "semi-structured/array_to_string_text.toml#array_to_string_numbers": 1017,
    +    "semi-structured/array_to_string_text.toml#array_to_string_numbers_in_objects": 987,
    +    "semi-structured/array_to_string_text.toml#array_to_string_sorted_elements": 1150,
    +    "semi-structured/array_to_string_text.toml#array_to_string_unsorted_keys_mixed": 987,
    +    "semi-structured/array_to_string_text.toml#array_to_string_unsorted_nested": 1007,
    +    "semi-structured/array_to_string_text.toml#array_to_string_unsorted_object": 969,
         "semi-structured/arrays_batch2.toml#array_cat_coalesce_construct": 1160,
         "semi-structured/arrays_batch2.toml#array_cat_coalesce_literal": 1745,
         "semi-structured/arrays_batch2.toml#array_cat_not_array": 897,
    @@ -6579,7 +6579,7 @@
         "semi-structured/arrays_batch2.toml#transform_not_array": 962,
         "semi-structured/arrays_batch2.toml#transform_object_insert": 1901,
         "semi-structured/arrays_batch2.toml#transform_size": 1066,
    -    "semi-structured/arrays_batch2.toml#transform_split_left": 9943,
    +    "semi-structured/arrays_batch2.toml#transform_split_left": 3931,
         "semi-structured/arrays_batch2.toml#transform_text": 1226,
         "semi-structured/arrays_batch2.toml#transform_typed_varchar": 2280,
         "semi-structured/arrays_batch2.toml#transform_typed_varchar_parenthesized": 2280,
    @@ -6593,14 +6593,14 @@
         "semi-structured/constructors.toml#array_construct_values": 1868,
         "semi-structured/constructors.toml#array_contains_values": 2987,
         "semi-structured/constructors.toml#array_size_values": 1495,
    -    "semi-structured/constructors.toml#array_to_string_empty_array": 929,
    -    "semi-structured/constructors.toml#array_to_string_json_nulls": 938,
    -    "semi-structured/constructors.toml#array_to_string_not_array": 802,
    -    "semi-structured/constructors.toml#array_to_string_path_absent": 1743,
    -    "semi-structured/constructors.toml#array_to_string_path_json_null": 1601,
    -    "semi-structured/constructors.toml#array_to_string_path_nested": 1618,
    -    "semi-structured/constructors.toml#array_to_string_scalars": 962,
    -    "semi-structured/constructors.toml#array_to_string_sql_null": 946,
    +    "semi-structured/constructors.toml#array_to_string_empty_array": 951,
    +    "semi-structured/constructors.toml#array_to_string_json_nulls": 960,
    +    "semi-structured/constructors.toml#array_to_string_not_array": 824,
    +    "semi-structured/constructors.toml#array_to_string_path_absent": 1787,
    +    "semi-structured/constructors.toml#array_to_string_path_json_null": 1645,
    +    "semi-structured/constructors.toml#array_to_string_path_nested": 1662,
    +    "semi-structured/constructors.toml#array_to_string_scalars": 984,
    +    "semi-structured/constructors.toml#array_to_string_sql_null": 968,
         "semi-structured/constructors.toml#coalesce_variants": 835,
         "semi-structured/constructors.toml#object_construct_duplicate_key": 831,
         "semi-structured/constructors.toml#object_construct_empty": 615,
    @@ -6625,7 +6625,7 @@
         "semi-structured/filter.toml#filter_objects_by_label": 1165,
         "semi-structured/filter.toml#filter_objects_first": 1128,
         "semi-structured/filter.toml#filter_size": 1103,
    -    "semi-structured/filter.toml#filter_split_length": 9182,
    +    "semi-structured/filter.toml#filter_split_length": 3192,
         "semi-structured/filter.toml#filter_split_nonempty": 1114,
         "semi-structured/filter.toml#filter_startswith": 978,
         "semi-structured/flatten.toml#flatten_after_two_sources": 1652,
    @@ -6758,7 +6758,7 @@
         "semi-structured/next_swathe_variants.toml#array_literal_values": 1148,
         "semi-structured/next_swathe_variants.toml#object_constant_column_values": 1178,
         "semi-structured/next_swathe_variants.toml#object_constant_nested_values": 1078,
    -    "semi-structured/next_swathe_variants.toml#reduce_text_amounts": 2459,
    +    "semi-structured/next_swathe_variants.toml#reduce_text_amounts": 2423,
         "semi-structured/next_swathe_variants.toml#variant_equals_variant": 1127,
         "semi-structured/next_swathe_variants.toml#variant_equals_variant_in_filter": 1107,
         "semi-structured/object_constants.toml#object_constant_empty": 314,
    @@ -6879,8 +6879,8 @@
         "semi-structured/try_parse_json_truncated.toml#try_parse_json_truncated_typeof": 1693,
         "semi-structured/undefined_elements.toml#array_size_counts_undefined": 2589,
         "semi-structured/undefined_elements.toml#array_size_of_non_array": 590,
    -    "semi-structured/undefined_elements.toml#undefined_elements_as_text": 1131,
    -    "semi-structured/undefined_elements.toml#undefined_elements_distinct_union": 3180,
    +    "semi-structured/undefined_elements.toml#undefined_elements_as_text": 1175,
    +    "semi-structured/undefined_elements.toml#undefined_elements_distinct_union": 3202,
         "semi-structured/variant_branches.toml#coalesce_case_and_index": 526,
         "semi-structured/variant_branches.toml#coalesce_paths": 1313,
         "semi-structured/variant_branches.toml#coalesce_variant_result": 602,
    @@ -6950,8 +6950,8 @@
         "string/base64_binary.toml#base64_utf8_zero_byte": 687,
         "string/case_folding_letters.toml#case_insensitive_like_long_s_and_kelvin": 3566,
         "string/case_folding_letters.toml#case_insensitive_long_s_and_kelvin": 2903,
    -    "string/case_mapping.toml#lower": 636,
    -    "string/case_mapping.toml#upper": 3012,
    +    "string/case_mapping.toml#lower": 383,
    +    "string/case_mapping.toml#upper": 2278,
         "string/charindex.toml#charindex_characters": 543,
         "string/charindex.toml#charindex_values": 730,
         "string/charindex.toml#position_in_query": 905,
    @@ -6981,7 +6981,7 @@
         "string/pad.toml#lpad_values": 1171,
         "string/pad.toml#pad_default": 958,
         "string/pad.toml#rpad_values": 928,
    -    "string/parse_url.toml#parse_url_lowered_hosts_aggregated": 11482,
    +    "string/parse_url.toml#parse_url_lowered_hosts_aggregated": 10723,
         "string/parse_url.toml#parse_url_permissive_fields": 10805,
         "string/regexp.toml#regexp_like": 354,
         "string/regexp.toml#regexp_operator_whole_string": 426,
    @@ -6995,7 +6995,7 @@
         "string/regexp.toml#regexp_substr_group": 321,
         "string/regexp_batch2.toml#regexp_like_bracket_colon": 460,
         "string/regexp_batch2.toml#regexp_like_column_pattern": 779,
    -    "string/regexp_batch2.toml#regexp_like_column_pattern_parameters": 1679,
    +    "string/regexp_batch2.toml#regexp_like_column_pattern_parameters": 1426,
         "string/regexp_batch2.toml#regexp_like_fullwidth_colon": 398,
         "string/regexp_batch2.toml#regexp_like_is": 367,
         "string/regexp_batch2.toml#regexp_like_space_class_words": 444,
    @@ -7039,12 +7039,12 @@
         "string/regexp_substr_batch.toml#regexp_substr_space_class": 423,
         "string/regexp_substr_batch.toml#regexp_substr_space_class_trim": 395,
         "string/regexp_word_boundary.toml#regexp_substr_word_boundary": 672,
    -    "string/split.toml#array_to_string_split": 1109,
    +    "string/split.toml#array_to_string_split": 1131,
         "string/split.toml#split_index": 880,
    -    "string/split.toml#split_part_delimiters": 571,
    -    "string/split.toml#split_part_positions": 957,
    +    "string/split.toml#split_part_delimiters": 351,
    +    "string/split.toml#split_part_positions": 627,
         "string/split.toml#split_part_window_part_over_variant_text": 4224,
    -    "string/split.toml#split_part_zero": 290,
    +    "string/split.toml#split_part_zero": 180,
         "string/split_array.toml#split_escapes": 381,
         "string/split_array.toml#split_separators": 1057,
         "string/split_array.toml#split_values": 985,
    @@ -7062,12 +7062,12 @@
         "string/text_functions_batch2.toml#hex_encode_lower": 283,
         "string/text_functions_batch2.toml#ilike_non_ascii": 2392,
         "string/text_functions_batch2.toml#ilike_non_ascii_sharp_s": 1321,
    -    "string/text_functions_batch2.toml#initcap_delimiters": 1329,
    -    "string/text_functions_batch2.toml#initcap_digraphs": 1433,
    -    "string/text_functions_batch2.toml#initcap_empty_delimiters": 1224,
    -    "string/text_functions_batch2.toml#initcap_georgian": 1421,
    -    "string/text_functions_batch2.toml#initcap_replace": 1405,
    -    "string/text_functions_batch2.toml#initcap_words": 1616,
    +    "string/text_functions_batch2.toml#initcap_delimiters": 1098,
    +    "string/text_functions_batch2.toml#initcap_digraphs": 1202,
    +    "string/text_functions_batch2.toml#initcap_empty_delimiters": 993,
    +    "string/text_functions_batch2.toml#initcap_georgian": 1190,
    +    "string/text_functions_batch2.toml#initcap_replace": 1174,
    +    "string/text_functions_batch2.toml#initcap_words": 1385,
         "string/text_functions_batch2.toml#not_ilike_any": 2288,
         "string/text_functions_batch2.toml#to_boolean_invalid": 533,
         "string/text_functions_batch2.toml#to_boolean_text": 673,
    @@ -7075,22 +7075,22 @@
         "string/text_functions_batch2.toml#try_hex_decode_string_edges": 540,
         "string/text_functions_batch2.toml#try_to_boolean_text": 1001,
         "string/text_functions_batch2.toml#try_to_boolean_variant": 922,
    -    "string/text_functions_batch3.toml#chr_built_arguments": 764,
    +    "string/text_functions_batch3.toml#chr_built_arguments": 544,
         "string/text_functions_batch3.toml#dates_read_as_text": 412,
         "string/text_functions_batch3.toml#digests_and_day_names": 689,
         "string/text_functions_batch3.toml#flattened_split_values_as_text": 1832,
         "string/text_functions_batch3.toml#hex_decode_invalid": 530,
    -    "string/text_functions_batch3.toml#jarowinkler_accented_both_cases": 1498,
    -    "string/text_functions_batch3.toml#jarowinkler_latin_letters": 1506,
    -    "string/text_functions_batch3.toml#jarowinkler_prefix_and_threshold": 1633,
    -    "string/text_functions_batch3.toml#jarowinkler_similarity": 4211,
    +    "string/text_functions_batch3.toml#jarowinkler_accented_both_cases": 1514,
    +    "string/text_functions_batch3.toml#jarowinkler_latin_letters": 1522,
    +    "string/text_functions_batch3.toml#jarowinkler_prefix_and_threshold": 1649,
    +    "string/text_functions_batch3.toml#jarowinkler_similarity": 4259,
         "string/text_functions_batch3.toml#regexp_count_and_instr": 3850,
         "string/text_functions_batch3.toml#regexp_count_and_instr_plain": 3645,
         "string/text_functions_batch3.toml#regexp_instr_end_anchor_empty_text": 1941,
         "string/text_functions_batch3.toml#regexp_instr_lazy_after_partial_match": 1112,
         "string/text_functions_batch3.toml#regexp_lazy_quantifiers_count_instr": 2351,
         "string/text_functions_batch3.toml#regexp_multiline_dot_carriage_return": 1150,
    -    "string/text_functions_batch3.toml#variants_read_as_text": 1241,
    +    "string/text_functions_batch3.toml#variants_read_as_text": 1131,
         "string/translate.toml#translate_column_spellings": 489,
         "string/trim.toml#ltrim_rtrim": 352,
         "string/trim.toml#trim_characters": 341,
    @@ -8020,9 +8020,9 @@
         "translation/expressions/data-types-logical.toml#t004_other_text": 561,
         "translation/expressions/data-types-logical.toml#t007_implicit_to_text": 343,
         "translation/expressions/data-types-logical.toml#t009_null": 622,
    -    "translation/expressions/data-types-numeric.double.toml#t001_synonyms": 2733,
    -    "translation/expressions/data-types-numeric.double.toml#t002_special_values": 1808,
    -    "translation/expressions/data-types-numeric.double.toml#t003_null": 724,
    +    "translation/expressions/data-types-numeric.double.toml#t001_synonyms": 2643,
    +    "translation/expressions/data-types-numeric.double.toml#t002_special_values": 1754,
    +    "translation/expressions/data-types-numeric.double.toml#t003_null": 706,
         "translation/expressions/data-types-numeric.int.toml#t001_synonyms_wide": 5653,
         "translation/expressions/data-types-numeric.int.toml#t002_thirty_eight_digits": 1189,
         "translation/expressions/data-types-numeric.int.toml#t003_past_38_digits": 1106,
    @@ -8112,12 +8112,12 @@
         "translation/expressions/operators-arithmetic.unary-minus.toml#t004_null": 181,
         "translation/expressions/operators-arithmetic.unary-minus.toml#t005_max": 320,
         "translation/expressions/operators-arithmetic.unary-minus.toml#t006_double_neg": 330,
    -    "translation/expressions/operators-arithmetic.unary-plus.toml#t001_text": 1249,
    +    "translation/expressions/operators-arithmetic.unary-plus.toml#t001_text": 1213,
         "translation/expressions/operators-arithmetic.unary-plus.toml#t002_dec": 249,
         "translation/expressions/operators-arithmetic.unary-plus.toml#t003_float": 235,
    -    "translation/expressions/operators-arithmetic.unary-plus.toml#t004_null": 644,
    -    "translation/expressions/operators-arithmetic.unary-plus.toml#t005_empty": 625,
    -    "translation/expressions/operators-arithmetic.unary-plus.toml#t006_bad_text": 627,
    +    "translation/expressions/operators-arithmetic.unary-plus.toml#t004_null": 626,
    +    "translation/expressions/operators-arithmetic.unary-plus.toml#t005_empty": 607,
    +    "translation/expressions/operators-arithmetic.unary-plus.toml#t006_bad_text": 609,
         "translation/expressions/operators-comparison.equal.toml#t001_number_float": 532,
         "translation/expressions/operators-comparison.equal.toml#t002_varchar": 358,
         "translation/expressions/operators-comparison.equal.toml#t003_date_timestamp": 738,
    @@ -8263,7 +8263,7 @@
         "translation/functions/array-slice.toml#t003_beyond_ends": 1323,
         "translation/functions/array-slice.toml#t004_null_from": 1335,
         "translation/functions/array-sort.toml#t001_defaults": 2302,
    -    "translation/functions/array-to-string.toml#t002_sql_null_element": 668,
    +    "translation/functions/array-to-string.toml#t002_sql_null_element": 690,
         "translation/functions/arrays-overlap.toml#t001_overlap": 1075,
         "translation/functions/arrays-overlap.toml#t002_objects": 1101,
         "translation/functions/arrays-overlap.toml#t003_number_vs_text": 1018,
    @@ -8570,10 +8570,10 @@
         "translation/functions/in.in.toml#t003_varchar": 216,
         "translation/functions/in.in.toml#t004_null_value": 282,
         "translation/functions/in.in.toml#t005_null_value_1": 340,
    -    "translation/functions/initcap.toml#t001_varchar": 1351,
    -    "translation/functions/initcap.toml#t002_delimiters": 2311,
    -    "translation/functions/initcap.toml#t003_null_expr": 1284,
    -    "translation/functions/initcap.toml#t005_empty_delimiters": 1162,
    +    "translation/functions/initcap.toml#t001_varchar": 1120,
    +    "translation/functions/initcap.toml#t002_delimiters": 1849,
    +    "translation/functions/initcap.toml#t003_null_expr": 1053,
    +    "translation/functions/initcap.toml#t005_empty_delimiters": 931,
         "translation/functions/is-array.toml#t001_json": 622,
         "translation/functions/is-array.toml#t003_null_variant_expr": 365,
         "translation/functions/is-binary.toml#t001_json": 886,
    @@ -8604,10 +8604,10 @@
         "translation/functions/is-timestamp.is-timestamp-ntz.toml#t003_null_variant_expr": 629,
         "translation/functions/is-timestamp.is-timestamp-tz.toml#t001_json": 886,
         "translation/functions/is-timestamp.is-timestamp-tz.toml#t003_null_variant_expr": 629,
    -    "translation/functions/jarowinkler-similarity.toml#t001_varchar": 1484,
    -    "translation/functions/jarowinkler-similarity.toml#t002_null_string_expr1": 1360,
    -    "translation/functions/jarowinkler-similarity.toml#t003_null_string_expr2": 1361,
    -    "translation/functions/jarowinkler-similarity.toml#t004_empty": 1339,
    +    "translation/functions/jarowinkler-similarity.toml#t001_varchar": 1500,
    +    "translation/functions/jarowinkler-similarity.toml#t002_null_string_expr1": 1376,
    +    "translation/functions/jarowinkler-similarity.toml#t003_null_string_expr2": 1377,
    +    "translation/functions/jarowinkler-similarity.toml#t004_empty": 1355,
         "translation/functions/lag.toml#t001_offset_default": 895,
         "translation/functions/lag.toml#t002_ignore_nulls": 857,
         "translation/functions/lag.toml#t003_negative_offset": 845,
    @@ -8665,9 +8665,9 @@
         "translation/functions/ln.toml#t004_null": 370,
         "translation/functions/ln.toml#t005_tiny": 437,
         "translation/functions/ln.toml#t006_zero": 367,
    -    "translation/functions/lower.toml#t001_varchar": 507,
    -    "translation/functions/lower.toml#t002_null_expr": 500,
    -    "translation/functions/lower.toml#t003_empty": 435,
    +    "translation/functions/lower.toml#t001_varchar": 254,
    +    "translation/functions/lower.toml#t002_null_expr": 247,
    +    "translation/functions/lower.toml#t003_empty": 182,
         "translation/functions/lpad.toml#t001_varchar": 590,
         "translation/functions/lpad.toml#t002_truncate": 477,
         "translation/functions/lpad.toml#t003_default_pad": 473,
    @@ -8923,8 +8923,8 @@
         "translation/functions/sign.toml#t004_null": 206,
         "translation/functions/sign.toml#t005_extremes": 442,
         "translation/functions/split-part.toml#t001_varchar": 699,
    -    "translation/functions/split-part.toml#t002_part_zero": 286,
    -    "translation/functions/split-part.toml#t003_null_string": 348,
    +    "translation/functions/split-part.toml#t002_part_zero": 176,
    +    "translation/functions/split-part.toml#t003_null_string": 238,
         "translation/functions/split-part.toml#t004_null_delimiter": 555,
         "translation/functions/split-part.toml#t005_null_partnumber": 345,
         "translation/functions/split-part.toml#t006_empty_parts": 689,
    @@ -8952,7 +8952,7 @@
         "translation/functions/stddev-pop.stddev-pop-over.toml#t009_distinct_partition": 1451,
         "translation/functions/stddev-pop.stddev-pop.toml#t001_number": 1359,
         "translation/functions/stddev-pop.stddev-pop.toml#t002_single_row": 1308,
    -    "translation/functions/stddev-pop.stddev-pop.toml#t003_varchar": 4103,
    +    "translation/functions/stddev-pop.stddev-pop.toml#t003_varchar": 4085,
         "translation/functions/stddev-pop.stddev-pop.toml#t004_distinct": 1503,
         "translation/functions/stddev-pop.stddev-pop.toml#t005_null_expr1": 1116,
         "translation/functions/stddev-pop.stddev-pop.toml#t006_empty_input": 771,
    @@ -8975,14 +8975,14 @@
         "translation/functions/stddev.stddev-samp-over.toml#t009_distinct_partition": 1457,
         "translation/functions/stddev.stddev-samp.toml#t001_number": 1365,
         "translation/functions/stddev.stddev-samp.toml#t002_single_row": 1314,
    -    "translation/functions/stddev.stddev-samp.toml#t003_varchar": 4109,
    +    "translation/functions/stddev.stddev-samp.toml#t003_varchar": 4091,
         "translation/functions/stddev.stddev-samp.toml#t004_distinct": 1509,
         "translation/functions/stddev.stddev-samp.toml#t005_null_expr1": 1122,
         "translation/functions/stddev.stddev-samp.toml#t006_empty_input": 777,
         "translation/functions/stddev.stddev-samp.toml#t007_large_mean": 945,
         "translation/functions/stddev.stddev.toml#t001_number": 1365,
         "translation/functions/stddev.stddev.toml#t002_single_row": 1314,
    -    "translation/functions/stddev.stddev.toml#t003_varchar": 4109,
    +    "translation/functions/stddev.stddev.toml#t003_varchar": 4091,
         "translation/functions/stddev.stddev.toml#t004_distinct": 1509,
         "translation/functions/stddev.stddev.toml#t005_null_expr1": 1122,
         "translation/functions/stddev.stddev.toml#t006_empty_input": 777,
    @@ -9101,9 +9101,9 @@
         "translation/functions/to-decimal.to-numeric.toml#t003_variant": 523,
         "translation/functions/to-decimal.to-numeric.toml#t004_precision": 1002,
         "translation/functions/to-decimal.to-numeric.toml#t005_null_expr": 1054,
    -    "translation/functions/to-double.toml#t001_strings": 763,
    -    "translation/functions/to-double.toml#t003_invalid": 628,
    -    "translation/functions/to-double.toml#t004_null_expr": 644,
    +    "translation/functions/to-double.toml#t001_strings": 745,
    +    "translation/functions/to-double.toml#t003_invalid": 610,
    +    "translation/functions/to-double.toml#t004_null_expr": 626,
         "translation/functions/to-json.toml#t001_compact": 370,
         "translation/functions/to-json.toml#t002_json_null": 435,
         "translation/functions/to-json.toml#t003_null_expr": 450,
    @@ -9162,17 +9162,17 @@
         "translation/functions/try-to-decimal.try-to-numeric.toml#t001_scale": 800,
         "translation/functions/try-to-decimal.try-to-numeric.toml#t002_invalid": 794,
         "translation/functions/try-to-decimal.try-to-numeric.toml#t004_null_string_expr": 788,
    -    "translation/functions/try-to-double.toml#t001_valid": 731,
    -    "translation/functions/try-to-double.toml#t002_invalid": 730,
    -    "translation/functions/try-to-double.toml#t004_null_string_expr": 696,
    +    "translation/functions/try-to-double.toml#t001_valid": 713,
    +    "translation/functions/try-to-double.toml#t002_invalid": 712,
    +    "translation/functions/try-to-double.toml#t004_null_string_expr": 678,
         "translation/functions/try-to-timestamp.toml#t001_strings": 1499,
         "translation/functions/try-to-timestamp.toml#t004_invalid": 303,
         "translation/functions/try-to-timestamp.toml#t005_null_string_expr": 255,
         "translation/functions/typeof.toml#t001_json": 1206,
         "translation/functions/typeof.toml#t003_null_expr": 949,
    -    "translation/functions/upper.toml#t001_varchar": 2884,
    -    "translation/functions/upper.toml#t003_null_expr": 2871,
    -    "translation/functions/upper.toml#t004_empty": 2806,
    +    "translation/functions/upper.toml#t001_varchar": 2150,
    +    "translation/functions/upper.toml#t003_null_expr": 2137,
    +    "translation/functions/upper.toml#t004_empty": 2072,
         "translation/functions/var-pop.var-pop-over.toml#t001_partition": 1439,
         "translation/functions/var-pop.var-pop-over.toml#t002_empty_over": 1271,
         "translation/functions/var-pop.var-pop-over.toml#t003_order_ties": 1691,
    @@ -9183,7 +9183,7 @@
         "translation/functions/var-pop.var-pop-over.toml#t009_distinct_partition": 1429,
         "translation/functions/var-pop.var-pop.toml#t001_number": 1337,
         "translation/functions/var-pop.var-pop.toml#t002_single_row": 1286,
    -    "translation/functions/var-pop.var-pop.toml#t003_varchar": 4097,
    +    "translation/functions/var-pop.var-pop.toml#t003_varchar": 4079,
         "translation/functions/var-pop.var-pop.toml#t004_distinct": 1481,
         "translation/functions/var-pop.var-pop.toml#t005_null_expr1": 1094,
         "translation/functions/var-pop.var-pop.toml#t006_empty_input": 749,
    @@ -9198,7 +9198,7 @@
         "translation/functions/var-samp.var-samp-over.toml#t008_distinct_ignored": 1435,
         "translation/functions/var-samp.var-samp.toml#t001_number": 1343,
         "translation/functions/var-samp.var-samp.toml#t002_single_row": 1292,
    -    "translation/functions/var-samp.var-samp.toml#t003_varchar": 4103,
    +    "translation/functions/var-samp.var-samp.toml#t003_varchar": 4085,
         "translation/functions/var-samp.var-samp.toml#t004_distinct": 1487,
         "translation/functions/var-samp.var-samp.toml#t005_null_expr1": 1100,
         "translation/functions/var-samp.var-samp.toml#t006_empty_input": 755,
    @@ -9213,7 +9213,7 @@
         "translation/functions/variance-pop.variance-pop-over.toml#t009_distinct_partition": 1429,
         "translation/functions/variance-pop.variance-pop.toml#t001_number": 1337,
         "translation/functions/variance-pop.variance-pop.toml#t002_single_row": 1286,
    -    "translation/functions/variance-pop.variance-pop.toml#t003_varchar": 4097,
    +    "translation/functions/variance-pop.variance-pop.toml#t003_varchar": 4079,
         "translation/functions/variance-pop.variance-pop.toml#t004_distinct": 1481,
         "translation/functions/variance-pop.variance-pop.toml#t005_null_expr1": 1094,
         "translation/functions/variance-pop.variance-pop.toml#t006_empty_input": 749,
    @@ -9227,7 +9227,7 @@
         "translation/functions/variance.variance-over.toml#t007_null_partition_key": 1246,
         "translation/functions/variance.variance.toml#t001_number": 1343,
         "translation/functions/variance.variance.toml#t002_single_row": 1292,
    -    "translation/functions/variance.variance.toml#t003_varchar": 4103,
    +    "translation/functions/variance.variance.toml#t003_varchar": 4085,
         "translation/functions/variance.variance.toml#t005_null_expr1": 1100,
         "translation/functions/variance.variance.toml#t006_empty_input": 755,
         "translation/functions/variance.variance.toml#t007_large_mean": 923,
    @@ -9339,9 +9339,9 @@
         "typing/array_agg.toml#array_agg_ordered": 1331,
         "typing/array_construct.toml#array_construct_types": 1662,
         "typing/array_size.toml#array_size_types": 1180,
    -    "typing/array_to_string.toml#array_to_string_cased": 1229,
    -    "typing/array_to_string.toml#array_to_string_first": 990,
    -    "typing/array_to_string.toml#array_to_string_types": 975,
    +    "typing/array_to_string.toml#array_to_string_cased": 1251,
    +    "typing/array_to_string.toml#array_to_string_first": 1012,
    +    "typing/array_to_string.toml#array_to_string_types": 997,
         "typing/count_if.toml#count_if_empty": 237,
         "typing/count_if.toml#count_if_grouped": 589,
         "typing/date_from_parts.toml#date_from_parts_numbers": 734,
    @@ -9363,7 +9363,7 @@
         "typing/object_delete.toml#object_delete_types": 2251,
         "typing/object_insert.toml#object_insert_types": 4022,
         "typing/split.toml#split_text": 624,
    -    "typing/try_to_double.toml#try_to_double_text": 881,
    +    "typing/try_to_double.toml#try_to_double_text": 863,
         "typing/try_to_number.toml#try_to_number_default": 1001,
         "typing/try_to_number.toml#try_to_number_precision": 887,
         "typing/try_to_number.toml#try_to_number_precision_scale": 932,