From 1414e1587fa6f99e04dcec9ef1979f18fa334d2d Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:44:21 +0000 Subject: [PATCH 1/3] fix(sqlite): convert bound parameters with --bind and bindings Bound values are written in place of their markers as typed DuckDB literals, so the output runs as it is, for one statement or a script. Each value must be one SQLite literal; a marker with no value and a value no statement names refuse. --- .../src/sqlite/analysis/_helpers/mod.rs | 1 + .../src/sqlite/analysis/_helpers/statement.rs | 42 +++++++++ .../src/sqlite/analysis/main/analyze_bound.rs | 36 +------- .../sqlite/analysis/main/analyze_effect.rs | 5 +- .../sqlite/analysis/main/analyze_inline.rs | 12 +++ .../src/sqlite/analysis/main/mod.rs | 1 + .../src/sqlite/analysis/mod.rs | 1 + .../conversion/_helpers/effects/statements.rs | 5 +- .../_helpers/expressions/dispatch.rs | 10 ++- .../conversion/_helpers/support/parameters.rs | 66 +++++++++++--- .../sqlite/conversion/main/_convert_effect.rs | 45 ++++++++-- .../conversion/main/_convert_statement.rs | 6 +- .../conversion/tests/test_convert_effect.rs | 2 +- .../conversion/tests/test_parameters.rs | 30 ++++++- .../src/bindings/_helpers/convert_json.rs | 1 + crates/sqlbabel-python/src/bindings/models.rs | 2 + .../analysis/_helpers/sqlite_conversion.rs | 2 +- crates/sqlbabel/src/analysis/tests/helpers.rs | 1 + .../src/cli/_helpers/convert_command.rs | 50 +++++++++-- crates/sqlbabel/src/cli/constants.rs | 2 + .../sqlbabel/src/cli/main/convert_report.rs | 4 + crates/sqlbabel/src/cli/models.rs | 3 + docs/architecture.md | 9 +- python/src/sqlbabel/api/main/convert.py | 1 + python/src/sqlbabel/api/models.py | 1 + .../src/sqlbabel/api/main/_test_types.py | 11 +++ .../python/src/sqlbabel/api/main/helpers.py | 19 ++++ .../src/sqlbabel/api/main/test_convert.py | 90 +++++++++++++++++++ website/src/content/docs/docs/cli/convert.mdx | 27 ++++++ website/src/content/docs/docs/python.mdx | 7 +- 30 files changed, 413 insertions(+), 79 deletions(-) create mode 100644 crates/sqlbabel-convert/src/sqlite/analysis/_helpers/mod.rs create mode 100644 crates/sqlbabel-convert/src/sqlite/analysis/_helpers/statement.rs create mode 100644 crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_inline.rs diff --git a/crates/sqlbabel-convert/src/sqlite/analysis/_helpers/mod.rs b/crates/sqlbabel-convert/src/sqlite/analysis/_helpers/mod.rs new file mode 100644 index 000000000..a13cce0e2 --- /dev/null +++ b/crates/sqlbabel-convert/src/sqlite/analysis/_helpers/mod.rs @@ -0,0 +1 @@ +pub(crate) mod statement; diff --git a/crates/sqlbabel-convert/src/sqlite/analysis/_helpers/statement.rs b/crates/sqlbabel-convert/src/sqlite/analysis/_helpers/statement.rs new file mode 100644 index 000000000..97ee303e1 --- /dev/null +++ b/crates/sqlbabel-convert/src/sqlite/analysis/_helpers/statement.rs @@ -0,0 +1,42 @@ +//! The one SQLite statement a conversion reads. + +use sqlbabel_diagnostics::classification::models::{Construct, ConstructFamily}; +use sqlbabel_diagnostics::refusals::main::missing::missing; +use sqlbabel_diagnostics::refusals::main::refuse_unparsed::refuse_unparsed; +use sqlbabel_diagnostics::refusals::models::Refusal; +use sqlbabel_parse::sqlite::parse::main::parse::parse; +use sqlbabel_syntax::Expression; +use sqlbabel_syntax::tokens::errors::ParseFailure; +use sqlbabel_syntax::tokens::models::SourceLines; + +/// The one statement `sql` holds, read whole by the parser; refused otherwise. +pub(crate) fn one_statement(sql: &str) -> Result { + let parsed = parse(sql).map_err(|error| { + refuse_unparsed( + &ParseFailure { + message: error.message, + location: None, + }, + &SourceLines::new(sql), + ) + })?; + if !parsed.gaps.is_empty() { + return Err(missing( + statement_construct(), + "the parser kept part of the statement outside the tree".to_owned(), + )); + } + let count = parsed.statements.len(); + let mut statements = parsed.statements.into_iter(); + match (statements.next(), statements.next()) { + (Some(statement), None) => Ok(statement), + _ => Err(missing( + statement_construct(), + format!("a conversion reads one statement, not {count}"), + )), + } +} + +fn statement_construct() -> Construct { + Construct::new(ConstructFamily::Node, "statement") +} diff --git a/crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_bound.rs b/crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_bound.rs index 33b33290c..5cea32296 100644 --- a/crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_bound.rs +++ b/crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_bound.rs @@ -1,42 +1,12 @@ //! `analyze_bound`: parse SQLite, then convert its one statement with its parameters bound, or refuse. -use sqlbabel_diagnostics::classification::models::{Construct, ConstructFamily}; -use sqlbabel_diagnostics::refusals::main::missing::missing; -use sqlbabel_diagnostics::refusals::main::refuse_unparsed::refuse_unparsed; use sqlbabel_diagnostics::refusals::models::Refusal; -use sqlbabel_parse::sqlite::parse::main::parse::parse; -use sqlbabel_syntax::tokens::errors::ParseFailure; -use sqlbabel_syntax::tokens::models::SourceLines; +use crate::sqlite::analysis::_helpers::statement::one_statement; use crate::sqlite::conversion::main::_convert_statement::convert_statement; use crate::sqlite::conversion::models::Converted; -/// The DuckDB conversion of `sql`, which must be one SQLite statement the parser reads whole, each parameter marker it names bound in `bindings` to a literal, by its name or as `?N`; the literal's storage class is the parameter's. +/// The DuckDB conversion of `sql`, which must be one SQLite statement the parser reads whole, each parameter marker it names bound in `bindings` to a literal, by its name or as `?N`; the literal's storage class is the parameter's, and each marker is DuckDB's `$n`, the literals in `parameters`. pub fn analyze_bound(sql: &str, bindings: &[(String, String)]) -> Result { - let parsed = parse(sql).map_err(|error| { - refuse_unparsed( - &ParseFailure { - message: error.message, - location: None, - }, - &SourceLines::new(sql), - ) - })?; - if !parsed.gaps.is_empty() { - return Err(missing( - statement_construct(), - "the parser kept part of the statement outside the tree".to_owned(), - )); - } - match parsed.statements.as_slice() { - [statement] => convert_statement(statement, sql, bindings), - statements => Err(missing( - statement_construct(), - format!("a conversion reads one statement, not {}", statements.len()), - )), - } -} - -fn statement_construct() -> Construct { - Construct::new(ConstructFamily::Node, "statement") + convert_statement(&one_statement(sql)?, sql, (bindings, false)) } diff --git a/crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_effect.rs b/crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_effect.rs index 37371331c..1a6c54623 100644 --- a/crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_effect.rs +++ b/crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_effect.rs @@ -12,15 +12,16 @@ use sqlbabel_syntax::tokens::models::SourceLines; use crate::sqlite::conversion::main::_convert_effect::convert_effect; use crate::sqlite::conversion::models::{ConvertedEffect, EffectProbe}; -/// The DuckDB setup, statements and probes of an effect case: `setup` and `statements` each one SQLite statement, run in order. +/// The DuckDB setup, statements and probes of an effect case: `setup` and `statements` each one SQLite statement, run in order, each parameter marker written as the literal `bindings` bind it to; each binding must name a marker of some statement. pub fn analyze_effect( (setup, statements): (&[String], &[String]), probes: &[EffectProbe], + bindings: &[(String, String)], ) -> Result { let read = |sources: &[String]| -> Result, Refusal> { sources.iter().map(|sql| sourced(sql)).collect() }; - convert_effect((&read(setup)?, &read(statements)?), probes) + convert_effect((&read(setup)?, &read(statements)?), probes, bindings) } /// The one statement `sql` holds, with its text. diff --git a/crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_inline.rs b/crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_inline.rs new file mode 100644 index 000000000..8b6eec992 --- /dev/null +++ b/crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_inline.rs @@ -0,0 +1,12 @@ +//! `analyze_inline`: parse SQLite, then convert its one statement with each parameter's value written in place, or refuse. + +use sqlbabel_diagnostics::refusals::models::Refusal; + +use crate::sqlite::analysis::_helpers::statement::one_statement; +use crate::sqlite::conversion::main::_convert_statement::convert_statement; +use crate::sqlite::conversion::models::Converted; + +/// The DuckDB conversion of `sql`, which must be one SQLite statement the parser reads whole, each parameter marker it names bound in `bindings` to a literal, by its name or as `?N`; each marker is its literal, typed by its storage class, so the SQL runs as it is for those values only. +pub fn analyze_inline(sql: &str, bindings: &[(String, String)]) -> Result { + convert_statement(&one_statement(sql)?, sql, (bindings, true)) +} diff --git a/crates/sqlbabel-convert/src/sqlite/analysis/main/mod.rs b/crates/sqlbabel-convert/src/sqlite/analysis/main/mod.rs index 4674c75dd..d71daa747 100644 --- a/crates/sqlbabel-convert/src/sqlite/analysis/main/mod.rs +++ b/crates/sqlbabel-convert/src/sqlite/analysis/main/mod.rs @@ -1,3 +1,4 @@ pub mod analyze; pub mod analyze_bound; pub mod analyze_effect; +pub mod analyze_inline; diff --git a/crates/sqlbabel-convert/src/sqlite/analysis/mod.rs b/crates/sqlbabel-convert/src/sqlite/analysis/mod.rs index 0e910f9f8..d6adcb58d 100644 --- a/crates/sqlbabel-convert/src/sqlite/analysis/mod.rs +++ b/crates/sqlbabel-convert/src/sqlite/analysis/mod.rs @@ -1,3 +1,4 @@ //! Analysing one SQLite statement. +pub(crate) mod _helpers; pub mod main; diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/statements.rs b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/statements.rs index 8d8bad1be..d35e58966 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/statements.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/statements.rs @@ -13,12 +13,14 @@ use crate::sqlite::conversion::_helpers::effects::rows::{delete, insert, update} use crate::sqlite::conversion::_helpers::effects::sessions::{begin, commit, pragma, rollback}; use crate::sqlite::conversion::_helpers::effects::tables::create_table; use crate::sqlite::conversion::_helpers::queries::query::declared_collations_read_directly; +use crate::sqlite::conversion::_helpers::support::parameters::bind_parameters; use crate::sqlite::conversion::_helpers::support::tree::{node_kind, refused}; use crate::sqlite::conversion::constants::{FAILURE_MODES, MAX_TREE_DEPTH}; -/// `tree`, whose SQLite text is `source`, as DuckDB SQL, the catalog updated with what it defines; refused once an earlier statement may have failed in a way that leaves what is defined unknown. +/// `tree`, whose SQLite text is `source`, as DuckDB SQL with each parameter marker written as the literal `bindings` bind it to, the catalog updated with what it defines; refused once an earlier statement may have failed in a way that leaves what is defined unknown. pub(crate) fn effect_statement( (tree, source): (&Expression, &str), + bindings: &[(String, String)], (catalog, log): (&mut Catalog, &ProvenanceLog), ) -> Result { if tree.tree_depth() > MAX_TREE_DEPTH { @@ -35,6 +37,7 @@ pub(crate) fn effect_statement( } let node: Value = serde_json::to_value(tree) .map_err(|error| refused("statement", format!("the tree does not serialise: {error}")))?; + let (node, _) = bind_parameters(node, source, (bindings, true), log)?; let declared: Vec = catalog .relations .iter() diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/expressions/dispatch.rs b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/expressions/dispatch.rs index 7d20f891d..bc6b1daad 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/expressions/dispatch.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/expressions/dispatch.rs @@ -116,9 +116,9 @@ pub(crate) fn expression(node: &Value, site: Site<'_>) -> Result) -> Result { - let payload = understood(payload, BOUND_PARAMETER_KIND, &["number", "class"])?; + let payload = understood(payload, BOUND_PARAMETER_KIND, &["number", "class", "value"])?; let class = match field(payload, "class").as_str() { Some("integer") => StorageClass::Integer, Some("real") => StorageClass::Real, @@ -139,7 +139,11 @@ fn bound_parameter(payload: &Value, site: Site<'_>) -> Result )); }; let _rule = site.log.rule(PARAMETER_RULE); - Ok(Emitted::of(format!("${number}"), class)) + let sql = match field(payload, "value").as_str() { + Some(value) => value.to_owned(), + None => format!("${number}"), + }; + Ok(Emitted::of(sql, class)) } /// The `this` operand of a one-operand node. diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/support/parameters.rs b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/support/parameters.rs index 2d4722ce3..d2a7973c7 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/support/parameters.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/support/parameters.rs @@ -1,4 +1,4 @@ -//! Bound parameters: SQLite's numbering of a statement's markers, each marker bound to a literal whose storage class it then has, written as DuckDB's `$n`. +//! Bound parameters: SQLite's numbering of a statement's markers, each marker bound to a literal whose storage class it then has, written as DuckDB's `$n` or as the literal itself. use std::collections::{BTreeMap, BTreeSet}; @@ -7,7 +7,7 @@ use sqlbabel_diagnostics::provenance::models::ProvenanceLog; use sqlbabel_diagnostics::refusals::models::Refusal; use sqlbabel_parse::sqlite::parse::main::parse::parse; use sqlbabel_parse::sqlite::scan; -use sqlbabel_parse::sqlite::scan::models::TokenKind; +use sqlbabel_parse::sqlite::scan::models::{Token, TokenKind}; use crate::sqlite::conversion::_helpers::expressions::dispatch::expression; use crate::sqlite::conversion::_helpers::support::scope::{Scope, Site}; @@ -16,6 +16,9 @@ use crate::sqlite::conversion::_helpers::support::values::{literal_sql, single}; use crate::sqlite::conversion::constants::BOUND_PARAMETER_KIND; use crate::sqlite::conversion::models::StorageClass; +/// A parameter bound: its DuckDB number, the storage class of its value, and its literal where that is written in place of `$n`. +type Bound = (u32, StorageClass, Option); + /// The parameters SQLite numbers in a statement: each number with the markers that name it. struct Numbering { /// Each parameter number, with its named markers and `?N` for its number. @@ -34,11 +37,11 @@ impl Numbering { } } -/// `node` with every marker rewritten as a bound parameter numbered for DuckDB, and the DuckDB literal of each `$n` in order; a marker bound to no value refuses, as does a binding naming no marker. +/// `node` with every marker rewritten as a bound parameter numbered for DuckDB, and the DuckDB literal of each `$n` in order; `inline` writes each literal in place of its `$n` and returns none. A marker bound to no value refuses, as does a binding naming no marker. pub(crate) fn bind_parameters( node: Value, source: &str, - bindings: &[(String, String)], + (bindings, inline): (&[(String, String)], bool), log: &ProvenanceLog, ) -> Result<(Value, Vec), Refusal> { let numbering = numbering(source)?; @@ -51,7 +54,7 @@ pub(crate) fn bind_parameters( format!("a value is bound to {marker}, which the statement does not name"), )); } - let mut numbers: BTreeMap = BTreeMap::new(); + let mut numbers: BTreeMap = BTreeMap::new(); let mut values: Vec = Vec::new(); for (number, markers) in &numbering.markers { let bound: Vec<&String> = bindings @@ -70,7 +73,7 @@ pub(crate) fn bind_parameters( return Err(refused( "parameter", format!( - "the parameter {named} is bound to no value, which would give its storage class" + "the parameter {named} has no bound value; pass --bind {named}=LITERAL (bindings= in Python)" ), )); } @@ -82,13 +85,31 @@ pub(crate) fn bind_parameters( } }; let (class, sql) = bound_value(value, log)?; - values.push(sql); + values.push(sql.clone()); numbers.insert( *number, - (u32::try_from(values.len()).unwrap_or(u32::MAX), class), + ( + u32::try_from(values.len()).unwrap_or(u32::MAX), + class, + inline.then_some(sql), + ), ); } - Ok((rewrite(node, &numbering, &numbers)?, values)) + let node = rewrite(node, &numbering, &numbers)?; + Ok((node, if inline { Vec::new() } else { values })) +} + +/// Those of `bindings` whose marker the statement `source` names, for a script whose statements share them. +pub(crate) fn named_bindings( + source: &str, + bindings: &[(String, String)], +) -> Result, Refusal> { + let numbering = numbering(source)?; + Ok(bindings + .iter() + .filter(|(marker, _)| numbering.number(marker).is_some()) + .cloned() + .collect()) } /// SQLite's parameter numbers, assigned in token order: `?` takes the next number, `?N` the number N, and a name its first use's next number. @@ -155,6 +176,9 @@ fn bound_value(value: &str, log: &ProvenanceLog) -> Result<(StorageClass, String format!("the bound value {value} is no single literal"), ) }; + if !literal(&scan(value)) { + return Err(not_literal()); + } let parsed = parse(&format!("SELECT {value}")).map_err(|_| not_literal())?; let [statement] = parsed.statements.as_slice() else { return Err(not_literal()); @@ -194,11 +218,25 @@ fn bound_value(value: &str, log: &ProvenanceLog) -> Result<(StorageClass, String }) } -/// `node` with each marker node under it replaced by its bound parameter. +/// Whether `tokens` are one string, blob or number, a number optionally signed, or `NULL`. +fn literal(tokens: &[Token]) -> bool { + match tokens { + [sign, number] if matches!(sign.kind, TokenKind::Op("MINUS" | "PLUS")) => { + matches!(number.kind, TokenKind::Number(_)) + } + [token] => matches!( + token.kind, + TokenKind::String | TokenKind::Blob | TokenKind::Number(_) | TokenKind::Keyword("NULL") + ), + _ => false, + } +} + +/// `node` with each marker node under it replaced by its bound parameter, which carries its literal where that is written in place. fn rewrite( node: Value, numbering: &Numbering, - numbers: &BTreeMap, + numbers: &BTreeMap, ) -> Result { let marker = match node_kind(&node) { Some(("placeholder", payload)) => { @@ -230,13 +268,15 @@ fn rewrite( _ => None, }; if let Some(number) = marker { - let Some((duckdb, class)) = number.and_then(|number| numbers.get(&number)) else { + let Some((duckdb, class, value)) = number.and_then(|number| numbers.get(&number)) else { return Err(refused( "parameter", "a marker in the tree is not one the statement's text numbers".to_owned(), )); }; - return Ok(json!({ BOUND_PARAMETER_KIND: { "number": duckdb, "class": class } })); + return Ok( + json!({ BOUND_PARAMETER_KIND: { "number": duckdb, "class": class, "value": value } }), + ); } Ok(match node { Value::Array(items) => Value::Array( diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/main/_convert_effect.rs b/crates/sqlbabel-convert/src/sqlite/conversion/main/_convert_effect.rs index 43b48f0e1..dcdce1890 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/main/_convert_effect.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/main/_convert_effect.rs @@ -1,29 +1,35 @@ //! `convert_effect`: an effect case's setup, statements and probes as DuckDB SQL, or the first refusal. +use std::collections::BTreeSet; + use sqlbabel_diagnostics::provenance::models::ProvenanceLog; use sqlbabel_diagnostics::refusals::models::Refusal; use crate::sqlite::conversion::_helpers::effects::catalog::Catalog; use crate::sqlite::conversion::_helpers::effects::probes::duckdb_probe; use crate::sqlite::conversion::_helpers::effects::statements::effect_statement; +use crate::sqlite::conversion::_helpers::support::parameters::named_bindings; +use crate::sqlite::conversion::_helpers::support::tree::refused; use crate::sqlite::conversion::models::{ConvertedEffect, EffectProbe}; use crate::sqlite::conversion::types::SourcedStatement; -/// Converts the setup, then the statements under test, each knowing the tables the ones before it defined; each tree comes with its SQLite text. +/// Converts the setup, then the statements under test, each knowing the tables the ones before it defined; each tree comes with its SQLite text. Each statement takes the `bindings` whose markers it names, and a binding no statement names refuses. pub(crate) fn convert_effect( (setup, statements): (&[SourcedStatement], &[SourcedStatement]), probes: &[EffectProbe], + bindings: &[(String, String)], ) -> Result { let log = ProvenanceLog::default(); let mut catalog = Catalog::default(); - let mut converted = |trees: &[SourcedStatement]| -> Result, Refusal> { - trees - .iter() - .map(|(tree, source)| effect_statement((tree, source), (&mut catalog, &log))) - .collect() - }; - let setup = converted(setup)?; - let statements = converted(statements)?; + let mut named: BTreeSet = BTreeSet::new(); + let setup = converted(setup, bindings, (&mut catalog, &log, &mut named))?; + let statements = converted(statements, bindings, (&mut catalog, &log, &mut named))?; + if let Some((marker, _)) = bindings.iter().find(|(marker, _)| !named.contains(marker)) { + return Err(refused( + "parameter", + format!("a value is bound to {marker}, which no statement names"), + )); + } let probes: Vec = probes.iter().map(duckdb_probe).collect::>()?; Ok(ConvertedEffect { setup, @@ -32,3 +38,24 @@ pub(crate) fn convert_effect( provenance: log.finish(), }) } + +/// `trees` as DuckDB SQL in order, each with the `bindings` it names, whose markers join `named`. +fn converted( + trees: &[SourcedStatement], + bindings: &[(String, String)], + (catalog, log, named): (&mut Catalog, &ProvenanceLog, &mut BTreeSet), +) -> Result, Refusal> { + let mut sql: Vec = Vec::new(); + for (tree, source) in trees { + let bound = named_bindings(source, bindings)?; + for (marker, _) in &bound { + named.insert(marker.clone()); + } + sql.push(effect_statement( + (tree, source), + &bound, + (&mut *catalog, log), + )?); + } + Ok(sql) +} diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/main/_convert_statement.rs b/crates/sqlbabel-convert/src/sqlite/conversion/main/_convert_statement.rs index 47bc43ed5..68b382962 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/main/_convert_statement.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/main/_convert_statement.rs @@ -11,11 +11,11 @@ use crate::sqlite::conversion::_helpers::support::tree::refused; use crate::sqlite::conversion::constants::MAX_TREE_DEPTH; use crate::sqlite::conversion::models::Converted; -/// Converts a statement that defines every relation it reads, `source` its SQLite text, each parameter marker bound to one of `bindings`' literals; DuckDB must parse and bind the result. +/// Converts a statement that defines every relation it reads, `source` its SQLite text, each parameter marker bound to one of `bindings`' literals, written in place of its `$n` where `inline`; DuckDB must parse and bind the result. pub(crate) fn convert_statement( tree: &Expression, source: &str, - bindings: &[(String, String)], + bound: (&[(String, String)], bool), ) -> Result { let depth = tree.tree_depth(); if depth > MAX_TREE_DEPTH { @@ -31,7 +31,7 @@ pub(crate) fn convert_statement( let node = serde_json::to_value(tree) .map_err(|error| refused("statement", format!("the tree does not serialise: {error}")))?; let log = ProvenanceLog::default(); - let (node, parameters) = bind_parameters(node, source, bindings, &log)?; + let (node, parameters) = bind_parameters(node, source, bound, &log)?; let (sql, columns) = statement(&node, source, &log)?; check_printed(&sql, (&|_| None, &|_| None)).map_err(|failure| { refused( diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_convert_effect.rs b/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_convert_effect.rs index 45af91177..be25adae9 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_convert_effect.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_convert_effect.rs @@ -550,7 +550,7 @@ fn given_sqlite_effect_statements_when_converted_then_duckdb_runs_them_alike_or_ .iter() .map(|sql| (*sql).to_owned()) .collect(); - let converted = analyze_effect((&setup, &statements), &[]); + let converted = analyze_effect((&setup, &statements), &[], &[]); let converted_statements: Vec = converted .as_ref() .map_or_else(|_| Vec::new(), |converted| converted.statements.clone()); diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs b/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs index 7c09c634d..14cc93eb3 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs @@ -67,7 +67,7 @@ fn given_bound_markers_when_converted_then_each_is_a_duckdb_parameter_typed_by_i sql: "SELECT :a AS r", bindings: &[], expected_conversion: Err( - "the parameter :a is bound to no value, which would give its storage class", + "the parameter :a has no bound value; pass --bind :a=LITERAL (bindings= in Python)", ), }, ParameterTestCase { @@ -96,6 +96,34 @@ fn given_bound_markers_when_converted_then_each_is_a_duckdb_parameter_typed_by_i bindings: &[("?1", "abs(-1)")], expected_conversion: Err("the bound value abs(-1) is no single literal"), }, + ParameterTestCase { + description: "a literal followed by another statement", + sql: "SELECT ?1 AS r", + bindings: &[("?1", "1; DROP TABLE t")], + expected_conversion: Err("the bound value 1; DROP TABLE t is no single literal"), + }, + ParameterTestCase { + description: "a sign before an expression that folds to a constant", + sql: "SELECT ?1 AS r", + bindings: &[("?1", "-abs(-1)")], + expected_conversion: Err("the bound value -abs(-1) is no single literal"), + }, + ParameterTestCase { + description: "a sign before a string", + sql: "SELECT ?1 AS r", + bindings: &[("?1", "-'1'")], + expected_conversion: Err("the bound value -'1' is no single literal"), + }, + ParameterTestCase { + description: "a signed number is one literal", + sql: "SELECT ?1 AS r", + bindings: &[("?1", "+ 3")], + expected_conversion: Ok(BoundConversion { + sql: "SELECT $1 AS \"r\"", + values: &["CAST(3 AS BIGINT)"], + classes: &[StorageClass::Integer], + }), + }, ]; for test_case in test_cases { assert_eq!( diff --git a/crates/sqlbabel-python/src/bindings/_helpers/convert_json.rs b/crates/sqlbabel-python/src/bindings/_helpers/convert_json.rs index 89e351255..3f11a219f 100644 --- a/crates/sqlbabel-python/src/bindings/_helpers/convert_json.rs +++ b/crates/sqlbabel-python/src/bindings/_helpers/convert_json.rs @@ -39,6 +39,7 @@ pub(crate) fn convert_json(sql: &str, request: &str, path: &str) -> PyResult, /// `--session NAME=VALUE`, by name. pub session: BTreeMap, + /// `--bind MARKER=LITERAL`, by marker. + pub bindings: BTreeMap, /// `--compact`. pub compact: bool, /// `--no-bind-check`. diff --git a/crates/sqlbabel/src/analysis/_helpers/sqlite_conversion.rs b/crates/sqlbabel/src/analysis/_helpers/sqlite_conversion.rs index 60aaedbd8..fed0196a4 100644 --- a/crates/sqlbabel/src/analysis/_helpers/sqlite_conversion.rs +++ b/crates/sqlbabel/src/analysis/_helpers/sqlite_conversion.rs @@ -111,7 +111,7 @@ pub(crate) fn sqlite_effect_conversion(case: &LoadedCase) -> EffectConversion { names: probe.names.clone(), }); } - match analyze_effect((&case.setup, &effect.statements), &probes) { + match analyze_effect((&case.setup, &effect.statements), &probes, &[]) { Ok(converted) => EffectConversion::Converted { setup: converted.setup, statements: converted.statements, diff --git a/crates/sqlbabel/src/analysis/tests/helpers.rs b/crates/sqlbabel/src/analysis/tests/helpers.rs index 14b674ede..6e644f41b 100644 --- a/crates/sqlbabel/src/analysis/tests/helpers.rs +++ b/crates/sqlbabel/src/analysis/tests/helpers.rs @@ -1002,6 +1002,7 @@ fn everyday_arguments(root: &std::path::Path, no_config: bool) -> ConvertArgumen overrides: None, verified_overrides: Vec::new(), session: Vec::new(), + bindings: Vec::new(), compact: true, no_bind_check: false, verbose: false, diff --git a/crates/sqlbabel/src/cli/_helpers/convert_command.rs b/crates/sqlbabel/src/cli/_helpers/convert_command.rs index 62a0804c3..0ca682187 100644 --- a/crates/sqlbabel/src/cli/_helpers/convert_command.rs +++ b/crates/sqlbabel/src/cli/_helpers/convert_command.rs @@ -63,6 +63,7 @@ use sqlbabel_convert::postgres::analysis::main::analyze_effect::analyze_effect a use sqlbabel_convert::snowflake::analysis::main::with_divergence_help::with_divergence_help; use sqlbabel_convert::sqlite::analysis::main::analyze::analyze as analyze_sqlite; use sqlbabel_convert::sqlite::analysis::main::analyze_effect::analyze_effect as analyze_sqlite_effect; +use sqlbabel_convert::sqlite::analysis::main::analyze_inline::analyze_inline as analyze_sqlite_inline; use sqlbabel_diagnostics::provenance::models::Provenance; use sqlbabel_parse::databricks::parse::main::parse::parse as parse_databricks; use sqlbabel_parse::databricks::scan::main::scan::scan as scan_databricks; @@ -90,6 +91,11 @@ const STDIN_NAME: &str = ""; /// DuckDB SQL and the rules used, or the first refusal. type ScriptConversion = Result<(String, Provenance), Refusal>; +/// The query rules and the effect rules a script is converted by. +type ScriptConverters<'a> = ( + &'a dyn Fn(&str) -> ScriptConversion, + &'a dyn Fn(&[String]) -> ScriptConversion, +); /// How `convert` reads a script in one dialect: its statements as its scanner separates them and its parser reads them, its query rules and its effect rules. struct ScriptRules { @@ -169,7 +175,7 @@ const SQLITE_SCRIPTS: ScriptRules = ScriptRules { parsed: |sql| parse_sqlite(sql).map_err(|error| error.message), query: |sql| analyze_sqlite(sql).map(|converted| (converted.sql, converted.provenance)), effects: |statements| { - analyze_sqlite_effect((&[], statements), &[]).map(|converted| { + analyze_sqlite_effect((&[], statements), &[], &[]).map(|converted| { ( effect_sql(converted.setup, converted.statements), converted.provenance, @@ -267,6 +273,7 @@ fn run_printed(arguments: &RunArguments, palette: &Palette) -> RunPrinted { overrides: arguments.overrides.clone(), verified_overrides: arguments.verified_overrides.clone(), session: arguments.session.clone(), + bindings: Vec::new(), compact: true, no_bind_check: false, verbose: false, @@ -950,7 +957,7 @@ pub(crate) fn postgres_report( }) } -/// The report of SQLite `sql`: converted by the SQLite rules or refused; the Snowflake options do not apply. +/// The report of SQLite `sql`: converted by the SQLite rules with each `--bind` value written in place of its marker, or refused; the Snowflake options do not apply. pub(crate) fn sqlite_report( arguments: &ConvertArguments, sql: &str, @@ -966,7 +973,27 @@ pub(crate) fn sqlite_report( if snowflake_options { return Err(SQLITE_OPTIONS_ERROR.to_owned()); } - let (converted_sql, refusals) = match script_conversion(sql, &SQLITE_SCRIPTS) { + let bindings = arguments + .bindings + .iter() + .map(|binding| match binding.split_once('=') { + Some((marker, value)) => Ok((marker.to_owned(), value.to_owned())), + None => Err(format!("--bind {binding} is no MARKER=LITERAL")), + }) + .collect::, String>>()?; + let query = |sql: &str| { + analyze_sqlite_inline(sql, &bindings).map(|converted| (converted.sql, converted.provenance)) + }; + let effects = |statements: &[String]| { + analyze_sqlite_effect((&[], statements), &[], &bindings).map(|converted| { + ( + effect_sql(converted.setup, converted.statements), + converted.provenance, + ) + }) + }; + let (converted_sql, refusals) = match converted_script(sql, &SQLITE_SCRIPTS, (&query, &effects)) + { Ok((sql, _)) => (sql, Vec::new()), Err(refusal) => (String::new(), vec![refusal]), }; @@ -985,16 +1012,25 @@ pub(crate) fn sqlite_report( /// `sql` as DuckDB SQL: one statement by the query rules, or, where those refuse a statement that is no query, and for a script of several statements, by the effect rules with one catalog across the statements. Only input the parser reads whole, into the statements the separators split, takes the effect rules; any other input is refused by the query rules as before. fn script_conversion(sql: &str, rules: &ScriptRules) -> ScriptConversion { + converted_script(sql, rules, (&rules.query, &rules.effects)) +} + +/// `sql` as DuckDB SQL as [`script_conversion`] converts it, by the dialect's separators and parser in `rules` and the `query` and `effects` rules given. +fn converted_script( + sql: &str, + rules: &ScriptRules, + (query, effects): ScriptConverters<'_>, +) -> ScriptConversion { let parsed = match (rules.parsed)(sql) { Ok(parsed) if parsed.gaps.is_empty() => parsed, - Ok(_) | Err(_) => return (rules.query)(sql), + Ok(_) | Err(_) => return query(sql), }; let statements = (rules.statements)(sql); if statements.len() > 1 && parsed.statements.len() == statements.len() { - return (rules.effects)(&statements); + return effects(&statements); } - match (rules.query)(sql) { - Err(_) if statements.len() == 1 && one_effect(&parsed) => (rules.effects)(&statements), + match query(sql) { + Err(_) if statements.len() == 1 && one_effect(&parsed) => effects(&statements), converted => converted, } } diff --git a/crates/sqlbabel/src/cli/constants.rs b/crates/sqlbabel/src/cli/constants.rs index a536c38bd..f0d5fbc4a 100644 --- a/crates/sqlbabel/src/cli/constants.rs +++ b/crates/sqlbabel/src/cli/constants.rs @@ -23,5 +23,7 @@ pub const POSTGRES_PROFILE: &str = "pg-default-v1"; pub const SQLITE_PROFILE: &str = "sqlite-default-v1"; /// Why `--dialect sqlite` exits 2 with a Snowflake-only option. pub const SQLITE_OPTIONS_ERROR: &str = "--dialect sqlite takes no project, schema, session, override, verified-override, python-runtime or allow option"; +/// Why `--bind` exits 2 with a dialect other than SQLite. +pub const BIND_DIALECT_ERROR: &str = "--bind takes --dialect sqlite"; /// Why `--dialect postgres` exits 2 with a Snowflake-only option. pub const POSTGRES_OPTIONS_ERROR: &str = "--dialect postgres takes no project, schema, session, override, verified-override, python-runtime or allow option"; diff --git a/crates/sqlbabel/src/cli/main/convert_report.rs b/crates/sqlbabel/src/cli/main/convert_report.rs index ccd541aa3..e3254bc4e 100644 --- a/crates/sqlbabel/src/cli/main/convert_report.rs +++ b/crates/sqlbabel/src/cli/main/convert_report.rs @@ -7,6 +7,7 @@ use crate::cli::_helpers::convert_command::{ sqlite_report, }; use crate::cli::_helpers::project::project_choices; +use crate::cli::constants::BIND_DIALECT_ERROR; use crate::cli::models::{ConvertArguments, ConvertReport, SourceDialect}; use sqlbabel_convert::snowflake::analysis::main::analyze::analyze; use sqlbabel_convert::snowflake::session::main::parse_session::parse_session; @@ -14,6 +15,9 @@ use sqlbabel_convert::snowflake::session::main::session_conversion_options::sess /// The report `convert` prints for `sql` under `arguments`, or why it cannot be made (exit 2). pub fn convert_report(arguments: &ConvertArguments, sql: &str) -> Result { + if !arguments.bindings.is_empty() && arguments.dialect != SourceDialect::Sqlite { + return Err(BIND_DIALECT_ERROR.to_owned()); + } match arguments.dialect { SourceDialect::Databricks => databricks_report(arguments, sql), SourceDialect::Postgres => postgres_report(arguments, sql), diff --git a/crates/sqlbabel/src/cli/models.rs b/crates/sqlbabel/src/cli/models.rs index 052b6c9cb..1f082bcf0 100644 --- a/crates/sqlbabel/src/cli/models.rs +++ b/crates/sqlbabel/src/cli/models.rs @@ -133,6 +133,9 @@ pub struct ConvertArguments { /// A Snowflake session parameter of the caller's session, `NAME=VALUE`; repeatable. #[arg(long = "session", value_name = "NAME=VALUE")] pub session: Vec, + /// A SQLite parameter marker and the one literal bound to it, `?1=5`, `:name='x'` or `@n=NULL`, written in place of the marker; repeatable, `--dialect sqlite` only. + #[arg(long = "bind", value_name = "MARKER=LITERAL")] + pub bindings: Vec, /// Print each converted statement on one line instead of one clause per line, in `--json` too. #[arg(long)] pub compact: bool, diff --git a/docs/architecture.md b/docs/architecture.md index 3f4cf1e2d..23f8309bb 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -593,8 +593,13 @@ bound twice and a value that is not one literal. and echoes them on the journal line, which then answers only a case with the same bindings. - Conversion: each marker becomes DuckDB's `$n`, numbered in the order of SQLite's parameter numbers, and has its value's storage class; DuckDB types a parameter by the value bound to it. A - marker bound to no value, a value bound to no marker, and a statement with more than one `?` - refuse. + marker bound to no value, a value bound to no marker, a value that is not one literal by SQLite's + tokenizer (a number, optionally signed, a string, a blob or `NULL`), and a statement with more + than one `?` refuse. +- `convert --bind` (`bindings` in Python): the same binding, with each typed literal written in + place of its marker, so the output runs as it is and is specialised to the values bound. In a + script, each statement takes the bindings its markers name, and a binding no statement names + refuses. - Replay: verify prepares the converted SQL as `bound` and runs `EXECUTE bound(...)` with each value as a typed DuckDB literal. diff --git a/python/src/sqlbabel/api/main/convert.py b/python/src/sqlbabel/api/main/convert.py index 6194c8800..b4bcd009e 100644 --- a/python/src/sqlbabel/api/main/convert.py +++ b/python/src/sqlbabel/api/main/convert.py @@ -28,6 +28,7 @@ def convert( "allow_location": chosen.allow_location, "overrides": path_argument(chosen.overrides), "verified_overrides": dict(chosen.verified_overrides), + "bindings": dict(chosen.bindings), "compact": chosen.compact, "max_call_depth": chosen.max_call_depth, "no_bind_check": not chosen.bind_check, diff --git a/python/src/sqlbabel/api/models.py b/python/src/sqlbabel/api/models.py index fc17fa4bc..d9d39a092 100644 --- a/python/src/sqlbabel/api/models.py +++ b/python/src/sqlbabel/api/models.py @@ -76,6 +76,7 @@ class ConvertOptions: allow_location: str | None = None overrides: str | os.PathLike[str] | None = None verified_overrides: Mapping[str, str] = field(default_factory=dict) + bindings: Mapping[str, str] = field(default_factory=dict) compact: bool = False max_call_depth: int | None = None bind_check: bool = True diff --git a/tests/unit/python/src/sqlbabel/api/main/_test_types.py b/tests/unit/python/src/sqlbabel/api/main/_test_types.py index ad82c69af..5137db437 100644 --- a/tests/unit/python/src/sqlbabel/api/main/_test_types.py +++ b/tests/unit/python/src/sqlbabel/api/main/_test_types.py @@ -3,6 +3,7 @@ from __future__ import annotations from dataclasses import dataclass +from typing import Any from sqlbabel import ConvertOptions, Span @@ -59,6 +60,16 @@ class CommandLineTestCase: expected_converted: bool +@dataclass(frozen=True) +class BoundSqliteTestCase: + description: str + #: Each SQLite statement of the script, with the values sqlite3 binds to it. + statements: tuple[tuple[str, tuple[Any, ...] | dict[str, Any]], ...] + bindings: dict[str, str] + #: The rows the last statement returns, as SQLite returns them. + expected_rows: list[tuple[Any, ...]] + + @dataclass(frozen=True) class TypedDiagnosticTestCase: description: str diff --git a/tests/unit/python/src/sqlbabel/api/main/helpers.py b/tests/unit/python/src/sqlbabel/api/main/helpers.py index 147fbc47d..edaa46437 100644 --- a/tests/unit/python/src/sqlbabel/api/main/helpers.py +++ b/tests/unit/python/src/sqlbabel/api/main/helpers.py @@ -4,6 +4,7 @@ import json import os +import sqlite3 import subprocess from operator import attrgetter from pathlib import Path @@ -47,6 +48,24 @@ def command_report(sql: str, arguments: tuple[str, ...], directory: Path) -> dic return json.loads(completed.stdout) +def sqlite_rows(statements: tuple[tuple[str, Any], ...]) -> list[tuple[Any, ...]]: + """The rows SQLite returns from the last of `statements`, each run with its bound values.""" + connection: sqlite3.Connection = sqlite3.connect(":memory:") + rows: list[tuple[Any, ...]] = [] + for statement, values in statements: + rows = connection.execute(statement, values).fetchall() + connection.close() + return rows + + +def typed(rows: list[tuple[Any, ...]]) -> list[tuple[tuple[str, Any], ...]]: + """Each value of `rows` with its Python type, so `True` and `1` differ.""" + typed_rows: list[tuple[tuple[str, Any], ...]] = [] + for row in rows: + typed_rows.append(tuple((type(value).__name__, value) for value in row)) + return typed_rows + + def positions(result: CheckResult) -> tuple[tuple[int, int], ...]: """The line and column of each diagnostic of `result`.""" return tuple(attrgetter("span.line", "span.column")(found) for found in result.diagnostics) diff --git a/tests/unit/python/src/sqlbabel/api/main/test_convert.py b/tests/unit/python/src/sqlbabel/api/main/test_convert.py index 39c72b2ba..ec4413563 100644 --- a/tests/unit/python/src/sqlbabel/api/main/test_convert.py +++ b/tests/unit/python/src/sqlbabel/api/main/test_convert.py @@ -5,6 +5,7 @@ from dataclasses import replace from pathlib import Path +import duckdb import pytest import sqlbabel @@ -12,6 +13,7 @@ from tests.unit.python.src.sqlbabel.api.main._test_types import ( AllowTestCase, BindCheckTestCase, + BoundSqliteTestCase, CommandLineTestCase, ConfiguredAllowTestCase, DeepChainTestCase, @@ -23,6 +25,8 @@ SCHEMA, command_report, source_project, + sqlite_rows, + typed, ) CONFIG: str = str(Path(__file__).resolve().parents[7] / "sqlbabel.toml") @@ -110,6 +114,38 @@ options=ConvertOptions(no_config=True, dialect="databricks"), expected_converted=True, ), + CommandLineTestCase( + description="a SQLite query with its parameter bound", + sql="SELECT ? + 1 AS r", + arguments=("--no-config", "--dialect", "sqlite", "--bind", "?1=41"), + options=ConvertOptions(no_config=True, dialect="sqlite", bindings={"?1": "41"}), + expected_converted=True, + ), + CommandLineTestCase( + description="a SQLite parameter no value is bound to", + sql="SELECT ? + 1 AS r", + arguments=("--no-config", "--dialect", "sqlite"), + options=ConvertOptions(no_config=True, dialect="sqlite"), + expected_converted=False, + ), + CommandLineTestCase( + description="a SQLite value bound to no marker", + sql="SELECT ?1 AS r", + arguments=("--no-config", "--dialect", "sqlite", "--bind", "?1=1", "--bind", ":z=2"), + options=ConvertOptions( + no_config=True, dialect="sqlite", bindings={"?1": "1", ":z": "2"} + ), + expected_converted=False, + ), + CommandLineTestCase( + description="a SQLite value that is a literal and then a statement", + sql="SELECT ?1 AS r", + arguments=("--no-config", "--dialect", "sqlite", "--bind", "?1=1; DROP TABLE t"), + options=ConvertOptions( + no_config=True, dialect="sqlite", bindings={"?1": "1; DROP TABLE t"} + ), + expected_converted=False, + ), CommandLineTestCase( description="a Databricks query no Databricks rule proves", sql="SELECT tan(1.0) AS r", @@ -249,6 +285,12 @@ def test_given_a_refusal_when_converting_then_the_diagnostic_is_typed( options=ConvertOptions(no_config=True, schema={"ORDERS": "order_id"}), expected_message="the schema option is not a schema", ), + FailureTestCase( + description="a bound value with a dialect other than SQLite", + sql="SELECT 1 AS r", + options=ConvertOptions(no_config=True, dialect="postgres", bindings={"?1": "1"}), + expected_message="--bind takes --dialect sqlite", + ), FailureTestCase( description="a Snowflake option with the Databricks dialect", sql="SELECT 1 AS r", @@ -424,3 +466,51 @@ def test_given_a_configuration_when_the_caller_allows_over_it_then_the_caller_wi ) assert tuple(found.help for found in conversion.diagnostics) == test_case.expected_helps + + +@pytest.mark.parametrize( + "test_case", + ( + BoundSqliteTestCase( + description="a ? query, its text value bound", + statements=(("SELECT ? || 'b' AS r, typeof(?1) AS t", ("a",)),), + bindings={"?1": "'a'"}, + expected_rows=[("ab", "text")], + ), + BoundSqliteTestCase( + description="?N in an INSERT, then an UPDATE ... RETURNING, an integer and a real bound", + statements=( + ("CREATE TABLE t(a INTEGER, b REAL)", ()), + ("INSERT INTO t VALUES (?1, ?2)", (7, 2.5)), + ("UPDATE t SET a = a / 2 + ?1 WHERE b = ?2 RETURNING a, b", (7, 2.5)), + ), + bindings={"?1": "7", "?2": "2.5"}, + expected_rows=[(10, 2.5)], + ), + BoundSqliteTestCase( + description=":name in an INSERT ... RETURNING, a negative integer and NULL bound", + statements=( + ("CREATE TABLE t(a INTEGER, b TEXT)", ()), + ( + "INSERT INTO t VALUES (:a, :b) RETURNING a * 2 AS c, b IS NULL AS n", + {"a": -3, "b": None}, + ), + ), + bindings={":a": "-3", ":b": "NULL"}, + expected_rows=[(-6, 1)], + ), + ), + ids=lambda case: case.description, +) +def test_given_sqlite_with_bound_parameters_when_converted_then_duckdb_returns_sqlites_rows( + test_case: BoundSqliteTestCase, +) -> None: + script: str = ";\n".join(statement for statement, _ in test_case.statements) + conversion: Conversion = sqlbabel.convert( + sql=script, + options=ConvertOptions(no_config=True, dialect="sqlite", bindings=test_case.bindings), + ) + assert conversion.converted, conversion.rendered + connection: duckdb.DuckDBPyConnection = duckdb.connect() + assert typed(sqlite_rows(test_case.statements)) == typed(test_case.expected_rows) + assert typed(connection.execute(conversion.sql).fetchall()) == typed(test_case.expected_rows) diff --git a/website/src/content/docs/docs/cli/convert.mdx b/website/src/content/docs/docs/cli/convert.mdx index a34b5b317..a4513172a 100644 --- a/website/src/content/docs/docs/cli/convert.mdx +++ b/website/src/content/docs/docs/cli/convert.mdx @@ -105,6 +105,32 @@ error[SBL0002]: SQLBabel can't convert TABLE yet sqlbabel convert: refused, 1 refusal ``` +## Binding SQLite parameters + +With `--dialect sqlite`, a parameter marker (`?`, `?N`, `:name`, `@name` or `$name`) converts only +with a value bound to it: `--bind MARKER=LITERAL`, repeatable, where the value is one SQLite +literal, a number (signed or not), a `'string'`, an `x'blob'` or `NULL`. Bind a `?` by the +number SQLite gives it: `?1` when it is the statement's first marker. The value is written in place of +the marker, cast to the type of its SQLite storage class, so the converted SQL runs as it is but +only for those values: its result types follow the values bound, as SQLite's do. Convert again for +other values. + +A marker with no value, a value no statement names, and a value that is not one literal are +refused. + +{/* example: no-inputs */} +```console +$ echo "SELECT ? + 1 AS r" | sqlbabel convert --dialect sqlite --bind '?1=41' +SELECT CAST(41 AS BIGINT) + 1 AS "r" +sqlbabel convert: done, converted +$ echo "SELECT ? + 1 AS r" | sqlbabel convert --dialect sqlite +error[SBL0002]: SQLBabel can't convert PARAMETER yet + --> + | + = note: the parameter ?1 has no bound value; pass --bind ?1=LITERAL (bindings= in Python) +sqlbabel convert: refused, 1 refusal +``` + ## Refusals A refused statement prints its refusals instead, each as a coded diagnostic, and `convert` exits 1. @@ -133,6 +159,7 @@ SQL that does not parse, or that Snowflake rejects, is refused with the same cod | `--session NAME=VALUE` | A Snowflake session parameter of your session, replacing the project's. Repeatable. See [Sessions](/docs/sessions/). | | `--overrides ` | [Replacements](/docs/policy/#replace): a `FUNCTION()` file, or a directory of them, each with `replaces` and `dialect duckdb`. Replaces the project's `overrides/` folder. | | `--verified-override NAME=SHA256` | An override verified for the body with that hash, as `convert --json` reports. | +| `--bind MARKER=LITERAL` | A SQLite parameter's value, written in place of its marker. Repeatable; `--dialect sqlite` only. See [Binding SQLite parameters](#binding-sqlite-parameters). | | `--compact` | Print each statement on one line instead, in the JSON report too. | | `--no-bind-check` | Skip DuckDB's parse and bind of the converted SQL, often the larger part of the conversion time, for callers that run the SQL and handle DuckDB's errors. The check only catches SQLBabel bugs, converted SQL that DuckDB cannot bind; without it, such SQL is reported as converted and fails when run. The other checks and refusals are unchanged. | | `--max-call-depth ` | Refuse function calls nested more than `n` deep, as for [`check`](/docs/cli/check/#options). Default `256`, at most `512`. `run`, `function` and `census` take it too. | diff --git a/website/src/content/docs/docs/python.mdx b/website/src/content/docs/docs/python.mdx index 7faa413f5..79bcd2c4b 100644 --- a/website/src/content/docs/docs/python.mdx +++ b/website/src/content/docs/docs/python.mdx @@ -78,9 +78,10 @@ default and at most `512`. It returns a `CheckResult`: `ConvertOptions` has one field per [`convert`](/docs/cli/convert/) flag, with the same defaults: `project`, `config`, `no_config`, `session`, `strict`, `python_runtime`, `overrides`, -`verified_overrides`, `compact`, `max_call_depth`, `bind_check` and `dialect`. `project`, `config` and -`overrides` take a path (`str` or `os.PathLike`), not the parsed contents. `session` and `verified_overrides` take a mapping, such as -`session={"TIMEZONE": "UTC"}`, not a list of `NAME=VALUE` strings. +`verified_overrides`, `bindings`, `compact`, `max_call_depth`, `bind_check` and `dialect`. `project`, +`config` and `overrides` take a path (`str` or `os.PathLike`), not the parsed contents. `session`, +`verified_overrides` and `bindings` take a mapping, such as `session={"TIMEZONE": "UTC"}` or +`bindings={"?1": "41"}`, not a list of `NAME=VALUE` strings. Two fields have no flag, for a tool that keeps SQLBabel's settings in its own configuration: From a37fa86caad978e2fda2c4cb43adeef99179af0c Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Mon, 30 Nov 2026 13:57:32 +0000 Subject: [PATCH 2/3] fix(sqlite): refuse bound markers in views and bind ?N only to positional markers --- .../conversion/_helpers/effects/objects.rs | 8 ++ .../conversion/_helpers/support/parameters.rs | 29 +++++- .../conversion/tests/test_parameters.rs | 93 ++++++++++++++++++- .../src/sqlite/conversion/tests/test_types.rs | 10 ++ 4 files changed, 136 insertions(+), 4 deletions(-) diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/objects.rs b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/objects.rs index 3fc74b9bf..60281f5f1 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/objects.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/objects.rs @@ -14,6 +14,7 @@ use crate::sqlite::conversion::_helpers::effects::tables::{ }; use crate::sqlite::conversion::_helpers::queries::query::query; use crate::sqlite::conversion::_helpers::queries::relations::derived; +use crate::sqlite::conversion::_helpers::support::parameters::has_markers; use crate::sqlite::conversion::_helpers::support::scope::Site; use crate::sqlite::conversion::_helpers::support::tree::{ Payload, field, flag, identifier, list, node_kind, quoted, refused, understood, @@ -46,6 +47,13 @@ pub(crate) fn create_view( "table", &["name", "schema"], )?)?; + if has_markers(source) { + return Err(refused( + "create_view", + "a view names a parameter, which SQLite refuses: parameters are not allowed in views" + .to_owned(), + )); + } let temporary = flag(create, "temporary") || schema == Some(true); let if_not_exists = flag(create, "if_not_exists"); let _rule = log.rule(DEFINITION_RULE); diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/support/parameters.rs b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/support/parameters.rs index d2a7973c7..706f6a0b1 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/support/parameters.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/support/parameters.rs @@ -25,6 +25,8 @@ struct Numbering { markers: BTreeMap>, /// The number of the statement's one `?`, if it has one. anonymous: Option, + /// The numbers a `?` or `?N` marker names, rather than only a name. + positional: BTreeSet, } impl Numbering { @@ -35,9 +37,19 @@ impl Numbering { .find(|(_, markers)| markers.contains(marker)) .map(|(number, _)| *number) } + + /// Whether the statement names `marker`; where `strict`, `?N` names only a `?` or `?N` marker, not the name SQLite also numbers N. + fn names(&self, marker: &str, strict: bool) -> bool { + match self.number(marker) { + Some(number) => { + !(strict && marker.starts_with('?')) || self.positional.contains(&number) + } + None => false, + } + } } -/// `node` with every marker rewritten as a bound parameter numbered for DuckDB, and the DuckDB literal of each `$n` in order; `inline` writes each literal in place of its `$n` and returns none. A marker bound to no value refuses, as does a binding naming no marker. +/// `node` with every marker rewritten as a bound parameter numbered for DuckDB, and the DuckDB literal of each `$n` in order; `inline` writes each literal in place of its `$n` and returns none, and binds a named marker by its name only. A marker bound to no value refuses, as does a binding naming no marker. pub(crate) fn bind_parameters( node: Value, source: &str, @@ -47,7 +59,7 @@ pub(crate) fn bind_parameters( let numbering = numbering(source)?; if let Some((marker, _)) = bindings .iter() - .find(|(marker, _)| numbering.number(marker).is_none()) + .find(|(marker, _)| !numbering.names(marker, inline)) { return Err(refused( "parameter", @@ -107,16 +119,24 @@ pub(crate) fn named_bindings( let numbering = numbering(source)?; Ok(bindings .iter() - .filter(|(marker, _)| numbering.number(marker).is_some()) + .filter(|(marker, _)| numbering.names(marker, true)) .cloned() .collect()) } +/// Whether the statement `source` holds a parameter marker. +pub(crate) fn has_markers(source: &str) -> bool { + scan(source) + .iter() + .any(|token| token.kind == TokenKind::Variable) +} + /// SQLite's parameter numbers, assigned in token order: `?` takes the next number, `?N` the number N, and a name its first use's next number. fn numbering(source: &str) -> Result { let mut numbering = Numbering { markers: BTreeMap::new(), anonymous: None, + positional: BTreeSet::new(), }; let mut names: BTreeMap = BTreeMap::new(); let mut last: u32 = 0; @@ -159,6 +179,9 @@ fn numbering(source: &str) -> Result { } }, }; + if text.starts_with('?') { + numbering.positional.insert(number); + } numbering .markers .entry(number) diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs b/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs index 14cc93eb3..a1d391cd1 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs @@ -1,8 +1,11 @@ //! Binding parameter markers: SQLite's numbering, each value's storage class, and the refusals. +use crate::sqlite::analysis::main::analyze_effect::analyze_effect; use crate::sqlite::conversion::models::StorageClass; use crate::sqlite::conversion::tests::helpers::bound_conversion; -use crate::sqlite::conversion::tests::test_types::{BoundConversion, ParameterTestCase}; +use crate::sqlite::conversion::tests::test_types::{ + BoundConversion, ParameterTestCase, ScriptBindingTestCase, +}; #[test] fn given_bound_markers_when_converted_then_each_is_a_duckdb_parameter_typed_by_its_value_or_refused_naming_it() @@ -137,3 +140,91 @@ fn given_bound_markers_when_converted_then_each_is_a_duckdb_parameter_typed_by_i ); } } + +#[test] +fn given_a_script_with_bound_markers_when_converted_then_each_marker_is_its_literal_or_the_script_is_refused() + { + let test_cases = [ + ScriptBindingTestCase { + description: "each statement takes the values its markers name, a name in every statement naming it", + statements: &[ + "CREATE TABLE t(a INTEGER, b TEXT)", + "INSERT INTO t VALUES (?1, :b)", + "UPDATE t SET a = a + ?2 WHERE b = :b RETURNING a", + ], + bindings: &[("?1", "1"), (":b", "'x'"), ("?2", "5")], + expected_statements: &[ + "CREATE TABLE \"t\" (\"a\" BIGINT, \"b\" VARCHAR)", + "INSERT INTO \"t\" VALUES (CAST(1 AS BIGINT), CAST('x' AS VARCHAR))", + "UPDATE \"t\" SET \"a\" = \"a\" + CAST(5 AS BIGINT) WHERE \"b\" = CAST('x' AS VARCHAR) RETURNING \"a\"", + ], + expected_refusal: "", + }, + ScriptBindingTestCase { + description: "?N binds no name another statement numbers N", + statements: &[ + "CREATE TABLE t(a INTEGER)", + "INSERT INTO t VALUES (:x)", + "UPDATE t SET a = a + ?1 RETURNING a", + ], + bindings: &[("?1", "5")], + expected_statements: &[], + expected_refusal: "the parameter :x has no bound value; pass --bind :x=LITERAL (bindings= in Python)", + }, + ScriptBindingTestCase { + description: "a value no statement names", + statements: &["CREATE TABLE t(a INTEGER)", "INSERT INTO t VALUES (?1)"], + bindings: &[("?1", "1"), (":z", "2")], + expected_statements: &[], + expected_refusal: "a value is bound to :z, which no statement names", + }, + ScriptBindingTestCase { + description: "a view naming a parameter, which SQLite refuses", + statements: &[ + "CREATE TABLE t(a INTEGER)", + "CREATE VIEW v AS SELECT ?1 AS b", + ], + bindings: &[("?1", "1")], + expected_statements: &[], + expected_refusal: "parameters are not allowed in views", + }, + ]; + for test_case in test_cases { + let statements: Vec = test_case + .statements + .iter() + .map(|sql| (*sql).to_owned()) + .collect(); + let bindings: Vec<(String, String)> = test_case + .bindings + .iter() + .map(|(marker, value)| ((*marker).to_owned(), (*value).to_owned())) + .collect(); + let converted = analyze_effect((&[], &statements), &[], &bindings); + let converted_statements: Vec = converted + .as_ref() + .map_or_else(|_| Vec::new(), |converted| converted.statements.clone()); + let reason: String = converted + .as_ref() + .map_or_else(|refusal| refusal.reason.clone(), |_| String::new()); + let expected_statements: Vec = test_case + .expected_statements + .iter() + .map(|sql| (*sql).to_owned()) + .collect(); + assert_eq!( + ( + converted_statements, + reason.contains(test_case.expected_refusal), + reason.is_empty() + ), + ( + expected_statements, + true, + test_case.expected_refusal.is_empty() + ), + "{}: {reason}", + test_case.description + ); + } +} diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_types.rs b/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_types.rs index a641042b2..786b80ced 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_types.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_types.rs @@ -64,3 +64,13 @@ impl BoundConversion { ) } } + +/// A script's SQLite statements and the values bound to their markers, and the DuckDB statements they convert to, or the refusal's reason. +pub(crate) struct ScriptBindingTestCase { + pub(crate) description: &'static str, + pub(crate) statements: &'static [&'static str], + pub(crate) bindings: &'static [(&'static str, &'static str)], + pub(crate) expected_statements: &'static [&'static str], + /// Empty when the script converts. + pub(crate) expected_refusal: &'static str, +} From 9a8afccb37243f5b90ea3e77fd9c26d125da4e95 Mon Sep 17 00:00:00 2001 From: Kevin Longe <273747162+kvlonge@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:01:24 +0000 Subject: [PATCH 3/3] fix(sqlite): refuse a view's markers before binding them, and test both readings of ?N --- .../conversion/_helpers/effects/objects.rs | 8 -------- .../conversion/_helpers/effects/statements.rs | 9 ++++++++- .../conversion/tests/test_parameters.rs | 20 +++++++++++++++++++ .../src/sqlbabel/api/main/test_convert.py | 14 +++++++++++++ 4 files changed, 42 insertions(+), 9 deletions(-) diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/objects.rs b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/objects.rs index 60281f5f1..3fc74b9bf 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/objects.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/objects.rs @@ -14,7 +14,6 @@ use crate::sqlite::conversion::_helpers::effects::tables::{ }; use crate::sqlite::conversion::_helpers::queries::query::query; use crate::sqlite::conversion::_helpers::queries::relations::derived; -use crate::sqlite::conversion::_helpers::support::parameters::has_markers; use crate::sqlite::conversion::_helpers::support::scope::Site; use crate::sqlite::conversion::_helpers::support::tree::{ Payload, field, flag, identifier, list, node_kind, quoted, refused, understood, @@ -47,13 +46,6 @@ pub(crate) fn create_view( "table", &["name", "schema"], )?)?; - if has_markers(source) { - return Err(refused( - "create_view", - "a view names a parameter, which SQLite refuses: parameters are not allowed in views" - .to_owned(), - )); - } let temporary = flag(create, "temporary") || schema == Some(true); let if_not_exists = flag(create, "if_not_exists"); let _rule = log.rule(DEFINITION_RULE); diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/statements.rs b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/statements.rs index d35e58966..4145013ae 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/statements.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/_helpers/effects/statements.rs @@ -13,7 +13,7 @@ use crate::sqlite::conversion::_helpers::effects::rows::{delete, insert, update} use crate::sqlite::conversion::_helpers::effects::sessions::{begin, commit, pragma, rollback}; use crate::sqlite::conversion::_helpers::effects::tables::create_table; use crate::sqlite::conversion::_helpers::queries::query::declared_collations_read_directly; -use crate::sqlite::conversion::_helpers::support::parameters::bind_parameters; +use crate::sqlite::conversion::_helpers::support::parameters::{bind_parameters, has_markers}; use crate::sqlite::conversion::_helpers::support::tree::{node_kind, refused}; use crate::sqlite::conversion::constants::{FAILURE_MODES, MAX_TREE_DEPTH}; @@ -37,6 +37,13 @@ pub(crate) fn effect_statement( } let node: Value = serde_json::to_value(tree) .map_err(|error| refused("statement", format!("the tree does not serialise: {error}")))?; + if matches!(node_kind(&node), Some(("create_view", _))) && has_markers(source) { + return Err(refused( + "create_view", + "a view names a parameter, which SQLite refuses: parameters are not allowed in views" + .to_owned(), + )); + } let (node, _) = bind_parameters(node, source, (bindings, true), log)?; let declared: Vec = catalog .relations diff --git a/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs b/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs index a1d391cd1..b6b51b6ec 100644 --- a/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs +++ b/crates/sqlbabel-convert/src/sqlite/conversion/tests/test_parameters.rs @@ -93,6 +93,16 @@ fn given_bound_markers_when_converted_then_each_is_a_duckdb_parameter_typed_by_i "the statement has more than one `?`; number each parameter as ?N", ), }, + ParameterTestCase { + description: "for PREPARE, ?N binds a name SQLite numbers N, as sqlite3_bind does", + sql: "SELECT :x AS r", + bindings: &[("?1", "5")], + expected_conversion: Ok(BoundConversion { + sql: "SELECT $1 AS \"r\"", + values: &["CAST(5 AS BIGINT)"], + classes: &[StorageClass::Integer], + }), + }, ParameterTestCase { description: "a value that is no literal", sql: "SELECT ?1 AS r", @@ -188,6 +198,16 @@ fn given_a_script_with_bound_markers_when_converted_then_each_marker_is_its_lite expected_statements: &[], expected_refusal: "parameters are not allowed in views", }, + ScriptBindingTestCase { + description: "a view naming a parameter no value is bound to is refused as a view, not for the value", + statements: &[ + "CREATE TABLE t(a INTEGER)", + "CREATE VIEW v AS SELECT a FROM t WHERE a = :x", + ], + bindings: &[], + expected_statements: &[], + expected_refusal: "parameters are not allowed in views", + }, ]; for test_case in test_cases { let statements: Vec = test_case diff --git a/tests/unit/python/src/sqlbabel/api/main/test_convert.py b/tests/unit/python/src/sqlbabel/api/main/test_convert.py index ec4413563..546538b35 100644 --- a/tests/unit/python/src/sqlbabel/api/main/test_convert.py +++ b/tests/unit/python/src/sqlbabel/api/main/test_convert.py @@ -137,6 +137,20 @@ ), expected_converted=False, ), + CommandLineTestCase( + description="a SQLite name and the ?N SQLite gives it, bound by the name", + sql="SELECT :x AS r, ?1 AS s", + arguments=("--no-config", "--dialect", "sqlite", "--bind", ":x=5"), + options=ConvertOptions(no_config=True, dialect="sqlite", bindings={":x": "5"}), + expected_converted=True, + ), + CommandLineTestCase( + description="a SQLite name bound only as ?N, which --bind does not read as the name", + sql="SELECT :x AS r", + arguments=("--no-config", "--dialect", "sqlite", "--bind", "?1=5"), + options=ConvertOptions(no_config=True, dialect="sqlite", bindings={"?1": "5"}), + expected_converted=False, + ), CommandLineTestCase( description="a SQLite value that is a literal and then a statement", sql="SELECT ?1 AS r",