Skip to content
Merged
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 = 182110245
parse = 246355409
25 changes: 3 additions & 22 deletions crates/sqlquack-blocks/src/checking/main/check_printed.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,15 @@
//! `check_printed`: DuckDB parses printed SQL as one statement and binds it.

use crate::checking::_helpers::binding::bound;
use crate::checking::_helpers::dotted_parameters::dotted_parameters;
use crate::checking::_helpers::lexing::lexed;
use crate::checking::errors::{CheckStage, PrintedSqlFailure};
use crate::checking::errors::PrintedSqlFailure;
use crate::checking::main::check_unbound::check_unbound;
use crate::checking::types::{FunctionLookup, RelationLookup};

/// Succeeds when DuckDB parses `sql` as one statement and binds it over the relations and functions.
pub fn check_printed(
sql: &str,
(lookup, functions): (RelationLookup<'_>, FunctionLookup<'_>),
) -> Result<(), PrintedSqlFailure> {
let dotted = dotted_parameters(sql);
if !dotted.is_empty() {
return Err(failure(
CheckStage::CapturedParameter,
format!("{} read with a dot", dotted.join(", ")),
));
}
let lexed = lexed(sql);
if lexed.statements != 1 {
return Err(failure(
CheckStage::StatementCount,
format!("{} statements", lexed.statements),
));
}
let names: Vec<String> = lexed.names.into_iter().collect();
let names: Vec<String> = check_unbound(sql)?;
bound(sql, &names, (lookup, functions))
}

fn failure(stage: CheckStage, message: String) -> PrintedSqlFailure {
PrintedSqlFailure { stage, message }
}
28 changes: 28 additions & 0 deletions crates/sqlquack-blocks/src/checking/main/check_unbound.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
//! `check_unbound`: printed SQL is one statement with no lambda parameter read with a dot.

use crate::checking::_helpers::dotted_parameters::dotted_parameters;
use crate::checking::_helpers::lexing::lexed;
use crate::checking::errors::{CheckStage, PrintedSqlFailure};

/// The names `sql` reads, when it is one statement reading no lambda parameter with a dot.
pub fn check_unbound(sql: &str) -> Result<Vec<String>, PrintedSqlFailure> {
let dotted = dotted_parameters(sql);
if !dotted.is_empty() {
return Err(failure(
CheckStage::CapturedParameter,
format!("{} read with a dot", dotted.join(", ")),
));
}
let lexed = lexed(sql);
if lexed.statements != 1 {
return Err(failure(
CheckStage::StatementCount,
format!("{} statements", lexed.statements),
));
}
Ok(lexed.names.into_iter().collect())
}

fn failure(stage: CheckStage, message: String) -> PrintedSqlFailure {
PrintedSqlFailure { stage, message }
}
1 change: 1 addition & 0 deletions crates/sqlquack-blocks/src/checking/main/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@

pub mod bound_outside_lambdas;
pub mod check_printed;
pub mod check_unbound;
pub mod create_table;
pub mod quoted_relation;
2 changes: 2 additions & 0 deletions crates/sqlquack-blocks/src/checking/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,7 @@ mod helpers;
mod test_bound_outside_lambdas;
#[path = "tests/test_check_printed.rs"]
mod test_check_printed;
#[path = "tests/test_check_unbound.rs"]
mod test_check_unbound;
#[path = "tests/test_types.rs"]
mod test_types;
42 changes: 42 additions & 0 deletions crates/sqlquack-blocks/src/checking/tests/test_check_unbound.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
use crate::checking::errors::CheckStage;
use crate::checking::main::check_unbound::check_unbound;
use crate::checking::tests::test_types::CheckTestCase;

