Skip to content

Commit d3b3bc4

Browse files
committed
fix(convert): bind a simple CASE's computed operand once in DuckDB
A simple CASE over a computed operand binds the operand once in a lambda that returns the first equal WHEN's position, then chose the result with a simple CASE over that position. DuckDB repeats a simple CASE's operand in every WHEN, so the whole lambda, and everything in the operand, was bound once per WHEN: binding grew with the WHENs times the operand's size. When every result and the ELSE are a column or a literal, they are now packed beside the operand and chosen inside the lambda, so DuckDB parses the operand once. Each result is still cast only where it is chosen. Other CASEs keep the position form.
1 parent 3e73276 commit d3b3bc4

5 files changed

Lines changed: 198 additions & 20 deletions

File tree

‎crates/sqlquack-convert/src/snowflake/conversion/_helpers/expressions/conditionals.rs‎

Lines changed: 84 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -280,11 +280,27 @@ pub(crate) fn case_expression(payload: &Value, site: Site<'_>) -> Result<Emitted
280280
require_understood(payload, &["operand", "whens", "else_"], &construct)?;
281281
let whens = list(payload, "whens");
282282
let operand_node = payload.get("operand").filter(|operand| !operand.is_null());
283+
let otherwise_node = payload.get("else_").filter(|value| !value.is_null());
284+
let mut carried: Option<Vec<String>> = None;
283285
let (subject, conditions, mut branches) = match operand_node {
284286
Some(node) if !plain(node) && whens.iter().all(|when| when.get(0).is_some_and(plain)) => {
285-
let (subject, results) = bound_whens(node, whens, site)?;
286-
let positions = (1..=results.len()).map(|position| position.to_string());
287-
(format!(" {subject}"), positions.collect(), results)
287+
let carry = whens.iter().all(|when| when.get(1).is_some_and(plain))
288+
&& otherwise_node.is_none_or(plain);
289+
let bound = bound_whens(node, whens, carry, site)?;
290+
match carry {
291+
true => {
292+
carried = Some(bound.packed);
293+
(String::new(), bound.tests, bound.results)
294+
}
295+
false => {
296+
let positions = (1..=bound.results.len()).map(|position| position.to_string());
297+
(
298+
format!(" {}", bound.subject()),
299+
positions.collect(),
300+
bound.results,
301+
)
302+
}
303+
}
288304
}
289305
Some(node) => {
290306
let operand = convert_expression(node, site)?;
@@ -296,8 +312,12 @@ pub(crate) fn case_expression(payload: &Value, site: Site<'_>) -> Result<Emitted
296312
(String::new(), conditions, results)
297313
}
298314
};
299-
let otherwise = match payload.get("else_").filter(|value| !value.is_null()) {
300-
Some(otherwise) => Some(convert_expression(otherwise, site)?),
315+
let otherwise = match otherwise_node {
316+
Some(otherwise) => Some(carried_branch(
317+
convert_expression(otherwise, site)?,
318+
"e",
319+
carried.as_mut(),
320+
)),
301321
None => None,
302322
};
303323
branches.extend(otherwise.iter().cloned());
@@ -310,6 +330,9 @@ pub(crate) fn case_expression(payload: &Value, site: Site<'_>) -> Result<Emitted
310330
sql.push_str(&format!(" ELSE {last}"));
311331
}
312332
sql.push_str(" END)");
333+
if let Some(packed) = carried {
334+
sql = bound_subject(&packed, &sql);
335+
}
313336
let mut values = marks(&branches);
314337
if otherwise.is_none() {
315338
values.push((SnowflakeType::Null, false));
@@ -338,12 +361,56 @@ fn plain(node: &Value) -> bool {
338361
}
339362
}
340363

341-
/// A simple CASE's operand bound once beside its WHEN values: the first equal WHEN's position.
364+
/// A simple CASE's operand packed once, as DuckDB repeats a simple CASE's operand in every WHEN.
365+
struct BoundWhens {
366+
/// The `struct_pack` fields: the operand, the WHEN values and any carried results.
367+
packed: Vec<String>,
368+
/// Each WHEN's test of the packed operand against its packed value.
369+
tests: Vec<String>,
370+
/// The results, read from the pack when carried.
371+
results: Vec<Emitted>,
372+
}
373+
374+
impl BoundWhens {
375+
/// The first equal WHEN's position, for a CASE over the positions choosing uncarried results.
376+
fn subject(&self) -> String {
377+
let tests: Vec<String> = self
378+
.tests
379+
.iter()
380+
.enumerate()
381+
.map(|(position, test)| format!(" WHEN {test} THEN {}", position + 1))
382+
.collect();
383+
bound_subject(&self.packed, &format!("CASE{} END", tests.concat()))
384+
}
385+
}
386+
387+
/// `body` over the packed fields, read through the lambda parameter once per row.
388+
fn bound_subject(packed: &[String], body: &str) -> String {
389+
format!(
390+
"list_transform([struct_pack({})], lambda {CASE_SUBJECT}: {body})[1]",
391+
packed.join(", ")
392+
)
393+
}
394+
395+
/// `branch` read from the pack as `field` when the results are carried in it.
396+
fn carried_branch(branch: Emitted, field: &str, packed: Option<&mut Vec<String>>) -> Emitted {
397+
let Some(packed) = packed else {
398+
return branch;
399+
};
400+
packed.push(format!("{field} := {}", branch.sql));
401+
Emitted {
402+
sql: format!("{CASE_SUBJECT}['{field}']"),
403+
..branch
404+
}
405+
}
406+
407+
/// A simple CASE's operand packed once with its WHEN values and, when `carry`, its plain results.
342408
fn bound_whens(
343409
operand: &Value,
344410
whens: &[Value],
411+
carry: bool,
345412
site: Site<'_>,
346-
) -> Result<(String, Vec<Emitted>), Refusal> {
413+
) -> Result<BoundWhens, Refusal> {
347414
let construct = node_construct("case");
348415
let operand = convert_expression(operand, site)?;
349416
let mut packed = vec![format!("o := {}", operand.sql)];
@@ -367,25 +434,22 @@ fn bound_whens(
367434
..value
368435
};
369436
let (left, right) = comparable(subject.clone(), value, &construct, site.context)?;
370-
tests.push(format!(
371-
" WHEN {} = {} THEN {}",
372-
left.sql,
373-
right.sql,
374-
position + 1
437+
tests.push(format!("{} = {}", left.sql, right.sql));
438+
let result = convert_expression(result, site)?;
439+
results.push(carried_branch(
440+
result,
441+
&format!("r{position}"),
442+
carry.then_some(&mut packed),
375443
));
376-
results.push(convert_expression(result, site)?);
377444
}
378445
if tests.is_empty() {
379446
return Err(missing(construct, "CASE without WHEN".to_owned()));
380447
}
381-
Ok((
382-
format!(
383-
"list_transform([struct_pack({})], lambda {CASE_SUBJECT}: CASE{} END)[1]",
384-
packed.join(", "),
385-
tests.concat()
386-
),
448+
Ok(BoundWhens {
449+
packed,
450+
tests,
387451
results,
388-
))
452+
})
389453
}
390454

391455
fn case_whens(

‎crates/sqlquack/tests/cli.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ mod test_bind_check;
66
mod test_builtin_policy;
77
#[path = "cli/test_bundled.rs"]
88
mod test_bundled;
9+
#[path = "cli/test_case_subject.rs"]
10+
mod test_case_subject;
911
#[path = "cli/test_check.rs"]
1012
mod test_check;
1113
#[path = "cli/test_compare.rs"]

‎crates/sqlquack/tests/cli/helpers.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1364,3 +1364,14 @@ pub(crate) fn bracket_depth(sql: &str) -> i64 {
13641364
.max()
13651365
.unwrap_or_default()
13661366
}
1367+
1368+
/// How many times `marker` appears in DuckDB's parse of the converted `sql`, what DuckDB binds.
1369+
pub(crate) fn parsed_copies(sql: &str, marker: &str) -> usize {
1370+
let (converted, _) = convert_streams(sql, &["--no-config", "--compact"]);
1371+
let connection = duckdb::Connection::open_in_memory().expect("DuckDB opens");
1372+
let query = after_setup(&connection, &converted);
1373+
let parsed: String = connection
1374+
.query_row("SELECT json_serialize_sql(?)", [query], |row| row.get(0))
1375+
.expect("DuckDB parses the converted statement");
1376+
parsed.matches(marker).count()
1377+
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
use crate::helpers::{converted_first_value, parsed_copies};
2+
use crate::test_types::{CaseSubjectTestCase, ChainValueTestCase};
3+
4+
#[test]
5+
fn given_a_simple_case_over_a_computed_operand_when_converting_then_duckdb_binds_the_operand_once()
6+
{
7+
let test_cases = [
8+
CaseSubjectTestCase {
9+
description: "two WHENs with literal results",
10+
branches: 2,
11+
result: "'v{i}'",
12+
expected_copies: 1,
13+
},
14+
CaseSubjectTestCase {
15+
description: "thirty-two WHENs with literal results",
16+
branches: 32,
17+
result: "'v{i}'",
18+
expected_copies: 1,
19+
},
20+
CaseSubjectTestCase {
21+
description: "thirty-two WHENs with column results",
22+
branches: 32,
23+
result: "b",
24+
expected_copies: 1,
25+
},
26+
];
27+
for test_case in test_cases {
28+
let whens: Vec<String> = (0..test_case.branches)
29+
.map(|i| {
30+
format!(
31+
"WHEN 'W{i}' THEN {}",
32+
test_case.result.replace("{i}", &i.to_string())
33+
)
34+
})
35+
.collect();
36+
let sql = format!(
37+
"SELECT CASE UPPER(a || 'operand_marker') {} ELSE NULL END AS c \
38+
FROM (SELECT 'x' AS a, 'y' AS b)",
39+
whens.join(" ")
40+
);
41+
42+
let copies = parsed_copies(&sql, "operand_marker");
43+
44+
assert_eq!(
45+
copies, test_case.expected_copies,
46+
"{}",
47+
test_case.description
48+
);
49+
}
50+
}
51+
52+
#[test]
53+
fn given_a_simple_case_with_plain_results_when_converting_then_duckdb_returns_snowflakes_value() {
54+
let test_cases = [
55+
ChainValueTestCase {
56+
description: "the first equal WHEN's literal result",
57+
sql: "SELECT CASE UPPER(a) WHEN 'X' THEN 'first' WHEN 'X' THEN 'second' END AS c \
58+
FROM (SELECT 'x' AS a)",
59+
expected_value: "first",
60+
},
61+
ChainValueTestCase {
62+
description: "a column result",
63+
sql: "SELECT CASE UPPER(a) WHEN 'Y' THEN 'no' WHEN 'X' THEN b END AS c \
64+
FROM (SELECT 'x' AS a, 'from b' AS b)",
65+
expected_value: "from b",
66+
},
67+
ChainValueTestCase {
68+
description: "ELSE when no WHEN equals the operand",
69+
sql: "SELECT CASE UPPER(a) WHEN 'Y' THEN 'no' ELSE b END AS c \
70+
FROM (SELECT 'x' AS a, 'else' AS b)",
71+
expected_value: "else",
72+
},
73+
ChainValueTestCase {
74+
description: "a NULL operand equals no WHEN",
75+
sql: "SELECT CASE UPPER(a) WHEN 'X' THEN 'no' ELSE 'null operand' END AS c \
76+
FROM (SELECT CAST(NULL AS VARCHAR) AS a)",
77+
expected_value: "null operand",
78+
},
79+
ChainValueTestCase {
80+
description: "a number result cast to the CASE's type only where chosen",
81+
sql: "SELECT CAST(CASE a + 1 WHEN 2 THEN 1.5 WHEN 3 THEN n END AS VARCHAR) AS c \
82+
FROM (SELECT 1 AS a, 7 AS n)",
83+
expected_value: "1.5",
84+
},
85+
];
86+
for test_case in test_cases {
87+
let value = converted_first_value(test_case.sql);
88+
89+
assert_eq!(value, test_case.expected_value, "{}", test_case.description);
90+
}
91+
}

‎crates/sqlquack/tests/cli/test_types.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -448,3 +448,13 @@ pub(crate) struct BindCheckTestCase {
448448
/// Whether it converts, printing SQL on standard output.
449449
pub(crate) expected_converted: bool,
450450
}
451+
452+
/// A simple CASE over a computed operand, with `branches` WHENs choosing `result`.
453+
pub(crate) struct CaseSubjectTestCase {
454+
pub(crate) description: &'static str,
455+
pub(crate) branches: usize,
456+
/// One WHEN's result, `{i}` replaced by its position.
457+
pub(crate) result: &'static str,
458+
/// How many copies of the operand DuckDB parses, whatever the number of WHENs.
459+
pub(crate) expected_copies: usize,
460+
}

0 commit comments

Comments
 (0)