use crate::analysis::{bare, constant_key, diag, KeyClause, ResultTarget};
use crate::api::{Analysis, Column, Param, Scope};
use crate::dialect::Dialect;
use crate::fresh::Tables;
use crate::host::{as_str, Host, Lazy};
use crate::lex::{self, Lexed, Target};
use crate::sqlite_tree::{self as tree, From, Node, Sel, Tree};
use crate::types::{Cardinality, Field, FloatType, Kind, StatementKind, TextType, Type};
#[derive(Debug, Clone, PartialEq)]
enum Ty {
Scalar { name: String },
Object { fields: Vec<TyField> },
List { of: Box<Ty>, nullable_items: bool },
Json { schema: Option<serde_json::Value> },
Unknown,
}
#[derive(Debug, Clone, PartialEq)]
struct TyField {
name: String,
ty: Ty,
nullable: bool,
}
use std::collections::{HashMap, HashSet};
pub const DDL_QUERY: &str = "select sql from sqlite_schema where sql is not null and type in ('table', 'view', 'index', 'trigger') order by rowid";
pub const FUNCTIONS_QUERY: &str = "select name, narg, type from pragma_function_list";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostFunction {
pub name: String,
pub arity: i32,
pub kind: char,
}
pub fn host_functions(rows: &[Vec<serde_json::Value>]) -> Option<Vec<HostFunction>> {
let listed: Vec<HostFunction> = rows
.iter()
.filter_map(|row| {
let name = row.first().and_then(as_str)?.to_string();
let arity = row.get(1).and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok())).unwrap_or(-1) as i32;
let kind = row.get(2).and_then(as_str).and_then(|k| k.chars().next()).unwrap_or('s');
Some(HostFunction { name, arity, kind })
})
.collect();
(!listed.is_empty()).then_some(listed)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TotalFunction {
pub name: String,
pub arity: i32,
pub returns: Affinity,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Affinity {
Integer,
Real,
Text,
Blob,
Numeric,
Any,
}
impl Affinity {
pub fn name(self) -> &'static str {
match self {
Affinity::Integer => "integer",
Affinity::Real => "real",
Affinity::Text => "text",
Affinity::Blob => "blob",
Affinity::Numeric => "numeric",
Affinity::Any => "none",
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Extras {
pub total: Vec<TotalFunction>,
pub host: Option<Vec<HostFunction>>,
}
impl Extras {
fn function(&self, name: &str, args: usize) -> Option<&TotalFunction> {
self.total.iter().find(|f| f.name.eq_ignore_ascii_case(name) && (f.arity < 0 || f.arity as usize == args))
}
}
#[derive(Debug, Clone)]
pub struct SqliteAnalysis {
pub analysis: Analysis,
pub declared: Vec<Option<String>>,
pub readonly: bool,
pub unique_keys: HashMap<String, Vec<Vec<String>>>,
pub booleans: Vec<bool>,
}
pub fn analyze(sql: &str, lexed: &Lexed, host: &Host, marked: &[String]) -> Lazy<Analysis> {
let schema = host.query(DDL_QUERY, Vec::new(), Scope::Session);
let functions = host.query(FUNCTIONS_QUERY, Vec::new(), Scope::Session);
let (rows, functions) = (schema?, functions?);
let ddl: Vec<String> = match rows {
Ok(rows) => rows.iter().filter_map(|r| r.first().and_then(as_str)).map(String::from).collect(),
Err(e) => return Some(bare(sql, lexed, Dialect::Sqlite, vec![diag(format!("Cannot read the schema: {}", e.message), 0, 1, 5)])),
};
let extras = Extras { total: Vec::new(), host: functions.ok().and_then(|rows| host_functions(&rows)) };
Some(run(sql, lexed, &ddl, &extras, marked).analysis)
}
pub fn analyze_ddl(sql: &str, ddl: &[String], extras: &Extras) -> SqliteAnalysis {
crate::stack::run(|| analyze_ddl_here(sql, ddl, extras))
}
fn analyze_ddl_here(sql: &str, ddl: &[String], extras: &Extras) -> SqliteAnalysis {
match crate::analysis::lexed(sql, Dialect::Sqlite) {
Ok(lexed) => run(sql, &lexed, ddl, extras, &[]),
Err(analysis) => SqliteAnalysis { analysis, declared: Vec::new(), readonly: false, unique_keys: HashMap::new(), booleans: Vec::new() },
}
}
fn result_targets(t: &Tree) -> Option<Vec<ResultTarget>> {
let target = |c: &tree::Col| if c.named || matches!(c.expr.op.as_str(), "column" | "id" | "dot") { ResultTarget::Named } else { ResultTarget::Unnamed(None) };
if let Some(returning) = &t.returning {
return Some(returning.iter().map(target).collect());
}
let mut first = t.statement.as_ref().filter(|_| t.dml.is_none())?;
while let Some(prior) = first.prior.as_deref() {
first = prior;
}
if first.values {
return Some(vec![ResultTarget::Unnamed(None); first.columns.len()]);
}
Some(first.columns.iter().map(target).collect())
}
const KINDS: &[&str] = &["select", "with", "values", "insert", "replace", "update", "delete"];
fn run(sql: &str, lexed: &Lexed, ddl: &[String], extras: &Extras, marked: &[String]) -> SqliteAnalysis {
let failed = |analysis: Analysis| SqliteAnalysis { analysis, declared: Vec::new(), readonly: false, unique_keys: HashMap::new(), booleans: Vec::new() };
let statement = match lex::one_statement(sql, lexed, KINDS) {
Ok(statement) => statement,
Err(message) => return failed(bare(sql, lexed, Dialect::Sqlite, vec![diag(message, 0, sql.trim_end().len(), 10)])),
};
let numbered = lex::rewrite(sql, lexed, Target::Numbered);
let rewritten = lex::rewrite(sql, lexed, Target::Question);
let functions: Vec<(&str, i32)> = extras.total.iter().map(|f| (f.name.as_str(), f.arity)).collect();
let (triggers, replay) = replayed(ddl);
let skipping = skipping_triggers(&triggers);
let listed = listed(extras.host.as_deref());
let alter = if lexed.params.is_empty() { alter_column(&numbered.sql) } else { None };
let (prepared, sent) = match &alter {
Some((stand_in, _)) => (stand_in.as_str(), stand_in.as_str()),
None => (numbered.sql.as_str(), rewritten.sql.as_str()),
};
let t = match tree::analyze(&replay, prepared, sent, &functions, listed.as_deref()) {
Ok(t) => t,
Err(message) => return failed(bare(sql, lexed, Dialect::Sqlite, vec![diag(message, 0, sql.trim_end().len(), 6)])),
};
let mut diagnostics = Vec::new();
if let Some(err) = &t.error {
let offset = |o: usize| match &alter {
Some((_, after)) if o >= *after => o - 1,
_ => o,
};
let start = usize::try_from(err.offset).map_or(0, |o| numbered.to_original(offset(o))).min(sql.len());
let length = match err.length {
Some(length) if err.offset >= 0 => length,
_ if err.offset >= 0 => token_len(&sql[start..]),
_ => sql.trim_end().len(),
};
let message = match (&err.missing_function, &err.missing_schema) {
(Some(name), _) => match &err.view {
Some(view) => format!("no such function: {name} on this database's SQLite (the view {view} calls it)"),
None => format!("no such function: {name} on this database's SQLite"),
},
(None, Some(schema)) => format!("{}: the database has no schema `{schema}`. A database the application attaches at run time (ATTACH ... AS {schema}) is not in the file the type check reads, so a table in it cannot be typed", err.message),
(None, None) => err.message.clone(),
};
let message = if matches!(statement, lex::Statement::Command(_)) { lex::refused_command(&message) } else { message };
diagnostics.push(diag(message, start, length, 6));
for e in &t.schema_errors {
let message = match &e.function {
Some(name) => format!("The schema replay could not register the host function {name}: {}", e.message),
None => format!("The schema replay skipped statement {}: {}", e.index + 1, e.message),
};
diagnostics.push(diag(message, 0, 1, 8));
}
return failed(bare(sql, lexed, Dialect::Sqlite, diagnostics));
}
for p in t.params.iter().filter(|p| !lexed_parameter(p, lexed)) {
let text = |start: &usize| lexed.opaque.iter().any(|(from, to)| (*from..*to).contains(start));
let at = p.name.as_deref().and_then(|name| sql.match_indices(name).map(|(start, _)| start).find(|start| !text(start)).map(|start| (start, name.len())));
let written = p.name.as_deref().unwrap_or("a ? in this statement");
let (start, length) = at.unwrap_or((0, sql.trim_end().len()));
diagnostics.push(diag(format!("SQLite reads {written} as a parameter that Reylo does not bind; name a parameter with the letters a to z, digits and underscores, starting with a letter or an underscore"), start, length, 1));
}
let registered = |name: &str| extras.total.iter().any(|f| f.name.eq_ignore_ascii_case(name)) || extras.host.iter().flatten().any(|f| f.name.eq_ignore_ascii_case(name) && f.arity >= 0);
let constructors: Vec<&str> = ["json_object", "jsonb_object"].into_iter().filter(|n| !registered(n)).collect();
diagnostics.extend(crate::analysis::odd_pairs(sql, lexed, &constructors));
diagnostics.extend(constant_keys(sql, lexed, &t));
if let (false, Some(message)) = (matches!(statement, lex::Statement::Command(_)), unwritten(&t, &skipping)) {
let (start, length) = insert_target_at(sql, lexed).unwrap_or((0, sql.trim_end().len()));
diagnostics.push(diag(message, start, length, 16));
}
let nullable_params: HashSet<String> = lexed.params.iter().enumerate().filter(|(_, name)| marked.contains(name)).map(|(k, _)| format!("?{}", k + 1)).collect();
let a = Analyzer { tree: &t, extras, skipping: &skipping, nullable_values: nullable_params.clone(), nullable_params, written: std::cell::RefCell::new(HashSet::new()), level: std::cell::RefCell::new(Level::default()), shapes: std::cell::RefCell::new(HashMap::new()), recursion: std::cell::RefCell::new(Vec::new()), settled: std::cell::RefCell::new(HashMap::new()) };
let a = Analyzer { nullable_values: a.bare_nullable().into_iter().chain(a.nullable_params.iter().cloned()).collect(), ..a };
if let lex::Statement::Command(kind) = statement {
let columns: Vec<Column> = t.columns.iter().map(|c| Column::new(c.name.clone(), Type::unknown(), true)).collect();
let cardinality = if columns.is_empty() { Cardinality::None } else { Cardinality::Many };
let capabilities = crate::capabilities::of_command(&rewritten.sql, &kind);
let analysis = Analysis {
kind: Some(StatementKind::of(&kind)),
comment: None,
params: a.params(lexed).0,
columns,
cardinality,
cardinality_reason: None,
key: None,
unique: Vec::new(),
order: Vec::new(),
ordered: false,
value: false,
rewritten,
sql_mode: None,
style: lexed.style,
diagnostics,
unresolved: Vec::new(),
structured: Vec::new(),
errors: None,
capabilities: Some(capabilities),
read_only: false,
notes: Vec::new(),
tables: None,
domains: Default::default(),
};
return SqliteAnalysis { analysis, declared: t.columns.iter().map(|c| c.declared.clone()).collect(), readonly: t.readonly, unique_keys: HashMap::new(), booleans: vec![false; t.columns.len()] };
}
let (facts, kind) = a.columns();
let booleans = a.booleans();
let literals = a.literals();
let columns: Vec<Column> = facts
.into_iter()
.zip(a.flags())
.zip(&booleans)
.zip(&t.columns)
.zip(a.exacts())
.enumerate()
.map(|(i, (((((name, fact), flag), computed), public), exact))| {
let ty = if flag { Ty::Scalar { name: "bool".into() } } else { fact.ty };
let ty = descriptor(&ty, public.declared.as_deref(), *computed, exact);
let ty = match literals.get(i) {
Some(Some(written)) => reylo_engine_core::literal::narrow(&ty, written).unwrap_or(ty),
_ => ty,
};
Column::new(name, ty, !fact.non_null)
})
.collect();
let (params, refused) = a.params(lexed);
for (numbered, table, column) in refused {
let name = numbered.strip_prefix('?').and_then(|k| k.parse::<usize>().ok()).and_then(|k| lexed.params.get(k.checked_sub(1)?));
let Some(at) = name.and_then(|name| lexed.placeholders.iter().find(|p| &p.name == name)) else { continue };
let written = &sql[at.start..at.end];
diagnostics.push(diag(format!("The parameter {written} is cast to nullable(…), but it is written to {table}.{column}, which refuses null: cast it to its type alone."), at.start, at.end - at.start, crate::structured::CODE));
}
let (cardinality, reason) = a.cardinality();
let mut analysis = Analysis {
kind: (!kind.is_empty()).then(|| StatementKind::of(&kind)),
comment: None,
params,
columns,
cardinality,
cardinality_reason: reason,
key: None,
unique: Vec::new(),
order: Vec::new(),
ordered: false,
value: false,
rewritten,
sql_mode: None,
style: lexed.style,
diagnostics,
unresolved: Vec::new(),
structured: Vec::new(),
errors: None,
capabilities: Some(crate::capabilities::of_statement(&t)),
read_only: false,
notes: Vec::new(),
tables: Some(tables(&t)),
domains: Default::default(),
};
crate::analysis::names(sql, Dialect::Sqlite, &mut analysis, result_targets(&t).as_deref(), &|_| None);
let unique_keys = t.tables.iter().map(|(name, info)| (name.clone(), info.unique_keys.clone())).collect();
SqliteAnalysis { analysis, declared: t.columns.iter().map(|c| c.declared.clone()).collect(), readonly: t.readonly, unique_keys, booleans }
}
fn replayed(ddl: &[String]) -> (Vec<String>, Vec<String>) {
let (triggers, mut replay): (Vec<String>, Vec<String>) = ddl.iter().cloned().partition(|s| trigger_header(s).is_some());
replay.extend(triggers.iter().filter_map(|s| instead_of_stub(s)));
(triggers, replay)
}
fn listed(host: Option<&[HostFunction]>) -> Option<Vec<tree::Listed<'_>>> {
host.map(|host| host.iter().map(|f| (f.name.as_str(), f.arity, f.kind)).collect())
}
pub(crate) fn declares_replace(analysis: &Analysis, host: &Host) -> Lazy<bool> {
let schema = host.query(DDL_QUERY, Vec::new(), Scope::Session);
let functions = host.query(FUNCTIONS_QUERY, Vec::new(), Scope::Session);
let (Ok(rows), functions) = (schema?, functions?) else { return Some(true) };
let ddl: Vec<String> = rows.iter().filter_map(|r| r.first().and_then(as_str)).map(String::from).collect();
let host_functions = functions.ok().and_then(|rows| host_functions(&rows));
let (_, replay) = replayed(&ddl);
let sql = &analysis.rewritten.sql;
let Ok(t) = tree::analyze(&replay, sql, sql, &[], listed(host_functions.as_deref()).as_deref()) else { return Some(true) };
Some(t.dml.as_ref().and_then(|dml| t.tables.get(&dml.table)).is_none_or(|info| info.replaces))
}
fn reads_itself(sel: &Sel) -> bool {
let mut arm = Some(sel);
while let Some(a) = arm {
if a.from.iter().any(|f| f.recursive) {
return true;
}
arm = a.prior.as_deref();
}
false
}
fn tables(t: &Tree) -> Tables {
#[derive(Default)]
struct Walk {
read: Vec<String>,
ctes: Vec<String>,
}
impl Walk {
fn node(&mut self, n: &Node) {
if let Some(q) = &n.select {
self.sel(q);
}
for child in n.left.iter().chain(&n.right) {
self.node(child);
}
for child in n.list.iter().chain(&n.args) {
self.node(child);
}
}
fn sel(&mut self, s: &Sel) {
for c in &s.columns {
self.node(&c.expr);
}
for f in &s.from {
if f.cte {
self.ctes.extend(f.table.clone());
}
if f.cte || f.subquery.is_some() && f.table.is_none() {
if let Some(q) = &f.subquery {
self.sel(q);
}
} else if !f.tab_func {
self.read.extend(f.table.clone());
}
for n in f.args.iter().chain(&f.on) {
self.node(n);
}
}
for n in s.rows.iter().flatten().chain(&s.where_).chain(&s.group_by).chain(&s.having).chain(&s.order_by).chain(&s.limit).chain(&s.offset) {
self.node(n);
}
if let Some(prior) = &s.prior {
self.sel(prior);
}
}
}
let mut walk = Walk::default();
if let Some(s) = &t.statement {
walk.sel(s);
}
for c in t.returning.iter().flatten() {
walk.node(&c.expr);
}
let mut write = Vec::new();
if let Some(dml) = &t.dml {
write.push(dml.table.clone());
let upsert = dml.upserts.iter().flat_map(|u| u.set.iter().map(|s| &s.expr).chain(&u.where_));
for n in dml.values.iter().flatten().chain(dml.set.iter().map(|s| &s.expr)).chain(&dml.where_).chain(upsert) {
walk.node(n);
}
}
let Walk { mut read, ctes } = walk;
read.retain(|table| !ctes.iter().any(|cte| cte.eq_ignore_ascii_case(table)));
Tables { read, write, ..Default::default() }
}
fn lexed_parameter(p: &tree::PublicParam, lexed: &Lexed) -> bool {
p.name.as_deref().and_then(|name| name.strip_prefix('?')).and_then(|k| k.parse::<usize>().ok()).is_some_and(|k| (1..=lexed.params.len()).contains(&k))
}
fn constant_keys(sql: &str, lexed: &Lexed, t: &Tree) -> Vec<crate::api::Diagnostic> {
fn param(n: &Node) -> Option<i64> {
match n.op.as_str() {
"variable" => Some(n.index),
"cast" | "collate" => n.left.as_deref().and_then(param),
_ => None,
}
}
fn reads(n: &Node, out: &mut HashSet<i64>) {
if n.op == "variable" {
out.insert(n.index);
}
for child in n.left.iter().chain(&n.right).map(|b| b.as_ref()).chain(&n.list).chain(&n.args).chain(&n.order_by).chain(&n.partition_by) {
reads(child, out);
}
}
#[derive(Default)]
struct Walk {
found: Vec<(i64, KeyClause, bool)>,
}
impl Walk {
fn keys(&mut self, list: &[Node], clause: KeyClause) {
self.found.extend(list.iter().filter_map(param).map(|index| (index, clause, list.len() == 1)));
}
fn select_keys(&mut self, s: &Sel) {
let mut listed = HashSet::new();
s.columns.iter().for_each(|c| reads(&c.expr, &mut listed));
for (list, clause) in [(&s.group_by, KeyClause::GroupBy), (&s.order_by, KeyClause::OrderBy)] {
let alone = list.len() == 1;
self.found.extend(list.iter().filter_map(param).filter(|index| !listed.contains(index)).map(|index| (index, clause, alone)));
}
}
fn node(&mut self, n: &Node) {
self.keys(&n.order_by, KeyClause::OrderBy);
self.keys(&n.partition_by, KeyClause::PartitionBy);
if let Some(q) = &n.select {
self.sel(q);
}
for child in n.left.iter().chain(&n.right) {
self.node(child);
}
for child in n.list.iter().chain(&n.args).chain(&n.order_by).chain(&n.partition_by) {
self.node(child);
}
}
fn sel(&mut self, s: &Sel) {
self.select_keys(s);
for c in &s.columns {
self.node(&c.expr);
}
for f in &s.from {
if let Some(q) = &f.subquery {
self.sel(q);
}
for n in f.args.iter().chain(&f.on) {
self.node(n);
}
}
for n in s.rows.iter().flatten().chain(&s.where_).chain(&s.group_by).chain(&s.having).chain(&s.order_by).chain(&s.limit).chain(&s.offset) {
self.node(n);
}
if let Some(prior) = &s.prior {
self.sel(prior);
}
}
}
let mut walk = Walk::default();
if let Some(s) = &t.statement {
walk.sel(s);
}
for c in t.returning.iter().flatten() {
walk.node(&c.expr);
}
if let Some(dml) = &t.dml {
let upsert = dml.upserts.iter().flat_map(|u| u.set.iter().map(|s| &s.expr).chain(&u.where_));
for n in dml.values.iter().flatten().chain(dml.set.iter().map(|s| &s.expr)).chain(&dml.where_).chain(upsert) {
walk.node(n);
}
}
let mut out: Vec<_> = walk
.found
.into_iter()
.filter_map(|(index, clause, alone)| {
let name = lexed.params.get(usize::try_from(index).ok()?.checked_sub(1)?)?;
let p = lexed.placeholders.iter().find(|p| &p.name == name)?;
Some(constant_key(sql, p.start, p.end, clause, alone))
})
.collect();
out.sort_by_key(|d| d.start);
out.dedup_by_key(|d| d.start);
out
}
fn unwritten(t: &Tree, skipping: &HashMap<String, i32>) -> Option<String> {
let dml = t.dml.as_ref().filter(|d| d.kind == "insert")?;
let info = t.tables.get(&dml.table)?;
let ignored = dml.on_error == "ignore" || (dml.on_error == "default" && info.ignores_null);
let triggered = skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & TRIGGER_ROW_INSERT != 0);
if ignored || triggered {
return None;
}
let written = |name: &str| dml.columns.iter().flatten().any(|c| c.eq_ignore_ascii_case(name));
let alias = |name: &str| info.rowid_alias.as_deref().is_some_and(|a| a.eq_ignore_ascii_case(name));
let missing: Vec<String> = info.columns.iter().filter(|c| c.not_null && !c.has_default && !c.generated && !alias(&c.name) && !written(&c.name)).map(|c| format!("\"{}\"", c.name)).collect();
match missing.as_slice() {
[] => None,
[one] => Some(format!("Column {one} of \"{}\" is NOT NULL with no default, and this insert leaves it out, so SQLite refuses every row it inserts.", dml.table)),
many => Some(format!("Columns {} of \"{}\" are NOT NULL with no default, and this insert leaves them out, so SQLite refuses every row it inserts.", many.join(", "), dml.table)),
}
}
fn insert_target_at(sql: &str, lexed: &Lexed) -> Option<(usize, usize)> {
let bytes = sql.as_bytes();
let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$' || b >= 0x80;
let word_end = |mut at: usize| {
while at < bytes.len() && word(bytes[at]) {
at += 1;
}
at
};
let mut spans: Vec<(usize, usize)> = lexed.opaque.iter().copied().chain(lexed.placeholders.iter().map(|p| (p.start, p.end))).collect();
spans.sort_unstable();
let mut next = 0;
let comment = |at: usize| lexed.opaque.iter().find(|(from, _)| *from == at && (sql[at..].starts_with("--") || sql[at..].starts_with("/*"))).map(|(_, to)| *to);
let gap = |mut at: usize| loop {
while at < bytes.len() && bytes[at].is_ascii_whitespace() {
at += 1;
}
match comment(at) {
Some(to) => at = to,
None => return at,
}
};
let part = |at: usize| match lexed.opaque.iter().find(|(from, _)| *from == at) {
Some((_, to)) => Some(*to),
None => Some(word_end(at)).filter(|end| *end > at),
};
let mut at = 0;
let into = loop {
if at >= bytes.len() {
return None;
}
while spans.get(next).is_some_and(|(_, to)| *to <= at) {
next += 1;
}
if let Some((_, to)) = spans.get(next).filter(|(from, _)| *from <= at) {
at = *to;
} else if word(bytes[at]) {
let end = word_end(at);
if sql[at..end].eq_ignore_ascii_case("into") {
break end;
}
at = end;
} else {
at += 1;
}
};
let start = gap(into);
let mut end = part(start)?;
let dot = gap(end);
if bytes.get(dot) == Some(&b'.') {
end = part(gap(dot + 1))?;
}
Some((start, end - start))
}
fn token_len(rest: &str) -> usize {
rest.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_' || *c == ':' || *c == '$' || *c == '@' || *c == '?').count().max(1)
}
#[derive(Debug, Clone)]
struct Fact {
ty: Ty,
non_null: bool,
}
impl Fact {
fn new(aff: &str, non_null: bool) -> Fact {
Fact { ty: affinity_type(aff), non_null }
}
fn unknown() -> Fact {
Fact { ty: Ty::Unknown, non_null: false }
}
}
fn int64() -> Type {
Type::integer(64)
}
fn real() -> Type {
Type::new(Kind::Float(FloatType { exponent_bits: 11, mantissa_bits: 52, infinity: true, ..FloatType::default() }))
}
fn text() -> Type {
Type::new(Kind::Text(TextType { encoding: Some("UTF-8".into()), ill_formed: true, ..TextType::default() }))
}
fn stored(aff: &str) -> Type {
let members = match aff {
"real" => vec![real(), text(), Type::bytes()],
"text" => vec![text(), Type::bytes()],
_ => vec![int64(), real(), text(), Type::bytes()],
};
Type::union(members)
}
fn descriptor(ty: &Ty, declared: Option<&str>, computed: bool, exact: bool) -> Type {
let declared = declared.map(str::trim).filter(|d| !d.is_empty()).filter(|d| match ty {
Ty::Scalar { name } if name == "bool" => is_boolean_declared(d),
Ty::Scalar { .. } => !is_boolean_declared(d) && column_type(d, affinity(d), false) == *ty,
_ => false,
});
match ty {
Ty::Scalar { name } if name == "bool" && computed => Type::boolean(),
Ty::Scalar { name } if name == "bool" => stored("numeric").named(declared.unwrap_or("BOOLEAN")),
Ty::Scalar { name } => match (declared, name.as_str()) {
(Some(d), "integer" | "int8") if exact => int64().named(d),
(Some(d), "real") if exact => real().named(d),
(Some(d), "text") if exact => text().named(d),
(Some(d), "blob") if exact => Type::bytes().named(d),
(Some(d), aff) => stored(if aff == "int8" { "integer" } else { aff }).named(d),
(None, "integer") => int64(),
(None, "int8") => int64().named("BIGINT"),
(None, "real") => real(),
(None, "text") => text(),
(None, "blob") => Type::bytes(),
(None, "numeric") => stored("numeric").named("NUMERIC"),
_ => Type::unknown(),
},
Ty::Object { .. } | Ty::List { .. } => Type::json_of(crate::types::Slot::non_null(content(ty))),
Ty::Json { schema: Some(schema) } => Type::json_schema_of(schema.clone()),
Ty::Json { schema: None } => Type::json(),
Ty::Unknown => Type::unknown(),
}
}
fn literals_of(n: &Node) -> Option<Vec<reylo_engine_core::literal::Literal>> {
use reylo_engine_core::literal::Literal;
match n.op.as_str() {
"null" => Some(Vec::new()),
"string" => Some(vec![Literal::Text(n.value.clone()?)]),
"integer" | "float" => Some(vec![Literal::Number(n.value.clone()?)]),
"truefalse" => Some(vec![Literal::Boolean(n.value.as_deref()?.eq_ignore_ascii_case("true"))]),
"neg" => match literals_of(n.left.as_deref()?)?.as_slice() {
[Literal::Number(v)] => Some(vec![Literal::Number(match v.strip_prefix('-') {
Some(positive) => positive.to_string(),
None => format!("-{v}"),
})]),
_ => None,
},
"pos" | "collate" => literals_of(n.left.as_deref()?),
"case" => {
let mut values = Vec::new();
for pair in n.list.chunks(2) {
values.extend(literals_of(pair.last()?)?);
}
Some(values)
}
_ => None,
}
}
fn content(ty: &Ty) -> Type {
match ty {
Ty::Object { fields } => Type::structure(fields.iter().map(|f| Field::new(f.name.clone(), content(&f.ty), f.nullable)).collect()),
Ty::List { of, nullable_items } => Type::array(crate::types::Slot::new(content(of), *nullable_items)),
other => descriptor(other, None, false, false),
}
}
fn column_type(declared: &str, aff: &str, strict: bool) -> Ty {
let declared = declared.trim();
if declared.is_empty() || (strict && declared.eq_ignore_ascii_case("any")) {
Ty::Unknown
} else if aff == "integer" && is_int8_declared(declared) {
Ty::Scalar { name: "int8".into() }
} else {
affinity_type(aff)
}
}
fn is_int8_declared(declared: &str) -> bool {
let base = declared.split('(').next().unwrap_or("").split_whitespace().map(str::to_ascii_lowercase).collect::<Vec<_>>().join(" ");
matches!(base.as_str(), "bigint" | "int8" | "unsigned big int")
}
fn affinity_type(aff: &str) -> Ty {
match aff {
"integer" | "real" | "text" | "blob" | "numeric" => Ty::Scalar { name: aff.to_string() },
_ => Ty::Unknown,
}
}
fn scalar_name(t: &Ty) -> Option<&str> {
match t {
Ty::Scalar { name } => Some(name.as_str()),
_ => None,
}
}
fn is_numeric(t: &Ty) -> bool {
matches!(scalar_name(t), Some("integer" | "int8" | "real" | "numeric"))
}
fn is_integral(t: &Ty) -> bool {
matches!(scalar_name(t), Some("integer" | "int8"))
}
fn computed(t: Ty) -> Ty {
if scalar_name(&t) == Some("int8") {
Ty::Scalar { name: "integer".into() }
} else {
t
}
}
fn shared(facts: &[&Fact]) -> Ty {
let known: Vec<&Ty> = facts.iter().map(|f| &f.ty).filter(|t| !matches!(t, Ty::Unknown)).collect();
let Some(first) = known.first() else { return Ty::Unknown };
if known.len() < facts.len() && known.iter().any(|t| is_built(t)) {
return Ty::Scalar { name: "text".into() };
}
if known.iter().all(|t| t == first) {
return (*first).clone();
}
if let Some(ty) = same_json(&known) {
return ty;
}
let known: Vec<Ty> = known.iter().map(|t| textual(t)).collect();
let known: Vec<&Ty> = known.iter().collect();
let first = known[0];
if known.iter().all(|t| *t == first) {
return first.clone();
}
if known.iter().all(|t| is_integral(t)) {
return Ty::Scalar { name: "int8".into() };
}
if known.iter().all(|t| is_numeric(t)) {
let numeric = known.iter().any(|t| scalar_name(t) == Some("numeric"));
return Ty::Scalar { name: if numeric { "numeric" } else { "real" }.into() };
}
Ty::Unknown
}
fn reached(args: &[Fact]) -> &[Fact] {
let count = args.iter().position(|f| f.non_null).map_or(args.len(), |i| i + 1);
&args[..count]
}
fn values_type(values: &[(&Node, &Fact)]) -> Ty {
let valued: Vec<&Fact> = values.iter().filter(|(e, _)| e.op != "null").map(|(_, f)| *f).collect();
if values.iter().any(|(e, f)| matches!(f.ty, Ty::Unknown) && e.op != "null" && e.op != "variable") {
return Ty::Unknown;
}
shared(&valued)
}
fn is_built(t: &Ty) -> bool {
matches!(t, Ty::Object { .. } | Ty::List { .. } | Ty::Json { .. })
}
fn textual(t: &Ty) -> Ty {
if is_built(t) { Ty::Scalar { name: "text".into() } } else { t.clone() }
}
fn same_json(types: &[&Ty]) -> Option<Ty> {
let empty = |t: &Ty| matches!(t, Ty::Json { schema: Some(s) } if s.get("prefixItems").is_none() && s["type"] == "array" && s["items"] == false);
let lists: Vec<&Ty> = types.iter().copied().filter(|t| !empty(t)).collect();
let first = lists.first()?;
(matches!(first, Ty::List { .. }) && lists.iter().all(|t| t == first)).then(|| (*first).clone())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Carry {
No,
Yes,
Maybe,
}
fn combine(carries: &[Carry]) -> Carry {
if carries.iter().all(|c| *c == Carry::No) {
Carry::No
} else if carries.iter().all(|c| *c == Carry::Yes) {
Carry::Yes
} else {
Carry::Maybe
}
}
struct JsonFact {
ty: Ty,
non_null: bool,
carry: Carry,
}
fn is_json_result(name: &str) -> bool {
name.starts_with("jsonb")
|| matches!(
name,
"json" | "json_object" | "json_array" | "json_group_array" | "json_group_object" | "json_insert" | "json_replace" | "json_set" | "json_remove" | "json_patch" | "json_extract" | "->" | "json_quote"
)
}
const PASSING: &[&str] = &["min", "max", "lag", "lead", "first_value", "last_value", "nth_value"];
const PLAIN: &[&str] = &[
"row_number", "rank", "dense_rank", "ntile", "percent_rank", "cume_dist", "count", "total", "sum", "avg", "group_concat", "string_agg", "abs", "round", "length", "instr",
"json_valid", "octet_length", "json_array_length", "json_type", "unicode", "like", "glob", "regexp", "match", "concat", "concat_ws", "substr", "substring", "printf", "format",
"upper", "lower", "trim", "ltrim", "rtrim", "replace", "char", "date", "time", "datetime", "julianday", "unixepoch", "strftime", "timediff", "hex", "quote", "typeof",
"soundex", "sqlite_version", "sqlite_source_id", "current_date", "current_time", "current_timestamp", "random", "last_insert_rowid", "changes", "total_changes",
"randomblob", "zeroblob", "->>", "atan", "atan2", "asinh", "sinh", "cosh", "tanh", "exp", "degrees", "radians", "ceil", "ceiling", "floor", "trunc", "sign", "acos", "acosh",
"asin", "atanh", "cos", "sin", "tan", "ln", "log", "log10", "log2", "mod", "pow", "power", "sqrt", "pi",
"bm25", "highlight", "snippet", "offsets", "matchinfo",
];
fn in_json(t: &Ty) -> Ty {
match scalar_name(t) {
Some("integer" | "int8" | "real" | "text" | "numeric") => t.clone(),
_ => Ty::Unknown,
}
}
fn nullable_in_json(f: &JsonFact) -> bool {
match f.ty {
Ty::Unknown => false,
Ty::Json { schema: None } => true,
_ => !f.non_null,
}
}
fn value_schema(t: &Ty, nullable: bool) -> serde_json::Value {
use serde_json::json;
let schema = match t {
Ty::Scalar { name } => match name.as_str() {
"integer" | "int8" => json!({"type": "integer", "format": "int64"}),
"real" => json!({"type": "number", "format": "double"}),
"text" => json!({"type": "string"}),
"numeric" => json!({"type": ["number", "string"]}),
_ => json!({}),
},
Ty::Object { fields } => {
let properties: serde_json::Map<String, serde_json::Value> = fields.iter().map(|f| (f.name.clone(), value_schema(&f.ty, f.nullable))).collect();
json!({"type": "object", "properties": properties, "required": fields.iter().map(|f| f.name.clone()).collect::<Vec<_>>(), "additionalProperties": false})
}
Ty::List { of, nullable_items } => json!({"type": "array", "items": value_schema(of, *nullable_items)}),
Ty::Json { schema: Some(schema) } => schema.clone(),
_ => json!({}),
};
if nullable { reylo_engine_core::schema::nullable(schema) } else { schema }
}
fn record(values: Vec<serde_json::Value>) -> Ty {
let mut distinct: Vec<serde_json::Value> = Vec::new();
for v in values {
if !distinct.contains(&v) {
distinct.push(v);
}
}
let rest = if distinct.len() == 1 { distinct.pop().unwrap_or_default() } else { serde_json::json!({"anyOf": distinct}) };
Ty::Json { schema: Some(serde_json::json!({"type": "object", "additionalProperties": rest})) }
}
type ScopeStack<'a> = Vec<&'a [From]>;
struct Analyzer<'a> {
tree: &'a Tree,
extras: &'a Extras,
skipping: &'a HashMap<String, i32>,
nullable_params: HashSet<String>,
nullable_values: HashSet<String>,
written: std::cell::RefCell<HashSet<String>>,
level: std::cell::RefCell<Level>,
shapes: std::cell::RefCell<HashMap<usize, Option<Ty>>>,
recursion: std::cell::RefCell<Vec<(String, Vec<Fact>)>>,
settled: std::cell::RefCell<HashMap<usize, Vec<Fact>>>,
}
#[derive(Debug, Clone, Default)]
struct Level {
narrowed: HashSet<(i64, String)>,
reduced: HashSet<i64>,
grouped: bool,
lone: HashSet<i64>,
aggregating: u32,
own: HashSet<i64>,
around: HashSet<i64>,
foreign: u32,
windowed: bool,
}
fn cast_variable<'n>(n: &'n Node, extras: &Extras) -> Option<&'n String> {
let inner = match n.op.as_str() {
"cast" => n.left.as_deref(),
"function" if matches!(n.name.as_deref(), Some("json" | "jsonb")) && n.args.len() == 1 && extras.function(n.name.as_deref().unwrap_or(""), 1).is_none() => n.args.first(),
_ => None,
}?;
inner.name.as_ref().filter(|_| inner.op == "variable")
}
fn level_of(sel: &Sel, extras: &Extras) -> Level {
let own: HashSet<i64> = sel.from.iter().map(|f| f.cursor).collect();
let outer: HashSet<i64> = sel.from.iter().filter(|f| f.outer).map(|f| f.cursor).collect();
let extended: HashSet<i64> = sel.from.iter().filter(|f| f.left_of_right).map(|f| f.cursor).collect();
let mut narrowed = HashSet::new();
for term in conjuncts(sel.where_.as_ref()).into_iter().filter(|t| !t.outer_on) {
narrowed.extend(strict_in(term, extras).into_iter().filter(|(cursor, _)| own.contains(cursor) && !(term.inner_on && extended.contains(cursor))));
}
let reduced = narrowed.iter().map(|(cursor, _)| *cursor).filter(|c| outer.contains(c)).collect();
let lone = if sel.aggregate && sel.group_by.is_empty() { own.clone() } else { HashSet::new() };
Level { narrowed, reduced, grouped: !sel.group_by.is_empty(), lone, aggregating: 0, own, around: HashSet::new(), foreign: 0, windowed: sel.window }
}
fn reads_cursor(n: &Node, cursors: &HashSet<i64>) -> bool {
if (n.op == "column" && cursors.contains(&n.cursor)) || n.select.is_some() {
return true;
}
n.left.as_deref().is_some_and(|x| reads_cursor(x, cursors))
|| n.right.as_deref().is_some_and(|x| reads_cursor(x, cursors))
|| n.list.iter().chain(&n.args).chain(&n.order_by).chain(&n.partition_by).any(|x| reads_cursor(x, cursors))
}
fn strict_in(n: &Node, extras: &Extras) -> HashSet<(i64, String)> {
let nulls = |x: &Node| nulls_with(x, extras);
match n.op.as_str() {
"and" => n.left.iter().chain(n.right.iter()).flat_map(|x| strict_in(x, extras)).collect(),
"or" => {
let (Some(l), Some(r)) = (n.left.as_deref(), n.right.as_deref()) else { return HashSet::new() };
let right = strict_in(r, extras);
strict_in(l, extras).into_iter().filter(|c| right.contains(c)).collect()
}
"notnull" | "in" | "between" => n.left.as_deref().map(nulls).unwrap_or_default(),
"=" | "!=" | "<" | "<=" | ">" | ">=" => n.left.iter().chain(n.right.iter()).flat_map(|x| nulls(x)).collect(),
"not" => match n.left.as_deref() {
Some(inner) if inner.op == "isnull" => inner.left.as_deref().map(nulls).unwrap_or_default(),
Some(inner) => strict_in(inner, extras).into_iter().filter(|_| matches!(inner.op.as_str(), "=" | "!=" | "<" | "<=" | ">" | ">=" | "between") || (inner.op == "in" && inner.select.is_none())).collect(),
None => HashSet::new(),
},
"function" if !n.agg && !n.window && matches!(n.name.as_deref(), Some("like" | "glob")) && extras.function(n.name.as_deref().unwrap_or(""), n.args.len()).is_none() => {
n.args.iter().flat_map(nulls).collect()
}
"column" => nulls(n),
_ => HashSet::new(),
}
}
fn nulls_with(n: &Node, extras: &Extras) -> HashSet<(i64, String)> {
const STRICT: &[&str] = &["upper", "lower", "length", "abs", "trim", "ltrim", "rtrim", "substr", "substring", "replace", "round", "instr", "unicode", "sign", "octet_length"];
match n.op.as_str() {
"column" => n.column.clone().map(|c| HashSet::from([(n.cursor, c)])).unwrap_or_default(),
"+" | "-" | "*" | "/" | "%" | "||" => n.left.iter().chain(n.right.iter()).flat_map(|x| nulls_with(x, extras)).collect(),
"neg" | "pos" | "cast" | "collate" => n.left.as_deref().map(|x| nulls_with(x, extras)).unwrap_or_default(),
"function" if !n.agg && !n.window && n.name.as_deref().is_some_and(|f| STRICT.contains(&f) && extras.function(f, n.args.len()).is_none()) => n.args.iter().flat_map(|x| nulls_with(x, extras)).collect(),
_ => HashSet::new(),
}
}
fn alter_column(sql: &str) -> Option<(String, usize)> {
let words = words(sql);
let keyword = |i: usize, want: &str| words.get(i).is_some_and(|(w, quoted, _)| !quoted && w.eq_ignore_ascii_case(want));
if !keyword(0, "alter") || !keyword(1, "table") {
return None;
}
let alter = if keyword(3, ".") { 5 } else { 3 };
if !keyword(alter, "alter") {
return None;
}
let column = if keyword(alter + 1, "column") { alter + 2 } else { alter + 1 };
if !keyword(column + 1, "to") {
return None;
}
let byte = |chars: usize| sql.char_indices().nth(chars).map_or(sql.len(), |(at, _)| at);
let at = byte(words[alter].2);
let to = byte(words[column + 1].2) + 2;
Some((format!("{}rename{} \"reylo libsql column\"", &sql[..at], &sql[at + 5..to]), at + 6))
}
fn words(sql: &str) -> Vec<(String, bool, usize)> {
let chars: Vec<char> = sql.chars().collect();
let mut out = Vec::new();
let mut i = 0;
while i < chars.len() {
let c = chars[i];
if c.is_whitespace() {
i += 1;
} else if c == '-' && chars.get(i + 1) == Some(&'-') {
i += chars[i..].iter().position(|c| *c == '\n').unwrap_or(chars.len() - i);
} else if c == '/' && chars.get(i + 1) == Some(&'*') {
i += 2;
while i < chars.len() && !(chars[i] == '*' && chars.get(i + 1) == Some(&'/')) {
i += 1;
}
i += 2;
} else if matches!(c, '"' | '`' | '\'' | '[') {
let close = if c == '[' { ']' } else { c };
let mut name = String::new();
let at = i;
i += 1;
while i < chars.len() {
if chars[i] == close {
if close != ']' && chars.get(i + 1) == Some(&close) {
i += 1;
} else {
break;
}
}
name.push(chars[i]);
i += 1;
}
i += 1;
out.push((name, true, at));
} else if c.is_alphanumeric() || c == '_' || c == '$' || !c.is_ascii() {
let end = chars[i..].iter().position(|c| !(c.is_alphanumeric() || *c == '_' || *c == '$' || !c.is_ascii())).map_or(chars.len(), |n| i + n);
out.push((chars[i..end].iter().collect(), false, i));
i = end;
} else {
out.push((c.to_string(), false, i));
i += 1;
}
}
out
}
fn trigger_header(sql: &str) -> Option<(String, String, String)> {
if !sql.as_bytes().windows(7).any(|w| w.eq_ignore_ascii_case(b"trigger")) {
return None;
}
let words = words(sql);
let keyword = |i: usize| words.get(i).filter(|(_, quoted, _)| !quoted).map(|(w, _, _)| w.to_ascii_lowercase());
let take = |i: &mut usize, want: &[&str]| {
let hit = keyword(*i).is_some_and(|w| want.contains(&w.as_str()));
if hit {
*i += 1;
}
hit
};
let mut i = 0;
if !take(&mut i, &["create"]) {
return None;
}
take(&mut i, &["temp", "temporary"]);
if !take(&mut i, &["trigger"]) {
return None;
}
if take(&mut i, &["if"]) {
take(&mut i, &["not"]);
take(&mut i, &["exists"]);
}
i += 1;
if take(&mut i, &["."]) {
i += 1;
}
let timing = if take(&mut i, &["before"]) {
"before"
} else if take(&mut i, &["after"]) {
"after"
} else if take(&mut i, &["instead"]) {
take(&mut i, &["of"]);
"instead"
} else {
"before"
};
let event = keyword(i)?;
let on = (i..words.len()).find(|j| keyword(*j).as_deref() == Some("on"))?;
let mut table = &words.get(on + 1)?.0;
if keyword(on + 2).as_deref() == Some(".") {
table = &words.get(on + 3)?.0;
}
Some((timing.to_string(), event, table.to_ascii_lowercase()))
}
fn instead_of_stub(sql: &str) -> Option<String> {
let (timing, _, _) = trigger_header(sql)?;
if timing != "instead" {
return None;
}
let words = words(sql);
let keyword = |w: &(String, bool, usize)| !w.1 && (w.0.eq_ignore_ascii_case("when") || w.0.eq_ignore_ascii_case("begin"));
let on = words.iter().position(|w| !w.1 && w.0.eq_ignore_ascii_case("on"))?;
let after = if words.get(on + 2).is_some_and(|w| !w.1 && w.0 == ".") { on + 4 } else { on + 2 };
let body = words.iter().skip(after).find(|w| keyword(w))?.2;
let header: String = sql.chars().take(body).collect();
Some(format!("{}\nBEGIN SELECT 1; END", header.trim_end()))
}
const TRIGGER_ROW_INSERT: i32 = 4;
const TRIGGER_ROW_DELETE: i32 = 8;
const TRIGGER_ROW_UPDATE: i32 = 16;
fn skipping_triggers(triggers: &[String]) -> HashMap<String, i32> {
let mut out: HashMap<String, i32> = HashMap::new();
for sql in triggers {
let Some((timing, event, table)) = trigger_header(sql) else { continue };
if timing == "after" {
continue;
}
let bit = match event.as_str() {
"insert" => TRIGGER_ROW_INSERT,
"update" => TRIGGER_ROW_UPDATE,
"delete" => TRIGGER_ROW_DELETE,
_ => TRIGGER_ROW_INSERT | TRIGGER_ROW_UPDATE | TRIGGER_ROW_DELETE,
};
*out.entry(table).or_default() |= bit;
}
out
}
#[derive(Clone, Copy)]
enum Nulls {
Never,
IfArgs,
Always,
}
impl Analyzer<'_> {
fn columns(&self) -> (Vec<(String, Fact)>, String) {
let t = self.tree;
let kind = t.dml.as_ref().map(|d| if d.kind == "upsert" { "insert".to_string() } else { d.kind.clone() }).unwrap_or_else(|| if t.statement.is_some() { "select".into() } else { String::new() });
let facts: Vec<Fact> = if let Some(returning) = &t.returning {
let written = self.written_non_null();
*self.written.borrow_mut() = written;
returning.iter().map(|c| self.type_of(&c.expr, &Vec::new())).collect()
} else if let (Some(sel), None) = (&t.statement, &t.dml) {
(0..sel.columns.len()).map(|i| self.select_column(sel, i, &Vec::new())).collect()
} else {
Vec::new()
};
let columns = t
.columns
.iter()
.enumerate()
.map(|(i, public)| {
(public.name.clone(), facts.get(i).cloned().unwrap_or_else(Fact::unknown))
})
.collect();
(columns, kind)
}
fn literals(&self) -> Vec<Option<Vec<reylo_engine_core::literal::Literal>>> {
let t = self.tree;
if let Some(returning) = &t.returning {
return returning.iter().map(|c| literals_of(&c.expr)).collect();
}
let (Some(sel), None) = (&t.statement, &t.dml) else { return Vec::new() };
let mut arms: Vec<&Sel> = Vec::new();
let mut s = Some(sel);
while let Some(arm) = s {
arms.push(arm);
s = arm.prior.as_deref();
}
arms.reverse();
(0..sel.columns.len())
.map(|i| {
let mut values = Vec::new();
for (k, arm) in arms.iter().enumerate() {
if k > 0 && matches!(arm.op.as_deref(), Some("intersect" | "except")) {
continue;
}
for e in std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i))) {
values.extend(literals_of(e?)?);
}
}
Some(values)
})
.collect()
}
fn booleans(&self) -> Vec<bool> {
self.result_truths(false)
}
fn flags(&self) -> Vec<bool> {
self.result_truths(true)
}
fn result_truths(&self, declared: bool) -> Vec<bool> {
let t = self.tree;
let truths: Vec<bool> = if let Some(returning) = &t.returning {
returning.iter().map(|c| self.truth(&c.expr, &Vec::new(), declared)).collect()
} else if let (Some(sel), None) = (&t.statement, &t.dml) {
(0..sel.columns.len()).map(|i| self.select_truth(sel, i, &Vec::new(), declared)).collect()
} else {
Vec::new()
};
(0..t.columns.len()).map(|i| truths.get(i).copied().unwrap_or(false)).collect()
}
fn exacts(&self) -> Vec<bool> {
let t = self.tree;
let exact: Vec<bool> = if let Some(returning) = &t.returning {
returning.iter().map(|c| self.exact(&c.expr, &Vec::new())).collect()
} else if let (Some(sel), None) = (&t.statement, &t.dml) {
(0..sel.columns.len()).map(|i| self.select_exact(sel, i, &Vec::new())).collect()
} else {
Vec::new()
};
(0..t.columns.len()).map(|i| exact.get(i).copied().unwrap_or(false)).collect()
}
fn select_exact(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> bool {
let mut s = Some(sel);
while let Some(arm) = s {
let mut inner = scope.clone();
inner.push(&arm.from);
if !arm.columns.get(i).is_some_and(|c| self.exact(&c.expr, &inner)) || !arm.rows.is_empty() {
return false;
}
s = arm.prior.as_deref();
}
true
}
fn exact(&self, n: &Node, scope: &ScopeStack) -> bool {
if n.op != "column" {
return false;
}
for froms in scope.iter().rev() {
if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
if let Some(sub) = f.subquery.as_deref() {
return self.select_exact(sub, n.index.max(0) as usize, scope);
}
break;
}
}
(n.strict && !n.generated) || n.rowid
}
fn select_truth(&self, sel: &Sel, i: usize, scope: &ScopeStack, declared: bool) -> bool {
let mut s = Some(sel);
while let Some(arm) = s {
let mut inner = scope.clone();
inner.push(&arm.from);
if !arm.columns.get(i).is_some_and(|c| self.truth(&c.expr, &inner, declared)) || !arm.rows.iter().all(|row| row.get(i).is_some_and(|e| self.truth(e, &inner, declared))) {
return false;
}
s = arm.prior.as_deref();
}
true
}
fn truth(&self, n: &Node, scope: &ScopeStack, declared: bool) -> bool {
let every = |nodes: &mut dyn Iterator<Item = &Node>| {
let mut any = false;
for x in nodes {
if x.op == "null" {
continue;
}
if !self.truth(x, scope, declared) {
return false;
}
any = true;
}
any
};
match n.op.as_str() {
"=" | "!=" | "<" | "<=" | ">" | ">=" | "is" | "is not" | "isnull" | "notnull" | "in" | "between" | "exists" | "and" | "or" | "not" | "truefalse" => true,
"collate" => n.left.as_deref().is_some_and(|l| self.truth(l, scope, declared)),
"function" if !n.agg && !n.window => match n.name.as_deref().unwrap_or("") {
"like" | "glob" | "regexp" | "match" => self.extras.function(n.name.as_deref().unwrap_or(""), n.args.len()).is_none(),
"starts_with" | "text_has_prefix" | "text_has_suffix" | "text_contains" | "text_like" | "regexp_like" => self.extras.function(n.name.as_deref().unwrap_or(""), n.args.len()).is_none(),
"likely" | "unlikely" | "likelihood" => n.args.first().is_some_and(|a| self.truth(a, scope, declared)),
"coalesce" | "ifnull" => every(&mut n.args.iter()),
"iif" | "if" => every(&mut iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i))),
_ => false,
},
"case" => {
let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
every(&mut results.chain(otherwise))
}
"select" => n.select.as_deref().is_some_and(|sub| self.select_truth(sub, 0, scope, declared)),
"column" => {
for froms in scope.iter().rev() {
if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
if let Some(sub) = f.subquery.as_deref() {
return self.select_truth(sub, n.index.max(0) as usize, scope, declared);
}
break;
}
}
declared && !n.rowid && n.declared.as_deref().is_some_and(is_boolean_declared)
}
_ => false,
}
}
fn select_column(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> Fact {
let mut arms: Vec<&Sel> = Vec::new();
let mut s = Some(sel);
while let Some(arm) = s {
arms.push(arm);
s = arm.prior.as_deref();
}
arms.reverse();
let facts: Vec<(Option<&Node>, Fact)> = arms
.iter()
.flat_map(|arm| {
let mut inner = scope.clone();
inner.push(&arm.from);
let outer = self.level.replace(self.level_within(arm));
let rows = std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i)));
let facts: Vec<(Option<&Node>, Fact)> = rows.map(|e| (e, e.map(|e| self.type_of(e, &inner)).unwrap_or_else(Fact::unknown))).collect();
self.level.replace(outer);
facts
})
.collect();
let Some((_, first)) = facts.first() else { return Fact::unknown() };
let values: Option<Vec<(&Node, &Fact)>> = facts.iter().map(|(e, f)| Some(((*e)?, f))).collect();
let ty = match values {
_ if facts.iter().all(|(_, f)| f.ty == first.ty) => first.ty.clone(),
Some(values) => values_type(&values),
None => Ty::Unknown,
};
Fact { ty, non_null: facts.iter().all(|(_, f)| f.non_null) }
}
fn recursive_column(&self, name: &str, sub: &Sel, i: usize, scope: &ScopeStack) -> Fact {
let key = sub as *const Sel as usize;
if let Some(facts) = self.settled.borrow().get(&key) {
return facts.get(i).cloned().unwrap_or_else(Fact::unknown);
}
let mut first = sub;
while let Some(prior) = first.prior.as_deref() {
first = prior;
}
let width = first.columns.len();
let mut inner = scope.clone();
inner.push(&first.from);
let outer = self.level.replace(self.level_within(first));
let mut assumed: Vec<Fact> = first.columns.iter().map(|c| Fact { ty: self.type_of(&c.expr, &inner).ty, non_null: true }).collect();
self.level.replace(outer);
let shapes = self.shapes.borrow().clone();
let nested = self.settled.borrow().clone();
let mut settled = None;
for _ in 0..=width + 1 {
*self.shapes.borrow_mut() = shapes.clone();
*self.settled.borrow_mut() = nested.clone();
self.recursion.borrow_mut().push((name.to_string(), assumed.clone()));
let got: Vec<Fact> = (0..width).map(|k| self.select_column(sub, k, scope)).collect();
self.recursion.borrow_mut().pop();
if got.iter().zip(&assumed).all(|(g, a)| g.ty == a.ty && g.non_null == a.non_null) {
settled = Some(got);
break;
}
assumed = got.iter().zip(&assumed).map(|(g, a)| Fact { ty: g.ty.clone(), non_null: g.non_null && a.non_null }).collect();
}
if settled.is_none() {
*self.shapes.borrow_mut() = shapes;
*self.settled.borrow_mut() = nested;
}
let facts = settled.unwrap_or_else(|| vec![Fact::unknown(); width]);
let fact = facts.get(i).cloned().unwrap_or_else(Fact::unknown);
self.settled.borrow_mut().insert(key, facts);
fact
}
fn column_ref(&self, n: &Node, scope: &ScopeStack) -> Fact {
if n.register && !n.view && !n.generated && n.column.as_ref().is_some_and(|c| self.written.borrow().contains(&c.to_ascii_lowercase())) {
let aff = n.affinity.as_deref().unwrap_or(&n.aff);
let ty = match &n.declared {
Some(declared) if !n.rowid => column_type(declared, aff, n.strict),
_ => affinity_type(aff),
};
return Fact { ty, non_null: true };
}
let (narrowed, reduced, lone) = {
let level = self.level.borrow();
(n.column.as_ref().is_some_and(|c| level.narrowed.contains(&(n.cursor, c.clone()))), level.reduced.contains(&n.cursor), (level.aggregating == 0 && level.lone.contains(&n.cursor)) || (level.foreign == 0 && level.around.contains(&n.cursor)))
};
for froms in scope.iter().rev() {
if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
let index = n.index.max(0) as usize;
let inner = match (&f.subquery, f.table.as_deref()) {
(None, Some("vector_top_k")) if f.tab_func && n.column.as_deref().is_some_and(|c| c.eq_ignore_ascii_case("id")) => self.vector_key(f),
(None, Some("generate_series" | "stats_seq")) if f.tab_func && n.column.as_deref().is_some_and(|c| c.eq_ignore_ascii_case("value")) => Some(Fact::new("integer", true)),
(Some(sub), Some(name)) if f.cte && reads_itself(sub) => Some(self.recursive_column(name, sub, index, scope)),
(Some(sub), _) => Some(self.select_column(sub, index, scope)),
(None, Some(name)) if f.recursive => self.recursion.borrow().iter().rev().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, facts)| facts.get(index).cloned().unwrap_or_else(Fact::unknown)),
_ => None,
};
if let Some(inner) = inner {
return Fact { ty: inner.ty, non_null: !lone && (narrowed || (inner.non_null && ((!f.outer && !n.outer) || reduced))) };
}
break;
}
}
if n.view && self.tree.dml.as_ref().is_some_and(|d| d.kind == "insert") {
return Fact::unknown();
}
let aff = n.affinity.as_deref().unwrap_or(&n.aff);
let ty = match &n.declared {
Some(declared) if !n.rowid => column_type(declared, aff, n.strict),
_ => affinity_type(aff),
};
Fact { ty, non_null: !lone && (narrowed || ((n.not_null || n.rowid) && (!n.outer || reduced))) }
}
fn vector_key(&self, f: &From) -> Option<Fact> {
let table = self.tree.tables.get(f.vector_table.as_deref()?)?;
Some(if table.without_rowid { Fact { ty: Ty::Unknown, non_null: true } } else { Fact::new("integer", true) })
}
fn call(&self, n: &Node, scope: &ScopeStack) -> Fact {
if let Some(ty) = self.built_text(n, scope) {
return Fact { ty, non_null: self.built_non_null(n, scope) };
}
let args: Vec<Fact> = n.args.iter().map(|a| self.type_of(a, scope)).collect();
self.function(n, &args)
}
fn built_non_null(&self, n: &Node, scope: &ScopeStack) -> bool {
match (self.builtin_name(n), n.args.as_slice()) {
(Some("json" | "jsonb"), [a]) if !n.agg && !n.window => if a.op == "select" { self.type_of(a, scope).non_null } else { self.built_non_null(a, scope) },
_ => true,
}
}
fn type_of(&self, n: &Node, scope: &ScopeStack) -> Fact {
let arg = |x: &Option<Box<Node>>| x.as_deref().map(|x| self.type_of(x, scope)).unwrap_or_else(Fact::unknown);
match n.op.as_str() {
"column" => self.column_ref(n, scope),
"integer" => Fact::new(if integer_literal_fits(n) { "integer" } else { "real" }, true),
"truefalse" => Fact::new("integer", true),
"float" => Fact::new("real", true),
"string" => Fact::new("text", true),
"blob" => Fact::new("blob", true),
"null" => Fact::unknown(),
"variable" => Fact { ty: Ty::Unknown, non_null: n.name.as_ref().is_some_and(|name| !self.nullable_values.contains(name)) },
"function" => {
self.aggregated(n, || self.call(n, scope))
}
"+" | "-" | "*" => {
let (l, r) = (arg(&n.left), arg(&n.right));
Fact { ty: arithmetic(&l.ty, &r.ty), non_null: l.non_null && r.non_null }
}
"/" | "%" => {
let (l, r) = (arg(&n.left), arg(&n.right));
let divisor = n.right.as_deref().filter(|d| matches!(d.op.as_str(), "integer" | "float")).and_then(|d| d.value.as_deref()?.parse::<f64>().ok());
let literal_divisor = divisor.is_some_and(|v| if n.op == "%" { v as i64 != 0 } else { v != 0.0 });
Fact { ty: arithmetic(&l.ty, &r.ty), non_null: l.non_null && r.non_null && literal_divisor }
}
"||" => {
let (l, r) = (arg(&n.left), arg(&n.right));
Fact::new("text", l.non_null && r.non_null)
}
"=" | "!=" | "<" | "<=" | ">" | ">=" | "and" | "or" | "in" | "between" | "&" | "|" | "<<" | ">>" => {
let (l, r) = (arg(&n.left), arg(&n.right));
let list_non_null = n.list.iter().all(|x| self.type_of(x, scope).non_null);
let right_non_null = if n.right.is_some() { r.non_null } else { list_non_null && n.select.is_none() };
Fact::new("integer", l.non_null && right_non_null)
}
"is" | "is not" | "isnull" | "notnull" | "exists" => Fact::new("integer", true),
"not" | "~" => {
let l = arg(&n.left);
Fact::new("integer", l.non_null)
}
"neg" if n.left.as_deref().is_some_and(is_two_to_the_63) => Fact::new("integer", true),
"neg" => {
let l = arg(&n.left);
Fact { ty: if is_numeric(&l.ty) { computed(l.ty) } else { Ty::Scalar { name: "real".into() } }, non_null: l.non_null }
}
"pos" => arg(&n.left),
"cast" => {
let l = arg(&n.left);
Fact::new(n.affinity.as_deref().unwrap_or("none"), l.non_null)
}
"collate" => arg(&n.left),
"case" => {
let results: Vec<(&Node, Fact)> = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some((&pair[1], self.type_of(&pair[1], scope))) } else { None }).collect();
let otherwise = if n.list.len() % 2 == 1 { n.list.last().map(|e| (e, self.type_of(e, scope))) } else { None };
let mut all: Vec<&(&Node, Fact)> = results.iter().collect();
if let Some(o) = &otherwise {
all.push(o);
}
let values: Vec<(&Node, &Fact)> = all.iter().map(|(e, f)| (*e, f)).collect();
Fact { ty: values_type(&values), non_null: otherwise.is_some() && all.iter().all(|(_, f)| f.non_null) }
}
"select" => {
let Some(sub) = n.select.as_deref() else { return Fact::unknown() };
let inner = self.select_column(sub, 0, scope);
Fact { ty: inner.ty, non_null: inner.non_null && self.exactly_one(sub).is_ok() }
}
_ => Fact::unknown(),
}
}
fn function(&self, n: &Node, args: &[Fact]) -> Fact {
let name = n.name.as_deref().unwrap_or("");
let all_non_null = args.iter().all(|a| a.non_null);
let first = args.first().cloned().unwrap_or_else(Fact::unknown);
let done = |aff: &str, nulls: Nulls| {
let non_null = match nulls {
Nulls::Never => true,
Nulls::IfArgs => all_non_null,
Nulls::Always => false,
};
Fact::new(aff, non_null)
};
let typed = |ty: Ty, nulls: Nulls| Fact { ty, non_null: matches!(nulls, Nulls::Never) || (matches!(nulls, Nulls::IfArgs) && all_non_null) };
if !n.agg && !n.window {
if let Some(f) = self.extras.function(name, args.len()) {
return done(f.returns.name(), Nulls::IfArgs);
}
}
let name = sqlean_alias(name);
if n.window {
let has_a_row = holds_current_row(n);
return match name {
"row_number" | "rank" | "dense_rank" | "ntile" => done("integer", Nulls::Never),
"percent_rank" | "cume_dist" => done("real", Nulls::Never),
"count" => done("integer", Nulls::Never),
"total" => done("real", total_nulls(&first)),
"sum" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::Always),
"avg" => done("real", Nulls::Always),
"lag" | "lead" if args.len() >= 3 => typed(values_type(&[(&n.args[0], &args[0]), (&n.args[2], &args[2])]), Nulls::Always),
"min" | "max" => typed(first.ty.clone(), if has_a_row { Nulls::IfArgs } else { Nulls::Always }),
"lag" | "lead" | "first_value" | "last_value" | "nth_value" => typed(first.ty.clone(), Nulls::Always),
"group_concat" | "string_agg" => done("text", Nulls::Always),
_ => Fact::unknown(),
};
}
if n.agg {
let grouped = self.level.borrow().grouped;
return match name {
"count" => done("integer", Nulls::Never),
"total" => done("real", total_nulls(&first)),
"sum" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::Always),
"avg" => done("real", Nulls::Always),
"min" | "max" => typed(first.ty.clone(), if grouped { Nulls::IfArgs } else { Nulls::Always }),
"group_concat" | "string_agg" => done("text", if grouped { Nulls::IfArgs } else { Nulls::Always }),
"json_group_array" | "json_group_object" => done("text", Nulls::Never),
"jsonb_group_array" | "jsonb_group_object" => done("blob", Nulls::Never),
"median" | "percentile" | "percentile_25" | "percentile_75" | "percentile_90" | "percentile_95" | "percentile_99" => done("real", Nulls::Always),
"stddev" | "stddev_pop" | "stddev_samp" | "variance" | "var_pop" | "var_samp" => done("real", Nulls::Always),
_ => Fact::unknown(),
};
}
let numbers = all_non_null && args.iter().all(|a| matches!(scalar_name(&a.ty), Some("integer" | "int8" | "real")));
match name {
"coalesce" | "ifnull" => Fact { ty: values_type(&n.args.iter().zip(reached(args)).collect::<Vec<_>>()), non_null: args.iter().any(|a| a.non_null) },
"nullif" => Fact { ty: first.ty.clone(), non_null: false },
"iif" | "if" => {
let values = iif_values(args.len());
let arms: Vec<(&Node, &Fact)> = values.iter().filter_map(|i| Some((n.args.get(*i)?, args.get(*i)?))).collect();
Fact { ty: values_type(&arms), non_null: args.len() >= 3 && args.len() % 2 == 1 && arms.iter().all(|(_, a)| a.non_null) }
}
"min" | "max" => Fact { ty: values_type(&n.args.iter().zip(args).collect::<Vec<_>>()), non_null: all_non_null },
"abs" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::IfArgs),
"round" => done("real", Nulls::IfArgs),
"length" | "instr" | "json_valid" | "octet_length" => done("integer", Nulls::IfArgs),
"json_array_length" => done("integer", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
"json_type" => done("text", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
"json_remove" => done("text", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
"unicode" => done("integer", Nulls::Always),
"like" | "glob" | "regexp" | "match" | "likely" | "unlikely" | "likelihood" => {
if matches!(name, "likely" | "unlikely" | "likelihood") { first.clone() } else { done("integer", Nulls::IfArgs) }
}
"concat" => done("text", Nulls::Never),
"concat_ws" => Fact::new("text", first.non_null),
"substr" | "substring" => {
let blob = matches!(scalar_name(&first.ty), Some("blob"));
let any = matches!(first.ty, Ty::Unknown) && n.args.first().is_some_and(|a| a.op != "variable");
let ty = if blob { first.ty.clone() } else if any { Ty::Unknown } else { Ty::Scalar { name: "text".into() } };
Fact { ty, non_null: all_non_null && !blob && !any }
}
"printf" | "format" => Fact::new("text", n.args.first().and_then(literal_text).is_some_and(printf_writes)),
"upper" | "lower" | "trim" | "ltrim" | "rtrim" | "replace" | "json" | "json_patch" | "json_pretty" => done("text", Nulls::IfArgs),
"char" | "json_array" | "json_object" | "json_quote" => done("text", Nulls::Never),
"json_insert" | "json_replace" | "json_set" => Fact::new("text", first.non_null),
"jsonb" => done("blob", Nulls::IfArgs),
"date" | "time" | "datetime" => Fact::new("text", current_time(&n.args)),
"julianday" => Fact::new("real", current_time(&n.args)),
"unixepoch" => {
let whole = n.args.iter().skip(1).all(|m| literal_text(m).is_some_and(|m| !matches!(m.to_ascii_lowercase().as_str(), "subsec" | "subsecond")));
Fact::new(if whole { "integer" } else { "real" }, current_time(&n.args))
}
"strftime" => Fact::new("text", n.args.first().and_then(literal_text).is_some_and(strftime_format) && current_time(n.args.get(1..).unwrap_or_default())),
"timediff" => Fact::new("text", n.args.len() == 2 && current_time(&n.args[..1]) && current_time(&n.args[1..])),
"hex" | "quote" | "typeof" => done("text", Nulls::Never),
"soundex" => done("text", Nulls::IfArgs),
"sqlite_version" | "sqlite_source_id" | "current_date" | "current_time" | "current_timestamp" => done("text", Nulls::Never),
"random" | "last_insert_rowid" | "changes" | "total_changes" => done("integer", Nulls::Never),
"randomblob" | "zeroblob" => done("blob", Nulls::IfArgs),
"json_extract" | "jsonb_extract" | "->" | "->>" => Fact::unknown(),
"atan" | "atan2" | "asinh" | "sinh" | "cosh" | "tanh" | "exp" | "degrees" | "radians" | "ceil" | "ceiling" | "floor" | "trunc" => Fact::new("real", numbers),
"sign" => Fact::new("integer", numbers),
"acos" | "acosh" | "asin" | "atanh" | "cos" | "sin" | "tan" | "ln" | "log" | "log10" | "log2" | "mod" | "pow" | "power" | "sqrt" => done("real", Nulls::Always),
"pi" => done("real", Nulls::Never),
"bm25" => done("real", if n.args.len() == 1 { Nulls::Never } else { Nulls::Always }),
"highlight" | "snippet" => done("text", Nulls::Always),
"offsets" => done("text", Nulls::Never),
"matchinfo" => done("blob", Nulls::Never),
"vector" | "vector32" | "vector64" | "vector1bit" | "vector8" | "vector16" | "vectorb16" => done("blob", Nulls::Never),
"vector_extract" => done("text", Nulls::Never),
"vector_distance_cos" | "vector_distance_l2" => done("real", Nulls::Always),
"libsql_vector_idx" => Fact { ty: Ty::Unknown, non_null: first.non_null },
"uuid4" | "gen_random_uuid" | "uuid7" => done("text", Nulls::Never),
"uuid_str" => done("text", Nulls::Always),
"uuid_blob" => done("blob", Nulls::Always),
"uuid7_timestamp_ms" => done("integer", Nulls::Always),
"md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" => done("blob", Nulls::IfArgs),
"encode" => Fact::new("text", first.non_null),
"decode" => Fact::new("blob", first.non_null),
"levenshtein" | "dlevenshtein" | "edit_distance" | "osa_distance" | "hamming" => done("integer", Nulls::Never),
"jaro_winkler" => done("real", Nulls::Never),
"caverphone" | "phonetic_hash" | "rsoundex" => done("text", Nulls::IfArgs),
"translit" => done("text", Nulls::Never),
"script_code" => done("integer", Nulls::Never),
"bit_length" | "char_length" | "character_length" | "text_size" | "text_bitsize" | "text_length" => done("integer", Nulls::IfArgs),
"strpos" | "text_index" | "text_last_index" | "text_count" => done("integer", Nulls::IfArgs),
"starts_with" | "text_has_prefix" | "text_has_suffix" | "text_contains" | "text_like" => done("integer", Nulls::IfArgs),
"btrim" | "left" | "right" | "lpad" | "rpad" | "repeat" | "reverse" | "split_part" | "translate" | "text_trim" | "text_ltrim" | "text_rtrim" | "text_left" | "text_right"
| "text_lpad" | "text_rpad" | "text_repeat" | "text_reverse" | "text_split" | "text_translate" | "text_title" | "text_casefold" | "text_lower" | "text_upper"
| "text_replace" | "text_slice" | "text_substring" => done("text", Nulls::IfArgs),
"text_concat" => done("text", Nulls::Never),
"text_join" => Fact::new("text", first.non_null),
"regexp_like" => done("integer", Nulls::Never),
"regexp_substr" | "regexp_capture" => done("text", Nulls::Always),
"regexp_replace" => Fact { ty: if scalar_name(&first.ty) == Some("text") { first.ty.clone() } else { Ty::Unknown }, non_null: first.non_null },
_ => Fact::unknown(),
}
}
fn built_text(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
match self.builtin_name(n)? {
"json_object" | "json_array" | "json_group_array" | "json_group_object" => self.shape(n, scope),
"json" if n.args.len() == 1 && !n.agg && !n.window => self.shape(&n.args[0], scope).or_else(|| self.subquery_shape(&n.args[0], scope)),
_ => None,
}
}
fn subquery_shape(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
if n.op != "select" {
return None;
}
let sub = n.select.as_deref()?;
if sub.columns.len() != 1 || sub.prior.is_some() || !sub.rows.is_empty() || sub.values {
return None;
}
let col = sub.columns.first()?;
self.within(sub, scope, |inner| self.built_text(&col.expr, inner))
}
fn builtin_name<'n>(&self, n: &'n Node) -> Option<&'n str> {
let name = n.name.as_deref().filter(|_| n.op == "function")?;
(n.agg || n.window || self.extras.function(name, n.args.len()).is_none()).then_some(name)
}
fn shape(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
let key = n as *const Node as usize;
if let Some(found) = self.shapes.borrow().get(&key) {
return found.clone();
}
let shape = self.aggregated(n, || self.shape_here(n, scope));
self.shapes.borrow_mut().insert(key, shape.clone());
shape
}
fn shape_here(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
let name = self.builtin_name(n)?;
let aggregate = n.agg || n.window;
let value = |x: &Node| {
let f = self.json_fact(x, scope);
let nullable = nullable_in_json(&f);
(f.ty, nullable)
};
match name {
"json_object" | "jsonb_object" if !aggregate => {
if n.args.len() % 2 != 0 {
return Some(Ty::Json { schema: None });
}
let mut fields: Vec<TyField> = Vec::new();
let mut dynamic = false;
for pair in n.args.chunks(2) {
let (ty, nullable) = value(&pair[1]);
match literal_text(&pair[0]) {
Some(key) => match fields.iter_mut().find(|f| f.name == key) {
Some(f) => {
f.ty = ty;
f.nullable = nullable;
}
None => fields.push(TyField { name: key.to_string(), ty, nullable }),
},
None => {
dynamic = true;
fields.push(TyField { name: String::new(), ty, nullable });
}
}
}
if dynamic {
return Some(record(fields.iter().map(|f| value_schema(&f.ty, f.nullable)).collect()));
}
Some(Ty::Object { fields })
}
"json_array" | "jsonb_array" if !aggregate => {
let items: Vec<serde_json::Value> = n.args.iter().map(|x| {
let (ty, nullable) = value(x);
value_schema(&ty, nullable)
}).collect();
let mut schema = serde_json::json!({"type": "array", "items": false});
if !items.is_empty() {
schema["minItems"] = serde_json::json!(items.len());
schema["prefixItems"] = serde_json::Value::Array(items);
}
Some(Ty::Json { schema: Some(schema) })
}
"json_group_array" | "jsonb_group_array" if aggregate && n.args.len() == 1 => {
let (ty, nullable) = value(&n.args[0]);
Some(Ty::List { of: Box::new(ty), nullable_items: nullable })
}
"json_group_object" | "jsonb_group_object" if aggregate && n.args.len() == 2 => {
let (ty, nullable) = value(&n.args[1]);
Some(record(vec![value_schema(&ty, nullable)]))
}
"json" | "jsonb" if !aggregate && n.args.len() == 1 => self.shape(&n.args[0], scope).or_else(|| self.subquery_shape(&n.args[0], scope)),
_ => None,
}
}
fn json_fact(&self, n: &Node, scope: &ScopeStack) -> JsonFact {
let plain = || {
let f = self.type_of(n, scope);
JsonFact { ty: in_json(&f.ty), non_null: f.non_null, carry: Carry::No }
};
let any = JsonFact { ty: Ty::Unknown, non_null: false, carry: Carry::Maybe };
match n.op.as_str() {
"function" => {
let Some(name) = self.builtin_name(n) else { return any };
if n.over && is_json_result(name) {
return any;
}
if self.windowed_aggregate(n) && self.carry(n, scope) != Carry::No {
return any;
}
if let Some(ty) = self.shape(n, scope) {
let non_null = self.built_non_null(n, scope);
return JsonFact { ty, non_null, carry: Carry::Yes };
}
let first = n.args.first().into_iter();
let non_null = || self.type_of(n, scope).non_null;
match name {
"coalesce" | "ifnull" => self.json_arms(n.args.iter(), true, scope).map(|f| JsonFact { non_null: f.non_null, ..f }).unwrap_or_else(plain),
"nullif" => self.json_arms(first, false, scope).map(|f| JsonFact { non_null: false, ..f }).unwrap_or_else(plain),
"likely" | "unlikely" | "likelihood" => self.json_arms(first, false, scope).unwrap_or_else(plain),
"iif" | "if" => {
let arms = iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i));
self.json_arms(arms, false, scope).map(|f| JsonFact { non_null: non_null(), ..f }).unwrap_or_else(plain)
}
"min" | "max" if n.args.len() == 1 && !n.window => self.json_arms(first, false, scope).map(|f| JsonFact { non_null: non_null(), ..f }).unwrap_or_else(plain),
_ if is_json_result(name) => JsonFact { ty: Ty::Json { schema: None }, non_null: non_null(), carry: Carry::Yes },
_ if PASSING.contains(&name) => {
if n.args.iter().all(|a| self.carry(a, scope) == Carry::No) { plain() } else { any }
}
_ if PLAIN.contains(&name) => plain(),
_ => any,
}
}
"select" => if self.carry(n, scope) == Carry::No { plain() } else { any },
"collate" | "pos" => n.left.as_deref().map_or(any, |l| self.json_fact(l, scope)),
"case" => {
let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
match self.json_arms(results.chain(otherwise), false, scope) {
Some(f) => JsonFact { non_null: self.type_of(n, scope).non_null, ..f },
None => plain(),
}
}
"cast" | "column" => if self.carry(n, scope) == Carry::No { plain() } else { any },
_ => plain(),
}
}
fn json_arms<'n>(&self, arms: impl Iterator<Item = &'n Node>, coalesce: bool, scope: &ScopeStack) -> Option<JsonFact> {
let mut facts: Vec<JsonFact> = Vec::new();
for arm in arms.filter(|a| a.op != "null") {
let f = self.json_fact(arm, scope);
let last = coalesce && f.non_null;
facts.push(f);
if last {
break;
}
}
if facts.iter().all(|f| f.carry == Carry::No) {
return None;
}
let non_null = facts.iter().any(|f| f.non_null);
if !facts.iter().all(|f| f.carry == Carry::Yes) {
return Some(JsonFact { ty: Ty::Unknown, non_null, carry: Carry::Maybe });
}
let types: Vec<&Ty> = facts.iter().map(|f| &f.ty).collect();
let ty = if types.iter().all(|t| *t == types[0]) { types[0].clone() } else { same_json(&types).unwrap_or(Ty::Unknown) };
Some(JsonFact { ty, non_null, carry: Carry::Yes })
}
fn carry(&self, n: &Node, scope: &ScopeStack) -> Carry {
match n.op.as_str() {
"function" => {
let Some(name) = self.builtin_name(n) else { return Carry::Maybe };
let carry = match name {
"coalesce" | "ifnull" => self.carries(n.args.iter(), scope),
"nullif" | "likely" | "unlikely" | "likelihood" => self.carries(n.args.first().into_iter(), scope),
"iif" | "if" => self.carries(iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i)), scope),
"min" | "max" if n.args.len() == 1 && !n.window => self.carries(n.args.iter(), scope),
_ if is_json_result(name) => if n.over { Carry::Maybe } else { Carry::Yes },
_ if PASSING.contains(&name) => {
if self.carries(n.args.iter(), scope) == Carry::No { Carry::No } else { Carry::Maybe }
}
_ if PLAIN.contains(&name) => Carry::No,
_ => Carry::Maybe,
};
if carry != Carry::No && self.windowed_aggregate(n) { Carry::Maybe } else { carry }
}
"select" => {
let Some(sub) = n.select.as_deref() else { return Carry::No };
match self.select_carry(sub, 0, scope) {
Carry::No => Carry::No,
_ => Carry::Maybe,
}
}
"collate" | "pos" => n.left.as_deref().map_or(Carry::No, |l| self.carry(l, scope)),
"cast" => match n.left.as_deref().map_or(Carry::No, |l| self.carry(l, scope)) {
Carry::No => Carry::No,
_ => Carry::Maybe,
},
"case" => {
let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
self.carries(results.chain(otherwise), scope)
}
"column" => {
for froms in scope.iter().rev() {
if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
if let Some(sub) = f.subquery.as_deref() {
return if self.select_carry(sub, n.index.max(0) as usize, scope) == Carry::No { Carry::No } else { Carry::Maybe };
}
break;
}
}
if n.subtype { Carry::Maybe } else { Carry::No }
}
_ => Carry::No,
}
}
fn select_carry(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> Carry {
let mut carries = Vec::new();
let mut s = Some(sel);
while let Some(arm) = s {
self.within(arm, scope, |inner| {
for e in std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i))).flatten() {
carries.push(self.carry(e, inner));
}
});
s = arm.prior.as_deref();
}
combine(&carries)
}
fn carries<'n>(&self, arms: impl Iterator<Item = &'n Node>, scope: &ScopeStack) -> Carry {
let carries: Vec<Carry> = arms.filter(|a| a.op != "null").map(|a| self.carry(a, scope)).collect();
combine(&carries)
}
fn aggregated<T>(&self, n: &Node, f: impl FnOnce() -> T) -> T {
if !(n.op == "function" && n.agg && !n.over) {
return f();
}
let foreign = {
let level = self.level.borrow();
!n.window && !reads_cursor(n, &level.own)
};
{
let mut level = self.level.borrow_mut();
level.aggregating += 1;
level.foreign += u32::from(foreign);
}
let out = f();
let mut level = self.level.borrow_mut();
level.aggregating -= 1;
level.foreign -= u32::from(foreign);
out
}
fn windowed_aggregate(&self, n: &Node) -> bool {
n.op == "function" && n.agg && !n.over && self.level.borrow().windowed
}
fn level_within(&self, sel: &Sel) -> Level {
let mut level = level_of(sel, self.extras);
let outer = self.level.borrow();
level.around = outer.around.clone();
if outer.aggregating == 0 {
level.around.extend(outer.lone.iter().copied());
}
level
}
fn within<T>(&self, sel: &Sel, scope: &ScopeStack, f: impl FnOnce(&ScopeStack) -> T) -> T {
let mut inner = scope.clone();
inner.push(&sel.from);
let outer = self.level.replace(self.level_within(sel));
let out = f(&inner);
self.level.replace(outer);
out
}
fn written_non_null(&self) -> HashSet<String> {
let t = self.tree;
let (Some(dml), Some(_)) = (&t.dml, &t.returning) else { return HashSet::new() };
let events = match dml.kind.as_str() {
"update" => TRIGGER_ROW_UPDATE,
_ if dml.upserts.iter().any(|u| u.do_update) => TRIGGER_ROW_INSERT | TRIGGER_ROW_UPDATE,
_ => TRIGGER_ROW_INSERT,
};
if self.skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & events != 0) {
return HashSet::new();
}
let scope: ScopeStack = Vec::new();
let non_null = |known: HashMap<String, bool>| -> HashSet<String> { known.into_iter().filter(|(_, n)| *n).map(|(c, _)| c).collect() };
let assigned = |items: &[tree::SetItem]| -> HashSet<String> {
let mut known: HashMap<String, bool> = HashMap::new();
for item in items {
let Some(column) = &item.column else { continue };
*known.entry(column.to_ascii_lowercase()).or_insert(true) &= self.type_of(&item.expr, &scope).non_null;
}
non_null(known)
};
match dml.kind.as_str() {
"update" => assigned(&dml.set),
"insert" | "upsert" => {
let mut known: HashMap<String, bool> = HashMap::new();
for (i, column) in dml.columns.iter().enumerate() {
let Some(column) = column else { continue };
let fact = match (&dml.values, &t.statement) {
(Some(values), _) => values.get(i).map(|v| self.type_of(v, &scope)),
(None, Some(sel)) => Some(self.select_column(sel, i, &scope)),
(None, None) => None,
};
*known.entry(column.to_ascii_lowercase()).or_insert(true) &= fact.is_some_and(|f| f.non_null);
}
let mut written = non_null(known);
for upsert in dml.upserts.iter().filter(|u| u.do_update) {
let updated = assigned(&upsert.set);
written.retain(|c| updated.contains(c));
}
written
}
_ => HashSet::new(),
}
}
fn bare_nullable(&self) -> HashSet<String> {
let t = self.tree;
let Some(dml) = &t.dml else { return HashSet::new() };
let mut fills: HashMap<String, bool> = HashMap::new();
let mut fill = |v: &Node, column: Option<&str>| {
let (Some(name), Some(column)) = (v.name.as_ref().filter(|_| v.op == "variable"), column) else { return };
let Some(target) = self.table_column(&dml.table, column) else { return };
let refuses = target.non_null || self.checked_not_null(&dml.table, column);
*fills.entry(name.clone()).or_insert(true) &= !refuses;
};
if let (Some(sel), "insert" | "upsert") = (&t.statement, dml.kind.as_str()) {
if sel.prior.is_none() {
for (i, v) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
fill(v, dml.columns.get(i).and_then(|c| c.as_deref()));
}
}
}
for (i, v) in dml.values.iter().flatten().enumerate() {
fill(v, dml.columns.get(i).and_then(|c| c.as_deref()));
}
for item in dml.set.iter().chain(dml.upserts.iter().flat_map(|u| u.set.iter())) {
fill(&item.expr, item.column.as_deref());
}
fills.into_iter().filter(|(_, nullable)| *nullable).map(|(name, _)| name).collect()
}
fn params(&self, lexed: &Lexed) -> (Vec<Param>, Vec<(String, String, String)>) {
let mut found: Vec<(String, Fact)> = Vec::new();
let t = self.tree;
let checked = |c: Option<&str>| t.dml.as_ref().zip(c).is_some_and(|(dml, c)| self.checked_not_null(&dml.table, c));
let mut fills: HashMap<String, bool> = HashMap::new();
let mut refused: Vec<(String, String, String)> = Vec::new();
let mut fill = |v: &Node, target: &Option<Fact>, column: Option<&str>| {
let Some(target) = target else { return };
let refuses = target.non_null || checked(column);
let bare = v.op == "variable";
let Some(name) = (if bare { v.name.as_ref() } else { cast_variable(v, self.extras) }) else { return };
if bare {
*fills.entry(name.clone()).or_insert(true) &= !refuses;
}
if let (true, true, Some(column), Some(dml)) = (refuses, self.nullable_params.contains(name), column, t.dml.as_ref()) {
refused.push((name.clone(), dml.table.clone(), column.to_string()));
}
};
if let Some(sel) = &t.statement {
let targets: Vec<Option<Fact>> = match &t.dml {
Some(dml) if dml.kind == "insert" => dml.columns.iter().map(|c| c.as_deref().and_then(|c| self.table_column(&dml.table, c))).collect(),
_ => Vec::new(),
};
if sel.prior.is_none() {
for (i, v) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
if let Some(target) = targets.get(i) {
fill(v, target, t.dml.as_ref().and_then(|d| d.columns.get(i)).and_then(|c| c.as_deref()));
}
}
}
self.walk_select(sel, &Vec::new(), &targets, &mut found);
}
if let Some(dml) = &t.dml {
let scope: ScopeStack = Vec::new();
if let Some(values) = &dml.values {
for (i, v) in values.iter().enumerate() {
let target = dml.columns.get(i).and_then(|c| c.as_deref()).and_then(|c| self.table_column(&dml.table, c));
fill(v, &target, dml.columns.get(i).and_then(|c| c.as_deref()));
self.walk(v, Ctx::Typed(target), &scope, &mut found);
}
}
for item in dml.set.iter().chain(dml.upserts.iter().flat_map(|u| u.set.iter())) {
let target = item.column.as_deref().and_then(|c| self.table_column(&dml.table, c));
fill(&item.expr, &target, item.column.as_deref());
self.walk(&item.expr, Ctx::Typed(target), &scope, &mut found);
}
if let Some(w) = &dml.where_ {
self.walk(w, Ctx::Bool, &scope, &mut found);
}
for w in dml.upserts.iter().filter_map(|u| u.where_.as_ref()) {
self.walk(w, Ctx::Bool, &scope, &mut found);
}
}
if let Some(returning) = &t.returning {
for c in returning {
self.walk(&c.expr, Ctx::None, &Vec::new(), &mut found);
}
}
let mut typed: HashMap<&str, &Fact> = HashMap::new();
for (name, fact) in found.iter().filter(|(_, f)| !matches!(f.ty, Ty::Unknown)) {
typed.entry(name.as_str()).or_insert(fact);
}
let params = lexed
.params
.iter()
.enumerate()
.map(|(k, name)| {
let numbered = format!("?{}", k + 1);
let fact = typed.get(numbered.as_str()).map(|f| (*f).clone()).unwrap_or_else(Fact::unknown);
let fact = Fact { ty: textual(&fact.ty), ..fact };
let nullable = fills.get(&numbered).copied().unwrap_or(false) || self.nullable_params.contains(&numbered);
Param { nullable, ..Param::new(name.clone(), descriptor(&fact.ty, None, false, false)) }
})
.collect();
(params, refused)
}
fn checked_not_null(&self, table: &str, column: &str) -> bool {
self.tree.tables.get(table).and_then(|info| info.columns.iter().find(|c| c.name.eq_ignore_ascii_case(column))).is_some_and(|c| c.checked_not_null)
}
fn table_column(&self, table: &str, column: &str) -> Option<Fact> {
let info = self.tree.tables.get(table)?;
let col = info.columns.iter().find(|c| c.name.eq_ignore_ascii_case(column))?;
Some(Fact { ty: column_type(&col.declared, &col.affinity, info.strict), non_null: col.not_null || info.rowid_alias.as_deref().is_some_and(|a| a.eq_ignore_ascii_case(column)) })
}
fn walk_select(&self, sel: &Sel, scope: &ScopeStack, targets: &[Option<Fact>], found: &mut Vec<(String, Fact)>) {
let compound: Vec<Option<Fact>>;
let targets = if targets.is_empty() && (sel.prior.is_some() || !sel.rows.is_empty()) {
compound = (0..sel.columns.len())
.map(|i| {
let ty = self.select_column(sel, i, scope).ty;
(!matches!(ty, Ty::Unknown)).then_some(Fact { ty, non_null: true })
})
.collect();
compound.as_slice()
} else {
targets
};
let mut inner = scope.clone();
inner.push(&sel.from);
for (i, e) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
self.walk(e, Ctx::Typed(targets.get(i).cloned().flatten()), &inner, found);
}
for f in &sel.from {
if let Some(sub) = &f.subquery {
self.walk_select(sub, &inner, &[], found);
}
if let Some(on) = &f.on {
self.walk(on, Ctx::Bool, &inner, found);
}
let json = f.tab_func && matches!(f.table.as_deref(), Some("json_each" | "json_tree"));
let top_k = f.tab_func && f.table.as_deref() == Some("vector_top_k");
let series = f.tab_func && matches!(f.table.as_deref(), Some("generate_series" | "stats_seq"));
for (i, a) in f.args.iter().enumerate() {
let ctx = match i {
0 | 1 if json || top_k => Ctx::Typed(Some(Fact::new("text", true))),
2 if top_k => Ctx::Typed(Some(Fact::new("integer", true))),
_ if series => Ctx::Typed(Some(Fact::new("integer", true))),
_ => Ctx::None,
};
self.walk(a, ctx, &inner, found);
}
}
if let Some(w) = &sel.where_ {
self.walk(w, Ctx::Bool, &inner, found);
}
for g in &sel.group_by {
self.walk(g, Ctx::None, &inner, found);
}
if let Some(h) = &sel.having {
self.walk(h, Ctx::Bool, &inner, found);
}
for o in &sel.order_by {
self.walk(o, Ctx::None, &inner, found);
}
for l in sel.limit.iter().chain(sel.offset.iter()) {
self.walk(l, Ctx::Typed(Some(Fact::new("integer", true))), &inner, found);
}
if let Some(prior) = &sel.prior {
self.walk_select(prior, scope, targets, found);
}
}
fn walk(&self, n: &Node, ctx: Ctx, scope: &ScopeStack, found: &mut Vec<(String, Fact)>) {
if n.op == "variable" {
let fact = match ctx {
Ctx::Typed(Some(f)) => f,
Ctx::Typed(None) | Ctx::Row(_) | Ctx::None => Fact::unknown(),
Ctx::Bool => Fact::new("integer", false),
};
found.push((n.name.clone().unwrap_or_default(), fact));
return;
}
let sibling = |other: &Option<Box<Node>>| other.as_deref().map(|o| self.type_of(o, scope));
let case_results: std::cell::OnceCell<Ty> = std::cell::OnceCell::new();
let child_ctx = |slot: Position| -> Ctx {
match n.op.as_str() {
"=" | "!=" | "<" | "<=" | ">" | ">=" | "is" | "is not" => {
let (this, other) = match slot {
Position::Left => (&n.left, &n.right),
Position::Right => (&n.right, &n.left),
_ => return Ctx::None,
};
match (this.as_deref(), other.as_deref().and_then(|o| self.row(o, scope))) {
(Some(t), Some(row)) if matches!(t.op.as_str(), "vector" | "select") => Ctx::Row(row),
_ => Ctx::Typed(sibling(other)),
}
}
"in" => match slot {
Position::Left if is_vector(&n.left) => n.select.as_deref().map_or(Ctx::None, |s| Ctx::Row(self.select_columns(s, scope))),
Position::Left => Ctx::Typed(n.list.first().map(|x| self.type_of(x, scope)).or_else(|| n.select.as_deref().map(|s| self.select_column(s, 0, scope)))),
Position::List(_) => Ctx::Typed(sibling(&n.left)),
_ => Ctx::None,
},
"between" => match slot {
Position::Left if is_vector(&n.left) => Ctx::Row(self.rows(&n.list.iter().collect::<Vec<_>>(), scope)),
Position::Left => Ctx::Typed(n.list.first().map(|x| self.type_of(x, scope))),
Position::List(_) => match n.left.as_deref().and_then(|l| self.row(l, scope)) {
Some(row) if is_vector(&n.left) => Ctx::Row(row),
_ => Ctx::Typed(sibling(&n.left)),
},
_ => Ctx::None,
},
"vector" => match (slot, &ctx) {
(Position::List(i), Ctx::Row(row)) => Ctx::Typed(row.get(i).cloned().flatten()),
_ => Ctx::None,
},
"select_column" => match (slot, &ctx) {
(Position::Left, Ctx::Typed(Some(f))) => {
let mut row = vec![None; n.index.max(0) as usize + 1];
row[n.index.max(0) as usize] = Some(f.clone());
Ctx::Row(row)
}
_ => Ctx::None,
},
"cast" => Ctx::Typed(Some(Fact::new(n.affinity.as_deref().unwrap_or("none"), true))),
"+" | "-" | "*" | "/" | "%" => {
let other = match slot {
Position::Left => sibling(&n.right),
_ => sibling(&n.left),
};
Ctx::Typed(Some(match other {
Some(f) if is_numeric(&f.ty) => f,
_ => Fact::new("real", true),
}))
}
"||" => Ctx::Typed(Some(Fact::new("text", true))),
"neg" | "~" | "&" | "|" | "<<" | ">>" => Ctx::Typed(Some(Fact::new("real", true))),
"pos" | "collate" => ctx.clone(),
"and" | "or" | "not" => Ctx::Bool,
"case" => match slot {
Position::List(i) if i % 2 == 0 && i + 1 < n.list.len() => match &n.left {
Some(base) if base.op == "vector" => self.row(base, scope).map_or(Ctx::None, Ctx::Row),
Some(base) => Ctx::Typed(Some(self.type_of(base, scope))),
None => Ctx::Bool,
},
Position::List(_) => match case_results.get_or_init(|| {
let others: Vec<Fact> = n.list.iter().enumerate().filter(|(j, _)| j % 2 == 1 || (*j == n.list.len() - 1 && n.list.len() % 2 == 1)).map(|(_, x)| self.type_of(x, scope)).collect();
shared(&others.iter().collect::<Vec<_>>())
}) {
Ty::Unknown => outer_type(&ctx),
ty => Ctx::Typed(Some(Fact { ty: ty.clone(), non_null: true })),
},
Position::Left if is_vector(&n.left) => {
let values: Vec<&Node> = n.list.iter().enumerate().filter(|(j, _)| j % 2 == 0 && j + 1 < n.list.len()).map(|(_, x)| x).collect();
Ctx::Row(self.rows(&values, scope))
}
Position::Left => {
let values: Vec<Fact> = n.list.iter().enumerate().filter(|(j, _)| j % 2 == 0 && j + 1 < n.list.len()).map(|(_, x)| self.type_of(x, scope)).collect();
let refs: Vec<&Fact> = values.iter().collect();
match shared(&refs) {
Ty::Unknown => Ctx::None,
ty => Ctx::Typed(Some(Fact { ty, non_null: true })),
}
}
_ => Ctx::None,
},
"function" => match (slot, self.argument(n, i_of(slot), scope)) {
(Position::Arg(_), Ctx::Typed(None) | Ctx::None) if matches!(n.name.as_deref(), Some("coalesce" | "ifnull" | "nullif" | "min" | "max")) && !n.agg => outer_type(&ctx),
(Position::Arg(i), Ctx::Typed(None) | Ctx::None) if matches!(n.name.as_deref(), Some("iif" | "if")) && iif_values(n.args.len()).contains(&i) => outer_type(&ctx),
(Position::Arg(_), c) => c,
_ => Ctx::None,
},
_ => Ctx::None,
}
};
if let Some(l) = &n.left {
self.walk(l, child_ctx(Position::Left), scope, found);
}
if let Some(r) = &n.right {
self.walk(r, child_ctx(Position::Right), scope, found);
}
for (i, x) in n.list.iter().enumerate() {
self.walk(x, child_ctx(Position::List(i)), scope, found);
}
for (i, x) in n.args.iter().enumerate() {
self.walk(x, child_ctx(Position::Arg(i)), scope, found);
}
if let Some(s) = &n.select {
let targets: Vec<Option<Fact>> = match (n.op.as_str(), &ctx) {
("select", Ctx::Row(row)) => row.clone(),
("select", Ctx::Typed(Some(f))) => vec![Some(f.clone())],
("in", _) => match n.left.as_deref() {
Some(l) if l.op == "vector" => self.row(l, scope).unwrap_or_default(),
Some(l) => vec![Some(self.type_of(l, scope))],
None => Vec::new(),
},
_ => Vec::new(),
};
self.walk_select(s, scope, &targets, found);
}
}
fn row(&self, n: &Node, scope: &ScopeStack) -> Option<Vec<Option<Fact>>> {
match n.op.as_str() {
"vector" => Some(n.list.iter().map(|x| Some(self.type_of(x, scope))).collect()),
"select" => n.select.as_deref().map(|s| self.select_columns(s, scope)),
_ => None,
}
}
fn select_columns(&self, sel: &Sel, scope: &ScopeStack) -> Vec<Option<Fact>> {
(0..sel.columns.len()).map(|i| Some(self.select_column(sel, i, scope))).collect()
}
fn rows(&self, values: &[&Node], scope: &ScopeStack) -> Vec<Option<Fact>> {
let mut out: Vec<Option<Fact>> = Vec::new();
for row in values.iter().filter_map(|v| self.row(v, scope)) {
for (i, f) in row.into_iter().enumerate() {
if i >= out.len() {
out.push(None);
}
if out[i].as_ref().is_none_or(|known| matches!(known.ty, Ty::Unknown)) {
out[i] = f;
}
}
}
out
}
fn argument(&self, n: &Node, i: usize, scope: &ScopeStack) -> Ctx {
let name = n.name.as_deref().unwrap_or("");
if !n.agg && !n.window && self.extras.function(name, n.args.len()).is_some() {
return Ctx::None;
}
let name = sqlean_alias(name);
let text = || Ctx::Typed(Some(Fact::new("text", true)));
let integer = || Ctx::Typed(Some(Fact::new("integer", true)));
let real = || Ctx::Typed(Some(Fact::new("real", true)));
let others = || {
let facts: Vec<Fact> = n.args.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, a)| self.type_of(a, scope)).collect();
let refs: Vec<&Fact> = facts.iter().collect();
let ty = shared(&refs);
Ctx::Typed(if matches!(ty, Ty::Unknown) { None } else { Some(Fact { ty, non_null: true }) })
};
match name {
"like" | "glob" | "regexp" | "match" | "upper" | "lower" | "trim" | "ltrim" | "rtrim" | "length" | "hex" | "unicode" | "quote" | "instr" | "replace" | "soundex"
| "printf" | "format" | "concat" | "concat_ws" | "date" | "time" | "datetime" | "strftime" | "julianday" | "unixepoch" | "timediff" | "json"
| "json_extract" | "json_type" | "json_valid" | "json_array_length" | "json_quote" | "json_pretty" | "json_insert" | "json_replace" | "json_set"
| "json_remove" | "json_patch" | "->" | "->>" => text(),
"substr" | "substring" => {
if i == 0 { text() } else { integer() }
}
"zeroblob" | "randomblob" | "char" => integer(),
"abs" | "round" | "acos" | "acosh" | "asin" | "asinh" | "atan" | "atan2" | "atanh" | "ceil" | "ceiling" | "cos" | "cosh" | "degrees" | "exp"
| "floor" | "ln" | "log" | "log10" | "log2" | "mod" | "pow" | "power" | "radians" | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc" => real(),
"coalesce" | "ifnull" | "nullif" | "min" | "max" => others(),
"lag" | "lead" if n.args.len() >= 3 && (i == 0 || i == 2) => {
let other = self.type_of(&n.args[2 - i], scope);
Ctx::Typed(if matches!(other.ty, Ty::Unknown) { None } else { Some(Fact { ty: other.ty, non_null: true }) })
}
"iif" | "if" => {
let values = iif_values(n.args.len());
if !values.contains(&i) {
Ctx::Bool
} else {
let facts: Vec<Fact> = values.iter().filter(|j| **j != i).filter_map(|j| n.args.get(*j)).map(|a| self.type_of(a, scope)).collect();
let ty = shared(&facts.iter().collect::<Vec<_>>());
Ctx::Typed(if matches!(ty, Ty::Unknown) { None } else { Some(Fact { ty, non_null: true }) })
}
}
"sum" | "avg" | "total" => real(),
"highlight" if i == 1 => integer(),
"highlight" if i > 1 => text(),
"bm25" if i > 0 => real(),
"vector" | "vector32" | "vector64" | "vector1bit" | "vector8" | "vector16" | "vectorb16" | "vector_extract" | "vector_distance_cos" | "vector_distance_l2" => text(),
_ => match name {
"left" | "right" | "text_left" | "text_right" | "repeat" | "text_repeat" | "lpad" | "rpad" | "text_lpad" | "text_rpad" if i == 1 => integer(),
"split_part" | "text_split" | "regexp_capture" if i == 2 => integer(),
"text_slice" | "text_substring" if i > 0 => integer(),
"text_replace" if i == 3 => integer(),
"encode" if i == 0 => Ctx::None,
"uuid_str" | "uuid_blob" | "uuid7_timestamp_ms" | "md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" | "encode" | "decode" | "levenshtein" | "dlevenshtein"
| "edit_distance" | "osa_distance" | "hamming" | "jaro_winkler" | "caverphone" | "phonetic_hash" | "rsoundex" | "translit" | "script_code" | "bit_length"
| "char_length" | "character_length" | "btrim" | "left" | "right" | "lpad" | "rpad" | "repeat" | "reverse" | "split_part" | "starts_with" | "strpos" | "translate"
| "regexp_like" | "regexp_substr" | "regexp_capture" | "regexp_replace" => text(),
t if t.starts_with("text_") => text(),
"median" | "percentile" | "percentile_25" | "percentile_75" | "percentile_90" | "percentile_95" | "percentile_99" | "stddev" | "stddev_pop" | "stddev_samp" | "variance"
| "var_pop" | "var_samp" => real(),
_ => Ctx::None,
},
}
}
fn cardinality(&self) -> (Cardinality, Option<String>) {
let t = self.tree;
if let Some(dml) = &t.dml {
if t.returning.is_none() {
return (Cardinality::None, None);
}
return match dml.kind.as_str() {
"insert" => {
if dml.rows == 1 {
let triggered = |events: i32| self.skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & events != 0);
let declared_ignore = dml.on_error == "default" && self.tree.tables.get(&dml.table).is_some_and(|t| t.ignores);
let can_skip = dml.on_error == "ignore"
|| declared_ignore
|| dml.upserts.iter().any(|u| !u.do_update || u.where_.is_some() || triggered(TRIGGER_ROW_UPDATE))
|| triggered(TRIGGER_ROW_INSERT);
if can_skip { (Cardinality::AtMostOne, Some("ON CONFLICT DO NOTHING, OR IGNORE, a constraint declared ON CONFLICT IGNORE, a DO UPDATE with a WHERE, or a BEFORE trigger's RAISE(IGNORE) can insert no row".into())) } else { (Cardinality::One, None) }
} else if dml.rows > 1 {
(Cardinality::Many, Some(format!("a VALUES list of {} rows returns {} rows", dml.rows, dml.rows)))
} else {
(Cardinality::Many, Some("an INSERT ... SELECT returns a row per row it reads".into()))
}
}
_ => {
match self.pinned_by_name(&dml.table, dml.where_.as_ref()) {
Ok(()) => (Cardinality::AtMostOne, None),
Err(why) => (Cardinality::Many, Some(why)),
}
}
};
}
let Some(sel) = &t.statement else { return (Cardinality::None, None) };
match self.exactly_one(sel) {
Ok(()) => (Cardinality::One, None),
Err(one_why) => match self.at_most_one(sel) {
Ok(()) => (Cardinality::AtMostOne, Some(one_why)),
Err(why) => (Cardinality::Many, Some(why)),
},
}
}
fn exactly_one(&self, sel: &Sel) -> Result<(), String> {
let keeps = |n: &Node, least: i64| integer(n).is_some_and(|n| n >= least);
if sel.limit.as_ref().is_some_and(|l| !keeps(l, 1)) || sel.offset.as_ref().is_some_and(|o| integer(o) != Some(0)) {
return Err("a LIMIT or an OFFSET can remove the row (LIMIT 0, OFFSET 1)".into());
}
self.one_before_limit(sel)
}
fn one_before_limit(&self, sel: &Sel) -> Result<(), String> {
if sel.prior.is_some() {
return Err("a set operation (UNION, INTERSECT, EXCEPT) returns any number of rows".into());
}
if sel.values && !sel.rows.is_empty() {
return Err("a VALUES list returns a row per row it lists".into());
}
if sel.values {
return Ok(());
}
if !sel.group_by.is_empty() {
return Err("GROUP BY returns one row per group, and none when nothing matches".into());
}
if sel.having.is_some() {
return Err("HAVING can remove the row".into());
}
if sel.aggregate && sel.columns.iter().any(|c| has_aggregate(&c.expr)) {
return Ok(());
}
if sel.from.is_empty() && sel.where_.is_none() {
return Ok(());
}
if !sel.from.is_empty() && self.never_empty(sel) && self.arm_at_most_one(sel).is_ok() {
return Ok(());
}
Err("a FROM returns a row per row it matches, and only an aggregate with no GROUP BY collapses them to one".into())
}
fn never_empty(&self, sel: &Sel) -> bool {
let holds = |t: &Node| match (t.op.as_str(), t.left.as_deref().and_then(integer), t.right.as_deref().and_then(integer)) {
("=", Some(l), Some(r)) => l == r,
_ => integer(t).is_some_and(|n| n != 0),
};
sel.from.iter().all(|f| !f.right && (f.outer || f.subquery.as_ref().is_some_and(|sub| !sub.values && self.exactly_one(sub).is_ok())))
&& conjuncts(sel.where_.as_ref()).iter().all(|t| t.outer_on || holds(t))
}
fn at_most_one(&self, sel: &Sel) -> Result<(), String> {
if sel.limit.as_ref().and_then(integer).is_some_and(|n| (0..=1).contains(&n)) {
return Ok(());
}
if !sel.values && self.one_before_limit(sel).is_ok() {
return Ok(());
}
if let Some(prior) = &sel.prior {
let drawn = match sel.op.as_deref() {
Some("intersect") => self.at_most_one(prior).is_ok() || self.arm_at_most_one(sel).is_ok(),
Some("except") => self.at_most_one(prior).is_ok(),
_ => false,
};
return if drawn { Ok(()) } else { Err("a set operation (UNION, INTERSECT, EXCEPT) returns any number of rows".into()) };
}
self.arm_at_most_one(sel)
}
fn arm_at_most_one(&self, sel: &Sel) -> Result<(), String> {
if sel.values {
return Err("a VALUES list returns a row per row it lists".into());
}
if !sel.group_by.is_empty() {
if sel.from.iter().all(|f| !f.right) && self.determined(sel, false).iter().all(|d| *d) {
return Ok(());
}
let constant = self.determined(sel, true);
if sel.group_by.iter().all(|g| self.pinned(sel, g, &constant)) {
return Ok(());
}
return Err("GROUP BY returns one row per group; the engine proves one group only when every GROUP BY expression is pinned to one value: a column of a relation whose unique key the WHERE pins, or a column the WHERE equates to a value".into());
}
if sel.having.is_some() {
return Err("HAVING leaves a row per group".into());
}
if sel.from.is_empty() {
return Err("a SELECT with no FROM and a WHERE can return no row or one, and the engine proves that only through a LIMIT".into());
}
if sel.from.iter().any(|f| f.right) {
return Err("a RIGHT or FULL JOIN returns a row for each side that matches nothing".into());
}
let determined = self.determined(sel, false);
if determined.iter().all(|d| *d) {
return Ok(());
}
if sel.distinct {
let constant = self.determined(sel, true);
if !sel.columns.is_empty() && sel.columns.iter().all(|c| self.pinned(sel, &c.expr, &constant)) {
return Ok(());
}
}
let i = determined.iter().position(|d| !d).unwrap_or(0);
let f = &sel.from[i];
let Some(table) = f.table.as_deref().filter(|_| f.subquery.is_none() && !f.tab_func) else {
return Err(format!("`{}` in the FROM is a subquery or a table-valued function that returns any number of rows", f.alias.as_deref().or(f.table.as_deref()).unwrap_or("?")));
};
let keys = self.tree.tables.get(table).map(|t| t.unique_keys.clone()).unwrap_or_default();
if keys.is_empty() {
return Err(format!("`{table}` has no unique index the engine can read, so nothing bounds the rows a WHERE matches"));
}
let shown: Vec<String> = keys.iter().map(|k| format!("({})", k.join(", "))).collect();
if sel.from.len() == 1 {
Err(format!("the WHERE does not equate every column of a unique key of `{table}` — it has {}", shown.join(", ")))
} else {
let name = f.alias.as_deref().unwrap_or(table);
Err(format!("a join returns a row per pair it matches, and the WHERE and ON clauses do not equate every column of a unique key of `{name}` to values or to columns of relations pinned to one row — it has {}", shown.join(", ")))
}
}
fn determined(&self, sel: &Sel, constant: bool) -> Vec<bool> {
let derived = self.derived_keys(sel);
self.determined_from(sel, vec![false; sel.from.len()], &derived, constant)
}
fn derived_keys(&self, sel: &Sel) -> Vec<Vec<Vec<i64>>> {
sel.from.iter().map(|f| f.subquery.as_ref().map(|sub| self.output_keys(sub)).unwrap_or_default()).collect()
}
fn determined_from(&self, sel: &Sel, mut done: Vec<bool>, derived: &[Vec<Vec<i64>>], constant: bool) -> Vec<bool> {
let n = sel.from.len();
let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
let terms = conjuncts(sel.where_.as_ref());
loop {
let mut changed = false;
for i in 0..n {
if done[i] {
continue;
}
let f = &sel.from[i];
let pinned = if let Some(sub) = &f.subquery {
let usable: Vec<&Node> = terms.iter().copied().filter(|t| !t.outer_on || (!constant && t.join == f.cursor)).collect();
!(constant && f.outer) && (self.at_most_one(sub).is_ok() || self.derived_pinned(&derived[i], f.cursor, &usable, &done, &index))
} else if let (Some(table), false, false) = (f.table.as_deref(), f.tab_func, f.virtual_) {
let usable: Vec<&Node> = terms.iter().copied().filter(|t| !t.outer_on || (!constant && t.join == f.cursor)).collect();
self.key_pinned(table, f.cursor, &usable, &done, &index)
} else {
false
};
if pinned {
done[i] = true;
changed = true;
}
}
if !changed {
return done;
}
}
}
fn key_pinned(&self, table: &str, cursor: i64, terms: &[&Node], done: &[bool], index: &HashMap<i64, usize>) -> bool {
let Some(info) = self.tree.tables.get(table) else { return false };
let pins: Vec<&str> = terms.iter().filter_map(|t| self.pins(t, cursor, done, index)).collect();
info.unique_keys.iter().any(|key| !key.is_empty() && key.iter().all(|c| pins.iter().any(|p| p.eq_ignore_ascii_case(c))))
}
fn derived_pinned(&self, keys: &[Vec<i64>], cursor: i64, terms: &[&Node], done: &[bool], index: &HashMap<i64, usize>) -> bool {
let pinned: Vec<i64> = terms.iter().filter_map(|t| self.pinned_column(t, cursor, done, index)).map(|c| c.index).collect();
keys.iter().any(|key| !key.is_empty() && key.iter().all(|p| pinned.contains(p)))
}
fn output_keys(&self, sel: &Sel) -> Vec<Vec<i64>> {
if let Some(prior) = &sel.prior {
return self.compound_keys(sel, prior);
}
if sel.values {
return Vec::new();
}
let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
let position = |found: &dyn Fn(&Node) -> bool| sel.columns.iter().position(|c| c.expr.op == "column" && index.contains_key(&c.expr.cursor) && found(&c.expr)).map(|p| p as i64);
let mut keys = Vec::new();
if !sel.group_by.is_empty() {
let key: Option<Vec<i64>> = sel.group_by.iter().map(|g| if g.op == "column" { position(&|e: &Node| e.cursor == g.cursor && e.index == g.index) } else { None }).collect();
keys.extend(key);
return keys;
}
if sel.distinct && !sel.columns.is_empty() && sel.columns.iter().all(|c| c.expr.op == "column" && index.contains_key(&c.expr.cursor)) {
keys.push((0..sel.columns.len() as i64).collect());
}
if sel.from.iter().any(|f| f.right) {
return keys;
}
let derived = self.derived_keys(sel);
let n = sel.from.len();
for (r, f) in sel.from.iter().enumerate() {
if f.tab_func || f.virtual_ {
continue;
}
let mut seed = vec![false; n];
seed[r] = true;
if !self.determined_from(sel, seed, &derived, false).iter().all(|d| *d) {
continue;
}
if f.subquery.is_some() {
for key in &derived[r] {
keys.extend(key.iter().map(|p| position(&|e: &Node| e.cursor == f.cursor && e.index == *p)).collect::<Option<Vec<i64>>>());
}
} else if let Some(info) = f.table.as_deref().and_then(|t| self.tree.tables.get(t)) {
let fixed = |c: &str| {
let none = vec![false; n];
conjuncts(sel.where_.as_ref()).iter().filter(|t| !t.outer_on).any(|t| self.pinned_column(t, f.cursor, &none, &index).and_then(|col| col.column.as_deref()).is_some_and(|name| name.eq_ignore_ascii_case(c)))
};
for key in info.unique_keys.iter().filter(|k| !k.is_empty()) {
keys.extend(
key.iter()
.filter_map(|c| match position(&|e: &Node| e.cursor == f.cursor && e.column.as_deref().is_some_and(|name| name.eq_ignore_ascii_case(c))) {
Some(p) => Some(Some(p)),
None if fixed(c) => None,
None => Some(None),
})
.collect::<Option<Vec<i64>>>(),
);
}
}
}
keys
}
fn compound_keys(&self, sel: &Sel, prior: &Sel) -> Vec<Vec<i64>> {
let op = sel.op.as_deref().unwrap_or("");
let mut keys = Vec::new();
if op == "intersect" || op == "except" {
keys.extend(self.output_keys(prior));
}
if op != "union all" {
let mut arms = vec![sel];
let mut at = Some(prior);
while let Some(arm) = at {
arms.push(arm);
at = arm.prior.as_deref();
}
let width = sel.columns.len();
let alike = width > 0
&& arms.iter().all(|arm| !arm.values && arm.columns.len() == width)
&& (0..width).all(|i| {
let first = &sel.columns[i].expr;
first.op == "column" && arms.iter().all(|arm| {
let e = &arm.columns[i].expr;
e.op == "column" && e.aff == first.aff && e.coll.as_deref().unwrap_or("BINARY").eq_ignore_ascii_case(first.coll.as_deref().unwrap_or("BINARY"))
})
});
if alike {
keys.push((0..width as i64).collect());
}
}
keys
}
fn pins<'n>(&self, t: &'n Node, cursor: i64, done: &[bool], index: &HashMap<i64, usize>) -> Option<&'n str> {
self.pinned_column(t, cursor, done, index).and_then(|col| col.column.as_deref())
}
fn pinned_column<'n>(&self, t: &'n Node, cursor: i64, done: &[bool], index: &HashMap<i64, usize>) -> Option<&'n Node> {
if t.op != "=" {
return None;
}
let (l, r) = (t.left.as_deref()?, t.right.as_deref()?);
let collation = column_of(l).or_else(|| column_of(r)).and_then(|c| c.coll.as_deref()).unwrap_or("BINARY");
[(l, r), (r, l)].into_iter().find_map(|(col, other)| {
let value = col.op == "column"
&& col.cursor == cursor
&& !has_op(other, "collate")
&& keeps_column(col, other)
&& (collation.eq_ignore_ascii_case("BINARY") || col.coll.as_deref().is_some_and(|c| c.eq_ignore_ascii_case(collation)))
&& !self.calls_volatile(other)
&& other.select.is_none()
&& cursors(other).is_some_and(|read| read.iter().all(|c| *c != cursor && index.get(c).is_none_or(|i| done[*i])));
value.then_some(col)
})
}
fn pinned(&self, sel: &Sel, e: &Node, constant: &[bool]) -> bool {
let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
if e.op == "column" {
if index.get(&e.cursor).is_some_and(|i| constant[*i]) {
return true;
}
let terms = conjuncts(sel.where_.as_ref());
return terms.iter().filter(|t| !t.outer_on).filter_map(|t| self.pins(t, e.cursor, constant, &index)).any(|c| e.column.as_deref().is_some_and(|name| name.eq_ignore_ascii_case(c)));
}
e.select.is_none() && !self.calls_volatile(e) && cursors(e).is_some_and(|read| read.iter().all(|c| !index.contains_key(c)))
}
fn pinned_by_name(&self, table: &str, where_: Option<&Node>) -> Result<(), String> {
let equated = self.equated(where_);
let Some(info) = self.tree.tables.get(table) else { return Err(format!("`{table}` is not a table the engine can read")) };
let names: HashSet<String> = equated.iter().map(|(_, n)| n.to_ascii_lowercase()).collect();
if info.unique_keys.iter().any(|key| !key.is_empty() && key.iter().all(|c| names.contains(&c.to_ascii_lowercase()))) {
return Ok(());
}
if info.unique_keys.is_empty() {
return Err(format!("`{table}` has no unique index the engine can read, so nothing bounds the rows a WHERE matches"));
}
let shown: Vec<String> = info.unique_keys.iter().map(|k| format!("({})", k.join(", "))).collect();
Err(format!("the WHERE does not equate every column of a unique key of `{table}` — it has {}", shown.join(", ")))
}
fn equated(&self, where_: Option<&Node>) -> HashSet<(i64, String)> {
let mut out = HashSet::new();
for n in conjuncts(where_) {
if n.op != "=" || n.outer_on {
continue;
}
if let (Some(l), Some(r)) = (n.left.as_deref(), n.right.as_deref()) {
for (col, other) in [(l, r), (r, l)] {
if col.op == "column" && !reads_column(other) && !has_op(other, "collate") && keeps_column(col, other) && !self.calls_volatile(other) {
if let Some(name) = &col.column {
out.insert((col.cursor, name.clone()));
}
}
}
}
}
out
}
fn calls_volatile(&self, n: &Node) -> bool {
const VOLATILE: &[&str] = &["random", "randomblob", "changes", "total_changes", "last_insert_rowid", "date", "time", "datetime", "julianday", "unixepoch", "strftime", "timediff"];
if n.op == "function" {
if n.agg || n.window || n.over {
return true;
}
let name = n.name.as_deref().unwrap_or("").to_ascii_lowercase();
if VOLATILE.contains(&name.as_str()) || self.extras.function(&name, n.args.len()).is_some() || !KNOWN_FUNCTIONS.contains(&name.as_str()) {
return true;
}
}
n.left.as_deref().is_some_and(|x| self.calls_volatile(x)) || n.right.as_deref().is_some_and(|x| self.calls_volatile(x)) || n.list.iter().any(|x| self.calls_volatile(x)) || n.args.iter().any(|x| self.calls_volatile(x))
}
}
fn keeps_column(col: &Node, other: &Node) -> bool {
let numeric = |a: &str| matches!(a, "integer" | "real" | "numeric");
let none = |a: &str| matches!(a, "blob" | "none");
numeric(&col.aff) || none(&other.aff) || (col.aff == "text" && other.aff == "text")
}
fn column_of(n: &Node) -> Option<&Node> {
match n.op.as_str() {
"column" => Some(n),
"cast" | "pos" => n.left.as_deref().and_then(column_of),
_ => None,
}
}
fn literal_text(n: &Node) -> Option<&str> {
if n.op == "string" { n.value.as_deref() } else { None }
}
fn iif_values(count: usize) -> Vec<usize> {
let mut out: Vec<usize> = (1..count).step_by(2).collect();
if count >= 3 && count % 2 == 1 {
out.push(count - 1);
}
out
}
fn holds_current_row(n: &Node) -> bool {
let start = matches!(n.frame_start.as_deref(), Some("unbounded" | "preceding" | "current"));
let end = matches!(n.frame_end.as_deref(), Some("unbounded" | "following" | "current"));
let exclude = matches!(n.exclude.as_deref(), Some("no" | "ties"));
n.over && !n.filter && start && end && exclude
}
fn total_nulls(arg: &Fact) -> Nulls {
if is_integral(&arg.ty) { Nulls::Never } else { Nulls::Always }
}
fn current_time(args: &[Node]) -> bool {
let Some((value, modifiers)) = args.split_first() else { return true };
let now = literal_text(value).is_some_and(|v| v.eq_ignore_ascii_case("now"))
|| (value.op == "function" && value.args.is_empty() && matches!(value.name.as_deref(), Some("current_timestamp" | "current_date" | "current_time")));
let number = if matches!(value.op.as_str(), "integer" | "float") { value.value.as_deref().and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) } else { None };
let mut modifiers = modifiers.iter().map(literal_text).peekable();
let julian_day = match number {
Some(v) if modifiers.peek().is_some_and(|m| m.is_some_and(|m| m.eq_ignore_ascii_case("unixepoch"))) => {
modifiers.next();
v / 86_400.0 + 2_440_587.5
}
Some(v) => v,
None if now => 0.0,
None => return false,
};
let mut days = 0.0;
for m in modifiers {
let Some(m) = m else { return false };
let m = m.to_ascii_lowercase();
days += match m.as_str() {
"subsec" | "subsecond" => 0.0,
"localtime" | "utc" => 1.0,
"start of day" | "start of month" | "start of year" => 366.0,
_ if m.len() == 9 && m.starts_with("weekday ") && matches!(m.as_bytes()[8], b'0'..=b'6') => 7.0,
_ => match shift_days(&m) {
Some(d) => d,
None => return false,
},
};
}
if now {
days < 365_000.0
} else {
let margin = if days > 0.0 { days + 400.0 } else { 0.0 };
julian_day - margin >= 0.0 && julian_day + margin < 5_373_484.0
}
}
fn shift_days(m: &str) -> Option<f64> {
let (number, unit) = m.split_once(' ')?;
let unit = unit.trim_start_matches(' ');
let unit = unit.strip_suffix('s').unwrap_or(unit);
let days = match unit {
"second" => 1.0 / 86_400.0,
"minute" => 1.0 / 1_440.0,
"hour" => 1.0 / 24.0,
"day" => 1.0,
"month" => 31.0,
"year" => 366.0,
_ => return None,
};
let digits = number.strip_prefix(['+', '-']).unwrap_or(number);
let (whole, fraction) = digits.split_once('.').unwrap_or((digits, "0"));
let all_digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
if !all_digits(whole) || !all_digits(fraction) {
return None;
}
Some(digits.parse::<f64>().ok()? * days)
}
fn printf_writes(format: &str) -> bool {
let b = format.as_bytes();
let at = |i: usize| b.get(i).copied().unwrap_or(0);
let mut i = 0;
loop {
match at(i) {
0 => return false,
b'%' => {}
_ => return true,
}
i += 1;
if at(i) == 0 {
return true;
}
let mut c = at(i);
loop {
match c {
b'-' | b'+' | b' ' | b'#' | b'!' | b'0' | b',' => {}
b'l' => {
i += 1;
if at(i) == b'l' {
i += 1;
}
c = at(i);
break;
}
b'1'..=b'9' => {
while at(i + 1).is_ascii_digit() {
i += 1;
}
if !matches!(at(i + 1), b'.' | b'l') {
i += 1;
c = at(i);
break;
}
}
b'*' => {
if !matches!(at(i + 1), b'.' | b'l') {
i += 1;
c = at(i);
break;
}
}
b'.' => {
i += 1;
if at(i) == b'*' {
i += 1;
} else {
while at(i).is_ascii_digit() {
i += 1;
}
}
if at(i) != b'l' {
c = at(i);
break;
}
i -= 1;
}
_ => break,
}
i += 1;
c = at(i);
if c == 0 {
break;
}
}
match c {
b'%' => return true,
b's' | b'E' | b'u' | b'G' | b'w' | b'x' | b'c' | b'z' | b'd' | b'e' | b'f' | b'g' | b'Q' | b'i' | b'X' | b'n' | b'o' | b'p' | b'q' | b'r' => i += 1,
_ => return false,
}
}
}
fn strftime_format(format: &str) -> bool {
let mut bytes = format.bytes();
while let Some(b) = bytes.next() {
if b == b'%' && !bytes.next().is_some_and(|c| b"deFfHkIljJmMpPRsSTuwWY%".contains(&c)) {
return false;
}
}
true
}
fn sqlean_alias(name: &str) -> &str {
match name {
"fuzzy_caver" => "caverphone",
"fuzzy_damlev" => "dlevenshtein",
"fuzzy_editdist" => "edit_distance",
"fuzzy_hamming" => "hamming",
"fuzzy_jarowin" => "jaro_winkler",
"fuzzy_leven" => "levenshtein",
"fuzzy_osadist" => "osa_distance",
"fuzzy_phonetic" => "phonetic_hash",
"fuzzy_rsoundex" => "rsoundex",
"fuzzy_script" => "script_code",
"fuzzy_soundex" => "soundex",
"fuzzy_translit" => "translit",
"stats_median" => "median",
"stats_perc" => "percentile",
"stats_p25" => "percentile_25",
"stats_p75" => "percentile_75",
"stats_p90" => "percentile_90",
"stats_p95" => "percentile_95",
"stats_p99" => "percentile_99",
"stats_stddev" => "stddev",
"stats_stddev_pop" => "stddev_pop",
"stats_stddev_samp" => "stddev_samp",
"stats_var" => "variance",
"stats_var_pop" => "var_pop",
"stats_var_samp" => "var_samp",
_ => match name.strip_prefix("crypto_").or_else(|| name.strip_prefix("math_")) {
Some(base @ ("md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" | "encode" | "decode")) if name.starts_with("crypto_") => base,
Some(
base @ ("acos" | "acosh" | "asin" | "asinh" | "atan" | "atan2" | "atanh" | "ceil" | "cos" | "cosh" | "degrees" | "exp" | "floor" | "ln" | "log" | "log10" | "log2" | "mod" | "pi"
| "pow" | "radians" | "round" | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc"),
) if name.starts_with("math_") => base,
_ => name,
},
}
}
const KNOWN_FUNCTIONS: &[&str] = &[
"coalesce", "ifnull", "nullif", "iif", "if", "min", "max", "abs", "round", "length", "instr", "unicode", "json_array_length", "json_valid", "octet_length", "sign",
"like", "glob", "regexp", "match", "likely", "unlikely", "likelihood", "upper", "lower", "trim", "ltrim", "rtrim", "substr", "substring", "replace", "char",
"printf", "format", "concat", "concat_ws", "json", "jsonb", "json_array", "json_object", "json_insert", "json_replace", "json_set", "json_remove", "json_patch",
"json_quote", "json_pretty", "json_type", "hex", "quote", "typeof", "soundex", "zeroblob", "json_extract", "jsonb_extract", "->", "->>", "acos", "acosh", "asin", "asinh",
"atan", "atan2", "atanh", "ceil", "ceiling", "cos", "cosh", "degrees", "exp", "floor", "ln", "log", "log10", "log2", "mod", "pow", "power", "radians", "sin",
"sinh", "sqrt", "tan", "tanh", "trunc", "pi",
];
fn integer(n: &Node) -> Option<i64> {
if n.op == "integer" { n.value.as_deref().and_then(|v| v.parse().ok()) } else { None }
}
fn integer_literal_fits(n: &Node) -> bool {
n.value.as_deref().is_none_or(|v| v.starts_with("0x") || v.starts_with("0X") || v.parse::<i64>().is_ok())
}
fn is_two_to_the_63(n: &Node) -> bool {
n.op == "integer" && n.value.as_deref().and_then(|v| v.parse::<u64>().ok()) == Some(1 << 63)
}
fn conjuncts(n: Option<&Node>) -> Vec<&Node> {
let mut out = Vec::new();
let mut stack: Vec<&Node> = n.into_iter().collect();
while let Some(n) = stack.pop() {
if n.op == "and" {
stack.extend(n.left.as_deref());
stack.extend(n.right.as_deref());
} else {
out.push(n);
}
}
out
}
fn cursors(n: &Node) -> Option<Vec<i64>> {
if n.select.is_some() {
return None;
}
let mut out = Vec::new();
if n.op == "column" {
out.push(n.cursor);
}
for child in n.left.iter().chain(n.right.iter()).map(|b| b.as_ref()).chain(n.list.iter()).chain(n.args.iter()) {
out.extend(cursors(child)?);
}
Some(out)
}
fn arithmetic(l: &Ty, r: &Ty) -> Ty {
match (scalar_name(l), scalar_name(r)) {
(Some("integer" | "int8"), Some("integer" | "int8")) => Ty::Scalar { name: "integer".into() },
_ => Ty::Scalar { name: "real".into() },
}
}
fn has_op(n: &Node, op: &str) -> bool {
n.op == op || n.left.as_deref().is_some_and(|x| has_op(x, op)) || n.right.as_deref().is_some_and(|x| has_op(x, op)) || n.list.iter().any(|x| has_op(x, op)) || n.args.iter().any(|x| has_op(x, op))
}
fn has_aggregate(n: &Node) -> bool {
if n.op == "function" && n.agg && !n.window {
return true;
}
n.left.as_deref().is_some_and(has_aggregate) || n.right.as_deref().is_some_and(has_aggregate) || n.list.iter().any(has_aggregate) || n.args.iter().any(has_aggregate)
}
fn reads_column(n: &Node) -> bool {
if n.op == "column" {
return true;
}
n.left.as_deref().is_some_and(reads_column) || n.right.as_deref().is_some_and(reads_column) || n.list.iter().any(reads_column) || n.args.iter().any(reads_column) || n.select.is_some()
}
fn is_vector(n: &Option<Box<Node>>) -> bool {
n.as_deref().is_some_and(|n| n.op == "vector")
}
fn outer_type(ctx: &Ctx) -> Ctx {
match ctx {
Ctx::Typed(Some(f)) => Ctx::Typed(Some(f.clone())),
_ => Ctx::None,
}
}
fn i_of(slot: Position) -> usize {
match slot {
Position::Arg(i) => i,
_ => 0,
}
}
fn is_boolean_declared(declared: &str) -> bool {
let d = declared.trim();
d.eq_ignore_ascii_case("boolean") || d.eq_ignore_ascii_case("bool")
}
pub fn affinity(declared: &str) -> &'static str {
let d = declared.to_ascii_uppercase();
if d.contains("INT") {
"integer"
} else if d.contains("CHAR") || d.contains("CLOB") || d.contains("TEXT") {
"text"
} else if d.contains("BLOB") || d.is_empty() {
"blob"
} else if d.contains("REAL") || d.contains("FLOA") || d.contains("DOUB") {
"real"
} else {
"numeric"
}
}
#[derive(Clone)]
enum Ctx {
Typed(Option<Fact>),
Row(Vec<Option<Fact>>),
Bool,
None,
}
#[derive(Clone, Copy)]
enum Position {
Left,
Right,
List(usize),
Arg(usize),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_row_assigned_fewer_values_than_columns_is_the_database_s_error() {
let ddl = vec!["create table t1 (a integer primary key, b, c, d)".to_string(), "create table t2 (w, x, y)".to_string()];
for sql in ["update t1 set (b, c, d) = (select x, y from t2 where w = a)", "update t1 set (a, a, a, b) = (select 99, 100)"] {
let a = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
assert!(!a.diagnostics.is_empty(), "{sql}: {a:?}");
}
}
fn ddl() -> Vec<String> {
vec![
"create table users (id integer primary key, name text not null, email text unique, score real, avatar blob, created_at text not null default current_timestamp)".to_string(),
"create table posts (id integer primary key, user_id integer not null references users(id), title text not null, body text)".to_string(),
]
}
fn analysis(sql: &str) -> Analysis {
analyze_ddl(sql, &ddl(), &Extras::default()).analysis
}
fn marked(sql: &str, ddl: &[String], names: &[&str]) -> Analysis {
let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
run(sql, &lex::lex(sql, Dialect::Sqlite).unwrap(), ddl, &Extras::default(), &names).analysis
}
#[test]
fn the_facts_are_read_for_every_table_the_statement_names_and_no_with_query() {
let mut schema = ddl();
schema.push("create table tags (id integer primary key, post_id integer)".into());
schema.push("create view titles as select title from posts".into());
let tables = |sql: &str| {
let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
let mut t = a.tables.expect("the tree names its tables");
t.read.sort();
t.read.dedup();
(t.read, t.write)
};
let names = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
assert_eq!(tables("select u.id, (select count(*) from posts p where p.user_id = u.id) as n from USERS u where exists (select 1 from tags t where t.id = u.id)"), (names(&["posts", "tags", "users"]), vec![]));
assert_eq!(tables("with recent as (select user_id from posts) select title from titles join recent on true"), (names(&["posts", "titles"]), vec![]));
assert_eq!(tables("select value from json_each('[1]')"), (vec![], vec![]));
assert_eq!(tables("select s.n from (select count(*) as n from posts) s join titles on true"), (names(&["posts", "titles"]), vec![]));
assert_eq!(tables("update users set score = (with recursive c(n) as (select 1 union all select n + 1 from c where n < 3) select count(*) from c)"), (vec![], names(&["users"])));
assert_eq!(tables("insert into tags (post_id) select id from posts"), (names(&["posts"]), names(&["tags"])));
assert_eq!(tables("update users set name = (select max(title) from posts) where id = 1"), (names(&["posts"]), names(&["users"])));
assert_eq!(tables("delete from users where id in (select user_id from posts)"), (names(&["posts"]), names(&["users"])));
}
#[test]
fn a_key_declared_on_conflict_replace_is_read_from_sqlite_s_parse_however_the_ddl_spells_it() {
let replaces = |clause: &str| {
let ddl = vec![format!("create table p (id integer primary key, email text {clause})")];
let t = tree::analyze(&ddl, "insert into p (email) values (?1)", "insert into p (email) values (?)", &[], None).expect("the tree parses");
assert!(t.error.is_none(), "{clause}: {:?}", t.error);
t.tables["p"].replaces
};
for clause in ["unique on conflict replace", "unique on conflict\n replace", "UNIQUE On Conflict RePlace", "unique on /* the old row goes */ conflict -- and is deleted\n replace"] {
assert!(replaces(clause), "{clause}");
}
for clause in ["unique", "not null on conflict replace default '' unique", "unique on conflict ignore"] {
assert!(!replaces(clause), "{clause}");
}
}
#[test]
fn the_schema_replay_reaches_no_file_and_sets_no_pragma() {
let dir = std::env::temp_dir().join(format!("reylo-sqlite-replay-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let (attached, vacuumed) = (dir.join("attached.db"), dir.join("vacuumed.db"));
let ddl = vec![
format!("create table t (a integer not null); attach '{}' as x; create table x.y (z)", attached.display()),
format!("create table u (b); vacuum into '{}'", vacuumed.display()),
"create table v (c); pragma hard_heap_limit = 1; create table w (d)".to_string(),
];
let a = analyze_ddl("select a, b, c from t, u, v", &ddl, &Extras::default()).analysis;
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
assert!(!attached.exists() && !vacuumed.exists());
for _ in 0..2 {
let refused = analyze_ddl("select d from w", &ddl, &Extras::default()).analysis;
let messages: Vec<&str> = refused.diagnostics.iter().map(|d| d.message.as_str()).collect();
assert_eq!(messages.first(), Some(&"no such table: w"), "{messages:?}");
assert!(messages.contains(&"The schema replay skipped statement 1: not authorized"), "{messages:?}");
assert!(messages.contains(&"The schema replay skipped statement 3: not authorized"), "{messages:?}");
}
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn the_tree_describes_the_schema_tables_alone_and_no_with_query() {
let described = |sql: &str| {
let t = tree::analyze(&ddl(), sql, sql, &[], None).expect("the tree parses");
assert!(t.error.is_none(), "{sql}: {:?}", t.error);
let mut names = t.tables.into_keys().collect::<Vec<_>>();
names.sort();
names
};
assert_eq!(described("with recent as (select user_id from posts) select user_id from recent"), ["posts"]);
assert_eq!(described("with recursive c (n) as (select 1 union all select n + 1 from c where n < 3) select n from c"), Vec::<String>::new());
assert_eq!(described("with users as (select id from main.users) select id from users"), ["users"]);
let nested = "with recursive t (n, x, j) as (select 1, 'a', json_array('a') union all select n + 1, null, \
(with recursive u (m, y) as (select 1, t.x union all select m + 1, y from u where m < 2) select json_group_array(y) from u) \
from t where n < 3) select n, x, j from t";
assert_eq!(described(nested), Vec::<String>::new());
assert!(analysis(nested).diagnostics.is_empty());
}
#[test]
fn a_statement_as_deep_as_the_engine_reads_is_typed_and_one_level_past_it_is_an_error_at_the_bound() {
let ddl = vec!["create table users (id integer primary key, name text not null, nick text)".to_string()];
let small = |sql: String| std::thread::scope(|s| std::thread::Builder::new().stack_size(256 << 10).spawn_scoped(s, || analyze_ddl(&sql, &ddl, &Extras::default()).analysis).unwrap().join().unwrap());
for (shape, n) in [("sum", 350), ("and_or", 348), ("case", 348), ("coalesce", 349), ("subquery", 23)] {
let at = small(crate::stack::nested(shape, n));
assert!(at.diagnostics.is_empty() && at.kind == Some(StatementKind::Select), "{shape} at {n}: {:?}", at.diagnostics);
let past = small(crate::stack::nested(shape, n + 1));
assert_eq!(past.diagnostics.iter().map(|d| d.message.as_str()).collect::<Vec<_>>(), ["Expression tree is too large (maximum depth 350)"], "{shape} at {}", n + 1);
}
let list = (0..5_000).map(|i| i.to_string()).collect::<Vec<_>>().join(", ");
assert!(small(format!("select id from users where id in ({list})")).diagnostics.is_empty());
}
fn col(a: &Analysis, name: &str) -> (String, bool) {
let c = a.columns.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no column {name}"));
(affinity_of(&c.ty).unwrap_or("unknown").to_string(), c.nullable)
}
#[test]
fn returning_reads_a_value_the_statement_wrote_to_the_row() {
let nullable = |sql: &str| analysis(sql).columns.iter().map(|c| c.nullable).collect::<Vec<_>>();
assert_eq!(nullable("insert into users (name, email, score) values ('a', upper(:e), 1.5) returning email, score, avatar, upper(email) as loud"), [false, false, true, false]);
assert_eq!(nullable("insert into users (name, email) values ('a', :e) returning email"), [true]);
assert_eq!(nullable("update users set email = :e returning email"), [true]);
assert_eq!(nullable("insert into users (name, email) values ('a', 'x'), ('b', null) returning email"), [true]);
assert_eq!(nullable("insert into users (name, email) values ('a', 'x'), ('b', 'y') returning email"), [false]);
assert_eq!(nullable("insert into users (name, email) select name, email from users returning email"), [true]);
assert_eq!(nullable("insert into users (name, email) select name, name from users returning email"), [false]);
assert_eq!(nullable("update users set email = 'x', score = coalesce(score, 0) where id = 1 returning email, score, avatar"), [false, false, true]);
assert_eq!(nullable("update users set email = name returning email"), [false]);
assert_eq!(nullable("update users set email = score returning email"), [true]);
assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do update set email = 'y' returning email"), [false]);
assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do update set name = 'b' returning email"), [true]);
assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do nothing returning email"), [false]);
let triggered = |sql: &str, trigger: &str| {
let mut schema = ddl();
schema.push(trigger.to_string());
analyze_ddl(sql, &schema, &Extras::default()).analysis.columns.iter().map(|c| c.nullable).collect::<Vec<_>>()
};
assert_eq!(triggered("update users set email = 'x' returning email", "create trigger b before update on users begin select 1; end"), [true]);
assert_eq!(triggered("insert into users (name, email) values ('a', 'x') on conflict (email) do update set email = 'y' returning email", "create trigger b before update on users begin select 1; end"), [true]);
assert_eq!(triggered("insert into users (name, email) values ('a', 'x') returning email", "create trigger b before update on users begin select 1; end"), [false]);
assert_eq!(triggered("insert into users (name, email) values ('a', 'x') returning email", "create trigger a after insert on users begin update users set email = null; end"), [false]);
assert_eq!(nullable("delete from users where id = 1 returning email"), [true]);
assert_eq!(nullable("update users set email = 'x' returning (select email from users where id = 2) as other"), [true]);
}
fn param(a: &Analysis, name: &str) -> String {
let p = a.params.iter().find(|p| p.name == name).unwrap_or_else(|| panic!("no param {name}"));
affinity_of(&p.ty).unwrap_or("unknown").to_string()
}
#[test]
fn the_full_text_functions_are_typed() {
let mut schema = ddl();
schema.push("CREATE VIRTUAL TABLE docs USING fts5(title, body)".into());
schema.push("CREATE VIRTUAL TABLE notes USING fts4(body)".into());
let a = |sql: &str| {
let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
a
};
let fts5 = a("select rowid as id, bm25(docs) as rank, bm25(docs, :w, 1.0) as weighted, highlight(docs, :col, :open, '</b>') as hit, \
snippet(docs, -1, '<b>', '</b>', '…', 8) as excerpt from docs where docs match :q order by rank");
assert_eq!(col(&fts5, "rank"), ("real".into(), false));
assert_eq!(col(&fts5, "weighted"), ("real".into(), true));
assert_eq!(col(&fts5, "hit"), ("text".into(), true));
assert_eq!(col(&fts5, "excerpt"), ("text".into(), true));
assert_eq!((param(&fts5, "w"), param(&fts5, "col"), param(&fts5, "open"), param(&fts5, "q")), ("real".into(), "integer".into(), "text".into(), "text".into()));
let fts4 = a("select offsets(notes) as o, matchinfo(notes) as m, snippet(notes) as s from notes where notes match :q");
assert_eq!(col(&fts4, "o"), ("text".into(), false));
assert_eq!(col(&fts4, "m"), ("blob".into(), false));
assert_eq!(col(&fts4, "s"), ("text".into(), true));
let built = a("select json_object('hit', highlight(docs, 0, '<b>', '</b>'), 'rank', bm25(docs)) as j from docs where docs match :q");
assert_eq!(shown(&built), "j: { hit: string | null; rank: number }");
}
#[test]
fn a_built_in_is_non_null_only_where_sqlite_never_answers_null_for_non_null_arguments() {
let ddl = vec![
"create table o (id integer primary key, placed_at text not null, x real not null, n integer not null, b blob not null, v any not null, doc text not null, fmt text not null) strict".to_string(),
"create table loose (id integer primary key, num numeric not null)".to_string(),
];
let typed = |expr: &str| {
let a = analyze_ddl(&format!("select {expr} as v from o, loose"), &ddl, &Extras::default()).analysis;
assert!(a.diagnostics.is_empty(), "{expr}: {:?}", a.diagnostics);
col(&a, "v")
};
let nullable = |expr: &str| typed(expr).1;
for expr in [
"date(placed_at)", "time(placed_at)", "datetime(placed_at)", "julianday(placed_at)", "unixepoch(placed_at)", "strftime('%Y', placed_at)",
"date(placed_at, '+1 day')", "timediff(placed_at, 'now')", "date(n)", "date(x, 'unixepoch')", "date('2024-01-01')", "date(:d)",
"date('now', 'weekday 7')", "date('now', 'unixepoch')", "date('now', 'julianday')", "date('now', '+8000 years')", "date('now', '+1 day ')",
"date('now', '+600 years', '+600 years')", "date('now', fmt)", "date('now ')", "strftime('%Q', 'now')", "strftime('%Y%')", "strftime(fmt)",
"date(5373485)", "datetime(1e18, 'unixepoch')", "date(0, '-1 day')", "date(1700000000, 'unixepoch', 'unixepoch')", "date(1, 'auto')", "date(-1)",
] {
assert!(nullable(expr), "{expr}");
}
for expr in [
"date()", "time()", "datetime()", "julianday()", "unixepoch()", "date('now')", "date('NOW')", "datetime('now', 'localtime')", "datetime('now', 'utc')",
"date('now', 'start of month', '+1 month', '-1 day')", "date('now', 'weekday 0')", "datetime('now', '-7 days', '+1.5 hours', '+30 MINUTES')",
"date('now', 'subsec')", "strftime('%Y-%m-%d %H:%M:%f %% %j', 'now')", "strftime('%s')", "strftime('')", "timediff('now', 'now')",
"strftime('%Y', current_timestamp)", "date(current_date, '+1 month')", "datetime(0, 'unixepoch')", "date(2460000.5)", "date(1700000000, 'unixepoch', 'start of day', '+1 day')",
] {
assert!(!nullable(expr), "{expr}");
}
assert_eq!(typed("unixepoch()"), ("integer".into(), false));
assert_eq!(typed("unixepoch('now', 'subsec')"), ("real".into(), false));
assert_eq!(typed("unixepoch('now', fmt)"), ("real".into(), true));
for f in ["acos(x)", "acosh(x)", "asin(x)", "atanh(x)", "cos(x)", "sin(x)", "tan(x)", "ln(x)", "log(x)", "log(2, x)", "log10(x)", "log2(x)", "mod(n, x)", "pow(x, 0.5)", "power(x, n)", "sqrt(x)", "sqrt(4)"] {
assert_eq!(typed(f), ("real".into(), true), "{f}");
}
for f in ["atan(x)", "atan2(x, n)", "asinh(x)", "sinh(x)", "cosh(n)", "tanh(x)", "exp(x)", "degrees(x)", "radians(n)", "ceil(x)", "ceiling(x)", "floor(n)", "trunc(x)", "pi()"] {
assert_eq!(typed(f), ("real".into(), false), "{f}");
}
assert_eq!(typed("sign(x)"), ("integer".into(), false));
for f in ["sign(placed_at)", "sign(v)", "sign(num)", "ceil(placed_at)", "floor(b)", "exp(v)", "atan2(x, placed_at)", "sinh(num)"] {
assert!(nullable(f), "{f}");
}
for f in ["printf(fmt, n)", "printf('', n)", "printf('%T')", "printf('%s', placed_at)", "format('%d%d', n, n)", "printf('%T x')", "printf('%5-dx', n)", "printf('%ls', n)", "printf('%.*s', n, placed_at)", "printf('%-')"] {
assert!(nullable(f), "{f}");
}
for f in ["printf('x%s', null)", "format('-%d', n)", "printf('%%')", "printf('%')", "printf('%s-%d', placed_at, n)", "printf('%5.2f%%', x)", "printf('%-10s|', placed_at)", "printf('%lld:', n)", "printf('%*.*s.', n, n, placed_at)", "printf('a%T')"] {
assert!(!nullable(f), "{f}");
}
assert_eq!(typed("substr(placed_at, 2)"), ("text".into(), false));
assert_eq!(typed("substr(n, 2, 1)"), ("text".into(), false));
assert_eq!(typed("substr(:s, 2)"), ("text".into(), false));
assert_eq!(typed("substr(b, 2)"), ("blob".into(), true));
assert_eq!(typed("substring(v, 1, 2)"), ("unknown".into(), true));
for f in ["json_type(doc, '$.a')", "json_array_length(doc, '$.a')", "json_remove(doc, '$')", "json_remove(doc, '$.a')"] {
assert!(nullable(f), "{f}");
}
for f in ["json_type(doc)", "json_array_length(doc)", "json_remove(doc)", "json(doc)", "json_set(doc, '$.a', null)", "json_patch(doc, doc)", "json_valid(doc)"] {
assert!(!nullable(f), "{f}");
}
assert_eq!(typed("jsonb(doc)"), ("blob".into(), false));
assert_eq!(typed("(select jsonb_group_array(id) from o)"), ("blob".into(), false));
assert_eq!(typed("iif(n > 0, placed_at)"), ("text".into(), true));
assert_eq!(typed("iif(n > 0, placed_at, n > 1, doc)"), ("text".into(), true));
assert_eq!(typed("iif(n > 0, placed_at, n > 1, doc, fmt)"), ("text".into(), false));
assert_eq!(typed("if(n > 0, x, n > 1, x, 1.5)"), ("real".into(), false));
assert_eq!(param(&analyze_ddl("select id from o where x = iif(n > 0, 1.5, :c, 2.5, :e)", &ddl, &Extras::default()).analysis, "c"), "integer");
assert_eq!(param(&analyze_ddl("select id from o where x = iif(n > 0, 1.5, :c, 2.5, :e)", &ddl, &Extras::default()).analysis, "e"), "real");
assert_eq!(typed("(select total(x) from o)"), ("real".into(), true));
assert_eq!(typed("(select total(n) from o)"), ("real".into(), false));
assert_eq!(typed("total(x) over ()"), ("real".into(), true));
for f in [
"abs(x)", "round(x, 2)", "length(b)", "instr(placed_at, '')", "octet_length(b)", "upper(b)", "lower(placed_at)", "trim(placed_at, '')", "replace(placed_at, '', 'x')",
"char(n)", "hex(b)", "quote(v)", "typeof(v)", "concat(placed_at, null)", "like(placed_at, 'a%')", "glob('*', placed_at)", "json_array(n)", "json_object('a', n)", "json_quote(v)",
] {
assert!(!nullable(f), "{f}");
}
assert!(nullable("unicode(placed_at)"));
}
#[test]
fn the_postgres_nullability_rules_hold_on_sqlite() {
let nullable_param = |sql: &str, name: &str| analysis(sql).params.iter().find(|p| p.name == name).is_some_and(|p| p.nullable);
let marked_param = |sql: &str, name: &str| marked(sql, &ddl(), &[name]).params.iter().find(|p| p.name == name).is_some_and(|p| p.nullable);
assert!(marked_param("with input as (select cast(:p as integer) as p) select id from users, input where (input.p is null or score > input.p)", "p"));
assert!(!nullable_param("with input as (select cast(:p as integer) as p) select id from users, input where score = coalesce(input.p, score)", "p"));
assert!(!nullable_param("with input as (select :p as p) select id from users, input i where score = ifnull(p, score) and score > i.p", "p"));
assert!(!nullable_param("select id from users, (select :p as p) s where coalesce(s.p, score) = score", "p"));
assert!(!nullable_param("with input as (select :p as p) select id from users, input where score = coalesce(input.p, score)", "p"));
assert!(!nullable_param("with input as (select :p as p) select id from users, input where score > input.p", "p"));
assert!(!nullable_param("with input as (select :p as p union all select 1) select id from users, input where coalesce(input.p, 0) = 0", "p"));
assert!(!nullable_param("with input as (select cast(:p as integer) as p) select id from users, input where (input.p is null or score > input.p)", "p"));
assert!(!nullable_param("select id from users where cast(:p as integer) is null", "p"));
assert!(!nullable_param("select id from users where :p is not null", "p"));
assert!(!nullable_param("select id from users where email is :p", "p"));
assert!(!nullable_param("select id from users where :p is not email", "p"));
assert!(!nullable_param("select id from users where :p isnull", "p"));
assert!(!nullable_param("select id from users where score = coalesce(score, :p)", "p"));
let sql = "select id from users where (:p is null or score > :p)";
let repeated = analysis(sql);
assert_eq!(repeated.diagnostics.iter().map(|d| (d.code, d.start, d.length)).collect::<Vec<_>>(), [(3, sql.rfind(":p").unwrap(), 2)]);
assert!(!nullable_param("select coalesce(:s, 0) as x", "s"));
assert!(!nullable_param("select id from users where score > :p", "p"));
assert_eq!(col(&analysis("select upper(:s) as u"), "u"), ("text".into(), false));
assert_eq!(col(&analysis("select email from users where email is not null"), "email"), ("text".into(), false));
assert_eq!(col(&analysis("select email from users where lower(email) = :e or email like 'a%'"), "email").1, false);
assert_eq!(col(&analysis("select email from users where email like 'a%' or id = 1"), "email").1, true);
assert_eq!(col(&analysis("select email from users where lower(email) = :e and email like 'a%'"), "email").1, false);
let reduced = analysis("select p.title, u.name from posts p left join users u on u.id = p.user_id where u.email = :e");
assert_eq!(col(&reduced, "name"), ("text".into(), false));
assert_eq!(col(&analysis("select p.title, u.name from posts p left join users u on u.id = p.user_id"), "name"), ("text".into(), true));
let right = analysis("select p.title, u.name from posts p join users u on u.email is not null right join posts q on q.id = 0");
assert_eq!((col(&right, "title").1, col(&right, "name").1), (true, true));
assert_eq!(col(&analysis("select u.email from posts p join users u on u.email is not null"), "email").1, false);
assert_eq!(col(&analysis("select p.title, u.name from posts p left join users u on u.id = p.user_id and u.email = :e"), "name"), ("text".into(), true));
let grouped = analysis("select user_id, max(title) as t, min(id) as m, group_concat(title) as g from posts group by user_id");
assert_eq!((col(&grouped, "t").1, col(&grouped, "m").1, col(&grouped, "g").1), (false, false, false));
assert!(col(&analysis("select max(title) as t from posts"), "t").1);
let concat = analysis("select concat(email, 'x') as c, concat_ws(',', email) as w, concat_ws(email, 'a') as n from users");
assert_eq!((col(&concat, "c").1, col(&concat, "w").1, col(&concat, "n").1), (false, false, true));
}
#[test]
fn a_cast_parameter_is_its_casts_type_and_a_bare_one_its_columns() {
let ddl = vec!["create table users (id integer primary key, name text not null, email text unique, score real, n integer, doc text, meta text not null default '{}', nick text check (nick is not null), code text check (length(code) > 0 and code is not null), tag text check (tag <> '')) strict".to_string()];
let types = |sql: &str| {
let a = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
a.params.iter().map(|p| format!("{}{}", p.name, if p.nullable { "?" } else { "" })).collect::<Vec<_>>().join(" ")
};
for (sql, want) in [
("insert into users (name, email) values (:name, :email) on conflict (email) do update set name = excluded.name returning id", "name email?"),
("insert into users (name, email) values (CAST(:name AS TEXT), CAST(:email AS TEXT)) on conflict (email) do update set name = excluded.name returning id", "name email"),
("insert into users (name, email, score, n, doc, meta) values (:name, :email, :score, :n, :doc, :meta)", "name email? score? n? doc? meta"),
("insert into users (name, email, score, n, doc, meta) values (CAST(:name AS TEXT), CAST(:email AS TEXT), CAST(:score AS NUMERIC), CAST(:n AS INTEGER), json(:doc), jsonb(:meta))", "name email score n doc meta"),
("insert into users (name, email) values (:a, :b), (:c, CAST(:d AS TEXT))", "a b? c d"),
("update users set email = :email, name = :name, score = :score, n = CAST(:n AS INTEGER), doc = json(:doc) where id = :id", "email? name score? n doc id"),
("update users set (name, email) = (:name, :email) where id = :id", "name email? id"),
("update users set (name, email) = (CAST(:name AS TEXT), CAST(:email AS TEXT)) where id = CAST(:id AS INTEGER)", "name email id"),
("insert into users (name, email) values ('a', 'b') on conflict (email) do update set email = :e, n = CAST(:n AS INTEGER), name = :name", "e? n name"),
("update users set email = CAST(CAST(:e AS INTEGER) AS TEXT), meta = json(:m) where id = 1", "e m"),
("insert into users (name, nick, code, tag) values (:name, :nick, :code, :tag)", "name nick code tag?"),
("update users set nick = :nick, code = :code, tag = :tag where id = :id", "nick code tag? id"),
("update users set n = coalesce(CAST(:n AS INTEGER), n), doc = ifnull(json(:doc), doc), score = coalesce(:s, score) where id = CAST(:id AS INTEGER)", "n doc s id"),
("select id from users where (json(:doc) is null or doc = json(:d)) and :x is not null", "doc d x"),
("insert into users (name, email) select CAST(:name AS TEXT), CAST(:email AS TEXT)", "name email"),
("insert into users (name, email) select :name, :email", "name email?"),
] {
assert_eq!(types(sql), want, "{sql}");
}
let ddl: Vec<String> = ddl.iter().map(|s| s.to_string()).collect();
let sql = "insert into users (name, email, nick, doc, meta) values (CAST(:name AS TEXT), CAST(:email AS TEXT), CAST(:nick AS TEXT), :doc, json(:meta))";
let a = marked(sql, &ddl, &["name", "email", "nick", "doc", "meta"]);
assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true; 5]);
let said = |p: &str, column: &str| format!("The parameter {p} is cast to nullable(…), but it is written to users.{column}, which refuses null: cast it to its type alone.");
assert_eq!(a.diagnostics.iter().map(|d| (&sql[d.start..d.start + d.length], d.message.clone())).collect::<Vec<_>>(), [(":name", said(":name", "name")), (":nick", said(":nick", "nick")), (":meta", said(":meta", "meta"))]);
let sql = "insert into users (name, email) select CAST(:name AS TEXT), CAST(:email AS TEXT)";
let a = marked(sql, &ddl, &["name", "email"]);
assert_eq!(a.diagnostics.iter().map(|d| (&sql[d.start..d.start + d.length], d.message.clone())).collect::<Vec<_>>(), [(":name", said(":name", "name"))]);
let a = marked("update users set email = CAST(:e AS TEXT), n = coalesce(CAST(:n AS INTEGER), n) where id = 1", &ddl, &["e", "n"]);
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true, true]);
}
#[test]
fn a_parameter_takes_the_type_its_call_case_or_compound_stands_in() {
assert_eq!(param(&analysis("select id from users where name = coalesce(:a, :b)"), "a"), "text");
assert_eq!(param(&analysis("select id from users where name = coalesce(:a, :b)"), "b"), "text");
assert_eq!(param(&analysis("select id from users where name = case when id > 1 then :a else :b end"), "a"), "text");
assert_eq!(param(&analysis("select id from users where name = iif(id > 1, :a, 'x')"), "a"), "text");
assert_eq!(param(&analysis("select case :kind when 'a' then 1 else 2 end as k from users"), "kind"), "text");
assert_eq!(param(&analysis("select name from users union all select :x"), "x"), "text");
assert_eq!(param(&analysis("select :x union all select name from users"), "x"), "text");
assert_eq!(param(&analysis("select id from users where name = printf(:f, 1)"), "f"), "text");
assert_eq!(param(&analysis("select :x as v"), "x"), "unknown");
}
#[test]
fn an_outer_joins_on_term_pins_its_right_side_but_groups_nothing() {
assert_eq!(analysis("select u.name, count(*) as n from posts p left join users u on u.id = :id and u.id = p.user_id group by u.name").cardinality, "many");
assert_eq!(analysis("select u.name, count(*) as n from posts p left join users u on u.id = p.user_id where u.id = :id group by u.name").cardinality, "at_most_one");
assert_eq!(analysis("select p.title, u.name from posts p left join users u on u.id = :u where p.id = :id").cardinality, "at_most_one");
}
#[test]
fn an_insert_returns_no_row_where_something_can_skip_it() {
let count = |sql: &str, extra: &[&str]| {
let mut schema = ddl();
schema.extend(extra.iter().map(|s| s.to_string()));
analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
};
let insert = "insert into users (name) values (:n) returning id";
assert_eq!(count(insert, &[]), "one");
assert_eq!(count(insert, &["create trigger skip before insert on users begin select raise(ignore) where new.name = 'x'; end"]), "at_most_one");
assert_eq!(count(insert, &["create trigger untimed insert on users begin select 1; end"]), "at_most_one", "BEFORE is the default");
assert_eq!(count(insert, &["create trigger later after insert on users begin select 1; end"]), "one");
assert_eq!(count("insert into users (id, name) values (:id, :n) on conflict (id) do update set name = excluded.name where users.score > 1 returning id", &[]), "at_most_one");
assert_eq!(count("insert into users (id, name) values (:id, :n) on conflict (id) do update set name = excluded.name returning id", &[]), "one");
assert_eq!(count("insert into users (id, name) values (:id, :n) on conflict (id) do update set name = excluded.name on conflict do nothing returning id", &[]), "at_most_one");
let declared = |sql: &str, table: &str| {
let schema = vec![table.to_string()];
analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
};
assert_eq!(declared("insert into t (k) values (:k) returning id", "create table t (id integer primary key, k text unique on conflict ignore)"), "at_most_one");
assert_eq!(declared("insert into t (k) values (:k) returning id", "create table t (id integer primary key, k text not null on conflict ignore)"), "at_most_one");
assert_eq!(declared("insert into t (id) values (:id) returning id", "create table t (id integer primary key on conflict ignore, k text)"), "at_most_one");
assert_eq!(declared("insert into t (a, b) values (:a, :b) returning a", "create table t (a integer, b integer, unique (a, b) on conflict ignore)"), "at_most_one");
assert_eq!(declared("insert or abort into t (k) values (:k) returning id", "create table t (id integer primary key, k text unique on conflict ignore)"), "one");
assert_eq!(declared("insert into t (k) values (:k) returning id", "create table t (id integer primary key, k text unique on conflict replace)"), "one");
}
#[test]
fn a_write_to_a_view_goes_through_its_instead_of_trigger() {
let schema = vec![
"create table w (id integer primary key, k text not null, v integer)".to_string(),
"create view wv as select id, k, v from w".to_string(),
"create trigger wv_insert instead of insert on wv when lookup(new.k) begin insert into w (k, v) values (new.k, new.v); end".to_string(),
"create trigger \"wv update\" instead of update of v on main.wv begin update w set v = new.v where id = old.id; end".to_string(),
];
let analysis = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
let insert = analysis("insert into wv (k, v) values (42, 9) returning k");
assert!(insert.diagnostics.is_empty(), "{:?}", insert.diagnostics);
assert_eq!(col(&insert, "k"), ("unknown".into(), true));
assert!(analysis("update wv set v = :v where id = :id").diagnostics.is_empty());
assert_eq!(analysis("update wv set k = :k").diagnostics.first().map(|d| d.message.as_str()), Some("cannot modify wv because it is a view"));
assert_eq!(analysis("delete from wv").diagnostics.first().map(|d| d.message.as_str()), Some("cannot modify wv because it is a view"));
assert_eq!(instead_of_stub("create trigger t before insert on w begin select 1; end"), None);
assert_eq!(instead_of_stub(&schema[3]).as_deref(), Some("create trigger \"wv update\" instead of update of v on main.wv\nBEGIN SELECT 1; END"));
assert_eq!(instead_of_stub("CREATE TRIGGER x INSTEAD OF DELETE ON v -- on y\n BEGIN SELECT 1; END").as_deref(), Some("CREATE TRIGGER x INSTEAD OF DELETE ON v -- on y\nBEGIN SELECT 1; END"));
}
#[test]
fn a_unique_key_bounds_only_a_comparison_under_its_own_collation() {
let count = |sql: &str| {
let mut schema = ddl();
schema.push("create table c (id integer primary key, e text collate nocase, b text unique)".into());
schema.push("create unique index c_e on c (e collate binary)".into());
analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
};
assert_eq!(count("select id from c where e = :e"), "many");
assert_eq!(count("select id from c where b = :b"), "at_most_one");
assert_eq!(count("select id from c where b = :b collate nocase"), "many");
assert_eq!(count("select e from c where id = :id"), "at_most_one");
}
#[test]
fn a_function_the_host_registers_over_a_built_in_proves_nothing_strict() {
let lower = Extras { total: vec![TotalFunction { name: "lower".into(), arity: 1, returns: Affinity::Text }], host: None };
let nullable = |extras: &Extras| col(&analyze_ddl("select email from users where lower(email) = :e", &ddl(), extras).analysis, "email").1;
assert!(!nullable(&Extras::default()));
assert!(nullable(&lower));
}
#[test]
fn a_strict_column_and_a_rowid_hold_their_declared_type_alone() {
let ddl = [
"create table s (id integer primary key, n int not null, x real, t text, b blob, a any, g integer generated always as (n * 2) virtual) strict",
"create table loose (id integer primary key, n integer not null, t text)",
"create table desc_key (a integer primary key desc)",
]
.map(String::from);
let kinds = |sql: &str| {
let analysis = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
analysis.columns.iter().map(|c| serde_json::to_value(&c.ty).unwrap()["kind"].as_str().unwrap().to_string()).collect::<Vec<_>>().join(" ")
};
assert_eq!(kinds("select id, n, x, t, b, a from s"), "integer integer float text bytes unknown");
assert_eq!(kinds("select id, n, t from loose"), "integer union union");
assert_eq!(kinds("select a from desc_key"), "union");
assert_eq!(kinds("select g from s"), "union");
assert_eq!(kinds("select n, t from (select n, t from s)"), "integer text");
assert_eq!(kinds("select n from s union all select id from loose"), "integer");
assert_eq!(kinds("select n from s union all select n from loose"), "union");
assert_eq!(kinds("select n from s union all values (1)"), "union");
}
fn libsql_schema() -> Vec<String> {
[
"CREATE TABLE docs (id integer primary key, title text not null, emb F32_BLOB(3))",
"CREATE TABLE libsql_vector_meta_shadow ( name TEXT PRIMARY KEY, metadata BLOB ) WITHOUT ROWID",
"CREATE TABLE docs_emb_shadow (index_key INTEGER , data BLOB, PRIMARY KEY (index_key))",
"CREATE INDEX docs_emb_shadow_idx ON docs_emb_shadow (index_key)",
"CREATE INDEX docs_emb on docs (libsql_vector_idx(emb))",
"CREATE TABLE words (k text primary key, e F32_BLOB(2)) WITHOUT ROWID",
"CREATE INDEX words_e on words (libsql_vector_idx(e, 'metric=l2'))",
]
.map(String::from)
.to_vec()
}
fn sqlite_host() -> Extras {
Extras { total: vec![], host: Some(["lower", "upper", "length", "count"].map(|name| HostFunction { name: name.into(), arity: -1, kind: 's' }).to_vec()) }
}
#[test]
fn the_sqlean_functions_turso_cloud_loads_are_typed_whatever_the_host_lists() {
let ddl = vec!["create table people (id integer primary key, name text not null, nick text, score real not null) strict".to_string()];
for extras in [Extras::default(), sqlite_host()] {
let a = |sql: &str| {
let a = analyze_ddl(sql, &ddl, &extras).analysis;
assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
a
};
let fresh = a("select uuid4() as a, uuid7() as b, gen_random_uuid() as c, uuid_str(:id) as d, uuid_blob(:raw) as e, uuid7_timestamp_ms(:at) as f");
assert_eq!(["a", "b", "c", "d", "e", "f"].map(|c| col(&fresh, c)), [("text", false), ("text", false), ("text", false), ("text", true), ("blob", true), ("integer", true)].map(|(t, n)| (t.to_string(), n)));
assert_eq!(param(&fresh, "id"), "text");
let digest = a("select md5(name) as a, sha256(nick) as b, crypto_sha1(name) as c, encode(md5(name), 'hex') as d, decode(nick, 'base64') as e from people");
assert_eq!(["a", "b", "c", "d", "e"].map(|c| col(&digest, c)), [("blob", false), ("blob", true), ("blob", false), ("text", false), ("blob", true)].map(|(t, n)| (t.to_string(), n)));
let fuzzy = a("select levenshtein(name, :q) as a, fuzzy_leven(nick, :q2) as b, jaro_winkler(name, :q3) as c, caverphone(nick) as d, translit(nick) as e, script_code(name) as f from people");
assert_eq!(["a", "b", "c", "d", "e", "f"].map(|c| col(&fuzzy, c)), [("integer", false), ("integer", false), ("real", false), ("text", true), ("text", false), ("integer", false)].map(|(t, n)| (t.to_string(), n)));
assert_eq!(param(&fuzzy, "q"), "text");
let text = a("select left(name, :n) as a, lpad(nick, 5) as b, split_part(name, ',', 2) as c, text_title(name) as d, strpos(name, 'a') as e, char_length(nick) as f, text_concat(name, nick) as g, text_join(',', name, nick) as h from people");
assert_eq!(["a", "b", "c", "d", "e", "f", "g", "h"].map(|c| col(&text, c)), [("text", false), ("text", true), ("text", false), ("text", false), ("integer", false), ("integer", true), ("text", false), ("text", false)].map(|(t, n)| (t.to_string(), n)));
assert_eq!(param(&text, "n"), "integer");
let tests = a("select starts_with(name, 'a') as a, text_contains(name, :part) as b, regexp_like(nick, '^a') as c from people");
assert_eq!(["a", "b", "c"].map(|c| col(&tests, c)), [("bool", false), ("bool", false), ("bool", false)].map(|(t, n)| (t.to_string(), n)));
let re = a("select regexp_substr(name, 'a+') as a, regexp_capture(name, 'b(a+)', 1) as b, regexp_replace(name, 'a', 'b') as c, regexp_replace(nick, 'a', 'b') as d, regexp_replace(id, 'z', 'x') as e from people where name regexp 'a'");
assert_eq!(["a", "b", "c", "d", "e"].map(|c| col(&re, c)), [("text", true), ("text", true), ("text", false), ("text", true), ("unknown", false)].map(|(t, n)| (t.to_string(), n)));
let aliased = a("select math_floor(:x) as a, fuzzy_soundex(:s) as b, stats_perc(score, :p) as c from people");
assert_eq!((param(&aliased, "x"), param(&aliased, "s"), param(&aliased, "p")), ("real".into(), "text".into(), "real".into()));
let math = a("select math_floor(score) as a, math_sqrt(score) as b, math_pi() as c from people");
assert_eq!(["a", "b", "c"].map(|c| col(&math, c)), [("real", false), ("real", true), ("real", false)].map(|(t, n)| (t.to_string(), n)));
let stats = a("select stddev(score) as a, stats_p90(score) as b, variance(score) as c from people group by name");
assert_eq!(["a", "b", "c"].map(|c| col(&stats, c)), [("real", true), ("real", true), ("real", true)].map(|(t, n)| (t.to_string(), n)));
let series = a("select value from generate_series(1, :stop)");
assert_eq!((col(&series, "value"), param(&series, "stop")), (("integer".to_string(), false), "integer".to_string()));
assert_eq!(col(&a("select value from stats_seq(1, 3)"), "value"), ("integer".to_string(), false));
assert!(!analyze_ddl("select value from generate_series", &ddl, &extras).analysis.diagnostics.is_empty());
}
let own = analyze_ddl("select soundex(nick) as a, soundex(name) as b, median(score) as c from people group by name", &ddl, &Extras::default()).analysis;
assert_eq!(["a", "b", "c"].map(|c| col(&own, c)), [("text", true), ("text", false), ("real", true)].map(|(t, n)| (t.to_string(), n)));
}
#[test]
fn libsql_s_vector_functions_are_typed_whatever_the_host_lists() {
for extras in [Extras::default(), sqlite_host()] {
let a = |sql: &str| {
let a = analyze_ddl(sql, &libsql_schema(), &extras).analysis;
assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
a
};
let plain = a("select id, title from docs where id = :id");
assert_eq!((col(&plain, "id"), col(&plain, "title")), (("integer".into(), false), ("text".into(), false)));
assert_eq!(a("select emb from docs").columns[0].nullable, true);
let distance = a("select id, vector_distance_cos(emb, vector(:q)) as d, vector_distance_l2(emb, :r) as l from docs order by d limit 5");
assert_eq!((col(&distance, "d"), col(&distance, "l")), (("real".into(), true), ("real".into(), true)));
assert_eq!((param(&distance, "q"), param(&distance, "r")), ("text".into(), "text".into()));
let made = a("select vector(:v) as v, vector32(:a) as a, vector64(:b) as b, vector8(:c) as c, vector16(:d) as d, vectorb16(:e) as e, vector1bit(:f) as f, vector_extract(emb) as text from docs");
for name in ["v", "a", "b", "c", "d", "e", "f"] {
assert_eq!(col(&made, name), ("blob".into(), false), "{name}");
}
assert_eq!(col(&made, "text"), ("text".into(), false));
let insert = a("insert into docs (title, emb) values (:title, vector(:v)) returning id");
assert_eq!((param(&insert, "title"), param(&insert, "v")), ("text".into(), "text".into()));
}
}
#[test]
fn vector_top_k_returns_the_key_of_its_index_s_table() {
for extras in [Extras::default(), sqlite_host()] {
let a = |sql: &str| {
let a = analyze_ddl(sql, &libsql_schema(), &extras).analysis;
assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
a
};
let top = a("select id from vector_top_k('docs_emb', vector(:q), :k)");
assert_eq!(col(&top, "id"), ("integer".into(), false));
assert_eq!((param(&top, "q"), param(&top, "k")), ("text".into(), "integer".into()));
assert_eq!(a("select * from vector_top_k('docs_emb', :q, 5)").columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id"]);
let joined = a("select d.id, d.title from vector_top_k('docs_emb', vector(:q), 5) as t join docs d on d.id = t.id");
assert_eq!(col(&joined, "title"), ("text".into(), false));
assert_eq!(col(&a("select id from vector_top_k('words_e', :q, 3)"), "id"), ("unknown".into(), false));
assert_eq!(col(&a("select t.id from docs d left join vector_top_k('docs_emb', d.emb, 1) t"), "id"), ("integer".into(), true));
assert_eq!(a("select id from vector_top_k(:index, :q, 5)").columns[0].nullable, true);
}
}
#[test]
fn libsql_s_alter_column_prepares_on_a_table_and_column_that_exist() {
let a = |sql: &str| analyze_ddl(sql, &libsql_schema(), &Extras::default()).analysis;
for sql in ["alter table docs alter column title to title text not null", "ALTER TABLE main.docs ALTER emb TO emb F32_BLOB(3) NOT NULL", "alter table \"docs\" alter column \"title\" to \"title\" text"] {
let altered = a(sql);
assert!(altered.diagnostics.is_empty(), "{sql}: {:?}", altered.diagnostics);
assert!(altered.columns.is_empty());
assert_eq!(altered.cardinality, Cardinality::None);
}
let missing = a("alter table docs alter column nope to nope integer");
assert!(missing.diagnostics.len() == 1 && missing.diagnostics[0].message.starts_with("no such column: \"nope\", so if it is a migration"), "{:?}", missing.diagnostics);
assert!(!a("alter table nope alter column title to title text").diagnostics.is_empty());
assert!(!a("alter table docs alter column title").diagnostics.is_empty());
}
#[test]
fn a_table_whose_check_calls_a_function_the_host_lacks_still_replays() {
let ddl = vec!["create table docs (id integer primary key, doc text check (doc is null or jsonschema_matches('{\"type\":\"object\"}', doc)))".to_string()];
let without = Extras { total: vec![], host: Some(vec![HostFunction { name: "lower".into(), arity: 1, kind: 's' }]) };
for extras in [Extras::default(), without.clone()] {
let read = analyze_ddl("select id, doc from docs", &ddl, &extras).analysis;
assert!(read.diagnostics.is_empty(), "{:?}", read.diagnostics);
assert_eq!(read.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "doc"]);
let write = analyze_ddl("insert into docs (doc) values (:doc) returning id", &ddl, &extras).analysis;
assert!(write.diagnostics.is_empty(), "{:?}", write.diagnostics);
assert_eq!(param(&write, "doc"), "text");
}
let call = analyze_ddl("select jsonschema_matches('{}', doc) as m from docs", &ddl, &without).analysis;
assert!(!call.diagnostics.is_empty());
}
#[test]
fn columns_from_provenance_and_rules() {
let a = analysis("select id, name, email, score, length(email) as l, coalesce(email, 'x') as e, id * 2 as d, id / 2 as h from users");
assert_eq!(col(&a, "id"), ("integer".into(), false));
assert_eq!(col(&a, "name"), ("text".into(), false));
assert_eq!(col(&a, "email"), ("text".into(), true));
assert_eq!(col(&a, "score"), ("real".into(), true));
assert_eq!(col(&a, "l"), ("integer".into(), true));
assert_eq!(col(&a, "e"), ("text".into(), false));
assert_eq!(col(&a, "d"), ("integer".into(), false));
assert_eq!(col(&a, "h"), ("integer".into(), false));
assert_eq!(a.cardinality, "many");
}
#[test]
fn a_column_beside_an_aggregate_with_no_group_by_is_null_over_no_rows() {
let a = analysis("select id, name, coalesce(email, 'x') as e, id * 2 as d, count(*) as n, count(name) as c, max(id) as m from users where name = 'ada'");
assert_eq!(col(&a, "id"), ("integer".into(), true));
assert_eq!(col(&a, "name"), ("text".into(), true));
assert_eq!(col(&a, "e"), ("text".into(), false));
assert_eq!(col(&a, "d"), ("integer".into(), true));
assert_eq!(col(&a, "n"), ("integer".into(), false));
assert_eq!(col(&a, "c"), ("integer".into(), false));
assert_eq!(a.cardinality, "one");
let a = analysis("select name, count(*) as n from users group by name");
assert_eq!(col(&a, "name"), ("text".into(), false));
}
#[test]
fn outer_join_and_subquery_provenance() {
let a = analysis("select u.id, p.title from users u left join posts p on p.user_id = u.id");
assert_eq!(col(&a, "title"), ("text".into(), true));
let a = analysis("select t.id, t.name from (select id, name from users) t where t.id = :id");
assert_eq!(col(&a, "id"), ("integer".into(), false));
assert_eq!(col(&a, "name"), ("text".into(), false));
assert_eq!(param(&a, "id"), "integer");
}
#[test]
fn parameters_from_context() {
let a = analysis("select id from users where email = :email and score >= :min and id in (:a, :b) and created_at between :from and :to and name like :q and lower(name) = :n limit :lim offset :off");
assert_eq!(param(&a, "email"), "text");
assert_eq!(param(&a, "min"), "real");
assert_eq!(param(&a, "a"), "integer");
assert_eq!(param(&a, "from"), "text");
assert_eq!(param(&a, "q"), "text");
assert_eq!(param(&a, "n"), "text");
assert_eq!(param(&a, "lim"), "integer");
assert_eq!(param(&a, "off"), "integer");
let a = analysis("insert into users (email, name, score) values (:e, upper(:n), :s * 2) returning id");
assert_eq!(param(&a, "e"), "text");
assert_eq!(param(&a, "n"), "text");
assert_eq!(param(&a, "s"), "integer");
assert_eq!(a.cardinality, "one");
let a = analysis("update users set name = :name, score = :score where id = :id returning id");
assert_eq!(param(&a, "name"), "text");
assert_eq!(param(&a, "score"), "real");
assert_eq!(param(&a, "id"), "integer");
assert_eq!(a.cardinality, "at_most_one");
}
#[test]
fn json_each_reads_text() {
let a = analysis("select id from users where id in (select value from json_each(:ids))");
assert_eq!(param(&a, "ids"), "text");
assert!(!a.params.iter().find(|p| p.name == "ids").unwrap().nullable);
let a = analysis("select key, value from json_tree(:doc, :path)");
assert_eq!(param(&a, "doc"), "text");
assert_eq!(param(&a, "path"), "text");
assert_eq!(param(&analysis("select value from json_each(cast(:ids as text))"), "ids"), "text");
let a = marked("select value from json_each(coalesce(CAST(:ids AS TEXT), '[]'))", &ddl(), &["ids"]);
assert_eq!(param(&a, "ids"), "text");
assert!(a.params.iter().find(|p| p.name == "ids").unwrap().nullable);
let a = analysis("select users.id from users, json_each(:ids) j where users.id = j.value and users.name = :n");
assert_eq!(param(&a, "ids"), "text");
assert_eq!(param(&a, "n"), "text");
}
#[test]
fn cardinality_by_keys() {
assert_eq!(analysis("select id from users where email = :email").cardinality, "at_most_one");
assert_eq!(analysis("select id from users where name = :name").cardinality, "many");
assert_eq!(analysis("select u.id, count(p.id) as n from users u left join posts p on p.user_id = u.id where u.id = :id group by u.id").cardinality, "at_most_one");
assert_eq!(analysis("select id from users limit 1").cardinality, "at_most_one");
assert_eq!(analysis("insert or ignore into users (email, name) values (:e, :n) returning id").cardinality, "at_most_one");
assert_eq!(analysis("insert into users (email, name) values (:e, :n)").cardinality, "none");
assert_eq!(analysis("delete from users where id = :id returning id").cardinality, "at_most_one");
assert_eq!(analysis("select id from users union all select user_id from posts").cardinality, "many");
}
fn analyzed(sql: &str) -> Analysis {
let ddl = [
"create table users (id integer primary key, name text not null, email text unique, score real, avatar blob, created_at text not null default current_timestamp)",
];
let rows = ddl.iter().map(|d| vec![serde_json::Value::String(d.to_string())]).collect();
let answers = HashMap::from([(format!("query:{DDL_QUERY}|[]"), crate::api::Answer::Rows { rows }), (format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]))]);
let host = Host::new(&answers);
analyze(sql, &lex::lex(sql, Dialect::Sqlite).unwrap(), &host, &[]).expect("the schema and the functions were answered")
}
fn listed(extra: &[(&str, i32, char)]) -> Vec<Vec<serde_json::Value>> {
let core = [("count", 0, 'w'), ("count", 1, 'w'), ("max", 1, 'w'), ("max", -3, 's'), ("upper", 1, 's'), ("lower", 1, 's'), ("like", 2, 's'), ("like", 3, 's'), ("glob", 2, 's')];
let more = [("coalesce", -4, 's'), ("iif", -4, 's'), ("json_extract", -1, 's'), ("->>", 2, 's'), ("current_timestamp", 0, 's'), ("row_number", 0, 'w'), ("group_concat", 1, 'w'), ("abs", 1, 's')];
core.iter().chain(more.iter()).chain(extra.iter()).map(|(name, narg, kind)| vec![serde_json::json!(name), serde_json::json!(narg), serde_json::json!(kind.to_string())]).collect()
}
fn functions_answer(extra: &[(&str, i32, char)]) -> crate::api::Answer {
crate::api::Answer::Rows { rows: listed(extra) }
}
fn on_host(sql: &str, schema: &[String], extra: &[(&str, i32, char)], total: Vec<TotalFunction>) -> Analysis {
analyze_ddl(sql, schema, &Extras { total, host: host_functions(&listed(extra)) }).analysis
}
#[test]
fn names_fold_ascii_case_as_sqlite_folds_them() {
let schema: Vec<String> = [
"create table Books (id integer primary key, Title text not null, ISBN text unique, note text)",
"create table \"\u{c9}t\u{e9}\" (id integer primary key, v text)",
"create table wr (K text primary key, v text) without rowid",
"create table rt (RowId integer, v text)",
"create table \"my table\" (id integer primary key, v text)",
"create trigger \"skip one\" before insert on \"BOOKS\" begin select raise(ignore) where new.title = 'x'; end",
"create trigger skip_two before insert on \"my table\" begin select raise(ignore) where new.v = 'x'; end",
"create trigger [later] after update of \"on\", v on main . [my table] begin select 1; end",
]
.iter()
.map(|s| s.to_string())
.collect();
let a = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
for sql in [
"select * from books where id = :id",
"select * from BOOKS where ID = :id",
"select * from \"books\" where \"ID\" = :id",
"select * from [BOOKS] b where B.Id = :id",
"select b.* from main.bOOKS b join Books c on c.ID = b.id where C.id = :id",
"select title from books where isbn = :i",
"update BOOKS set TITLE = :t where ID = :id returning Title",
"delete from books where Isbn = :i returning id",
"select v from WR where k = :k",
"select v from Rt where _ROWID_ = :r",
] {
let got = a(sql);
assert!(got.diagnostics.is_empty(), "{sql}: {:?}", got.diagnostics);
assert_eq!(got.cardinality, "at_most_one", "{sql}: {:?}", got.cardinality_reason);
}
assert_eq!(a("select v from RT where ROWID = :r").cardinality, "many");
assert_eq!(a("select v from wr where rowid = 1").diagnostics[0].message, "no such column: rowid");
let insert = a("insert into BOOKS (TITLE, NOTE) values (:t, :n)");
assert_eq!((param(&insert, "t"), param(&insert, "n")), ("text".into(), "text".into()));
assert_eq!(insert.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [false, true]);
assert_eq!(col(&a("select TITLE, Note from books"), "Title"), ("text".into(), false));
assert_eq!(param(&a("insert into books (ROWID, title) values (:r, :t)"), "r"), "integer");
assert_eq!(param(&a("insert into rt (_rowid_, v) values (:r, :v)"), "r"), "unknown");
assert_eq!(a("select v from \"\u{c9}t\u{e9}\" where id = :id").cardinality, "at_most_one");
assert_eq!(a("select v from \"\u{e9}t\u{e9}\" where id = :id").diagnostics[0].message, "no such table: \u{e9}t\u{e9}");
assert_eq!(param(&a("select value from JSON_EACH(:ids)"), "ids"), "text");
assert_eq!(a("insert into books (title) values (:t) returning id").cardinality, "at_most_one");
assert_eq!(a("insert into \"My Table\" (v) values (:v) returning id").cardinality, "at_most_one");
assert_eq!(trigger_header(&schema[5]), Some(("before".into(), "insert".into(), "books".into())));
assert_eq!(trigger_header(&schema[7]), Some(("after".into(), "update".into(), "my table".into())));
assert_eq!(trigger_header("CREATE TRIGGER main.\"before\" /* on x */ INSTEAD OF DELETE ON v -- on y\n BEGIN SELECT 1; END"), Some(("instead".into(), "delete".into(), "v".into())));
assert_eq!(trigger_header("create table trigger_log (\"on\" text)"), None);
}
#[test]
fn every_row_of_a_values_list_types_its_parameters() {
let a = analysis("insert into users (id, name, email) values (:a, :b, :e), (:c, :d, :e2), (:f, upper(:g), 'x') returning id");
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
let got: Vec<(String, String, bool)> = a.params.iter().map(|p| (p.name.clone(), affinity_of(&p.ty).unwrap_or("unknown").to_string(), p.nullable)).collect();
let want = [("a", "integer", false), ("b", "text", false), ("e", "text", true), ("c", "integer", false), ("d", "text", false), ("e2", "text", true), ("f", "integer", false), ("g", "text", false)];
assert_eq!(got, want.map(|(n, t, null)| (n.to_string(), t.to_string(), null)));
assert_eq!((a.cardinality.as_str(), a.cardinality_reason.as_deref()), ("many", Some("a VALUES list of 3 rows returns 3 rows")));
let a = analysis("insert into users (name, email) values ('a', :x), (:w, 'b'), ('c', lower(:y))");
assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true, false, false]);
assert_eq!(a.cardinality, "none");
let a = analysis("insert into users (name, email) values ('a', :x), (:x, 'b')");
assert_eq!(a.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [3]);
let a = analysis("with w as (select 1) insert into posts values (:id, :u, :t, :b), (:id2, :u2, :t2, :b2)");
assert_eq!(a.params.iter().map(|p| (affinity_of(&p.ty).unwrap_or("unknown"), p.nullable)).collect::<Vec<_>>(), [("integer", false), ("integer", false), ("text", false), ("text", true)].repeat(2));
let rows: Vec<String> = (0..3000).map(|i| format!("(:n{i}, :e{i}, {i})")).collect();
let a = analysis(&format!("insert into users (name, email, score) values {}", rows.join(", ")));
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
assert_eq!((a.params.len(), param(&a, "n2999"), param(&a, "e2999")), (6000, "text".into(), "text".into()));
let a = analysis("values (1, 'a', :p), (2, null, 3), (:q, 'c', 4.5)");
assert_eq!((col(&a, "column1"), col(&a, "column2")), (("integer".into(), false), ("text".into(), true)));
assert_eq!((param(&a, "p"), param(&a, "q"), a.cardinality.as_str()), ("real".into(), "integer".into(), "many"));
assert_eq!(analysis("values (1, 'a')").cardinality, "one");
assert_eq!(col(&analysis("values (1), ('a')"), "column1").0, "unknown");
assert_eq!(analysis("select v.column1 from (values (1), (2)) v").cardinality, "many");
assert_eq!(analysis("select 1 union all values (2), (3)").cardinality, "many");
assert_eq!(col(&analysis("select (values (1), (2)) as x"), "x"), ("integer".into(), true));
}
#[test]
fn the_select_that_feeds_an_insert_types_its_parameters() {
let schema = vec!["create table bar (name text not null, ready bool not null, n integer)".to_string(), "create table foo (name text not null, meta text, k integer)".to_string(), "create table foo2 (name text not null, meta text, k integer)".to_string()];
let a = |sql: &str| {
let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
a
};
let params = |a: &Analysis| a.params.iter().map(|p| (affinity_of(&p.ty).unwrap_or("unknown").to_string(), p.nullable)).collect::<Vec<_>>();
let typed = |types: &[&str]| types.iter().map(|t| (t.to_string(), false)).collect::<Vec<_>>();
let got = a("insert into foo (name, meta) select name, ? from bar where ready = ?");
assert_eq!((got.kind.map_or("", StatementKind::as_str), got.cardinality.as_str()), ("insert", "none"));
assert_eq!(params(&got), [("text".to_string(), true), ("numeric".to_string(), false)]);
assert_eq!(params(&a("select name from bar where ready = ?")), typed(&["numeric"]));
assert_eq!(params(&a("insert into foo select :n, :m, :k from bar")), [("text".to_string(), false), ("text".to_string(), true), ("integer".to_string(), true)]);
assert_eq!(params(&a("insert into foo (k, name) select n + :d, upper(:u) from bar limit :l")), typed(&["integer", "text", "integer"]));
assert_eq!(params(&a("insert into foo (name, k) select name, :a from bar union all select :b, n from bar")), typed(&["integer", "text"]));
let returning = a("insert into foo (name, meta) select name, :m from bar where n > :n returning name, meta");
assert_eq!((params(&returning), returning.cardinality.as_str()), (vec![("text".to_string(), true), ("integer".to_string(), false)], "many"));
assert_eq!(params(&a("insert into foo (name, meta) select name, 'x' from bar returning (select :p) as p")), typed(&["unknown"]));
assert_eq!(params(&a("insert into foo (name, k) values ('a', (select :p))")), typed(&["integer"]));
let copy = a("insert into foo2 select * from foo");
assert_eq!((copy.kind.map_or("", StatementKind::as_str), copy.cardinality.as_str()), ("insert", "none"));
}
#[test]
fn the_hosts_sqlite_decides_which_functions_exist() {
let sql = "select id, ACOS(score) as a from users where name = :n";
let a = on_host(sql, &ddl(), &[], Vec::new());
assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
assert_eq!(a.diagnostics[0].message, "no such function: ACOS on this database's SQLite");
assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length, a.diagnostics[0].code), (sql.find("ACOS").unwrap(), 4, 6));
assert!(a.columns.is_empty());
let a = on_host(sql, &ddl(), &[("acos", 1, 's')], Vec::new());
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
assert_eq!(col(&a, "a"), ("real".into(), true));
let a = on_host("select soundex(name) as s from users where soundex(:x) = 'A000'", &ddl(), &[("SOUNDEX", 1, 's')], Vec::new());
assert_eq!((col(&a, "s"), param(&a, "x")), (("text".into(), false), "text".into()));
assert_eq!(on_host("select soundex(name) as s from users", &ddl(), &[], Vec::new()).diagnostics[0].message, "no such function: soundex on this database's SQLite");
assert_eq!(col(&analysis("select acos(score) as a, soundex(name) as s from users"), "a"), ("real".into(), true));
let a = on_host("select count(*) as n, max(name) as m, coalesce(email, 'x') as e, current_timestamp as t, email ->> '$.a' as j, row_number() over (order by id) as r from users where name like :p and email glob 'a*' and iif(id > 1, true, false)", &ddl(), &[], Vec::new());
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
for sql in [
"select row_number() over (order by sqrt(score)) as r from users",
"select id from users where id in (select id from users where sqrt(score) > 1)",
"with w as (select sqrt(score) as s from users) select s from w",
"select id from users order by sqrt(score)",
"update users set score = sqrt(score) where id = :id",
"insert into users (name, score) values (:n, sqrt(:s))",
"delete from users where id = :id returning sqrt(score) as s",
] {
let a = on_host(sql, &ddl(), &[], Vec::new());
assert_eq!(a.diagnostics.first().map(|d| (d.message.as_str(), d.start)), Some(("no such function: sqrt on this database's SQLite", sql.find("sqrt").unwrap())), "{sql}");
}
let mut schema = ddl();
schema.push("create view roots as select id, sqrt(score) as root from users".into());
let sql = "select root from roots";
let a = on_host(sql, &schema, &[], Vec::new());
assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
assert_eq!((a.diagnostics[0].message.as_str(), a.diagnostics[0].start, a.diagnostics[0].length), ("no such function: sqrt on this database's SQLite (the view roots calls it)", 0, sql.len()));
assert_eq!(col(&on_host(sql, &schema, &[("sqrt", 1, 's')], Vec::new()), "root"), ("real".into(), true));
assert!(on_host("select id from users", &schema, &[], Vec::new()).diagnostics.is_empty());
let extra = [("host_only", 2, 's'), ("host_only", 3, 's'), ("host_agg", 1, 'a'), ("host_win", -1, 'w')];
let a = on_host("select host_only(name, 1) as two, host_only(name, 1, 2) as three from users where id = :id", &ddl(), &extra, Vec::new());
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
assert_eq!((col(&a, "two"), col(&a, "three"), a.cardinality.as_str()), (("unknown".into(), true), ("unknown".into(), true), "at_most_one"));
assert_eq!(on_host("select name from users where id = host_only(1, 2)", &ddl(), &extra, Vec::new()).cardinality, "many");
let a = on_host("select host_agg(score) as total from users", &ddl(), &extra, Vec::new());
assert_eq!((col(&a, "total"), a.cardinality.as_str()), (("unknown".into(), true), "one"));
let a = on_host("select host_win(score, 1) over (partition by name) as w, host_win(id) as plain from users", &ddl(), &extra, Vec::new());
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
assert_eq!(on_host("select host_only(name) from users", &ddl(), &extra, Vec::new()).diagnostics[0].message, "wrong number of arguments to function host_only()");
let html = vec![TotalFunction { name: "reylo_html".into(), arity: 1, returns: Affinity::Text }];
assert_eq!(col(&on_host("select reylo_html(name) as h from users", &ddl(), &[], html), "h"), ("text".into(), false));
assert_eq!(host_functions(&[]), None);
assert_eq!(host_functions(&[vec![serde_json::json!("abs"), serde_json::json!("1"), serde_json::json!("s")]]), Some(vec![HostFunction { name: "abs".into(), arity: 1, kind: 's' }]));
}
#[test]
fn the_replay_asks_the_host_for_its_functions_with_the_schema() {
let sql = "select acos(score) as a from users";
let lexed = lex::lex(sql, Dialect::Sqlite).unwrap();
let schema = crate::api::Answer::Rows { rows: ddl().iter().map(|d| vec![serde_json::Value::String(d.clone())]).collect() };
let ask = |answers: &HashMap<String, crate::api::Answer>| {
let host = Host::new(answers);
let analysis = analyze(sql, &lexed, &host, &[]);
let needs: Vec<String> = host
.needs()
.iter()
.map(|n| match n {
crate::api::Need::Query { sql, scope, .. } => format!("{sql} {scope:?}"),
crate::api::Need::Describe { sql, .. } => format!("describe {sql}"),
})
.collect();
(analysis, needs)
};
let mut answers = HashMap::new();
let (analysis, needs) = ask(&answers);
assert!(analysis.is_none());
assert_eq!(needs, [format!("{DDL_QUERY} Session"), format!("{FUNCTIONS_QUERY} Session")]);
answers.insert(format!("query:{DDL_QUERY}|[]"), schema);
assert_eq!(ask(&answers).1, [format!("{FUNCTIONS_QUERY} Session")]);
answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]));
let (analysis, needs) = ask(&answers);
assert!(needs.is_empty());
assert_eq!(analysis.unwrap().diagnostics[0].message, "no such function: acos on this database's SQLite");
answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[("acos", 1, 's')]));
assert!(ask(&answers).0.unwrap().diagnostics.is_empty());
answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), crate::api::Answer::Error { error: crate::api::DbError { message: "not authorized".into(), code: None, position: None } });
assert_eq!(col(&ask(&answers).0.unwrap(), "a"), ("real".into(), true));
answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), crate::api::Answer::Rows { rows: Vec::new() });
assert_eq!(col(&ask(&answers).0.unwrap(), "a"), ("real".into(), true));
}
#[test]
fn a_table_in_an_attached_database_is_named_as_one() {
let message = |schema: &str| format!("no such table: {schema}.users: the database has no schema `{schema}`. A database the application attaches at run time (ATTACH ... AS {schema}) is not in the file the type check reads, so a table in it cannot be typed");
for (sql, reference) in [
("select id, name from baz.users where id = :id", "baz.users"),
("select u.id from \"baz\".[users] u", "\"baz\".[users]"),
("select 1 from users join /* x */ baz . users b on b.id = users.id", "baz . users"),
("insert into baz.users (id) values (:id)", "baz.users"),
("update baz.users set name = :n where id = :id", "baz.users"),
("delete from baz.users where id = :id", "baz.users"),
] {
let a = analysis(sql);
assert_eq!(a.diagnostics.len(), 1, "{sql}: {:?}", a.diagnostics);
assert_eq!(a.diagnostics[0].message, message("baz"), "{sql}");
assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length), (sql.find(reference).unwrap(), reference.len()), "{sql}");
}
let sql = "select :auth.user_id as u, id from baz.users";
assert_eq!(analysis(sql).diagnostics[0].start, sql.find("baz").unwrap());
assert_eq!(analysis("select id from main.nope").diagnostics[0].message, "no such table: main.nope");
assert_eq!(analysis("select id from temp.nope").diagnostics[0].message, "no such table: temp.nope");
assert_eq!(analysis("select id from \"baz.users\"").diagnostics[0].message, "no such table: baz.users");
assert_eq!(analysis("select id from nope").diagnostics[0].message, "no such table: nope");
assert!(analysis("select main.users.id from main.users").diagnostics.is_empty());
}
#[test]
fn sqlites_own_tables_replay_without_a_note() {
let schema: Vec<String> = [
"CREATE TABLE t (id integer primary key autoincrement, v text)",
"CREATE TABLE sqlite_sequence(name,seq)",
"CREATE TABLE sqlite_stat1(tbl,idx,stat)",
"CREATE VIRTUAL TABLE ft USING fts5(body)",
"CREATE TABLE 'ft_data'(id INTEGER PRIMARY KEY, block BLOB)",
"CREATE TABLE 'ft_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID",
"CREATE TABLE 'ft_content'(id INTEGER PRIMARY KEY, c0)",
"CREATE TABLE 'ft_docsize'(id INTEGER PRIMARY KEY, sz BLOB)",
"CREATE TABLE 'ft_config'(k PRIMARY KEY, v) WITHOUT ROWID",
"CREATE VIRTUAL TABLE rt USING rtree(id, minx, maxx)",
"CREATE TABLE \"rt_rowid\"(rowid INTEGER PRIMARY KEY,nodeno)",
"CREATE TABLE \"rt_node\"(nodeno INTEGER PRIMARY KEY,data)",
"CREATE TABLE \"rt_parent\"(nodeno INTEGER PRIMARY KEY,parentnode)",
"CREATE VIRTUAL TABLE f4 USING fts4(body)",
"CREATE TABLE 'f4_content'(docid INTEGER PRIMARY KEY, 'c0body')",
"CREATE TABLE 'f4_segments'(blockid INTEGER PRIMARY KEY, block BLOB)",
"CREATE TABLE 'f4_segdir'(level INTEGER,idx INTEGER,start_block INTEGER,leaves_end_block INTEGER,end_block INTEGER,root BLOB,PRIMARY KEY(level, idx))",
"CREATE TABLE 'f4_docsize'(docid INTEGER PRIMARY KEY, size BLOB)",
"CREATE TABLE 'f4_stat'(id INTEGER PRIMARY KEY, value BLOB)",
]
.iter()
.map(|s| s.to_string())
.collect();
let a = |sql: &str, schema: &[String]| analyze_ddl(sql, schema, &Extras::default()).analysis;
let failed = a("select nope from t", &schema);
assert_eq!(failed.diagnostics.iter().map(|d| d.message.as_str()).collect::<Vec<_>>(), ["no such column: nope"]);
for sql in [
"select name, seq from sqlite_sequence where name = :n",
"update sqlite_sequence set seq = :s where name = :n",
"select tbl, idx, stat from sqlite_stat1",
"select name, sql from sqlite_schema where type = 'table'",
"select name from sqlite_master",
"select rowid, body from ft where ft match :q",
"select id from rt where minx > :x",
"select docid from f4 where f4 match :q",
"select block from ft_data where id = :id",
"insert into t (v) values (:v) returning id",
] {
let got = a(sql, &schema);
assert!(got.diagnostics.is_empty(), "{sql}: {:?}", got.diagnostics);
}
assert_eq!(a("insert into t (v) values (:v) returning id", &schema).cardinality, "one");
assert_eq!(a("delete from sqlite_schema", &schema).diagnostics[0].message, "table sqlite_master may not be modified");
let later = vec!["CREATE TABLE sqlite_sequence(name,seq)".to_string(), "CREATE TABLE u (id integer primary key autoincrement, v text)".to_string()];
assert!(a("select seq from sqlite_sequence", &later).diagnostics.is_empty());
assert_eq!(a("insert into u (v) values (:v) returning id", &later).cardinality, "one");
assert_eq!(a("select nope from u", &later).diagnostics.len(), 1);
let broken = vec!["CREATE TABLE t (id integer primary key)".to_string(), "CREATE TABLE t (id integer primary key)".to_string(), "CREATE VIEW v AS SELECT".to_string()];
let notes: Vec<String> = a("select nope from t", &broken).diagnostics.iter().map(|d| d.message.clone()).collect();
assert_eq!(notes, ["no such column: nope", "The schema replay skipped statement 2: table t already exists", "The schema replay skipped statement 3: incomplete input"]);
}
#[test]
fn a_double_quoted_word_that_names_no_column_is_refused_as_the_drivers_refuse_it() {
let schema = vec!["create table t (id integer primary key, v text default \"none\" check (v <> \"bad\"))".to_string()];
let a = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
for sql in ["select \"hello\"", "select \"hello\" from t", "select id from t where v = \"x\""] {
let messages: Vec<String> = a(sql).diagnostics.iter().map(|d| d.message.clone()).collect();
assert_eq!(messages, [format!("no such column: \"{}\" - should this be a string literal in single-quotes?", if sql.contains("hello") { "hello" } else { "x" })], "{sql}");
}
for sql in ["select \"id\", \"v\" from t", "select 'hello'", "insert into t (id) values (1) returning v"] {
assert!(a(sql).diagnostics.is_empty(), "{sql}: {:?}", a(sql).diagnostics);
}
}
#[test]
fn the_version_reported_is_the_embedded_sqlites() {
assert!(tree::version().starts_with("3.53."), "{}", tree::version());
}
#[test]
fn a_parameter_sqlite_reads_and_the_lexer_does_not_is_an_error_at_its_place() {
let unbound = |sql: &str| analysis(sql).diagnostics.iter().filter(|d| d.code == 1).map(|d| (d.start, d.length, d.message.clone())).collect::<Vec<_>>();
for written in [":été", ":1st", "@2x"] {
let sql = format!("select id from users where name = :n and email = {written}");
let found = unbound(&sql);
assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(sql.find(written).unwrap(), written.len())], "{sql}");
assert_eq!(found[0].2, format!("SQLite reads {written} as a parameter that Reylo does not bind; name a parameter with the letters a to z, digits and underscores, starting with a letter or an underscore"));
}
let sql = "select ':été' from users where name = :été";
assert_eq!(unbound(sql).iter().map(|(s, _, _)| *s).collect::<Vec<_>>(), [sql.rfind(":été").unwrap()]);
for sql in ["select id from users where name = :n and email = :e", "select id from users where name = ?2 and email = ?", "select id as [it's], :n as n from users", "pragma table_info(users)"] {
assert!(unbound(sql).is_empty(), "{sql}");
}
assert_eq!(analysis("select id as [it's], :n as n from users").params.len(), 1);
}
#[test]
fn a_parameter_as_a_whole_sort_or_group_key_is_an_error_at_its_place() {
let full = |sql: &str| {
let ddl = ["create table users (id integer primary key, name text not null, email text unique, score real, avatar blob, created_at text not null default current_timestamp)"];
let rows = ddl.iter().map(|d| vec![serde_json::Value::String(d.to_string())]).collect();
let answers = HashMap::from([(format!("query:{DDL_QUERY}|[]"), crate::api::Answer::Rows { rows }), (format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]))]);
let host = Host::new(&answers);
<crate::api::Sqlite as reylo_engine_core::database::Database>::analyze(sql, &host).expect("answered")
};
let keys = |sql: &str| full(sql).diagnostics.iter().filter(|d| d.code == 17).map(|d| (d.start, d.length, d.message.clone())).collect::<Vec<_>>();
let at = |sql: &str, written: &str| sql.find(written).unwrap();
for (sql, length) in [("select id from users order by :sort", 5), ("select id from users order by :sort::text desc", 11), ("select id from users order by cast(:sort as text)", 5), ("select id from users order by :sort collate nocase", 5)] {
let found = keys(sql);
assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(at(sql, ":sort"), length)], "{sql}");
assert_eq!(found[0].2, "order by :sort sorts every row by the same value, since a parameter is a value and not a column's name; choose the column with case :sort when 'name' then name end");
}
for (sql, written) in [("select id from users order by ?", "?"), ("select id from users order by ?2", "?2"), ("select id from users order by @s", "@s"), ("select id from users order by $s", "$s")] {
let found = keys(sql);
assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(at(sql, written), written.len())], "{sql}");
assert!(found[0].2.starts_with(&format!("order by {written} sorts every row")), "{sql}");
}
assert_eq!(keys("select id from users order by ?2, ?1").iter().map(|(s, ..)| *s).collect::<Vec<_>>(), [30, 34]);
assert_eq!(keys("select id from users order by name, ?").len(), 1);
assert_eq!(keys("select count(*) as n from users group by :g")[0].2, "group by :g puts every row in one group, since a parameter is a value and not a column's name; choose the column with case :g when 'name' then name end");
assert!(keys("select count(*) as n from users group by name, :g::text")[0].2.starts_with("group by :g groups every row by the same value"));
let sql = "select row_number() over (partition by :p order by :o) as n from users";
let found = keys(sql);
assert_eq!(found.iter().map(|(s, _, m)| (*s, m.split(',').next().unwrap().to_string())).collect::<Vec<_>>(), [(at(sql, ":p"), "partition by :p puts every row in one partition".to_string()), (at(sql, ":o"), "order by :o sorts every row by the same value".to_string())]);
assert_eq!(keys("select row_number() over w as n from users window w as (order by :o)").len(), 1);
assert_eq!(keys("select group_concat(name, ',' order by :o) as names from users").len(), 1);
assert_eq!(keys("select id from (select id from users order by :s limit 3) t").len(), 1);
assert_eq!(keys("with t as (select name from users group by :g, name) select a.name from t a, t b").len(), 1);
assert_eq!(keys("select id from users where id in (select id from users order by :s limit 3)").len(), 1);
let refused = full("select id from users union select id from users order by :s");
assert_eq!(refused.diagnostics.iter().map(|d| (d.code, d.message.as_str())).collect::<Vec<_>>(), [(6, "1st ORDER BY term does not match any column in the result set")]);
assert_eq!(keys("insert into users (name) select name from users order by :s").len(), 1);
for sql in [
"select id, :tag as tag from users order by 2",
"select id, :tag as tag from users order by tag",
"select :tenant as tenant, name, count(*) as n from users group by 1, 2",
"select id, name from users order by case :sort when 'name' then name end",
"select id from users order by case when :desc then id end desc, id",
"select id from users order by 1 limit :n",
"select id from users order by lower(:x) || name",
] {
assert_eq!(keys(sql), [], "{sql}");
}
let a = full("select id from users order by :sort::text");
assert_eq!(a.columns.len(), 1);
assert_eq!(affinity_of(&a.params[0].ty), Some("text"));
}
#[test]
fn names_a_column_as_the_statement_is_sent() {
let names = |sql: &str| analysis(sql).columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>();
assert_eq!(names("select id + cast(:a as integer), name from users"), ["id + cast(? as integer)", "name"]);
assert_eq!(names("select * from (select id + cast(:a as integer) from users)"), ["id + cast(? as integer)"]);
assert_eq!(names("update users set name = name returning id + cast(:a as integer)"), ["id + cast(? as integer)"]);
assert_eq!(names("select cast(:a as integer) as a"), ["a"]);
}
#[test]
fn prepares_the_numbered_rewrite() {
let a = analyzed("select name from users where email = :auth.email and id = :auth.id and score > :auth.email");
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
assert_eq!(param(&a, "auth.email"), "text");
assert_eq!(param(&a, "auth.id"), "integer");
assert_eq!(a.rewritten.sql, "select name from users where email = ? and id = ? and score > ?");
assert_eq!(a.rewritten.order, ["auth.email", "auth.id", "auth.email"]);
assert_eq!(param(&analyzed("select name from users where id = ?3"), "3"), "integer");
assert_eq!(param(&analyzed("select name from users where email = ?"), "1"), "text");
let sql = "select :auth.user_id, nope from users";
let a = analyzed(sql);
assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length), (sql.find("nope").unwrap(), 4));
}
#[test]
fn a_column_declared_without_a_type_holds_any_value() {
let ddl = vec!["CREATE TABLE t (a, b TEXT, c ANY)".to_string(), "CREATE TABLE s (x ANY, y INTEGER) STRICT".to_string()];
let r = analyze_ddl("SELECT t.a, t.b, s.x, s.y FROM t, s WHERE t.a = :a AND s.x = :x", &ddl, &Extras::default());
let a = &r.analysis;
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
assert_eq!(col(a, "a"), ("unknown".into(), false));
assert_eq!(col(a, "b"), ("text".into(), true));
assert_eq!(col(a, "x"), ("unknown".into(), false));
assert_eq!(col(a, "y"), ("integer".into(), true));
assert_eq!((param(a, "a"), param(a, "x")), ("unknown".into(), "unknown".into()));
let r = analyze_ddl("SELECT c FROM t", &ddl, &Extras::default());
assert_eq!(col(&r.analysis, "c"), ("numeric".into(), true));
}
#[test]
fn the_direct_entry_reads_a_schema_it_is_handed() {
let ddl = vec![
"CREATE TABLE todos (id uuid PRIMARY KEY NOT NULL, owner_id text NOT NULL, org_id uuid, title varchar(200) NOT NULL, done boolean NOT NULL DEFAULT 0, UNIQUE (owner_id, title))".to_string(),
"CREATE INDEX todos_org ON todos (org_id)".to_string(),
];
let sql = "SELECT t.id, t.title, t.org_id, t.done, count(*) OVER () AS n FROM todos t WHERE t.owner_id = :auth.user_id AND t.title = :title";
let r = analyze_ddl(sql, &ddl, &Extras::default());
let a = &r.analysis;
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
assert_eq!(a.kind, Some(StatementKind::Select));
assert!(r.readonly);
assert_eq!(col(a, "id"), ("numeric".into(), false));
assert_eq!(col(a, "title"), ("text".into(), false));
assert_eq!(col(a, "org_id"), ("numeric".into(), true));
assert_eq!(col(a, "n"), ("integer".into(), false));
assert_eq!(r.declared, [Some("uuid".to_string()), Some("varchar(200)".into()), Some("uuid".into()), Some("boolean".into()), None]);
assert_eq!(param(a, "auth.user_id"), "text");
assert_eq!(param(a, "title"), "text");
assert_eq!(a.cardinality, "at_most_one");
assert_eq!(a.rewritten.sql, "SELECT t.id, t.title, t.org_id, t.done, count(*) OVER () AS n FROM todos t WHERE t.owner_id = ? AND t.title = ?");
let r = analyze_ddl("INSERT INTO todos (id, owner_id, title) VALUES (:id, :owner, :title) RETURNING id, done", &ddl, &Extras::default());
assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
assert!(!r.readonly);
assert_eq!((r.analysis.kind.map_or("", StatementKind::as_str), r.analysis.cardinality.as_str()), ("insert", "one"));
assert_eq!(col(&r.analysis, "done"), ("bool".into(), false));
assert_eq!(r.unique_keys.len(), 1, "{:?}", r.unique_keys);
let mut keys = r.unique_keys["todos"].clone();
keys.sort();
assert_eq!(keys, [vec!["id".to_string()], vec!["owner_id".into(), "title".into()], vec!["rowid".into()]]);
let r = analyze_ddl("SELECT id FROM todos WHERE id = :a AND title = ?", &ddl, &Extras::default());
assert_eq!(r.analysis.diagnostics.len(), 1, "{:?}", r.analysis.diagnostics);
assert!(r.declared.is_empty() && !r.readonly);
}
#[test]
fn the_unique_keys_of_every_table_read() {
let mut schema = ddl();
schema.push("create unique index users_lower_name on users (lower(name))".into());
schema.push("create unique index posts_title on posts (title) where body is not null".into());
schema.push("create table tags (label text not null, post_id integer not null, primary key (post_id, label)) without rowid".into());
schema.push("create view titled as select p.id, p.title from posts p".into());
let r = analyze_ddl("select t.title, (select count(*) from tags g where g.post_id = t.id) as n from titled t where exists (select 1 from users u where u.id = :id)", &schema, &Extras::default());
assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
let mut tables: Vec<&String> = r.unique_keys.keys().collect();
tables.sort();
assert_eq!(tables, ["posts", "tags", "users"]);
assert_eq!(r.unique_keys["users"], [vec!["id".to_string()], vec!["email".into()]]);
assert_eq!(r.unique_keys["posts"], [vec!["id".to_string()]]);
assert_eq!(r.unique_keys["tags"], [vec!["post_id".to_string(), "label".into()]]);
assert!(analyze_ddl("select nope from users", &schema, &Extras::default()).unique_keys.is_empty());
}
fn html() -> Extras {
Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: 1, returns: Affinity::Text }], host: None }
}
#[test]
fn a_host_function_prepares_and_is_typed_from_its_argument() {
let r = analyze_ddl("select reylo_html(name) as h, reylo_html(email) as e, upper(reylo_html(:q)) as q from users", &ddl(), &html());
let a = &r.analysis;
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
assert_eq!(col(a, "h"), ("text".into(), false));
assert_eq!(col(a, "e"), ("text".into(), true));
assert_eq!(col(a, "q"), ("text".into(), false));
assert_eq!(r.declared, [None, None, None]);
let sql = "select id, reylo_html(name) as h from users";
for (extras, message) in [(Extras::default(), "no such function: reylo_html"), (Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: 2, returns: Affinity::Text }], host: None }, "wrong number of arguments to function reylo_html()")] {
let a = analyze_ddl(sql, &ddl(), &extras).analysis;
assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
assert_eq!(a.diagnostics[0].message, message);
assert_eq!((a.diagnostics[0].start, a.diagnostics[0].code), (sql.find("reylo_html").unwrap(), 6));
assert!(a.columns.is_empty());
}
let any = Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: -1, returns: Affinity::Text }], host: None };
let mut schema = ddl();
schema.push("create view safe_users as select id, reylo_html(name) as name from users".into());
let a = analyze_ddl("select name, reylo_html(name, name) as twice from safe_users", &schema, &any).analysis;
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
assert_eq!(col(&a, "name"), ("text".into(), false));
assert_eq!(col(&a, "twice"), ("text".into(), false));
}
#[test]
fn a_scalar_subquery_is_non_null_only_when_it_always_finds_one_row() {
let a = analysis("select (select count(*) from posts p where p.user_id = u.id) as n, (select max(title) from posts) as top, (select title from posts limit 1) as one, (select count(*) from posts group by user_id) as g, (select 1) as k from users u");
assert_eq!(col(&a, "n"), ("integer".into(), false));
assert_eq!(col(&a, "top"), ("text".into(), true));
assert_eq!(col(&a, "one"), ("text".into(), true));
assert_eq!(col(&a, "g"), ("integer".into(), true));
assert_eq!(col(&a, "k"), ("integer".into(), false));
}
#[test]
fn truth_values_are_marked_and_typed_boolean() {
let r = analyze_ddl(
"select id = 1 as a, exists (select 1 from posts) as b, name like 'x%' as c, not (score > 1) as d, case when id > 1 then true end as e, coalesce(email is null, false) as f, email in ('a', 'b') as g, id as h, id + 1 as i, (select p.id > 1 from posts p limit 1) as j, iif(id > 1, 0, 1) as k from users",
&ddl(),
&Extras::default(),
);
assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
assert_eq!(r.booleans, [true, true, true, true, true, true, true, false, false, true, false]);
assert_eq!(col(&r.analysis, "a"), ("bool".into(), false));
assert_eq!(col(&r.analysis, "b"), ("bool".into(), false));
assert_eq!(col(&r.analysis, "h"), ("integer".into(), false));
let r = analyze_ddl("select t.x, t.y from (select id > 1 as x, id as y from users) t", &ddl(), &Extras::default());
assert_eq!(r.booleans, [true, false]);
let r = analyze_ddl("select id > 1 as x from users union all select exists (select 1 from posts) union all select 0", &ddl(), &Extras::default());
assert_eq!(r.booleans, [false]);
let r = analyze_ddl("select id > 1 as x from users union all select email is null from users", &ddl(), &Extras::default());
assert_eq!(r.booleans, [true]);
let r = analyze_ddl("insert into users (name) values ('a') returning id, id > 0 as positive", &ddl(), &Extras::default());
assert_eq!(r.booleans, [false, true]);
assert!(analyze_ddl("select nope from users", &ddl(), &Extras::default()).booleans.is_empty());
}
#[test]
fn a_column_declared_boolean_is_typed_boolean_and_no_truth_value() {
let ddl = vec!["CREATE TABLE flags (id INTEGER PRIMARY KEY, done BOOLEAN NOT NULL, b bool, n INTEGER, t TINYINT(1))".to_string(), "CREATE VIEW v AS SELECT done FROM flags".to_string()];
let r = analyze_ddl("select f.done, b, n, t, f.done + 0 as plus, coalesce(b, f.done) as either, coalesce(b, 0) as zero, case when n > 0 then f.done end as c, (select done from flags limit 1) as sub, x.done as derived from flags f, (select done from flags) x", &ddl, &Extras::default());
assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
let types: Vec<String> = r.analysis.columns.iter().map(|c| affinity_of(&c.ty).unwrap_or("?").to_string()).collect();
assert_eq!(types, ["bool", "bool", "integer", "integer", "real", "bool", "numeric", "bool", "bool", "bool"]);
assert_eq!(r.booleans, [false; 10]);
let r = analyze_ddl("select done from v", &ddl, &Extras::default());
assert_eq!(col(&r.analysis, "done"), ("bool".into(), false));
let r = analyze_ddl("select done from flags union all select 5", &ddl, &Extras::default());
assert_ne!(affinity_of(&r.analysis.columns[0].ty), Some("bool"));
let r = analyze_ddl("select done from flags union all select id > 1 from flags", &ddl, &Extras::default());
assert_eq!(affinity_of(&r.analysis.columns[0].ty), Some("bool"));
}
fn ts(t: &Type, in_json: bool) -> String {
let null = |s: String, nullable: bool| if nullable { format!("{s} | null") } else { s };
let list = |s: String| if s.contains('|') { format!("({s})[]") } else { format!("{s}[]") };
match &t.kind {
Kind::Json(crate::types::JsonType { content: Some(c), .. }) => ts(&c.ty, true),
Kind::Struct(r) => {
let fields: Vec<String> = r.fields.iter().map(|f| format!("{}: {}", f.name, null(ts(&f.ty, true), f.nullable))).collect();
if fields.is_empty() { "Record<never, never>".into() } else { format!("{{ {} }}", fields.join("; ")) }
}
Kind::Array(a) => list(null(ts(&a.element.ty, true), a.element.nullable)),
Kind::Json(crate::types::JsonType { schema: Some(_), .. }) => schema_ts(&t.schema().unwrap_or(serde_json::Value::Bool(true))),
_ => match (affinity_of(t).unwrap_or("?"), in_json) {
("integer" | "real", _) | ("int8", true) => "number".into(),
("int8", false) => "bigint".into(),
("text", _) => "string".into(),
("numeric", _) => "number | string".into(),
("blob", false) => "Uint8Array".into(),
("bool", _) => "boolean".into(),
_ => "unknown".into(),
},
}
}
fn affinity_of(t: &Type) -> Option<&'static str> {
let name = t.label.as_deref().unwrap_or("");
match &t.kind {
Kind::Enum(e) => affinity_of(&e.ty),
Kind::Boolean(_) => Some("bool"),
Kind::Integer(_) if name == "BIGINT" => Some("int8"),
Kind::Integer(_) => Some("integer"),
Kind::Float(_) => Some("real"),
Kind::Text(_) => Some("text"),
Kind::Bytes(_) => Some("blob"),
Kind::Union(_) if is_boolean_declared(name) => Some("bool"),
Kind::Union(u) if u.members.len() == 2 => Some("text"),
Kind::Union(u) if u.members.len() == 3 => Some("real"),
Kind::Union(_) if affinity(name) == "integer" && is_int8_declared(name) => Some("int8"),
Kind::Union(_) => Some(affinity(name)),
_ => None,
}
}
fn schema_ts(s: &serde_json::Value) -> String {
if let Some(any) = s["anyOf"].as_array() {
return any.iter().map(schema_ts).collect::<Vec<_>>().join(" | ");
}
let kinds: Vec<&str> = match &s["type"] {
serde_json::Value::String(k) => vec![k.as_str()],
serde_json::Value::Array(ks) => ks.iter().filter_map(|k| k.as_str()).collect(),
_ => return "unknown".into(),
};
let one = |kind: &str| match kind {
"integer" | "number" => "number".to_string(),
"string" => "string".into(),
"null" => "null".into(),
"array" => match s["prefixItems"].as_array() {
Some(items) => format!("[{}]", items.iter().map(schema_ts).collect::<Vec<_>>().join(", ")),
None if s["items"] == false => "[]".into(),
None => {
let item = schema_ts(&s["items"]);
if item.contains('|') { format!("({item})[]") } else { format!("{item}[]") }
}
},
"object" => match s["properties"].as_object() {
_ if s["additionalProperties"] == false && s["properties"].as_object().is_none_or(|p| p.is_empty()) => "Record<never, never>".into(),
Some(p) if !p.is_empty() => format!("{{ {} }}", p.iter().map(|(k, v)| format!("{k}: {}", schema_ts(v))).collect::<Vec<_>>().join("; ")),
_ => format!("{{ [key: string]: {} }}", schema_ts(&s["additionalProperties"])),
},
_ => "unknown".into(),
};
kinds.into_iter().map(one).collect::<Vec<_>>().join(" | ")
}
fn shown(a: &Analysis) -> String {
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
a.columns.iter().map(|c| format!("{}: {}{}", c.name, ts(&c.ty, false), if c.nullable { " | null" } else { "" })).collect::<Vec<_>>().join("; ")
}
fn json_ddl() -> Vec<String> {
vec![
"create table users (id integer primary key, name text not null, email text unique, github_id bigint, score real, active boolean not null default 1, avatar blob, doc text, extra, n numeric)".to_string(),
"create table posts (id integer primary key, user_id integer not null references users(id), title text not null, body text) strict".to_string(),
"create view titled as select id, json_object('id', id, 'title', title) as post from posts".to_string(),
]
}
fn json_typed(sql: &str) -> String {
shown(&analyze_ddl(sql, &json_ddl(), &Extras::default()).analysis)
}
#[test]
fn json_whose_subtype_is_out_of_sight_is_any_json() {
assert_eq!(
json_typed("select json_object('ids', json_group_array(id)) as doc, json_array(max(json_object('t', title))) as top, json_object('n', count(*)) as counted, count(*) over () as total from posts group by user_id"),
"doc: { ids: unknown }; top: [unknown]; counted: { n: number }; total: number"
);
assert_eq!(json_typed("select json_object('ids', json_group_array(id)) as doc from posts group by user_id"), "doc: { ids: number[] }");
assert_eq!(json_typed("select json_object('ids', json((select json_group_array(id) from posts where user_id = u.id))) as doc, rank() over () as r from users u"), "doc: { ids: number[] }; r: number");
assert_eq!(json_typed("select json(json((select json_object('a', 1) where 0))) as v"), "v: { a: number } | null");
assert_eq!(json_typed("select json_object('k', json(jsonb((select json_object('a', 1) where 0)))) as w"), "w: { k: { a: number } | null }");
let schema = vec!["create table d (id integer primary key, a integer not null, j text as (json_object('a', a)) virtual, js text as (json_object('a', a)) stored, jj text as (j) virtual, label text as ('#' || a) virtual)".to_string()];
assert_eq!(shown(&analyze_ddl("select json_array(j, js, jj, label) as v from d", &schema, &Extras::default()).analysis), "v: [unknown, string | null, unknown, string | null]");
assert_eq!(shown(&analyze_ddl("select json_object('j', j) as v from (select j from d)", &schema, &Extras::default()).analysis), "v: { j: unknown }");
}
#[test]
fn a_number_beside_a_numeric_value_is_a_number_or_text() {
let schema = vec!["create table dts (id integer primary key, d date not null, dt datetime, n integer not null, x real not null, ok boolean not null)".to_string()];
let typed = |sql: &str| col(&analyze_ddl(sql, &schema, &Extras::default()).analysis, "v");
assert_eq!(typed("select ifnull(dt, 0) as v from dts"), ("numeric".into(), false));
assert_eq!(typed("select case when ok then d else 0 end as v from dts"), ("numeric".into(), false));
assert_eq!(typed("select coalesce(dt, 1.5) as v from dts"), ("numeric".into(), false));
assert_eq!(typed("select coalesce(n, 1.5) as v from dts"), ("integer".into(), false));
assert_eq!(typed("select iif(ok, n, x) as v from dts"), ("real".into(), false));
}
#[test]
fn a_window_call_is_no_value_every_row_shares() {
let count = |sql: &str| analyze_ddl(sql, &ddl(), &Extras::default()).analysis.cardinality;
assert_eq!(count("select distinct min(1) over (order by id rows between 1 preceding and 1 preceding) as m from users"), "many");
assert_eq!(count("select distinct max(1) filter (where id > 2) over (order by id) as m from users"), "many");
assert_eq!(count("select distinct 1 as m from users"), "at_most_one");
}
#[test]
fn a_date_conversion_newer_than_libsql_s_sqlite_is_nullable() {
let typed = |sql: &str| col(&analyze_ddl(sql, &ddl(), &Extras::default()).analysis, "v");
assert_eq!(typed("select strftime('%Y-%m-%d', 'now') as v"), ("text".into(), false));
assert_eq!(typed("select strftime('%G-W%V', 'now') as v"), ("text".into(), true));
assert_eq!(typed("select date('now', 'start of month', '+1 month', 'floor') as v"), ("text".into(), true));
}
#[test]
fn a_json_constructor_is_typed_as_the_json_it_builds() {
let profile = "select json_object('user', json_object('id', u.id, 'name', u.name), 'posts', json((select json_group_array(json_object('id', p.id, 'title', p.title)) from posts p where p.user_id = u.id))) as profile from users u where u.id = :id";
assert_eq!(json_typed(profile), "profile: { user: { id: number; name: string }; posts: { id: number; title: string }[] }");
let bare = profile.replace("json((select", "((select");
assert_eq!(json_typed(&bare), "profile: { user: { id: number; name: string }; posts: unknown }");
assert_eq!(json_typed("select (select json_group_array(id) from posts) as ids"), "ids: number[]");
assert_eq!(json_typed("select json((select json_object('n', name) from users where id = 1)) as u"), "u: { n: string } | null");
assert_eq!(json_typed("select json_array((select name from users where id = 1)) as a, json_group_array((select name from users where id = 1)) as g, json_group_object((select name from users where id = 1), id) as o from users"), "a: [string | null]; g: (string | null)[]; o: { [key: string]: number }");
let a = analyze_ddl(profile, &json_ddl(), &Extras::default()).analysis;
assert_eq!((a.columns[0].ty.kind.name(), a.cardinality.as_str()), ("json", "at_most_one"));
assert_eq!(
json_typed("select json_object('i', 1, 'id', id, 'big', github_id, 'r', score, 't', name, 'e', email, 'n', n, 'nul', null, 'cmp', id > 1, 'tru', true, 'flag', active, 'b', avatar, 'any', extra) as o from users"),
"o: { i: number; id: number; big: number | null; r: number | null; t: string; e: string | null; n: number | string | null; nul: unknown; cmp: number; tru: number; flag: number | string; b: unknown; any: unknown }"
);
assert_eq!(json_typed("select json_array(id, name, email, json_array(), json_object()) as a from users"), "a: [number, string, string | null, [], Record<never, never>]");
assert_eq!(json_typed("select json_object(name, id) as o, json_object('id', id, name, score) as m from users"), "o: { [key: string]: number }; m: { [key: string]: number | number | null }");
assert_eq!(json_typed("select json_object('k', id, 'k', name) as o from users"), "o: { k: string }");
assert_eq!(json_typed("select json_group_array(email) as e, json_group_object(name, id) as g from users where id < 0"), "e: (string | null)[]; g: { [key: string]: number }");
assert_eq!(json_typed("select json_group_array(id) filter (where id > 1) as f, json_group_array(id) over (order by id) as w from users"), "f: number[]; w: (number | null)[]");
assert_eq!(
json_typed("select json_object('f', json_group_array(id) filter (where id > 1)) as f, json_object('w', json_group_array(id) over ()) as w from users"),
"f: { f: unknown }; w: { w: unknown }"
);
assert_eq!(
json_typed("select u.id, (select json_group_array(p.title) from posts p where p.user_id = u.id) as titles, (select json_group_array(p.title) from posts p where p.user_id = u.id group by p.user_id) as grouped from users u"),
"id: number; titles: string[]; grouped: string[] | null"
);
assert_eq!(json_typed("select json(json_object('a', id)) as j, json(jsonb_object('a', id)) as b, json_object('a', jsonb_array(id), 'b', jsonb(json_array(1))) as o from users"), "j: { a: number }; b: { a: number }; o: { a: [number]; b: [number] }");
assert_eq!(json_typed("select jsonb(json_array(1)) as b, (select jsonb_group_array(id) from users) as g"), "b: Uint8Array; g: Uint8Array");
assert_eq!(json_typed("select post from titled"), "post: { id: number; title: string }");
assert_eq!(json_typed("with t as (select json_array(id) as x from users) select x from t"), "x: [number]");
assert_eq!(json_typed("select max(json_array(id)) as m from users"), "m: [number] | null");
assert_eq!(json_typed("insert into posts (user_id, title) values (1, 'a') returning json_object('id', id, 'title', title) as post"), "post: { id: number; title: string }");
}
#[test]
fn a_value_nests_as_json_only_where_it_keeps_sqlites_json_subtype() {
for (expr, ty) in [
("coalesce(json_array(id), 'x')", "[number]"),
("ifnull(json_array(id), 'x')", "[number]"),
("nullif(json_array(id), 'x')", "[number] | null"),
("iif(id > 1, json_array(id), json_array(0))", "[number]"),
("case when id > 1 then json_object('x', id) end", "{ x: number } | null"),
("json_array(id) collate nocase", "[number]"),
("+json_array(id)", "[number]"),
("likely(json_array(id))", "[number]"),
("json((select json_object('n', name) from users u2 where u2.id = users.id))", "{ n: string } | null"),
("json((select json_group_array(p.id) from posts p where p.user_id = users.id order by p.id))", "number[]"),
("json((select json_array(1)))", "[number]"),
("json_array((select name from users u2 where u2.id = users.id))", "[string | null]"),
("json_group_array((select name from users u2 where u2.id = users.id))", "(string | null)[]"),
("coalesce(json((select json_group_array(p.id) from posts p where p.user_id = users.id)), '[]')", "number[]"),
("coalesce(json_object('e', email), json_array())", "{ e: string | null }"),
("coalesce(json((select json_group_array(p.id) from posts p where p.user_id = users.id group by p.user_id)), json_array())", "number[]"),
("doc", "string | null"),
("json_array(id) || ''", "string"),
("upper(json_array(id))", "string"),
("length(json_array(id))", "number"),
("json_type(json_array(id))", "string"),
("json_array_length(json_array(id))", "number"),
] {
assert_eq!(json_typed(&format!("select json_object('a', {expr}) as o from users")), format!("o: {{ a: {ty} }}"), "{expr}");
}
for expr in [
"x",
"post",
"(select json_object('n', name) from users u2 where u2.id = users.id)",
"(select json_array(1))",
"(select json_object('id', id) from users order by name limit 1)",
"(select distinct json_array(id) from users)",
"(select json_array(1) union all select json_array(2))",
"lag(json_array(id)) over (order by id)",
"max(json_array(id), json_array(0))",
"cast(json_array(id) as text)",
"doc ->> '$.a'",
"json_pretty(json_array(1))",
"case when id > 1 then json_array(id) else 'x' end",
"case when id > 1 then json_array(id) else json_object('a', 1) end",
] {
let sql = format!("select json_object('a', {expr}) as o from (select *, json_array(id) as x from users) users, (select post from titled)");
assert_eq!(json_typed(&sql), "o: { a: unknown }", "{expr}");
}
for expr in ["json(doc)", "json_extract(doc, '$.a')", "doc -> '$.a'", "json_set(doc, '$.a', 1)", "json_quote(name)"] {
assert_eq!(json_typed(&format!("select json_object('a', {expr}) as o from users")), "o: { a: unknown | null }", "{expr}");
}
let not_null = vec!["create table js (id integer primary key, doc text not null check (json_valid(doc)), b blob not null check (json_valid(b, 8)))".to_string()];
for (expr, ty) in [
("json_object('k', json(doc))", "{ k: unknown | null }"),
("json_object('k', doc -> '$')", "{ k: unknown | null }"),
("json_object('k', json_extract(doc, '$'))", "{ k: unknown | null }"),
("json_object('k', json(b))", "{ k: unknown | null }"),
("json_group_array(json(doc))", "(unknown | null)[]"),
] {
assert_eq!(shown(&analyze_ddl(&format!("select {expr} as o from js"), ¬_null, &Extras::default()).analysis), format!("o: {ty}"), "{expr}");
}
let host = Extras { total: vec![TotalFunction { name: "json_array".into(), arity: -1, returns: Affinity::Text }, TotalFunction { name: "html".into(), arity: 1, returns: Affinity::Text }], host: None };
let a = analyze_ddl("select json_array(1) as a, json_object('b', html(name)) as b from users", &json_ddl(), &host).analysis;
assert_eq!(shown(&a), "a: string; b: { b: unknown }");
}
#[test]
fn a_deep_constructor_is_read_once_per_node() {
let ddl = vec!["create table users (id integer primary key, name text not null)".to_string()];
let deep = |open: &str, close: &str, n: usize| format!("select {}id{} as o from users", open.repeat(n), close.repeat(n));
let started = std::time::Instant::now();
for sql in [deep("json_object('a', ", ")", 240), deep("json_array(coalesce(length(json_object('a', ", ")), 1))", 60), deep("coalesce((select json_group_array(", ") from users), 1)", 12)] {
let a = crate::stack::run(|| analyze_ddl(&sql, &ddl, &Extras::default()).analysis);
assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
}
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
}
#[test]
fn built_json_beside_other_text_is_the_text_it_is() {
assert_eq!(
json_typed("select coalesce(json_array(id), 'x') as a, case when id > 1 then json_object('a', 1) else json_object('b', 2) end as b, coalesce(doc, json_array()) as c, iif(id > 1, json_array(id), null) as d from users"),
"a: [number]; b: string; c: string; d: [number] | null"
);
assert_eq!(json_typed("select json_array(id) as a from users union all select 'x'"), "a: string");
assert_eq!(json_typed("select json_array(id) as a from users union all select null"), "a: [number] | null");
let a = marked("select coalesce(CAST(:doc AS TEXT), json_array()) as d, json_object('a', :a) as o from users where json_array(id) = :j", &json_ddl(), &["doc"]);
assert_eq!(shown(&a), "d: string; o: { a: unknown }");
assert_eq!(a.params.iter().map(|p| format!("{} {} {}", p.name, ts(&p.ty, false), affinity_of(&p.ty).unwrap_or(""))).collect::<Vec<_>>(), ["doc string text", "a unknown ", "j string text"]);
}
#[test]
fn a_json_object_of_an_odd_count_of_arguments_is_built_in_alone() {
let sql = "select json_object('id', id, 'name') as j from users";
let odd = |extras: &Extras| analyze_ddl(sql, &ddl(), extras).analysis.diagnostics.iter().filter(|d| d.code == 15).count();
assert_eq!(odd(&Extras::default()), 1);
let listed = |arities: &[i32]| Extras { total: vec![], host: Some(arities.iter().map(|&arity| HostFunction { name: "json_object".into(), arity, kind: 's' }).collect()) };
assert_eq!(odd(&listed(&[-1])), 1);
assert_eq!(odd(&listed(&[-1, 3])), 0);
assert_eq!(odd(&Extras { total: vec![TotalFunction { name: "JSON_OBJECT".into(), arity: 3, returns: Affinity::Text }], host: None }), 0);
}
#[test]
fn a_modulo_by_a_fractional_literal_under_one_is_nullable() {
let schema = vec!["create table items (id integer primary key, qty integer not null)".to_string()];
let typed = |sql: &str| {
let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
col(&a, "r")
};
assert_eq!(typed("select qty % 0.5 as r from items"), ("real".into(), true));
assert_eq!(typed("select qty % 0.99 as r from items"), ("real".into(), true));
assert_eq!(typed("select qty % 1e-3 as r from items"), ("real".into(), true));
assert_eq!(typed("select qty % 2.5 as r from items"), ("real".into(), false));
assert_eq!(typed("select qty % 2 as r from items"), ("integer".into(), false));
assert_eq!(typed("select qty % 1e999 as r from items"), ("real".into(), false));
assert_eq!(typed("select qty / 0.5 as r from items"), ("real".into(), false));
assert_eq!(typed("select qty / 0 as r from items"), ("integer".into(), true));
}
#[test]
fn sqlite_only_syntax_parses() {
let a = analysis("select id from users limit :n, :m");
assert_eq!(param(&a, "n"), "integer");
assert_eq!(analysis("insert or replace into users (id, name) values (:id, :name) returning id").cardinality, "one");
}
#[test]
fn an_insert_that_leaves_out_a_required_column_is_an_error() {
let schema = |extra: &[&str]| -> Vec<String> {
let mut s: Vec<String> = [
"create table req (id integer primary key not null, name text not null, email text not null, note text)",
"create table dflt (id integer primary key, name text not null default 'x', nulled text not null default null, made text not null generated always as (id || 'x'))",
"create table keyed (k text not null, v text, primary key (k)) without rowid",
"create table plain_key (k int primary key, v text)",
"create table ign (id integer primary key, name text not null on conflict ignore)",
"create table rep (id integer primary key, name text not null on conflict replace)",
]
.iter()
.map(|s| s.to_string())
.collect();
s.extend(extra.iter().map(|s| s.to_string()));
s
};
let said = |sql: &str, extra: &[&str]| -> Vec<(String, String)> {
let a = analyze_ddl(sql, &schema(extra), &Extras::default()).analysis;
a.diagnostics.iter().filter(|d| d.code == 16).map(|d| (sql[d.start..d.start + d.length].to_string(), d.message.clone())).collect()
};
let one = |column: &str, table: &str| format!("Column \"{column}\" of \"{table}\" is NOT NULL with no default, and this insert leaves it out, so SQLite refuses every row it inserts.");
assert_eq!(said("insert into req (id, name) values (:id, :name)", &[]), [("req".to_string(), one("email", "req"))]);
assert_eq!(said("insert into req (id) values (1)", &[]), [("req".to_string(), "Columns \"name\", \"email\" of \"req\" are NOT NULL with no default, and this insert leaves them out, so SQLite refuses every row it inserts.".to_string())]);
assert_eq!(said("insert into req default values", &[]).len(), 1);
assert_eq!(said("insert into \"req\" (name) select 'a'", &[]).first().map(|d| d.0.as_str()), Some("\"req\""));
assert_eq!(said("insert into main.req (name) select 'a' union all select 'b'", &[]).first().map(|d| d.0.as_str()), Some("main.req"));
assert_eq!(said("insert or replace into req (name) values ('a')", &[]).len(), 1);
assert_eq!(said("replace into req (name) values ('a')", &[]).len(), 1);
assert_eq!(said("insert into req (id, name) values (1, 'a') on conflict do nothing", &[]).len(), 1);
assert_eq!(said("insert into rep (id) values (1)", &[]), [("rep".to_string(), one("name", "rep"))]);
assert_eq!(said("insert into dflt (id) values (1)", &[]), [("dflt".to_string(), one("nulled", "dflt"))]);
assert_eq!(said("insert into keyed (v) values ('a')", &[]), [("keyed".to_string(), one("k", "keyed"))]);
for sql in [
"insert into req (name, email) values (:name, :email)",
"insert into req values (1, 'a', 'b', null)",
"insert into req (NAME, Email) values ('a', 'b'), ('c', 'd')",
"insert into req select * from req",
"insert into dflt (nulled) values ('a')",
"insert into plain_key (v) values ('a')",
"insert or ignore into req (id) values (1)",
"insert into ign (id) values (1)",
"select 1",
"update req set name = 'a'",
] {
assert_eq!(said(sql, &[]), Vec::<(String, String)>::new(), "{sql}");
}
assert!(said("insert into req (id) values (1)", &["create trigger skip before insert on req begin select raise(ignore); end"]).is_empty());
assert!(said("insert into req (id) values (1)", &["create trigger skip insert on REQ begin select 1; end"]).is_empty());
assert!(said("insert into v (id) values (1)", &["create view v as select id, name from req", "create trigger vi instead of insert on v begin insert into req (id, name, email) values (new.id, 'a', 'b'); end"]).is_empty());
assert_eq!(said("insert into req (id) values (1)", &["create trigger later after insert on req begin select 1; end"]).len(), 1);
assert_eq!(said("insert into req (id) values (1)", &["create trigger other before update on req begin select 1; end"]).len(), 1);
assert_eq!(said("insert into uniq (tag) values ('x')", &["create table uniq (required text not null, tag text unique on conflict ignore)"]).len(), 1);
assert_eq!(said("insert into plain (rowid, tag) values (1, 'x')", &["create table plain (required text not null, tag text)"]).len(), 1);
assert_eq!(said("insert into ign (id, name) values (1, :name)", &[]).len(), 0);
assert_eq!(said("insert into /* audit */ req default values", &[]).first().map(|d| d.0.as_str()), Some("req"));
assert_eq!(said("insert into main . req default values", &[]).first().map(|d| d.0.as_str()), Some("main . req"));
assert_eq!(said("with s as (select :into as name) insert into req (name) select name from s", &[]).first().map(|d| d.0.as_str()), Some("req"));
assert!(said("insert into g (_shape) values ('[[0,0],[1,0],[0,1],[0,0]]')", &["create virtual table g using geopoly(name text not null)"]).is_empty());
assert!(said("explain insert into req (id) values (1)", &[]).is_empty());
assert!(said("explain query plan insert into req (id) values (1)", &[]).is_empty());
}
}