#[test]
fn given_printed_sql_when_checked_without_binding_then_only_its_lexical_failures_refuse() {
let test_cases = [
CheckTestCase {
description: "an unknown column is left to the caller that runs the SQL",
sql: "SELECT \"MISSING\" FROM \"ORDERS\"".to_owned(),
expected_stage: None,
},
CheckTestCase {
description: "an unknown relation is left to the caller that runs the SQL",
sql: "SELECT 1 FROM \"CUSTOMERS\"".to_owned(),
expected_stage: None,
},
CheckTestCase {
description: "a type error is left to the caller that runs the SQL",
sql: "SELECT date_trunc('day', \"ID\") FROM \"ORDERS\"".to_owned(),
expected_stage: None,
},
CheckTestCase {
description: "a lambda parameter read with a dot is still refused",
sql: "SELECT list_transform([struct_pack(l := 1)], lambda p: p.l) FROM \"ORDERS\" AS p"
.to_owned(),
expected_stage: Some(CheckStage::CapturedParameter),
},
CheckTestCase {
description: "two statements are still refused",
sql: "SELECT 1; SELECT 2".to_owned(),
expected_stage: Some(CheckStage::StatementCount),
},
];
for test_case in test_cases {
let stage = check_unbound(&test_case.sql)
.err()
.map(|failure| failure.stage);

assert_eq!(stage, test_case.expected_stage, "{}", test_case.description);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -280,11 +280,27 @@ pub(crate) fn case_expression(payload: &Value, site: Site<'_>) -> Result<Emitted
require_understood(payload, &["operand", "whens", "else_"], &construct)?;
let whens = list(payload, "whens");
let operand_node = payload.get("operand").filter(|operand| !operand.is_null());
let otherwise_node = payload.get("else_").filter(|value| !value.is_null());
let mut carried: Option<Vec<String>> = None;
let (subject, conditions, mut branches) = match operand_node {
Some(node) if !plain(node) && whens.iter().all(|when| when.get(0).is_some_and(plain)) => {
let (subject, results) = bound_whens(node, whens, site)?;
let positions = (1..=results.len()).map(|position| position.to_string());
(format!(" {subject}"), positions.collect(), results)
let carry = whens.iter().all(|when| when.get(1).is_some_and(plain))
&& otherwise_node.is_none_or(plain);
let bound = bound_whens(node, whens, carry, site)?;
match carry {
true => {
carried = Some(bound.packed);
(String::new(), bound.tests, bound.results)
}
false => {
let positions = (1..=bound.results.len()).map(|position| position.to_string());
(
format!(" {}", bound.subject()),
positions.collect(),
bound.results,
)
}
}
}
Some(node) => {
let operand = convert_expression(node, site)?;
Expand All @@ -296,8 +312,12 @@ pub(crate) fn case_expression(payload: &Value, site: Site<'_>) -> Result<Emitted
(String::new(), conditions, results)
}
};
let otherwise = match payload.get("else_").filter(|value| !value.is_null()) {
Some(otherwise) => Some(convert_expression(otherwise, site)?),
let otherwise = match otherwise_node {
Some(otherwise) => Some(carried_branch(
convert_expression(otherwise, site)?,
"e",
carried.as_mut(),
)),
None => None,
};
branches.extend(otherwise.iter().cloned());
Expand All @@ -310,6 +330,9 @@ pub(crate) fn case_expression(payload: &Value, site: Site<'_>) -> Result<Emitted
sql.push_str(&format!(" ELSE {last}"));
}
sql.push_str(" END)");
if let Some(packed) = carried {
sql = bound_subject(&packed, &sql);
}
let mut values = marks(&branches);
if otherwise.is_none() {
values.push((SnowflakeType::Null, false));
Expand Down Expand Up @@ -338,12 +361,56 @@ fn plain(node: &Value) -> bool {
}
}

/// A simple CASE's operand bound once beside its WHEN values: the first equal WHEN's position.
/// A simple CASE's operand packed once, as DuckDB repeats a simple CASE's operand in every WHEN.
struct BoundWhens {
/// The `struct_pack` fields: the operand, the WHEN values and any carried results.
packed: Vec<String>,
/// Each WHEN's test of the packed operand against its packed value.
tests: Vec<String>,
/// The results, read from the pack when carried.
results: Vec<Emitted>,
}

impl BoundWhens {
/// The first equal WHEN's position, for a CASE over the positions choosing uncarried results.
fn subject(&self) -> String {
let tests: Vec<String> = self
.tests
.iter()
.enumerate()
.map(|(position, test)| format!(" WHEN {test} THEN {}", position + 1))
.collect();
bound_subject(&self.packed, &format!("CASE{} END", tests.concat()))
}
}

/// `body` over the packed fields, read through the lambda parameter once per row.
fn bound_subject(packed: &[String], body: &str) -> String {
format!(
"list_transform([struct_pack({})], lambda {CASE_SUBJECT}: {body})[1]",
packed.join(", ")
)
}

/// `branch` read from the pack as `field` when the results are carried in it.
fn carried_branch(branch: Emitted, field: &str, packed: Option<&mut Vec<String>>) -> Emitted {
let Some(packed) = packed else {
return branch;
};
packed.push(format!("{field} := {}", branch.sql));
Emitted {
sql: format!("{CASE_SUBJECT}['{field}']"),
..branch
}
}

/// A simple CASE's operand packed once with its WHEN values and, when `carry`, its plain results.
fn bound_whens(
operand: &Value,
whens: &[Value],
carry: bool,
site: Site<'_>,
) -> Result<(String, Vec<Emitted>), Refusal> {
) -> Result<BoundWhens, Refusal> {
let construct = node_construct("case");
let operand = convert_expression(operand, site)?;
let mut packed = vec![format!("o := {}", operand.sql)];
Expand All @@ -367,25 +434,22 @@ fn bound_whens(
..value
};
let (left, right) = comparable(subject.clone(), value, &construct, site.context)?;
tests.push(format!(
" WHEN {} = {} THEN {}",
left.sql,
right.sql,
position + 1
tests.push(format!("{} = {}", left.sql, right.sql));
let result = convert_expression(result, site)?;
results.push(carried_branch(
result,
&format!("r{position}"),
carry.then_some(&mut packed),
));
results.push(convert_expression(result, site)?);
}
if tests.is_empty() {
return Err(missing(construct, "CASE without WHEN".to_owned()));
}
Ok((
format!(
"list_transform([struct_pack({})], lambda {CASE_SUBJECT}: CASE{} END)[1]",
packed.join(", "),
tests.concat()
),
Ok(BoundWhens {
packed,
tests,
results,
))
})
}

fn case_whens(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use crate::snowflake::conversion::_helpers::support::typed_leaves::checked;
use sqlquack_blocks::blocks::main::quoted_identifier::quoted_identifier;
use sqlquack_blocks::checking::main::check_printed::check_printed;
use sqlquack_blocks::checking::main::check_unbound::check_unbound;
use sqlquack_blocks::checking::models::{FunctionStub, StubReturns};
use sqlquack_diagnostics::provenance::models::ProvenanceLog;
use sqlquack_diagnostics::refusals::main::missing::missing;
Expand Down Expand Up @@ -92,8 +93,11 @@ pub(crate) fn parameters_joined(
)
}

/// DuckDB parses and binds the body over NULL parameters and the schema's relations.
pub(crate) fn check_body(checked: &str, schema: &Schema) -> Result<(), Refusal> {
/// DuckDB parses and binds the body over NULL parameters and the schema's relations, unless `skip_bind`.
pub(crate) fn check_body(
checked: &str,
(schema, skip_bind): (&Schema, bool),
) -> Result<(), Refusal> {
let relation = |name: &str| -> Option<Vec<(String, SnowflakeType)>> {
Some(
schema
Expand All @@ -104,7 +108,11 @@ pub(crate) fn check_body(checked: &str, schema: &Schema) -> Result<(), Refusal>
.collect(),
)
};
check_printed(checked, (&relation, &|name| function_stub(schema, name))).map_err(|failure| {
match skip_bind {
true => check_unbound(checked).map(drop),
false => check_printed(checked, (&relation, &|name| function_stub(schema, name))),
}
.map_err(|failure| {
missing(
node_construct("function_body"),
format!("the emitted DuckDB SQL fails DuckDB's check: {failure}"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ pub(in crate::snowflake) fn convert_function_body(
"SELECT {selected} FROM {}",
joined(&vec!["NULL".to_owned(); held.len()])
),
schema,
(schema, options.skip_bind_check),
)?;
let body = match &spec.returns {
FunctionReturns::Scalar(_) => format!("(SELECT {selected} FROM {})", joined(&names)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use crate::snowflake::conversion::_helpers::support::typed_leaves::checked;
use sqlquack_blocks::blocks::main::quoted_identifier::quoted_identifier;
use sqlquack_blocks::checking::main::check_printed::check_printed;
use sqlquack_blocks::checking::main::check_unbound::check_unbound;
use sqlquack_blocks::held::main::variant_written::variant_written;
use sqlquack_blocks::semi_structured::main::json_output::json_output;
use sqlquack_diagnostics::provenance::models::ProvenanceLog;
Expand Down Expand Up @@ -66,7 +67,11 @@ pub fn convert_statement(
};
let function =
|name: &str| function_stub(schema, name).or_else(|| override_stub(options, name));
check_printed(&sql, (&relation, &function)).map_err(|failure| {
match options.skip_bind_check {
true => check_unbound(&sql).map(drop),
false => check_printed(&sql, (&relation, &function)),
}
.map_err(|failure| {
let refusal = missing(
node_construct("statement"),
format!("the emitted DuckDB SQL fails DuckDB's check: {failure}"),
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlquack-convert/src/snowflake/conversion/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ pub struct ConversionOptions {
pub verified_overrides: BTreeMap<String, String>,
/// Function calls nested deeper than this are a parse error; the parser's default when absent.
pub max_call_depth: Option<usize>,
/// Skip DuckDB's parse-and-bind of the emitted SQL, for a caller that runs it and reports errors.
pub skip_bind_check: bool,
}

/// A user's DuckDB SQL standing in for a Snowflake function, written in SQLBuild's FUNCTION() format.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ pub(crate) fn convert_json(sql: &str, request: &str, path: &str) -> PyResult<Str
verified_overrides: pairs(request.verified_overrides),
session: pairs(request.session),
compact: request.compact,
no_bind_check: request.no_bind_check,
verbose: false,
output: OutputArguments {
format: OutputFormat::Json,
Expand Down
2 changes: 2 additions & 0 deletions crates/sqlquack-python/src/bindings/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ pub struct ConvertRequest {
pub session: BTreeMap<String, String>,
/// `--compact`.
pub compact: bool,
/// `--no-bind-check`.
pub no_bind_check: bool,
/// `--max-call-depth`; the default when absent.
pub max_call_depth: Option<usize>,
}
Loading
Loading