Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions coverage/instruction-counts.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@ rustc = "rustc 1.99.1 (58cf8f9c3 2026-10-13)"
tolerance_percent = 2

[counts]
analysis = 182168067
parse = 252986430
analysis = 182072257
parse = 246355897
10,450 changes: 5,225 additions & 5,225 deletions coverage/sql-size/baseline.json

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use crate::snowflake::conversion::_helpers::support::divergence::{
use crate::snowflake::conversion::_helpers::support::scope::{Context, Emitted, Scope};
use crate::snowflake::conversion::_helpers::support::site::{Placement, Site};
use crate::snowflake::conversion::_helpers::support::tree::{
field, flag, node_construct, payload_object, require_understood,
Payload, field, flag, node_construct, node_kind, payload_object, require_understood,
};
use crate::snowflake::conversion::constants::DUPLICATE_VARIANTS;
use crate::snowflake::conversion::constants::{
Expand Down Expand Up @@ -110,12 +110,8 @@ pub(crate) fn convert_set_operation(
};
let context = &context.projecting(context.free_projections && keyword == UNION_ALL);
let (with_sql, context) = convert_with(operation.get("with"), outer, context)?;
let left = convert_query(
field(operation, "left", &construct)?,
outer,
&context,
named,
)?;
let left_node: &Value = field(operation, "left", &construct)?;
let left = convert_query(left_node, outer, &context, named)?;
let right = convert_query(
field(operation, "right", &construct)?,
outer,
Expand All @@ -134,9 +130,14 @@ pub(crate) fn convert_set_operation(
}
false => {
let columns = unified_columns((&left.1, &right.1), &construct, &context)?;
let canonical = keyword != UNION_ALL
&& columns
.iter()
.any(|column| column.data_type == SnowflakeType::SemiStructured);
let bare = !canonical && continues_chain(left_node, kind, operation);
(
conform(left, &columns, &construct, &context)?,
conform(right, &columns, &construct, &context)?,
conform(left, (&columns, bare), &construct, &context)?,
conform(right, (&columns, false), &construct, &context)?,
columns,
)
}
Expand Down Expand Up @@ -205,6 +206,23 @@ pub(crate) fn convert_set_operation(
))
}

/// Whether `left` is `operation`'s set operator, quantifier and nothing else, so it prints unbracketed.
fn continues_chain(left: &Value, kind: &str, operation: &Payload) -> bool {
let Some((left_kind, payload)) = node_kind(left) else {
return false;
};
let Some(inner) = payload.as_object() else {
return false;
};
left_kind == kind
&& flag(inner, "all") == flag(operation, "all")
&& flag(inner, "distinct") == flag(operation, "distinct")
&& !flag(inner, "by_name")
&& ["with", "order_by", "limit", "offset"]
.iter()
.all(|clause| inner.get(*clause).is_none_or(Value::is_null))
}

/// The branches' common column types.
fn unified_columns(
(left, right): (&[ColumnSpec], &[ColumnSpec]),
Expand Down Expand Up @@ -237,9 +255,10 @@ fn unified_columns(
Ok(columns)
}

/// `sql` cast to `target`, bracketed unless `bare`: a left operand continuing its chain, read left to right.
fn conform(
(sql, actual): ConvertedQuery,
target: &[ColumnSpec],
(target, bare): (&[ColumnSpec], bool),
construct: &Construct,
context: &Context<'_>,
) -> Result<String, Refusal> {
Expand All @@ -249,7 +268,7 @@ fn conform(
&& !joins_held(actual, target)
});
if same {
return Ok(format!("({sql})"));
return Ok(if bare { sql } else { format!("({sql})") });
}
let log = context.log;
let names: Vec<String> = (1..=actual.len())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ impl Parser {
guards_checked: false,
token_guard_stats: None,
if_expr_ruled_out: HashSet::new(),
source_char_bytes: std::cell::OnceCell::new(),
parsing_duckdb_json_path: false,
faithful_calls: HashMap::new(),
recursion: Arc::default(),
Expand All @@ -87,6 +88,7 @@ impl Parser {
guards_checked: false,
token_guard_stats: None,
if_expr_ruled_out: HashSet::new(),
source_char_bytes: std::cell::OnceCell::new(),
parsing_duckdb_json_path: false,
faithful_calls: HashMap::new(),
recursion: Arc::default(),
Expand All @@ -109,6 +111,7 @@ impl Parser {
guards_checked: false,
token_guard_stats: None,
if_expr_ruled_out: HashSet::new(),
source_char_bytes: std::cell::OnceCell::new(),
parsing_duckdb_json_path: false,
faithful_calls: HashMap::new(),
recursion: Arc::default(),
Expand All @@ -134,6 +137,7 @@ impl Parser {
guards_checked: false,
token_guard_stats: Some(token_guard_stats),
if_expr_ruled_out: HashSet::new(),
source_char_bytes: std::cell::OnceCell::new(),
parsing_duckdb_json_path: false,
faithful_calls: HashMap::new(),
recursion: Arc::default(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1415,14 +1415,26 @@ impl Parser {
return String::new();
};

if source.is_ascii() {
source
let offsets: &Option<Vec<usize>> = self.source_char_bytes.get_or_init(|| {
(!source.is_ascii()).then(|| {
source
.char_indices()
.map(|(byte, _)| byte)
.chain([source.len()])
.collect()
})
});
let Some(offsets) = offsets else {
return source
.get(start..end)
.map(ToString::to_string)
.unwrap_or_default()
} else {
source.chars().skip(start).take(end - start).collect()
}
.unwrap_or_default();
};
let byte = |offset: usize| offsets.get(offset).copied().unwrap_or(source.len());
source
.get(byte(start)..byte(end.max(start)))
.map(ToString::to_string)
.unwrap_or_default()
}

/// Keeps a ClickHouse `(EXPLAIN ... SELECT ...)` subquery as command text.
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlquack-syntax-snowflake/src/parser/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,8 @@ pub(crate) struct Parser {
pub(crate) eof_followed_by: Option<(TokenType, Span)>,
/// Positions where `IF` was rejected as an if-expression, so retries stay linear.
pub(crate) if_expr_ruled_out: HashSet<usize>,
/// Each character's byte offset in a non-ASCII `source`, built once, so slicing never rewalks it.
pub(crate) source_char_bytes: std::cell::OnceCell<Option<Vec<usize>>>,
pub(crate) parsing_duckdb_json_path: bool,
pub(crate) recursion: Arc<ParserRecursion>,
/// SQLQuack: faithful calls parsed so far, by argument start token, with the token after them.
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlquack/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ mod test_review;
mod test_row_limits;
#[path = "cli/test_run.rs"]
mod test_run;
#[path = "cli/test_set_chains.rs"]
mod test_set_chains;
#[path = "cli/test_set_quantifier.rs"]
mod test_set_quantifier;
#[path = "cli/test_types.rs"]
Expand Down
11 changes: 11 additions & 0 deletions crates/sqlquack/tests/cli/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1353,3 +1353,14 @@ fn project_folder(files: &[ProjectFile], folder: &str, sql: &str) -> tempfile::T
std::fs::write(directory.path().join("query.sql"), sql).expect("query written");
directory
}

/// The deepest bracket nesting of `sql`, which must hold no brackets in quoted text.
pub(crate) fn bracket_depth(sql: &str) -> i64 {
sql.chars()
.scan(0_i64, |depth, character| {
*depth += i64::from(character == '(') - i64::from(character == ')');
Some(*depth)
})
.max()
.unwrap_or_default()
}
128 changes: 128 additions & 0 deletions crates/sqlquack/tests/cli/test_set_chains.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
use crate::helpers::{bracket_depth, convert_streams, converted_first_value};
use crate::test_types::{ChainGrowthTestCase, ChainValueTestCase, SetChainTestCase};

#[test]
fn given_a_chain_of_one_set_operator_when_converting_then_its_output_nests_no_deeper_with_more_branches()
{
let test_cases = [
SetChainTestCase {
description: "four UNION ALL branches",
operator: " UNION ALL ",
branch: "SELECT 1 AS a",
branches: 4,
expected_depth: 4,
},
SetChainTestCase {
description: "sixty-four UNION ALL branches nest as deep as four",
operator: " UNION ALL ",
branch: "SELECT 1 AS a",
branches: 64,
expected_depth: 4,
},
SetChainTestCase {
description: "sixty-four UNION branches nest as deep as four",
operator: " UNION ",
branch: "SELECT 1 AS a",
branches: 64,
expected_depth: 4,
},
SetChainTestCase {
description: "sixty-four EXCEPT branches nest as deep as four",
operator: " EXCEPT ",
branch: "SELECT 1 AS a",
branches: 64,
expected_depth: 4,
},
];
for test_case in test_cases {
let sql = format!(
"WITH orders AS ({}) SELECT a FROM orders",
vec![test_case.branch; test_case.branches].join(test_case.operator)
);

let (converted, _) = convert_streams(&sql, &["--no-config", "--compact"]);

assert_eq!(
bracket_depth(&converted),
test_case.expected_depth,
"{}: {converted}",
test_case.description
);
}
}

#[test]
fn given_longer_chains_of_one_set_operator_when_converting_then_each_branch_adds_the_same_output() {
let test_cases = [
ChainGrowthTestCase {
description: "UNION ALL",
operator: " UNION ALL ",
branch: "SELECT 1 AS a",
expected_bytes_per_branch: 73,
},
ChainGrowthTestCase {
description: "UNION",
operator: " UNION ",
branch: "SELECT 1 AS a",
expected_bytes_per_branch: 69,
},
];
for test_case in test_cases {
let printed = |branches: usize| {
let sql = format!(
"WITH orders AS ({}) SELECT a FROM orders",
vec![test_case.branch; branches].join(test_case.operator)
);
convert_streams(&sql, &["--no-config"]).0.len()
};

let (short, middle, long) = (printed(4), printed(16), printed(64));

// Laid-out text grows with nesting, so a chain nested a level per branch grows
// quadratically, and every pass over it with it; a flat chain grows linearly.
assert_eq!(
((middle - short) / 12, (long - middle) / 48),
(
test_case.expected_bytes_per_branch,
test_case.expected_bytes_per_branch
),
"{}: {short}, {middle} and {long} bytes for 4, 16 and 64 branches",
test_case.description
);
}
}

#[test]
fn given_set_operator_chains_when_converting_then_duckdb_returns_snowflakes_rows() {
let test_cases = [
ChainValueTestCase {
description: "a UNION ALL chain keeps every row",
sql: "SELECT CAST(COUNT(*) AS VARCHAR) AS n FROM (SELECT 1 AS a UNION ALL SELECT 1 \
UNION ALL SELECT 1 UNION ALL SELECT 2)",
expected_value: "4",
},
ChainValueTestCase {
description: "a UNION between UNION ALLs still removes the duplicates before it only",
sql: "SELECT CAST(COUNT(*) AS VARCHAR) AS n FROM (SELECT 1 AS a UNION ALL SELECT 1 \
UNION SELECT 1 UNION ALL SELECT 1)",
expected_value: "2",
},
ChainValueTestCase {
description: "an EXCEPT chain removes left to right",
sql: "SELECT CAST(COUNT(*) AS VARCHAR) AS n FROM (SELECT 1 AS a UNION ALL SELECT 2 \
UNION ALL SELECT 3 EXCEPT SELECT 2 EXCEPT SELECT 3)",
expected_value: "1",
},
ChainValueTestCase {
description: "text around a multi-byte character keeps its aliases in a chain",
sql: "SELECT MIN(a || b) AS n FROM (SELECT 'caf\u{e9}' AS a, 'x' as b UNION ALL \
SELECT 'na\u{ef}ve' AS a, 'y' as b)",
expected_value: "caf\u{e9}x",
},
];
for test_case in test_cases {
let value = converted_first_value(test_case.sql);

assert_eq!(value, test_case.expected_value, "{}", test_case.description);
}
}
26 changes: 26 additions & 0 deletions crates/sqlquack/tests/cli/test_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -414,3 +414,29 @@ pub(crate) struct SetQuantifierTestCase {
pub(crate) expected_same_as: &'static str,
pub(crate) expected_unlike: &'static str,
}

/// A chain of `branches` copies of `branch` joined by one set operator, and how deep its output nests.
pub(crate) struct SetChainTestCase {
pub(crate) description: &'static str,
pub(crate) operator: &'static str,
pub(crate) branch: &'static str,
pub(crate) branches: usize,
/// The deepest bracket nesting of the compact converted SQL, which must not grow with `branches`.
pub(crate) expected_depth: i64,
}

/// A statement whose converted SQL returns one text value on DuckDB.
pub(crate) struct ChainValueTestCase {
pub(crate) description: &'static str,
pub(crate) sql: &'static str,
pub(crate) expected_value: &'static str,
}

/// A set operator whose chains of `branch` must cost the same output for every branch added.
pub(crate) struct ChainGrowthTestCase {
pub(crate) description: &'static str,
pub(crate) operator: &'static str,
pub(crate) branch: &'static str,
/// The bytes of laid-out SQL each further branch adds, the same from 4 to 16 as from 16 to 64.
pub(crate) expected_bytes_per_branch: usize,
}
Loading