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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub(crate) mod statement;
42 changes: 42 additions & 0 deletions crates/sqlbabel-convert/src/sqlite/analysis/_helpers/statement.rs
Original file line number Diff line number Diff line change
@@ -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<Expression, Refusal> {
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")
}
36 changes: 3 additions & 33 deletions crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_bound.rs
Original file line number Diff line number Diff line change
@@ -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<Converted, Refusal> {
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))
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<ConvertedEffect, Refusal> {
let read = |sources: &[String]| -> Result<Vec<(Expression, String)>, 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.
Expand Down
12 changes: 12 additions & 0 deletions crates/sqlbabel-convert/src/sqlite/analysis/main/analyze_inline.rs
Original file line number Diff line number Diff line change
@@ -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<Converted, Refusal> {
convert_statement(&one_statement(sql)?, sql, (bindings, true))
}
1 change: 1 addition & 0 deletions crates/sqlbabel-convert/src/sqlite/analysis/main/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub mod analyze;
pub mod analyze_bound;
pub mod analyze_effect;
pub mod analyze_inline;
1 change: 1 addition & 0 deletions crates/sqlbabel-convert/src/sqlite/analysis/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//! Analysing one SQLite statement.

pub(crate) mod _helpers;
pub mod main;
Original file line number Diff line number Diff line change
Expand Up @@ -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, has_markers};
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<String, Refusal> {
if tree.tree_depth() > MAX_TREE_DEPTH {
Expand All @@ -35,6 +37,14 @@ 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<String> = catalog
.relations
.iter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,9 @@ pub(crate) fn expression(node: &Value, site: Site<'_>) -> Result<Emitted, Refusa
}
}

/// A marker bound to a value: DuckDB's `$n`, of the storage class of the value bound, which DuckDB types the parameter by.
/// A marker bound to a value: DuckDB's `$n`, or the value's typed literal where it is written in place, of the storage class of the value bound, which DuckDB types the parameter by.
fn bound_parameter(payload: &Value, site: Site<'_>) -> Result<Emitted, Refusal> {
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,
Expand All @@ -139,7 +139,11 @@ fn bound_parameter(payload: &Value, site: Site<'_>) -> Result<Emitted, Refusal>
));
};
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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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};

Expand All @@ -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};
Expand All @@ -16,12 +16,17 @@ 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<String>);

/// 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.
markers: BTreeMap<u32, BTreeSet<String>>,
/// The number of the statement's one `?`, if it has one.
anonymous: Option<u32>,
/// The numbers a `?` or `?N` marker names, rather than only a name.
positional: BTreeSet<u32>,
}

impl Numbering {
Expand All @@ -32,26 +37,36 @@ 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; 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,
bindings: &[(String, String)],
(bindings, inline): (&[(String, String)], bool),
log: &ProvenanceLog,
) -> Result<(Value, Vec<String>), Refusal> {
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",
format!("a value is bound to {marker}, which the statement does not name"),
));
}
let mut numbers: BTreeMap<u32, (u32, StorageClass)> = BTreeMap::new();
let mut numbers: BTreeMap<u32, Bound> = BTreeMap::new();
let mut values: Vec<String> = Vec::new();
for (number, markers) in &numbering.markers {
let bound: Vec<&String> = bindings
Expand All @@ -70,7 +85,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)"
),
));
}
Expand All @@ -82,20 +97,46 @@ 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<Vec<(String, String)>, Refusal> {
let numbering = numbering(source)?;
Ok(bindings
.iter()
.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<Numbering, Refusal> {
let mut numbering = Numbering {
markers: BTreeMap::new(),
anonymous: None,
positional: BTreeSet::new(),
};
let mut names: BTreeMap<String, u32> = BTreeMap::new();
let mut last: u32 = 0;
Expand Down Expand Up @@ -138,6 +179,9 @@ fn numbering(source: &str) -> Result<Numbering, Refusal> {
}
},
};
if text.starts_with('?') {
numbering.positional.insert(number);
}
numbering
.markers
.entry(number)
Expand All @@ -155,6 +199,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());
Expand Down Expand Up @@ -194,11 +241,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<u32, (u32, StorageClass)>,
numbers: &BTreeMap<u32, Bound>,
) -> Result<Value, Refusal> {
let marker = match node_kind(&node) {
Some(("placeholder", payload)) => {
Expand Down Expand Up @@ -230,13 +291,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(
Expand Down
Loading
Loading