1use crate::analysis::{bare, constant_key, diag, KeyClause, ResultTarget};
14use crate::api::{Analysis, Column, Param, Scope};
15use crate::dialect::Dialect;
16use crate::fresh::Tables;
17use crate::host::{as_str, Host, Lazy};
18use crate::lex::{self, Lexed, Target};
19use crate::sqlite_tree::{self as tree, From, Node, Sel, Tree};
20use crate::types::{Cardinality, Field, FloatType, Kind, StatementKind, TextType, Type};
21
22#[derive(Debug, Clone, PartialEq)]
28enum Ty {
29 Scalar { name: String },
30 Object { fields: Vec<TyField> },
31 List { of: Box<Ty>, nullable_items: bool },
32 Json { schema: Option<serde_json::Value> },
33 Unknown,
34}
35
36#[derive(Debug, Clone, PartialEq)]
37struct TyField {
38 name: String,
39 ty: Ty,
40 nullable: bool,
41}
42use std::collections::{HashMap, HashSet};
43
44pub const DDL_QUERY: &str = "select sql from sqlite_schema where sql is not null and type in ('table', 'view', 'index', 'trigger') order by rowid";
48
49pub const FUNCTIONS_QUERY: &str = "select name, narg, type from pragma_function_list";
57
58#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct HostFunction {
61 pub name: String,
62 pub arity: i32,
64 pub kind: char,
66}
67
68pub fn host_functions(rows: &[Vec<serde_json::Value>]) -> Option<Vec<HostFunction>> {
71 let listed: Vec<HostFunction> = rows
72 .iter()
73 .filter_map(|row| {
74 let name = row.first().and_then(as_str)?.to_string();
75 let arity = row.get(1).and_then(|v| v.as_i64().or_else(|| v.as_str()?.parse().ok())).unwrap_or(-1) as i32;
76 let kind = row.get(2).and_then(as_str).and_then(|k| k.chars().next()).unwrap_or('s');
77 Some(HostFunction { name, arity, kind })
78 })
79 .collect();
80 (!listed.is_empty()).then_some(listed)
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct TotalFunction {
90 pub name: String,
91 pub arity: i32,
93 pub returns: Affinity,
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum Affinity {
100 Integer,
101 Real,
102 Text,
103 Blob,
104 Numeric,
105 Any,
107}
108
109impl Affinity {
110 pub fn name(self) -> &'static str {
112 match self {
113 Affinity::Integer => "integer",
114 Affinity::Real => "real",
115 Affinity::Text => "text",
116 Affinity::Blob => "blob",
117 Affinity::Numeric => "numeric",
118 Affinity::Any => "none",
119 }
120 }
121}
122
123#[derive(Debug, Clone, Default)]
126pub struct Extras {
127 pub total: Vec<TotalFunction>,
128 pub host: Option<Vec<HostFunction>>,
129}
130
131impl Extras {
132 fn function(&self, name: &str, args: usize) -> Option<&TotalFunction> {
135 self.total.iter().find(|f| f.name.eq_ignore_ascii_case(name) && (f.arity < 0 || f.arity as usize == args))
136 }
137}
138
139#[derive(Debug, Clone)]
142pub struct SqliteAnalysis {
143 pub analysis: Analysis,
144 pub declared: Vec<Option<String>>,
148 pub readonly: bool,
150 pub unique_keys: HashMap<String, Vec<Vec<String>>>,
156 pub booleans: Vec<bool>,
163}
164
165pub fn analyze(sql: &str, lexed: &Lexed, host: &Host, marked: &[String]) -> Lazy<Analysis> {
168 let schema = host.query(DDL_QUERY, Vec::new(), Scope::Session);
169 let functions = host.query(FUNCTIONS_QUERY, Vec::new(), Scope::Session);
170 let (rows, functions) = (schema?, functions?);
171 let ddl: Vec<String> = match rows {
172 Ok(rows) => rows.iter().filter_map(|r| r.first().and_then(as_str)).map(String::from).collect(),
173 Err(e) => return Some(bare(sql, lexed, Dialect::Sqlite, vec![diag(format!("Cannot read the schema: {}", e.message), 0, 1, 5)])),
174 };
175 let extras = Extras { total: Vec::new(), host: functions.ok().and_then(|rows| host_functions(&rows)) };
177 Some(run(sql, lexed, &ddl, &extras, marked).analysis)
178}
179
180pub fn analyze_ddl(sql: &str, ddl: &[String], extras: &Extras) -> SqliteAnalysis {
185 crate::stack::run(|| analyze_ddl_here(sql, ddl, extras))
186}
187
188fn analyze_ddl_here(sql: &str, ddl: &[String], extras: &Extras) -> SqliteAnalysis {
189 match crate::analysis::lexed(sql, Dialect::Sqlite) {
190 Ok(lexed) => run(sql, &lexed, ddl, extras, &[]),
191 Err(analysis) => SqliteAnalysis { analysis, declared: Vec::new(), readonly: false, unique_keys: HashMap::new(), booleans: Vec::new() },
192 }
193}
194
195fn result_targets(t: &Tree) -> Option<Vec<ResultTarget>> {
199 let target = |c: &tree::Col| if c.named || matches!(c.expr.op.as_str(), "column" | "id" | "dot") { ResultTarget::Named } else { ResultTarget::Unnamed(None) };
201 if let Some(returning) = &t.returning {
202 return Some(returning.iter().map(target).collect());
203 }
204 let mut first = t.statement.as_ref().filter(|_| t.dml.is_none())?;
205 while let Some(prior) = first.prior.as_deref() {
206 first = prior;
207 }
208 if first.values {
210 return Some(vec![ResultTarget::Unnamed(None); first.columns.len()]);
211 }
212 Some(first.columns.iter().map(target).collect())
213}
214
215const KINDS: &[&str] = &["select", "with", "values", "insert", "replace", "update", "delete"];
217
218fn run(sql: &str, lexed: &Lexed, ddl: &[String], extras: &Extras, marked: &[String]) -> SqliteAnalysis {
219 let failed = |analysis: Analysis| SqliteAnalysis { analysis, declared: Vec::new(), readonly: false, unique_keys: HashMap::new(), booleans: Vec::new() };
220 let statement = match lex::one_statement(sql, lexed, KINDS) {
221 Ok(statement) => statement,
222 Err(message) => return failed(bare(sql, lexed, Dialect::Sqlite, vec![diag(message, 0, sql.trim_end().len(), 10)])),
223 };
224 let numbered = lex::rewrite(sql, lexed, Target::Numbered);
228 let rewritten = lex::rewrite(sql, lexed, Target::Question);
229 let functions: Vec<(&str, i32)> = extras.total.iter().map(|f| (f.name.as_str(), f.arity)).collect();
230 let (triggers, replay) = replayed(ddl);
231 let skipping = skipping_triggers(&triggers);
232 let listed = listed(extras.host.as_deref());
233 let alter = if lexed.params.is_empty() { alter_column(&numbered.sql) } else { None };
237 let (prepared, sent) = match &alter {
238 Some((stand_in, _)) => (stand_in.as_str(), stand_in.as_str()),
239 None => (numbered.sql.as_str(), rewritten.sql.as_str()),
240 };
241 let t = match tree::analyze(&replay, prepared, sent, &functions, listed.as_deref()) {
242 Ok(t) => t,
243 Err(message) => return failed(bare(sql, lexed, Dialect::Sqlite, vec![diag(message, 0, sql.trim_end().len(), 6)])),
244 };
245 let mut diagnostics = Vec::new();
246 if let Some(err) = &t.error {
247 let offset = |o: usize| match &alter {
249 Some((_, after)) if o >= *after => o - 1,
250 _ => o,
251 };
252 let start = usize::try_from(err.offset).map_or(0, |o| numbered.to_original(offset(o))).min(sql.len());
253 let length = match err.length {
254 Some(length) if err.offset >= 0 => length,
255 _ if err.offset >= 0 => token_len(&sql[start..]),
256 _ => sql.trim_end().len(),
257 };
258 let message = match (&err.missing_function, &err.missing_schema) {
259 (Some(name), _) => match &err.view {
261 Some(view) => format!("no such function: {name} on this database's SQLite (the view {view} calls it)"),
262 None => format!("no such function: {name} on this database's SQLite"),
263 },
264 (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),
267 (None, None) => err.message.clone(),
268 };
269 let message = if matches!(statement, lex::Statement::Command(_)) { lex::refused_command(&message) } else { message };
270 diagnostics.push(diag(message, start, length, 6));
271 for e in &t.schema_errors {
273 let message = match &e.function {
274 Some(name) => format!("The schema replay could not register the host function {name}: {}", e.message),
275 None => format!("The schema replay skipped statement {}: {}", e.index + 1, e.message),
276 };
277 diagnostics.push(diag(message, 0, 1, 8));
278 }
279 return failed(bare(sql, lexed, Dialect::Sqlite, diagnostics));
280 }
281 for p in t.params.iter().filter(|p| !lexed_parameter(p, lexed)) {
285 let text = |start: &usize| lexed.opaque.iter().any(|(from, to)| (*from..*to).contains(start));
287 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())));
288 let written = p.name.as_deref().unwrap_or("a ? in this statement");
289 let (start, length) = at.unwrap_or((0, sql.trim_end().len()));
290 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));
291 }
292 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);
296 let constructors: Vec<&str> = ["json_object", "jsonb_object"].into_iter().filter(|n| !registered(n)).collect();
297 diagnostics.extend(crate::analysis::odd_pairs(sql, lexed, &constructors));
298 diagnostics.extend(constant_keys(sql, lexed, &t));
300 if let (false, Some(message)) = (matches!(statement, lex::Statement::Command(_)), unwritten(&t, &skipping)) {
303 let (start, length) = insert_target_at(sql, lexed).unwrap_or((0, sql.trim_end().len()));
304 diagnostics.push(diag(message, start, length, 16));
305 }
306 let nullable_params: HashSet<String> = lexed.params.iter().enumerate().filter(|(_, name)| marked.contains(name)).map(|(k, _)| format!("?{}", k + 1)).collect();
308 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()) };
309 let a = Analyzer { nullable_values: a.bare_nullable().into_iter().chain(a.nullable_params.iter().cloned()).collect(), ..a };
310 if let lex::Statement::Command(kind) = statement {
314 let columns: Vec<Column> = t.columns.iter().map(|c| Column::new(c.name.clone(), Type::unknown(), true)).collect();
315 let cardinality = if columns.is_empty() { Cardinality::None } else { Cardinality::Many };
316 let capabilities = crate::capabilities::of_command(&rewritten.sql, &kind);
317 let analysis = Analysis {
318 kind: Some(StatementKind::of(&kind)),
319 comment: None,
320 params: a.params(lexed).0,
321 columns,
322 cardinality,
323 cardinality_reason: None,
324 key: None,
325 unique: Vec::new(),
326 order: Vec::new(),
327 ordered: false,
328 value: false,
329 rewritten,
330 sql_mode: None,
331 style: lexed.style,
332 diagnostics,
333 unresolved: Vec::new(),
334 structured: Vec::new(),
335 errors: None,
336 capabilities: Some(capabilities),
337 read_only: false,
338 notes: Vec::new(),
339 tables: None,
340 domains: Default::default(),
341 };
342 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()] };
343 }
344 let (facts, kind) = a.columns();
345 let booleans = a.booleans();
346 let literals = a.literals();
347 let columns: Vec<Column> = facts
351 .into_iter()
352 .zip(a.flags())
353 .zip(&booleans)
354 .zip(&t.columns)
355 .zip(a.exacts())
356 .enumerate()
357 .map(|(i, (((((name, fact), flag), computed), public), exact))| {
358 let ty = if flag { Ty::Scalar { name: "bool".into() } } else { fact.ty };
359 let ty = descriptor(&ty, public.declared.as_deref(), *computed, exact);
360 let ty = match literals.get(i) {
361 Some(Some(written)) => reylo_engine_core::literal::narrow(&ty, written).unwrap_or(ty),
362 _ => ty,
363 };
364 Column::new(name, ty, !fact.non_null)
365 })
366 .collect();
367 let (params, refused) = a.params(lexed);
368 for (numbered, table, column) in refused {
371 let name = numbered.strip_prefix('?').and_then(|k| k.parse::<usize>().ok()).and_then(|k| lexed.params.get(k.checked_sub(1)?));
372 let Some(at) = name.and_then(|name| lexed.placeholders.iter().find(|p| &p.name == name)) else { continue };
373 let written = &sql[at.start..at.end];
374 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));
375 }
376 let (cardinality, reason) = a.cardinality();
377 let mut analysis = Analysis {
378 kind: (!kind.is_empty()).then(|| StatementKind::of(&kind)),
379 comment: None,
380 params,
381 columns,
382 cardinality,
383 cardinality_reason: reason,
384 key: None,
385 unique: Vec::new(),
386 order: Vec::new(),
387 ordered: false,
388 value: false,
389 rewritten,
390 sql_mode: None,
391 style: lexed.style,
392 diagnostics,
393 unresolved: Vec::new(),
394 structured: Vec::new(),
395 errors: None,
396 capabilities: Some(crate::capabilities::of_statement(&t)),
397 read_only: false,
398 notes: Vec::new(),
399 tables: Some(tables(&t)),
400 domains: Default::default(),
401 };
402 crate::analysis::names(sql, Dialect::Sqlite, &mut analysis, result_targets(&t).as_deref(), &|_| None);
403 let unique_keys = t.tables.iter().map(|(name, info)| (name.clone(), info.unique_keys.clone())).collect();
404 SqliteAnalysis { analysis, declared: t.columns.iter().map(|c| c.declared.clone()).collect(), readonly: t.readonly, unique_keys, booleans }
405}
406
407fn replayed(ddl: &[String]) -> (Vec<String>, Vec<String>) {
412 let (triggers, mut replay): (Vec<String>, Vec<String>) = ddl.iter().cloned().partition(|s| trigger_header(s).is_some());
413 replay.extend(triggers.iter().filter_map(|s| instead_of_stub(s)));
414 (triggers, replay)
415}
416
417fn listed(host: Option<&[HostFunction]>) -> Option<Vec<tree::Listed<'_>>> {
419 host.map(|host| host.iter().map(|f| (f.name.as_str(), f.arity, f.kind)).collect())
420}
421
422pub(crate) fn declares_replace(analysis: &Analysis, host: &Host) -> Lazy<bool> {
429 let schema = host.query(DDL_QUERY, Vec::new(), Scope::Session);
430 let functions = host.query(FUNCTIONS_QUERY, Vec::new(), Scope::Session);
431 let (Ok(rows), functions) = (schema?, functions?) else { return Some(true) };
432 let ddl: Vec<String> = rows.iter().filter_map(|r| r.first().and_then(as_str)).map(String::from).collect();
433 let host_functions = functions.ok().and_then(|rows| host_functions(&rows));
434 let (_, replay) = replayed(&ddl);
435 let sql = &analysis.rewritten.sql;
436 let Ok(t) = tree::analyze(&replay, sql, sql, &[], listed(host_functions.as_deref()).as_deref()) else { return Some(true) };
437 Some(t.dml.as_ref().and_then(|dml| t.tables.get(&dml.table)).is_none_or(|info| info.replaces))
438}
439
440fn reads_itself(sel: &Sel) -> bool {
443 let mut arm = Some(sel);
444 while let Some(a) = arm {
445 if a.from.iter().any(|f| f.recursive) {
446 return true;
447 }
448 arm = a.prior.as_deref();
449 }
450 false
451}
452
453fn tables(t: &Tree) -> Tables {
461 #[derive(Default)]
462 struct Walk {
463 read: Vec<String>,
464 ctes: Vec<String>,
465 }
466 impl Walk {
467 fn node(&mut self, n: &Node) {
468 if let Some(q) = &n.select {
469 self.sel(q);
470 }
471 for child in n.left.iter().chain(&n.right) {
472 self.node(child);
473 }
474 for child in n.list.iter().chain(&n.args) {
475 self.node(child);
476 }
477 }
478 fn sel(&mut self, s: &Sel) {
479 for c in &s.columns {
480 self.node(&c.expr);
481 }
482 for f in &s.from {
483 if f.cte {
484 self.ctes.extend(f.table.clone());
485 }
486 if f.cte || f.subquery.is_some() && f.table.is_none() {
487 if let Some(q) = &f.subquery {
488 self.sel(q);
489 }
490 } else if !f.tab_func {
491 self.read.extend(f.table.clone());
492 }
493 for n in f.args.iter().chain(&f.on) {
494 self.node(n);
495 }
496 }
497 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) {
498 self.node(n);
499 }
500 if let Some(prior) = &s.prior {
501 self.sel(prior);
502 }
503 }
504 }
505 let mut walk = Walk::default();
506 if let Some(s) = &t.statement {
507 walk.sel(s);
508 }
509 for c in t.returning.iter().flatten() {
510 walk.node(&c.expr);
511 }
512 let mut write = Vec::new();
513 if let Some(dml) = &t.dml {
514 write.push(dml.table.clone());
515 let upsert = dml.upserts.iter().flat_map(|u| u.set.iter().map(|s| &s.expr).chain(&u.where_));
516 for n in dml.values.iter().flatten().chain(dml.set.iter().map(|s| &s.expr)).chain(&dml.where_).chain(upsert) {
517 walk.node(n);
518 }
519 }
520 let Walk { mut read, ctes } = walk;
521 read.retain(|table| !ctes.iter().any(|cte| cte.eq_ignore_ascii_case(table)));
522 Tables { read, write, ..Default::default() }
523}
524
525fn lexed_parameter(p: &tree::PublicParam, lexed: &Lexed) -> bool {
528 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))
529}
530
531fn constant_keys(sql: &str, lexed: &Lexed, t: &Tree) -> Vec<crate::api::Diagnostic> {
536 fn param(n: &Node) -> Option<i64> {
537 match n.op.as_str() {
538 "variable" => Some(n.index),
539 "cast" | "collate" => n.left.as_deref().and_then(param),
540 _ => None,
541 }
542 }
543 fn reads(n: &Node, out: &mut HashSet<i64>) {
545 if n.op == "variable" {
546 out.insert(n.index);
547 }
548 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) {
549 reads(child, out);
550 }
551 }
552 #[derive(Default)]
553 struct Walk {
554 found: Vec<(i64, KeyClause, bool)>,
555 }
556 impl Walk {
557 fn keys(&mut self, list: &[Node], clause: KeyClause) {
558 self.found.extend(list.iter().filter_map(param).map(|index| (index, clause, list.len() == 1)));
559 }
560 fn select_keys(&mut self, s: &Sel) {
565 let mut listed = HashSet::new();
566 s.columns.iter().for_each(|c| reads(&c.expr, &mut listed));
567 for (list, clause) in [(&s.group_by, KeyClause::GroupBy), (&s.order_by, KeyClause::OrderBy)] {
568 let alone = list.len() == 1;
569 self.found.extend(list.iter().filter_map(param).filter(|index| !listed.contains(index)).map(|index| (index, clause, alone)));
570 }
571 }
572 fn node(&mut self, n: &Node) {
573 self.keys(&n.order_by, KeyClause::OrderBy);
574 self.keys(&n.partition_by, KeyClause::PartitionBy);
575 if let Some(q) = &n.select {
576 self.sel(q);
577 }
578 for child in n.left.iter().chain(&n.right) {
579 self.node(child);
580 }
581 for child in n.list.iter().chain(&n.args).chain(&n.order_by).chain(&n.partition_by) {
582 self.node(child);
583 }
584 }
585 fn sel(&mut self, s: &Sel) {
586 self.select_keys(s);
587 for c in &s.columns {
588 self.node(&c.expr);
589 }
590 for f in &s.from {
591 if let Some(q) = &f.subquery {
592 self.sel(q);
593 }
594 for n in f.args.iter().chain(&f.on) {
595 self.node(n);
596 }
597 }
598 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) {
599 self.node(n);
600 }
601 if let Some(prior) = &s.prior {
602 self.sel(prior);
603 }
604 }
605 }
606 let mut walk = Walk::default();
607 if let Some(s) = &t.statement {
608 walk.sel(s);
609 }
610 for c in t.returning.iter().flatten() {
611 walk.node(&c.expr);
612 }
613 if let Some(dml) = &t.dml {
614 let upsert = dml.upserts.iter().flat_map(|u| u.set.iter().map(|s| &s.expr).chain(&u.where_));
615 for n in dml.values.iter().flatten().chain(dml.set.iter().map(|s| &s.expr)).chain(&dml.where_).chain(upsert) {
616 walk.node(n);
617 }
618 }
619 let mut out: Vec<_> = walk
621 .found
622 .into_iter()
623 .filter_map(|(index, clause, alone)| {
624 let name = lexed.params.get(usize::try_from(index).ok()?.checked_sub(1)?)?;
625 let p = lexed.placeholders.iter().find(|p| &p.name == name)?;
626 Some(constant_key(sql, p.start, p.end, clause, alone))
627 })
628 .collect();
629 out.sort_by_key(|d| d.start);
630 out.dedup_by_key(|d| d.start);
631 out
632}
633
634fn unwritten(t: &Tree, skipping: &HashMap<String, i32>) -> Option<String> {
643 let dml = t.dml.as_ref().filter(|d| d.kind == "insert")?;
644 let info = t.tables.get(&dml.table)?;
645 let ignored = dml.on_error == "ignore" || (dml.on_error == "default" && info.ignores_null);
646 let triggered = skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & TRIGGER_ROW_INSERT != 0);
647 if ignored || triggered {
648 return None;
649 }
650 let written = |name: &str| dml.columns.iter().flatten().any(|c| c.eq_ignore_ascii_case(name));
651 let alias = |name: &str| info.rowid_alias.as_deref().is_some_and(|a| a.eq_ignore_ascii_case(name));
652 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();
653 match missing.as_slice() {
654 [] => None,
655 [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)),
656 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)),
657 }
658}
659
660fn insert_target_at(sql: &str, lexed: &Lexed) -> Option<(usize, usize)> {
664 let bytes = sql.as_bytes();
665 let word = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$' || b >= 0x80;
667 let word_end = |mut at: usize| {
668 while at < bytes.len() && word(bytes[at]) {
669 at += 1;
670 }
671 at
672 };
673 let mut spans: Vec<(usize, usize)> = lexed.opaque.iter().copied().chain(lexed.placeholders.iter().map(|p| (p.start, p.end))).collect();
675 spans.sort_unstable();
676 let mut next = 0;
677 let comment = |at: usize| lexed.opaque.iter().find(|(from, _)| *from == at && (sql[at..].starts_with("--") || sql[at..].starts_with("/*"))).map(|(_, to)| *to);
678 let gap = |mut at: usize| loop {
680 while at < bytes.len() && bytes[at].is_ascii_whitespace() {
681 at += 1;
682 }
683 match comment(at) {
684 Some(to) => at = to,
685 None => return at,
686 }
687 };
688 let part = |at: usize| match lexed.opaque.iter().find(|(from, _)| *from == at) {
690 Some((_, to)) => Some(*to),
691 None => Some(word_end(at)).filter(|end| *end > at),
692 };
693 let mut at = 0;
694 let into = loop {
695 if at >= bytes.len() {
696 return None;
697 }
698 while spans.get(next).is_some_and(|(_, to)| *to <= at) {
699 next += 1;
700 }
701 if let Some((_, to)) = spans.get(next).filter(|(from, _)| *from <= at) {
702 at = *to;
703 } else if word(bytes[at]) {
704 let end = word_end(at);
705 if sql[at..end].eq_ignore_ascii_case("into") {
706 break end;
707 }
708 at = end;
709 } else {
710 at += 1;
711 }
712 };
713 let start = gap(into);
714 let mut end = part(start)?;
715 let dot = gap(end);
716 if bytes.get(dot) == Some(&b'.') {
717 end = part(gap(dot + 1))?;
718 }
719 Some((start, end - start))
720}
721
722fn token_len(rest: &str) -> usize {
723 rest.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_' || *c == ':' || *c == '$' || *c == '@' || *c == '?').count().max(1)
724}
725
726#[derive(Debug, Clone)]
728struct Fact {
729 ty: Ty,
730 non_null: bool,
731}
732
733impl Fact {
734 fn new(aff: &str, non_null: bool) -> Fact {
735 Fact { ty: affinity_type(aff), non_null }
736 }
737 fn unknown() -> Fact {
738 Fact { ty: Ty::Unknown, non_null: false }
739 }
740}
741
742fn int64() -> Type {
745 Type::integer(64)
746}
747fn real() -> Type {
748 Type::new(Kind::Float(FloatType { exponent_bits: 11, mantissa_bits: 52, infinity: true, ..FloatType::default() }))
749}
750fn text() -> Type {
751 Type::new(Kind::Text(TextType { encoding: Some("UTF-8".into()), ill_formed: true, ..TextType::default() }))
752}
753
754fn stored(aff: &str) -> Type {
757 let members = match aff {
758 "real" => vec![real(), text(), Type::bytes()],
759 "text" => vec![text(), Type::bytes()],
760 _ => vec![int64(), real(), text(), Type::bytes()],
761 };
762 Type::union(members)
763}
764
765fn descriptor(ty: &Ty, declared: Option<&str>, computed: bool, exact: bool) -> Type {
773 let declared = declared.map(str::trim).filter(|d| !d.is_empty()).filter(|d| match ty {
776 Ty::Scalar { name } if name == "bool" => is_boolean_declared(d),
777 Ty::Scalar { .. } => !is_boolean_declared(d) && column_type(d, affinity(d), false) == *ty,
778 _ => false,
779 });
780 match ty {
781 Ty::Scalar { name } if name == "bool" && computed => Type::boolean(),
782 Ty::Scalar { name } if name == "bool" => stored("numeric").named(declared.unwrap_or("BOOLEAN")),
783 Ty::Scalar { name } => match (declared, name.as_str()) {
784 (Some(d), "integer" | "int8") if exact => int64().named(d),
785 (Some(d), "real") if exact => real().named(d),
786 (Some(d), "text") if exact => text().named(d),
787 (Some(d), "blob") if exact => Type::bytes().named(d),
788 (Some(d), aff) => stored(if aff == "int8" { "integer" } else { aff }).named(d),
789 (None, "integer") => int64(),
790 (None, "int8") => int64().named("BIGINT"),
791 (None, "real") => real(),
792 (None, "text") => text(),
793 (None, "blob") => Type::bytes(),
794 (None, "numeric") => stored("numeric").named("NUMERIC"),
795 _ => Type::unknown(),
796 },
797 Ty::Object { .. } | Ty::List { .. } => Type::json_of(crate::types::Slot::non_null(content(ty))),
798 Ty::Json { schema: Some(schema) } => Type::json_schema_of(schema.clone()),
799 Ty::Json { schema: None } => Type::json(),
800 Ty::Unknown => Type::unknown(),
801 }
802}
803
804fn literals_of(n: &Node) -> Option<Vec<reylo_engine_core::literal::Literal>> {
808 use reylo_engine_core::literal::Literal;
809 match n.op.as_str() {
810 "null" => Some(Vec::new()),
811 "string" => Some(vec![Literal::Text(n.value.clone()?)]),
812 "integer" | "float" => Some(vec![Literal::Number(n.value.clone()?)]),
813 "truefalse" => Some(vec![Literal::Boolean(n.value.as_deref()?.eq_ignore_ascii_case("true"))]),
814 "neg" => match literals_of(n.left.as_deref()?)?.as_slice() {
815 [Literal::Number(v)] => Some(vec![Literal::Number(match v.strip_prefix('-') {
816 Some(positive) => positive.to_string(),
817 None => format!("-{v}"),
818 })]),
819 _ => None,
820 },
821 "pos" | "collate" => literals_of(n.left.as_deref()?),
822 "case" => {
823 let mut values = Vec::new();
825 for pair in n.list.chunks(2) {
826 values.extend(literals_of(pair.last()?)?);
827 }
828 Some(values)
829 }
830 _ => None,
831 }
832}
833
834fn content(ty: &Ty) -> Type {
837 match ty {
838 Ty::Object { fields } => Type::structure(fields.iter().map(|f| Field::new(f.name.clone(), content(&f.ty), f.nullable)).collect()),
839 Ty::List { of, nullable_items } => Type::array(crate::types::Slot::new(content(of), *nullable_items)),
840 other => descriptor(other, None, false, false),
841 }
842}
843
844fn column_type(declared: &str, aff: &str, strict: bool) -> Ty {
850 let declared = declared.trim();
851 if declared.is_empty() || (strict && declared.eq_ignore_ascii_case("any")) {
852 Ty::Unknown
853 } else if aff == "integer" && is_int8_declared(declared) {
854 Ty::Scalar { name: "int8".into() }
855 } else {
856 affinity_type(aff)
857 }
858}
859
860fn is_int8_declared(declared: &str) -> bool {
866 let base = declared.split('(').next().unwrap_or("").split_whitespace().map(str::to_ascii_lowercase).collect::<Vec<_>>().join(" ");
867 matches!(base.as_str(), "bigint" | "int8" | "unsigned big int")
868}
869
870fn affinity_type(aff: &str) -> Ty {
872 match aff {
873 "integer" | "real" | "text" | "blob" | "numeric" => Ty::Scalar { name: aff.to_string() },
874 _ => Ty::Unknown,
875 }
876}
877
878fn scalar_name(t: &Ty) -> Option<&str> {
879 match t {
880 Ty::Scalar { name } => Some(name.as_str()),
881 _ => None,
882 }
883}
884
885fn is_numeric(t: &Ty) -> bool {
886 matches!(scalar_name(t), Some("integer" | "int8" | "real" | "numeric"))
887}
888
889fn is_integral(t: &Ty) -> bool {
891 matches!(scalar_name(t), Some("integer" | "int8"))
892}
893
894fn computed(t: Ty) -> Ty {
899 if scalar_name(&t) == Some("int8") {
900 Ty::Scalar { name: "integer".into() }
901 } else {
902 t
903 }
904}
905
906fn shared(facts: &[&Fact]) -> Ty {
910 let known: Vec<&Ty> = facts.iter().map(|f| &f.ty).filter(|t| !matches!(t, Ty::Unknown)).collect();
911 let Some(first) = known.first() else { return Ty::Unknown };
912 if known.len() < facts.len() && known.iter().any(|t| is_built(t)) {
915 return Ty::Scalar { name: "text".into() };
916 }
917 if known.iter().all(|t| t == first) {
918 return (*first).clone();
919 }
920 if let Some(ty) = same_json(&known) {
921 return ty;
922 }
923 let known: Vec<Ty> = known.iter().map(|t| textual(t)).collect();
924 let known: Vec<&Ty> = known.iter().collect();
925 let first = known[0];
926 if known.iter().all(|t| *t == first) {
927 return first.clone();
928 }
929 if known.iter().all(|t| is_integral(t)) {
930 return Ty::Scalar { name: "int8".into() };
931 }
932 if known.iter().all(|t| is_numeric(t)) {
933 let numeric = known.iter().any(|t| scalar_name(t) == Some("numeric"));
936 return Ty::Scalar { name: if numeric { "numeric" } else { "real" }.into() };
937 }
938 Ty::Unknown
939}
940
941fn reached(args: &[Fact]) -> &[Fact] {
944 let count = args.iter().position(|f| f.non_null).map_or(args.len(), |i| i + 1);
945 &args[..count]
946}
947
948fn values_type(values: &[(&Node, &Fact)]) -> Ty {
954 let valued: Vec<&Fact> = values.iter().filter(|(e, _)| e.op != "null").map(|(_, f)| *f).collect();
955 if values.iter().any(|(e, f)| matches!(f.ty, Ty::Unknown) && e.op != "null" && e.op != "variable") {
956 return Ty::Unknown;
957 }
958 shared(&valued)
959}
960
961fn is_built(t: &Ty) -> bool {
963 matches!(t, Ty::Object { .. } | Ty::List { .. } | Ty::Json { .. })
964}
965
966fn textual(t: &Ty) -> Ty {
968 if is_built(t) { Ty::Scalar { name: "text".into() } } else { t.clone() }
969}
970
971fn same_json(types: &[&Ty]) -> Option<Ty> {
974 let empty = |t: &Ty| matches!(t, Ty::Json { schema: Some(s) } if s.get("prefixItems").is_none() && s["type"] == "array" && s["items"] == false);
975 let lists: Vec<&Ty> = types.iter().copied().filter(|t| !empty(t)).collect();
976 let first = lists.first()?;
977 (matches!(first, Ty::List { .. }) && lists.iter().all(|t| t == first)).then(|| (*first).clone())
978}
979
980#[derive(Debug, Clone, Copy, PartialEq, Eq)]
988enum Carry {
989 No,
991 Yes,
993 Maybe,
995}
996
997fn combine(carries: &[Carry]) -> Carry {
999 if carries.iter().all(|c| *c == Carry::No) {
1000 Carry::No
1001 } else if carries.iter().all(|c| *c == Carry::Yes) {
1002 Carry::Yes
1003 } else {
1004 Carry::Maybe
1005 }
1006}
1007
1008struct JsonFact {
1010 ty: Ty,
1011 non_null: bool,
1012 carry: Carry,
1013}
1014
1015fn is_json_result(name: &str) -> bool {
1020 name.starts_with("jsonb")
1021 || matches!(
1022 name,
1023 "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"
1024 )
1025}
1026
1027const PASSING: &[&str] = &["min", "max", "lag", "lead", "first_value", "last_value", "nth_value"];
1029
1030const PLAIN: &[&str] = &[
1032 "row_number", "rank", "dense_rank", "ntile", "percent_rank", "cume_dist", "count", "total", "sum", "avg", "group_concat", "string_agg", "abs", "round", "length", "instr",
1033 "json_valid", "octet_length", "json_array_length", "json_type", "unicode", "like", "glob", "regexp", "match", "concat", "concat_ws", "substr", "substring", "printf", "format",
1034 "upper", "lower", "trim", "ltrim", "rtrim", "replace", "char", "date", "time", "datetime", "julianday", "unixepoch", "strftime", "timediff", "hex", "quote", "typeof",
1035 "soundex", "sqlite_version", "sqlite_source_id", "current_date", "current_time", "current_timestamp", "random", "last_insert_rowid", "changes", "total_changes",
1036 "randomblob", "zeroblob", "->>", "atan", "atan2", "asinh", "sinh", "cosh", "tanh", "exp", "degrees", "radians", "ceil", "ceiling", "floor", "trunc", "sign", "acos", "acosh",
1037 "asin", "atanh", "cos", "sin", "tan", "ln", "log", "log10", "log2", "mod", "pow", "power", "sqrt", "pi",
1038 "bm25", "highlight", "snippet", "offsets", "matchinfo",
1039];
1040
1041fn in_json(t: &Ty) -> Ty {
1046 match scalar_name(t) {
1047 Some("integer" | "int8" | "real" | "text" | "numeric") => t.clone(),
1048 _ => Ty::Unknown,
1049 }
1050}
1051
1052fn nullable_in_json(f: &JsonFact) -> bool {
1057 match f.ty {
1058 Ty::Unknown => false,
1059 Ty::Json { schema: None } => true,
1060 _ => !f.non_null,
1061 }
1062}
1063
1064fn value_schema(t: &Ty, nullable: bool) -> serde_json::Value {
1067 use serde_json::json;
1068 let schema = match t {
1069 Ty::Scalar { name } => match name.as_str() {
1070 "integer" | "int8" => json!({"type": "integer", "format": "int64"}),
1071 "real" => json!({"type": "number", "format": "double"}),
1072 "text" => json!({"type": "string"}),
1073 "numeric" => json!({"type": ["number", "string"]}),
1074 _ => json!({}),
1075 },
1076 Ty::Object { fields } => {
1077 let properties: serde_json::Map<String, serde_json::Value> = fields.iter().map(|f| (f.name.clone(), value_schema(&f.ty, f.nullable))).collect();
1078 json!({"type": "object", "properties": properties, "required": fields.iter().map(|f| f.name.clone()).collect::<Vec<_>>(), "additionalProperties": false})
1079 }
1080 Ty::List { of, nullable_items } => json!({"type": "array", "items": value_schema(of, *nullable_items)}),
1081 Ty::Json { schema: Some(schema) } => schema.clone(),
1082 _ => json!({}),
1083 };
1084 if nullable { reylo_engine_core::schema::nullable(schema) } else { schema }
1085}
1086
1087fn record(values: Vec<serde_json::Value>) -> Ty {
1089 let mut distinct: Vec<serde_json::Value> = Vec::new();
1090 for v in values {
1091 if !distinct.contains(&v) {
1092 distinct.push(v);
1093 }
1094 }
1095 let rest = if distinct.len() == 1 { distinct.pop().unwrap_or_default() } else { serde_json::json!({"anyOf": distinct}) };
1096 Ty::Json { schema: Some(serde_json::json!({"type": "object", "additionalProperties": rest})) }
1097}
1098
1099type ScopeStack<'a> = Vec<&'a [From]>;
1101
1102struct Analyzer<'a> {
1103 tree: &'a Tree,
1104 extras: &'a Extras,
1105 skipping: &'a HashMap<String, i32>,
1108 nullable_params: HashSet<String>,
1112 nullable_values: HashSet<String>,
1116 written: std::cell::RefCell<HashSet<String>>,
1119 level: std::cell::RefCell<Level>,
1121 shapes: std::cell::RefCell<HashMap<usize, Option<Ty>>>,
1123 recursion: std::cell::RefCell<Vec<(String, Vec<Fact>)>>,
1126 settled: std::cell::RefCell<HashMap<usize, Vec<Fact>>>,
1128}
1129
1130#[derive(Debug, Clone, Default)]
1132struct Level {
1133 narrowed: HashSet<(i64, String)>,
1135 reduced: HashSet<i64>,
1137 grouped: bool,
1139 lone: HashSet<i64>,
1143 aggregating: u32,
1146 own: HashSet<i64>,
1148 around: HashSet<i64>,
1152 foreign: u32,
1157 windowed: bool,
1162}
1163
1164fn cast_variable<'n>(n: &'n Node, extras: &Extras) -> Option<&'n String> {
1167 let inner = match n.op.as_str() {
1168 "cast" => n.left.as_deref(),
1169 "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(),
1170 _ => None,
1171 }?;
1172 inner.name.as_ref().filter(|_| inner.op == "variable")
1173}
1174
1175fn level_of(sel: &Sel, extras: &Extras) -> Level {
1178 let own: HashSet<i64> = sel.from.iter().map(|f| f.cursor).collect();
1179 let outer: HashSet<i64> = sel.from.iter().filter(|f| f.outer).map(|f| f.cursor).collect();
1180 let extended: HashSet<i64> = sel.from.iter().filter(|f| f.left_of_right).map(|f| f.cursor).collect();
1183 let mut narrowed = HashSet::new();
1184 for term in conjuncts(sel.where_.as_ref()).into_iter().filter(|t| !t.outer_on) {
1185 narrowed.extend(strict_in(term, extras).into_iter().filter(|(cursor, _)| own.contains(cursor) && !(term.inner_on && extended.contains(cursor))));
1186 }
1187 let reduced = narrowed.iter().map(|(cursor, _)| *cursor).filter(|c| outer.contains(c)).collect();
1188 let lone = if sel.aggregate && sel.group_by.is_empty() { own.clone() } else { HashSet::new() };
1189 Level { narrowed, reduced, grouped: !sel.group_by.is_empty(), lone, aggregating: 0, own, around: HashSet::new(), foreign: 0, windowed: sel.window }
1190}
1191
1192fn reads_cursor(n: &Node, cursors: &HashSet<i64>) -> bool {
1195 if (n.op == "column" && cursors.contains(&n.cursor)) || n.select.is_some() {
1196 return true;
1197 }
1198 n.left.as_deref().is_some_and(|x| reads_cursor(x, cursors))
1199 || n.right.as_deref().is_some_and(|x| reads_cursor(x, cursors))
1200 || n.list.iter().chain(&n.args).chain(&n.order_by).chain(&n.partition_by).any(|x| reads_cursor(x, cursors))
1201}
1202
1203fn strict_in(n: &Node, extras: &Extras) -> HashSet<(i64, String)> {
1208 let nulls = |x: &Node| nulls_with(x, extras);
1209 match n.op.as_str() {
1210 "and" => n.left.iter().chain(n.right.iter()).flat_map(|x| strict_in(x, extras)).collect(),
1211 "or" => {
1212 let (Some(l), Some(r)) = (n.left.as_deref(), n.right.as_deref()) else { return HashSet::new() };
1213 let right = strict_in(r, extras);
1214 strict_in(l, extras).into_iter().filter(|c| right.contains(c)).collect()
1215 }
1216 "notnull" | "in" | "between" => n.left.as_deref().map(nulls).unwrap_or_default(),
1217 "=" | "!=" | "<" | "<=" | ">" | ">=" => n.left.iter().chain(n.right.iter()).flat_map(|x| nulls(x)).collect(),
1218 "not" => match n.left.as_deref() {
1219 Some(inner) if inner.op == "isnull" => inner.left.as_deref().map(nulls).unwrap_or_default(),
1220 Some(inner) => strict_in(inner, extras).into_iter().filter(|_| matches!(inner.op.as_str(), "=" | "!=" | "<" | "<=" | ">" | ">=" | "between") || (inner.op == "in" && inner.select.is_none())).collect(),
1223 None => HashSet::new(),
1224 },
1225 "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() => {
1226 n.args.iter().flat_map(nulls).collect()
1227 }
1228 "column" => nulls(n),
1229 _ => HashSet::new(),
1230 }
1231}
1232
1233fn nulls_with(n: &Node, extras: &Extras) -> HashSet<(i64, String)> {
1237 const STRICT: &[&str] = &["upper", "lower", "length", "abs", "trim", "ltrim", "rtrim", "substr", "substring", "replace", "round", "instr", "unicode", "sign", "octet_length"];
1238 match n.op.as_str() {
1239 "column" => n.column.clone().map(|c| HashSet::from([(n.cursor, c)])).unwrap_or_default(),
1240 "+" | "-" | "*" | "/" | "%" | "||" => n.left.iter().chain(n.right.iter()).flat_map(|x| nulls_with(x, extras)).collect(),
1241 "neg" | "pos" | "cast" | "collate" => n.left.as_deref().map(|x| nulls_with(x, extras)).unwrap_or_default(),
1242 "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(),
1243 _ => HashSet::new(),
1244 }
1245}
1246
1247fn alter_column(sql: &str) -> Option<(String, usize)> {
1252 let words = words(sql);
1253 let keyword = |i: usize, want: &str| words.get(i).is_some_and(|(w, quoted, _)| !quoted && w.eq_ignore_ascii_case(want));
1254 if !keyword(0, "alter") || !keyword(1, "table") {
1255 return None;
1256 }
1257 let alter = if keyword(3, ".") { 5 } else { 3 };
1259 if !keyword(alter, "alter") {
1260 return None;
1261 }
1262 let column = if keyword(alter + 1, "column") { alter + 2 } else { alter + 1 };
1263 if !keyword(column + 1, "to") {
1264 return None;
1265 }
1266 let byte = |chars: usize| sql.char_indices().nth(chars).map_or(sql.len(), |(at, _)| at);
1268 let at = byte(words[alter].2);
1269 let to = byte(words[column + 1].2) + 2;
1270 Some((format!("{}rename{} \"reylo libsql column\"", &sql[..at], &sql[at + 5..to]), at + 6))
1271}
1272
1273fn words(sql: &str) -> Vec<(String, bool, usize)> {
1278 let chars: Vec<char> = sql.chars().collect();
1279 let mut out = Vec::new();
1280 let mut i = 0;
1281 while i < chars.len() {
1282 let c = chars[i];
1283 if c.is_whitespace() {
1284 i += 1;
1285 } else if c == '-' && chars.get(i + 1) == Some(&'-') {
1286 i += chars[i..].iter().position(|c| *c == '\n').unwrap_or(chars.len() - i);
1287 } else if c == '/' && chars.get(i + 1) == Some(&'*') {
1288 i += 2;
1289 while i < chars.len() && !(chars[i] == '*' && chars.get(i + 1) == Some(&'/')) {
1290 i += 1;
1291 }
1292 i += 2;
1293 } else if matches!(c, '"' | '`' | '\'' | '[') {
1294 let close = if c == '[' { ']' } else { c };
1296 let mut name = String::new();
1297 let at = i;
1298 i += 1;
1299 while i < chars.len() {
1300 if chars[i] == close {
1301 if close != ']' && chars.get(i + 1) == Some(&close) {
1302 i += 1;
1303 } else {
1304 break;
1305 }
1306 }
1307 name.push(chars[i]);
1308 i += 1;
1309 }
1310 i += 1;
1311 out.push((name, true, at));
1312 } else if c.is_alphanumeric() || c == '_' || c == '$' || !c.is_ascii() {
1313 let end = chars[i..].iter().position(|c| !(c.is_alphanumeric() || *c == '_' || *c == '$' || !c.is_ascii())).map_or(chars.len(), |n| i + n);
1314 out.push((chars[i..end].iter().collect(), false, i));
1315 i = end;
1316 } else {
1317 out.push((c.to_string(), false, i));
1318 i += 1;
1319 }
1320 }
1321 out
1322}
1323
1324fn trigger_header(sql: &str) -> Option<(String, String, String)> {
1328 if !sql.as_bytes().windows(7).any(|w| w.eq_ignore_ascii_case(b"trigger")) {
1330 return None;
1331 }
1332 let words = words(sql);
1333 let keyword = |i: usize| words.get(i).filter(|(_, quoted, _)| !quoted).map(|(w, _, _)| w.to_ascii_lowercase());
1334 let take = |i: &mut usize, want: &[&str]| {
1336 let hit = keyword(*i).is_some_and(|w| want.contains(&w.as_str()));
1337 if hit {
1338 *i += 1;
1339 }
1340 hit
1341 };
1342 let mut i = 0;
1343 if !take(&mut i, &["create"]) {
1344 return None;
1345 }
1346 take(&mut i, &["temp", "temporary"]);
1347 if !take(&mut i, &["trigger"]) {
1348 return None;
1349 }
1350 if take(&mut i, &["if"]) {
1351 take(&mut i, &["not"]);
1352 take(&mut i, &["exists"]);
1353 }
1354 i += 1;
1356 if take(&mut i, &["."]) {
1357 i += 1;
1358 }
1359 let timing = if take(&mut i, &["before"]) {
1360 "before"
1361 } else if take(&mut i, &["after"]) {
1362 "after"
1363 } else if take(&mut i, &["instead"]) {
1364 take(&mut i, &["of"]);
1365 "instead"
1366 } else {
1367 "before"
1369 };
1370 let event = keyword(i)?;
1371 let on = (i..words.len()).find(|j| keyword(*j).as_deref() == Some("on"))?;
1373 let mut table = &words.get(on + 1)?.0;
1374 if keyword(on + 2).as_deref() == Some(".") {
1375 table = &words.get(on + 3)?.0;
1376 }
1377 Some((timing.to_string(), event, table.to_ascii_lowercase()))
1378}
1379
1380fn instead_of_stub(sql: &str) -> Option<String> {
1386 let (timing, _, _) = trigger_header(sql)?;
1387 if timing != "instead" {
1388 return None;
1389 }
1390 let words = words(sql);
1391 let keyword = |w: &(String, bool, usize)| !w.1 && (w.0.eq_ignore_ascii_case("when") || w.0.eq_ignore_ascii_case("begin"));
1392 let on = words.iter().position(|w| !w.1 && w.0.eq_ignore_ascii_case("on"))?;
1393 let after = if words.get(on + 2).is_some_and(|w| !w.1 && w.0 == ".") { on + 4 } else { on + 2 };
1395 let body = words.iter().skip(after).find(|w| keyword(w))?.2;
1396 let header: String = sql.chars().take(body).collect();
1397 Some(format!("{}\nBEGIN SELECT 1; END", header.trim_end()))
1399}
1400
1401const TRIGGER_ROW_INSERT: i32 = 4;
1404const TRIGGER_ROW_DELETE: i32 = 8;
1405const TRIGGER_ROW_UPDATE: i32 = 16;
1406
1407fn skipping_triggers(triggers: &[String]) -> HashMap<String, i32> {
1409 let mut out: HashMap<String, i32> = HashMap::new();
1410 for sql in triggers {
1411 let Some((timing, event, table)) = trigger_header(sql) else { continue };
1412 if timing == "after" {
1413 continue;
1414 }
1415 let bit = match event.as_str() {
1416 "insert" => TRIGGER_ROW_INSERT,
1417 "update" => TRIGGER_ROW_UPDATE,
1418 "delete" => TRIGGER_ROW_DELETE,
1419 _ => TRIGGER_ROW_INSERT | TRIGGER_ROW_UPDATE | TRIGGER_ROW_DELETE,
1420 };
1421 *out.entry(table).or_default() |= bit;
1422 }
1423 out
1424}
1425
1426#[derive(Clone, Copy)]
1428enum Nulls {
1429 Never,
1431 IfArgs,
1433 Always,
1435}
1436
1437impl Analyzer<'_> {
1438 fn columns(&self) -> (Vec<(String, Fact)>, String) {
1441 let t = self.tree;
1442 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() });
1443 let facts: Vec<Fact> = if let Some(returning) = &t.returning {
1444 let written = self.written_non_null();
1445 *self.written.borrow_mut() = written;
1446 returning.iter().map(|c| self.type_of(&c.expr, &Vec::new())).collect()
1447 } else if let (Some(sel), None) = (&t.statement, &t.dml) {
1448 (0..sel.columns.len()).map(|i| self.select_column(sel, i, &Vec::new())).collect()
1449 } else {
1450 Vec::new()
1451 };
1452 let columns = t
1453 .columns
1454 .iter()
1455 .enumerate()
1456 .map(|(i, public)| {
1457 (public.name.clone(), facts.get(i).cloned().unwrap_or_else(Fact::unknown))
1458 })
1459 .collect();
1460 (columns, kind)
1461 }
1462
1463 fn literals(&self) -> Vec<Option<Vec<reylo_engine_core::literal::Literal>>> {
1467 let t = self.tree;
1468 if let Some(returning) = &t.returning {
1469 return returning.iter().map(|c| literals_of(&c.expr)).collect();
1470 }
1471 let (Some(sel), None) = (&t.statement, &t.dml) else { return Vec::new() };
1472 let mut arms: Vec<&Sel> = Vec::new();
1473 let mut s = Some(sel);
1474 while let Some(arm) = s {
1475 arms.push(arm);
1476 s = arm.prior.as_deref();
1477 }
1478 arms.reverse();
1479 (0..sel.columns.len())
1480 .map(|i| {
1481 let mut values = Vec::new();
1482 for (k, arm) in arms.iter().enumerate() {
1483 if k > 0 && matches!(arm.op.as_deref(), Some("intersect" | "except")) {
1484 continue;
1485 }
1486 for e in std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i))) {
1487 values.extend(literals_of(e?)?);
1488 }
1489 }
1490 Some(values)
1491 })
1492 .collect()
1493 }
1494
1495 fn booleans(&self) -> Vec<bool> {
1497 self.result_truths(false)
1498 }
1499
1500 fn flags(&self) -> Vec<bool> {
1506 self.result_truths(true)
1507 }
1508
1509 fn result_truths(&self, declared: bool) -> Vec<bool> {
1510 let t = self.tree;
1511 let truths: Vec<bool> = if let Some(returning) = &t.returning {
1512 returning.iter().map(|c| self.truth(&c.expr, &Vec::new(), declared)).collect()
1513 } else if let (Some(sel), None) = (&t.statement, &t.dml) {
1514 (0..sel.columns.len()).map(|i| self.select_truth(sel, i, &Vec::new(), declared)).collect()
1515 } else {
1516 Vec::new()
1517 };
1518 (0..t.columns.len()).map(|i| truths.get(i).copied().unwrap_or(false)).collect()
1519 }
1520
1521 fn exacts(&self) -> Vec<bool> {
1524 let t = self.tree;
1525 let exact: Vec<bool> = if let Some(returning) = &t.returning {
1526 returning.iter().map(|c| self.exact(&c.expr, &Vec::new())).collect()
1527 } else if let (Some(sel), None) = (&t.statement, &t.dml) {
1528 (0..sel.columns.len()).map(|i| self.select_exact(sel, i, &Vec::new())).collect()
1529 } else {
1530 Vec::new()
1531 };
1532 (0..t.columns.len()).map(|i| exact.get(i).copied().unwrap_or(false)).collect()
1533 }
1534
1535 fn select_exact(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> bool {
1536 let mut s = Some(sel);
1537 while let Some(arm) = s {
1538 let mut inner = scope.clone();
1539 inner.push(&arm.from);
1540 if !arm.columns.get(i).is_some_and(|c| self.exact(&c.expr, &inner)) || !arm.rows.is_empty() {
1541 return false;
1542 }
1543 s = arm.prior.as_deref();
1544 }
1545 true
1546 }
1547
1548 fn exact(&self, n: &Node, scope: &ScopeStack) -> bool {
1549 if n.op != "column" {
1550 return false;
1551 }
1552 for froms in scope.iter().rev() {
1553 if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
1554 if let Some(sub) = f.subquery.as_deref() {
1555 return self.select_exact(sub, n.index.max(0) as usize, scope);
1556 }
1557 break;
1558 }
1559 }
1560 (n.strict && !n.generated) || n.rowid
1563 }
1564
1565 fn select_truth(&self, sel: &Sel, i: usize, scope: &ScopeStack, declared: bool) -> bool {
1567 let mut s = Some(sel);
1568 while let Some(arm) = s {
1569 let mut inner = scope.clone();
1570 inner.push(&arm.from);
1571 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))) {
1572 return false;
1573 }
1574 s = arm.prior.as_deref();
1575 }
1576 true
1577 }
1578
1579 fn truth(&self, n: &Node, scope: &ScopeStack, declared: bool) -> bool {
1584 let every = |nodes: &mut dyn Iterator<Item = &Node>| {
1585 let mut any = false;
1586 for x in nodes {
1587 if x.op == "null" {
1588 continue;
1589 }
1590 if !self.truth(x, scope, declared) {
1591 return false;
1592 }
1593 any = true;
1594 }
1595 any
1596 };
1597 match n.op.as_str() {
1598 "=" | "!=" | "<" | "<=" | ">" | ">=" | "is" | "is not" | "isnull" | "notnull" | "in" | "between" | "exists" | "and" | "or" | "not" | "truefalse" => true,
1599 "collate" => n.left.as_deref().is_some_and(|l| self.truth(l, scope, declared)),
1600 "function" if !n.agg && !n.window => match n.name.as_deref().unwrap_or("") {
1601 "like" | "glob" | "regexp" | "match" => self.extras.function(n.name.as_deref().unwrap_or(""), n.args.len()).is_none(),
1602 "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(),
1604 "likely" | "unlikely" | "likelihood" => n.args.first().is_some_and(|a| self.truth(a, scope, declared)),
1605 "coalesce" | "ifnull" => every(&mut n.args.iter()),
1606 "iif" | "if" => every(&mut iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i))),
1607 _ => false,
1608 },
1609 "case" => {
1611 let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
1612 let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
1613 every(&mut results.chain(otherwise))
1614 }
1615 "select" => n.select.as_deref().is_some_and(|sub| self.select_truth(sub, 0, scope, declared)),
1616 "column" => {
1617 for froms in scope.iter().rev() {
1618 if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
1619 if let Some(sub) = f.subquery.as_deref() {
1620 return self.select_truth(sub, n.index.max(0) as usize, scope, declared);
1621 }
1622 break;
1623 }
1624 }
1625 declared && !n.rowid && n.declared.as_deref().is_some_and(is_boolean_declared)
1626 }
1627 _ => false,
1628 }
1629 }
1630
1631 fn select_column(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> Fact {
1634 let mut arms: Vec<&Sel> = Vec::new();
1635 let mut s = Some(sel);
1636 while let Some(arm) = s {
1637 arms.push(arm);
1638 s = arm.prior.as_deref();
1639 }
1640 arms.reverse();
1641 let facts: Vec<(Option<&Node>, Fact)> = arms
1643 .iter()
1644 .flat_map(|arm| {
1645 let mut inner = scope.clone();
1646 inner.push(&arm.from);
1647 let outer = self.level.replace(self.level_within(arm));
1648 let rows = std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i)));
1649 let facts: Vec<(Option<&Node>, Fact)> = rows.map(|e| (e, e.map(|e| self.type_of(e, &inner)).unwrap_or_else(Fact::unknown))).collect();
1650 self.level.replace(outer);
1651 facts
1652 })
1653 .collect();
1654 let Some((_, first)) = facts.first() else { return Fact::unknown() };
1655 let values: Option<Vec<(&Node, &Fact)>> = facts.iter().map(|(e, f)| Some(((*e)?, f))).collect();
1656 let ty = match values {
1657 _ if facts.iter().all(|(_, f)| f.ty == first.ty) => first.ty.clone(),
1658 Some(values) => values_type(&values),
1659 None => Ty::Unknown,
1660 };
1661 Fact { ty, non_null: facts.iter().all(|(_, f)| f.non_null) }
1662 }
1663
1664 fn recursive_column(&self, name: &str, sub: &Sel, i: usize, scope: &ScopeStack) -> Fact {
1673 let key = sub as *const Sel as usize;
1674 if let Some(facts) = self.settled.borrow().get(&key) {
1675 return facts.get(i).cloned().unwrap_or_else(Fact::unknown);
1676 }
1677 let mut first = sub;
1678 while let Some(prior) = first.prior.as_deref() {
1679 first = prior;
1680 }
1681 let width = first.columns.len();
1682 let mut inner = scope.clone();
1683 inner.push(&first.from);
1684 let outer = self.level.replace(self.level_within(first));
1685 let mut assumed: Vec<Fact> = first.columns.iter().map(|c| Fact { ty: self.type_of(&c.expr, &inner).ty, non_null: true }).collect();
1686 self.level.replace(outer);
1687 let shapes = self.shapes.borrow().clone();
1691 let nested = self.settled.borrow().clone();
1692 let mut settled = None;
1693 for _ in 0..=width + 1 {
1694 *self.shapes.borrow_mut() = shapes.clone();
1695 *self.settled.borrow_mut() = nested.clone();
1696 self.recursion.borrow_mut().push((name.to_string(), assumed.clone()));
1697 let got: Vec<Fact> = (0..width).map(|k| self.select_column(sub, k, scope)).collect();
1698 self.recursion.borrow_mut().pop();
1699 if got.iter().zip(&assumed).all(|(g, a)| g.ty == a.ty && g.non_null == a.non_null) {
1700 settled = Some(got);
1701 break;
1702 }
1703 assumed = got.iter().zip(&assumed).map(|(g, a)| Fact { ty: g.ty.clone(), non_null: g.non_null && a.non_null }).collect();
1704 }
1705 if settled.is_none() {
1706 *self.shapes.borrow_mut() = shapes;
1707 *self.settled.borrow_mut() = nested;
1708 }
1709 let facts = settled.unwrap_or_else(|| vec![Fact::unknown(); width]);
1710 let fact = facts.get(i).cloned().unwrap_or_else(Fact::unknown);
1711 self.settled.borrow_mut().insert(key, facts);
1712 fact
1713 }
1714
1715 fn column_ref(&self, n: &Node, scope: &ScopeStack) -> Fact {
1717 if n.register && !n.view && !n.generated && n.column.as_ref().is_some_and(|c| self.written.borrow().contains(&c.to_ascii_lowercase())) {
1722 let aff = n.affinity.as_deref().unwrap_or(&n.aff);
1723 let ty = match &n.declared {
1724 Some(declared) if !n.rowid => column_type(declared, aff, n.strict),
1725 _ => affinity_type(aff),
1726 };
1727 return Fact { ty, non_null: true };
1728 }
1729 let (narrowed, reduced, lone) = {
1732 let level = self.level.borrow();
1733 (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)))
1734 };
1735 for froms in scope.iter().rev() {
1736 if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
1737 let index = n.index.max(0) as usize;
1738 let inner = match (&f.subquery, f.table.as_deref()) {
1739 (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),
1740 (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)),
1743 (Some(sub), Some(name)) if f.cte && reads_itself(sub) => Some(self.recursive_column(name, sub, index, scope)),
1744 (Some(sub), _) => Some(self.select_column(sub, index, scope)),
1745 (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)),
1747 _ => None,
1748 };
1749 if let Some(inner) = inner {
1750 return Fact { ty: inner.ty, non_null: !lone && (narrowed || (inner.non_null && ((!f.outer && !n.outer) || reduced))) };
1751 }
1752 break;
1753 }
1754 }
1755 if n.view && self.tree.dml.as_ref().is_some_and(|d| d.kind == "insert") {
1758 return Fact::unknown();
1759 }
1760 let aff = n.affinity.as_deref().unwrap_or(&n.aff);
1761 let ty = match &n.declared {
1762 Some(declared) if !n.rowid => column_type(declared, aff, n.strict),
1763 _ => affinity_type(aff),
1764 };
1765 Fact { ty, non_null: !lone && (narrowed || ((n.not_null || n.rowid) && (!n.outer || reduced))) }
1766 }
1767
1768 fn vector_key(&self, f: &From) -> Option<Fact> {
1775 let table = self.tree.tables.get(f.vector_table.as_deref()?)?;
1776 Some(if table.without_rowid { Fact { ty: Ty::Unknown, non_null: true } } else { Fact::new("integer", true) })
1777 }
1778
1779 fn call(&self, n: &Node, scope: &ScopeStack) -> Fact {
1784 if let Some(ty) = self.built_text(n, scope) {
1786 return Fact { ty, non_null: self.built_non_null(n, scope) };
1787 }
1788 let args: Vec<Fact> = n.args.iter().map(|a| self.type_of(a, scope)).collect();
1789 self.function(n, &args)
1790 }
1791
1792 fn built_non_null(&self, n: &Node, scope: &ScopeStack) -> bool {
1796 match (self.builtin_name(n), n.args.as_slice()) {
1797 (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) },
1798 _ => true,
1799 }
1800 }
1801
1802 fn type_of(&self, n: &Node, scope: &ScopeStack) -> Fact {
1803 let arg = |x: &Option<Box<Node>>| x.as_deref().map(|x| self.type_of(x, scope)).unwrap_or_else(Fact::unknown);
1804 match n.op.as_str() {
1805 "column" => self.column_ref(n, scope),
1806 "integer" => Fact::new(if integer_literal_fits(n) { "integer" } else { "real" }, true),
1807 "truefalse" => Fact::new("integer", true),
1808 "float" => Fact::new("real", true),
1809 "string" => Fact::new("text", true),
1810 "blob" => Fact::new("blob", true),
1811 "null" => Fact::unknown(),
1812 "variable" => Fact { ty: Ty::Unknown, non_null: n.name.as_ref().is_some_and(|name| !self.nullable_values.contains(name)) },
1814 "function" => {
1815 self.aggregated(n, || self.call(n, scope))
1816 }
1817 "+" | "-" | "*" => {
1818 let (l, r) = (arg(&n.left), arg(&n.right));
1819 Fact { ty: arithmetic(&l.ty, &r.ty), non_null: l.non_null && r.non_null }
1820 }
1821 "/" | "%" => {
1822 let (l, r) = (arg(&n.left), arg(&n.right));
1826 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());
1827 let literal_divisor = divisor.is_some_and(|v| if n.op == "%" { v as i64 != 0 } else { v != 0.0 });
1828 Fact { ty: arithmetic(&l.ty, &r.ty), non_null: l.non_null && r.non_null && literal_divisor }
1829 }
1830 "||" => {
1831 let (l, r) = (arg(&n.left), arg(&n.right));
1832 Fact::new("text", l.non_null && r.non_null)
1833 }
1834 "=" | "!=" | "<" | "<=" | ">" | ">=" | "and" | "or" | "in" | "between" | "&" | "|" | "<<" | ">>" => {
1835 let (l, r) = (arg(&n.left), arg(&n.right));
1836 let list_non_null = n.list.iter().all(|x| self.type_of(x, scope).non_null);
1837 let right_non_null = if n.right.is_some() { r.non_null } else { list_non_null && n.select.is_none() };
1838 Fact::new("integer", l.non_null && right_non_null)
1839 }
1840 "is" | "is not" | "isnull" | "notnull" | "exists" => Fact::new("integer", true),
1841 "not" | "~" => {
1842 let l = arg(&n.left);
1843 Fact::new("integer", l.non_null)
1844 }
1845 "neg" if n.left.as_deref().is_some_and(is_two_to_the_63) => Fact::new("integer", true),
1848 "neg" => {
1849 let l = arg(&n.left);
1850 Fact { ty: if is_numeric(&l.ty) { computed(l.ty) } else { Ty::Scalar { name: "real".into() } }, non_null: l.non_null }
1851 }
1852 "pos" => arg(&n.left),
1855 "cast" => {
1856 let l = arg(&n.left);
1857 Fact::new(n.affinity.as_deref().unwrap_or("none"), l.non_null)
1858 }
1859 "collate" => arg(&n.left),
1860 "case" => {
1861 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();
1863 let otherwise = if n.list.len() % 2 == 1 { n.list.last().map(|e| (e, self.type_of(e, scope))) } else { None };
1864 let mut all: Vec<&(&Node, Fact)> = results.iter().collect();
1865 if let Some(o) = &otherwise {
1866 all.push(o);
1867 }
1868 let values: Vec<(&Node, &Fact)> = all.iter().map(|(e, f)| (*e, f)).collect();
1869 Fact { ty: values_type(&values), non_null: otherwise.is_some() && all.iter().all(|(_, f)| f.non_null) }
1870 }
1871 "select" => {
1872 let Some(sub) = n.select.as_deref() else { return Fact::unknown() };
1876 let inner = self.select_column(sub, 0, scope);
1877 Fact { ty: inner.ty, non_null: inner.non_null && self.exactly_one(sub).is_ok() }
1878 }
1879 _ => Fact::unknown(),
1880 }
1881 }
1882
1883 fn function(&self, n: &Node, args: &[Fact]) -> Fact {
1885 let name = n.name.as_deref().unwrap_or("");
1886 let all_non_null = args.iter().all(|a| a.non_null);
1887 let first = args.first().cloned().unwrap_or_else(Fact::unknown);
1888 let done = |aff: &str, nulls: Nulls| {
1889 let non_null = match nulls {
1890 Nulls::Never => true,
1891 Nulls::IfArgs => all_non_null,
1892 Nulls::Always => false,
1893 };
1894 Fact::new(aff, non_null)
1895 };
1896 let typed = |ty: Ty, nulls: Nulls| Fact { ty, non_null: matches!(nulls, Nulls::Never) || (matches!(nulls, Nulls::IfArgs) && all_non_null) };
1897 if !n.agg && !n.window {
1898 if let Some(f) = self.extras.function(name, args.len()) {
1899 return done(f.returns.name(), Nulls::IfArgs);
1900 }
1901 }
1902 let name = sqlean_alias(name);
1903 if n.window {
1904 let has_a_row = holds_current_row(n);
1909 return match name {
1910 "row_number" | "rank" | "dense_rank" | "ntile" => done("integer", Nulls::Never),
1911 "percent_rank" | "cume_dist" => done("real", Nulls::Never),
1912 "count" => done("integer", Nulls::Never),
1913 "total" => done("real", total_nulls(&first)),
1914 "sum" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::Always),
1915 "avg" => done("real", Nulls::Always),
1916 "lag" | "lead" if args.len() >= 3 => typed(values_type(&[(&n.args[0], &args[0]), (&n.args[2], &args[2])]), Nulls::Always),
1918 "min" | "max" => typed(first.ty.clone(), if has_a_row { Nulls::IfArgs } else { Nulls::Always }),
1919 "lag" | "lead" | "first_value" | "last_value" | "nth_value" => typed(first.ty.clone(), Nulls::Always),
1920 "group_concat" | "string_agg" => done("text", Nulls::Always),
1921 _ => Fact::unknown(),
1922 };
1923 }
1924 if n.agg {
1925 let grouped = self.level.borrow().grouped;
1930 return match name {
1931 "count" => done("integer", Nulls::Never),
1932 "total" => done("real", total_nulls(&first)),
1933 "sum" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::Always),
1934 "avg" => done("real", Nulls::Always),
1935 "min" | "max" => typed(first.ty.clone(), if grouped { Nulls::IfArgs } else { Nulls::Always }),
1936 "group_concat" | "string_agg" => done("text", if grouped { Nulls::IfArgs } else { Nulls::Always }),
1937 "json_group_array" | "json_group_object" => done("text", Nulls::Never),
1938 "jsonb_group_array" | "jsonb_group_object" => done("blob", Nulls::Never),
1939 "median" | "percentile" | "percentile_25" | "percentile_75" | "percentile_90" | "percentile_95" | "percentile_99" => done("real", Nulls::Always),
1942 "stddev" | "stddev_pop" | "stddev_samp" | "variance" | "var_pop" | "var_samp" => done("real", Nulls::Always),
1944 _ => Fact::unknown(),
1945 };
1946 }
1947 let numbers = all_non_null && args.iter().all(|a| matches!(scalar_name(&a.ty), Some("integer" | "int8" | "real")));
1950 match name {
1951 "coalesce" | "ifnull" => Fact { ty: values_type(&n.args.iter().zip(reached(args)).collect::<Vec<_>>()), non_null: args.iter().any(|a| a.non_null) },
1954 "nullif" => Fact { ty: first.ty.clone(), non_null: false },
1955 "iif" | "if" => {
1958 let values = iif_values(args.len());
1959 let arms: Vec<(&Node, &Fact)> = values.iter().filter_map(|i| Some((n.args.get(*i)?, args.get(*i)?))).collect();
1960 Fact { ty: values_type(&arms), non_null: args.len() >= 3 && args.len() % 2 == 1 && arms.iter().all(|(_, a)| a.non_null) }
1961 }
1962 "min" | "max" => Fact { ty: values_type(&n.args.iter().zip(args).collect::<Vec<_>>()), non_null: all_non_null },
1963 "abs" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::IfArgs),
1965 "round" => done("real", Nulls::IfArgs),
1966 "length" | "instr" | "json_valid" | "octet_length" => done("integer", Nulls::IfArgs),
1967 "json_array_length" => done("integer", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
1969 "json_type" => done("text", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
1970 "json_remove" => done("text", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
1972 "unicode" => done("integer", Nulls::Always),
1974 "like" | "glob" | "regexp" | "match" | "likely" | "unlikely" | "likelihood" => {
1975 if matches!(name, "likely" | "unlikely" | "likelihood") { first.clone() } else { done("integer", Nulls::IfArgs) }
1976 }
1977 "concat" => done("text", Nulls::Never),
1980 "concat_ws" => Fact::new("text", first.non_null),
1981 "substr" | "substring" => {
1984 let blob = matches!(scalar_name(&first.ty), Some("blob"));
1985 let any = matches!(first.ty, Ty::Unknown) && n.args.first().is_some_and(|a| a.op != "variable");
1986 let ty = if blob { first.ty.clone() } else if any { Ty::Unknown } else { Ty::Scalar { name: "text".into() } };
1987 Fact { ty, non_null: all_non_null && !blob && !any }
1988 }
1989 "printf" | "format" => Fact::new("text", n.args.first().and_then(literal_text).is_some_and(printf_writes)),
1992 "upper" | "lower" | "trim" | "ltrim" | "rtrim" | "replace" | "json" | "json_patch" | "json_pretty" => done("text", Nulls::IfArgs),
1993 "char" | "json_array" | "json_object" | "json_quote" => done("text", Nulls::Never),
1995 "json_insert" | "json_replace" | "json_set" => Fact::new("text", first.non_null),
1996 "jsonb" => done("blob", Nulls::IfArgs),
1997 "date" | "time" | "datetime" => Fact::new("text", current_time(&n.args)),
2001 "julianday" => Fact::new("real", current_time(&n.args)),
2002 "unixepoch" => {
2004 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")));
2005 Fact::new(if whole { "integer" } else { "real" }, current_time(&n.args))
2006 }
2007 "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())),
2009 "timediff" => Fact::new("text", n.args.len() == 2 && current_time(&n.args[..1]) && current_time(&n.args[1..])),
2010 "hex" | "quote" | "typeof" => done("text", Nulls::Never),
2012 "soundex" => done("text", Nulls::IfArgs),
2015 "sqlite_version" | "sqlite_source_id" | "current_date" | "current_time" | "current_timestamp" => done("text", Nulls::Never),
2016 "random" | "last_insert_rowid" | "changes" | "total_changes" => done("integer", Nulls::Never),
2017 "randomblob" | "zeroblob" => done("blob", Nulls::IfArgs),
2018 "json_extract" | "jsonb_extract" | "->" | "->>" => Fact::unknown(),
2019 "atan" | "atan2" | "asinh" | "sinh" | "cosh" | "tanh" | "exp" | "degrees" | "radians" | "ceil" | "ceiling" | "floor" | "trunc" => Fact::new("real", numbers),
2022 "sign" => Fact::new("integer", numbers),
2023 "acos" | "acosh" | "asin" | "atanh" | "cos" | "sin" | "tan" | "ln" | "log" | "log10" | "log2" | "mod" | "pow" | "power" | "sqrt" => done("real", Nulls::Always),
2026 "pi" => done("real", Nulls::Never),
2027 "bm25" => done("real", if n.args.len() == 1 { Nulls::Never } else { Nulls::Always }),
2035 "highlight" | "snippet" => done("text", Nulls::Always),
2036 "offsets" => done("text", Nulls::Never),
2037 "matchinfo" => done("blob", Nulls::Never),
2038 "vector" | "vector32" | "vector64" | "vector1bit" | "vector8" | "vector16" | "vectorb16" => done("blob", Nulls::Never),
2042 "vector_extract" => done("text", Nulls::Never),
2043 "vector_distance_cos" | "vector_distance_l2" => done("real", Nulls::Always),
2046 "libsql_vector_idx" => Fact { ty: Ty::Unknown, non_null: first.non_null },
2049 "uuid4" | "gen_random_uuid" | "uuid7" => done("text", Nulls::Never),
2053 "uuid_str" => done("text", Nulls::Always),
2054 "uuid_blob" => done("blob", Nulls::Always),
2055 "uuid7_timestamp_ms" => done("integer", Nulls::Always),
2056 "md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" => done("blob", Nulls::IfArgs),
2059 "encode" => Fact::new("text", first.non_null),
2060 "decode" => Fact::new("blob", first.non_null),
2061 "levenshtein" | "dlevenshtein" | "edit_distance" | "osa_distance" | "hamming" => done("integer", Nulls::Never),
2064 "jaro_winkler" => done("real", Nulls::Never),
2065 "caverphone" | "phonetic_hash" | "rsoundex" => done("text", Nulls::IfArgs),
2066 "translit" => done("text", Nulls::Never),
2067 "script_code" => done("integer", Nulls::Never),
2068 "bit_length" | "char_length" | "character_length" | "text_size" | "text_bitsize" | "text_length" => done("integer", Nulls::IfArgs),
2070 "strpos" | "text_index" | "text_last_index" | "text_count" => done("integer", Nulls::IfArgs),
2071 "starts_with" | "text_has_prefix" | "text_has_suffix" | "text_contains" | "text_like" => done("integer", Nulls::IfArgs),
2072 "btrim" | "left" | "right" | "lpad" | "rpad" | "repeat" | "reverse" | "split_part" | "translate" | "text_trim" | "text_ltrim" | "text_rtrim" | "text_left" | "text_right"
2073 | "text_lpad" | "text_rpad" | "text_repeat" | "text_reverse" | "text_split" | "text_translate" | "text_title" | "text_casefold" | "text_lower" | "text_upper"
2074 | "text_replace" | "text_slice" | "text_substring" => done("text", Nulls::IfArgs),
2075 "text_concat" => done("text", Nulls::Never),
2077 "text_join" => Fact::new("text", first.non_null),
2078 "regexp_like" => done("integer", Nulls::Never),
2080 "regexp_substr" | "regexp_capture" => done("text", Nulls::Always),
2081 "regexp_replace" => Fact { ty: if scalar_name(&first.ty) == Some("text") { first.ty.clone() } else { Ty::Unknown }, non_null: first.non_null },
2084 _ => Fact::unknown(),
2085 }
2086 }
2087
2088 fn built_text(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
2103 match self.builtin_name(n)? {
2104 "json_object" | "json_array" | "json_group_array" | "json_group_object" => self.shape(n, scope),
2105 "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)),
2106 _ => None,
2107 }
2108 }
2109
2110 fn subquery_shape(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
2114 if n.op != "select" {
2115 return None;
2116 }
2117 let sub = n.select.as_deref()?;
2118 if sub.columns.len() != 1 || sub.prior.is_some() || !sub.rows.is_empty() || sub.values {
2119 return None;
2120 }
2121 let col = sub.columns.first()?;
2122 self.within(sub, scope, |inner| self.built_text(&col.expr, inner))
2123 }
2124
2125 fn builtin_name<'n>(&self, n: &'n Node) -> Option<&'n str> {
2128 let name = n.name.as_deref().filter(|_| n.op == "function")?;
2129 (n.agg || n.window || self.extras.function(name, n.args.len()).is_none()).then_some(name)
2130 }
2131
2132 fn shape(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
2136 let key = n as *const Node as usize;
2137 if let Some(found) = self.shapes.borrow().get(&key) {
2138 return found.clone();
2139 }
2140 let shape = self.aggregated(n, || self.shape_here(n, scope));
2141 self.shapes.borrow_mut().insert(key, shape.clone());
2142 shape
2143 }
2144
2145 fn shape_here(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
2146 let name = self.builtin_name(n)?;
2147 let aggregate = n.agg || n.window;
2148 let value = |x: &Node| {
2150 let f = self.json_fact(x, scope);
2151 let nullable = nullable_in_json(&f);
2152 (f.ty, nullable)
2153 };
2154 match name {
2155 "json_object" | "jsonb_object" if !aggregate => {
2156 if n.args.len() % 2 != 0 {
2158 return Some(Ty::Json { schema: None });
2159 }
2160 let mut fields: Vec<TyField> = Vec::new();
2161 let mut dynamic = false;
2162 for pair in n.args.chunks(2) {
2163 let (ty, nullable) = value(&pair[1]);
2164 match literal_text(&pair[0]) {
2165 Some(key) => match fields.iter_mut().find(|f| f.name == key) {
2167 Some(f) => {
2168 f.ty = ty;
2169 f.nullable = nullable;
2170 }
2171 None => fields.push(TyField { name: key.to_string(), ty, nullable }),
2172 },
2173 None => {
2174 dynamic = true;
2175 fields.push(TyField { name: String::new(), ty, nullable });
2176 }
2177 }
2178 }
2179 if dynamic {
2181 return Some(record(fields.iter().map(|f| value_schema(&f.ty, f.nullable)).collect()));
2182 }
2183 Some(Ty::Object { fields })
2184 }
2185 "json_array" | "jsonb_array" if !aggregate => {
2187 let items: Vec<serde_json::Value> = n.args.iter().map(|x| {
2188 let (ty, nullable) = value(x);
2189 value_schema(&ty, nullable)
2190 }).collect();
2191 let mut schema = serde_json::json!({"type": "array", "items": false});
2192 if !items.is_empty() {
2193 schema["minItems"] = serde_json::json!(items.len());
2194 schema["prefixItems"] = serde_json::Value::Array(items);
2195 }
2196 Some(Ty::Json { schema: Some(schema) })
2197 }
2198 "json_group_array" | "jsonb_group_array" if aggregate && n.args.len() == 1 => {
2200 let (ty, nullable) = value(&n.args[0]);
2201 Some(Ty::List { of: Box::new(ty), nullable_items: nullable })
2202 }
2203 "json_group_object" | "jsonb_group_object" if aggregate && n.args.len() == 2 => {
2205 let (ty, nullable) = value(&n.args[1]);
2206 Some(record(vec![value_schema(&ty, nullable)]))
2207 }
2208 "json" | "jsonb" if !aggregate && n.args.len() == 1 => self.shape(&n.args[0], scope).or_else(|| self.subquery_shape(&n.args[0], scope)),
2209 _ => None,
2210 }
2211 }
2212
2213 fn json_fact(&self, n: &Node, scope: &ScopeStack) -> JsonFact {
2218 let plain = || {
2219 let f = self.type_of(n, scope);
2220 JsonFact { ty: in_json(&f.ty), non_null: f.non_null, carry: Carry::No }
2221 };
2222 let any = JsonFact { ty: Ty::Unknown, non_null: false, carry: Carry::Maybe };
2223 match n.op.as_str() {
2224 "function" => {
2225 let Some(name) = self.builtin_name(n) else { return any };
2227 if n.over && is_json_result(name) {
2230 return any;
2231 }
2232 if self.windowed_aggregate(n) && self.carry(n, scope) != Carry::No {
2234 return any;
2235 }
2236 if let Some(ty) = self.shape(n, scope) {
2237 let non_null = self.built_non_null(n, scope);
2238 return JsonFact { ty, non_null, carry: Carry::Yes };
2239 }
2240 let first = n.args.first().into_iter();
2241 let non_null = || self.type_of(n, scope).non_null;
2242 match name {
2243 "coalesce" | "ifnull" => self.json_arms(n.args.iter(), true, scope).map(|f| JsonFact { non_null: f.non_null, ..f }).unwrap_or_else(plain),
2244 "nullif" => self.json_arms(first, false, scope).map(|f| JsonFact { non_null: false, ..f }).unwrap_or_else(plain),
2245 "likely" | "unlikely" | "likelihood" => self.json_arms(first, false, scope).unwrap_or_else(plain),
2246 "iif" | "if" => {
2247 let arms = iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i));
2248 self.json_arms(arms, false, scope).map(|f| JsonFact { non_null: non_null(), ..f }).unwrap_or_else(plain)
2249 }
2250 "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),
2252 _ if is_json_result(name) => JsonFact { ty: Ty::Json { schema: None }, non_null: non_null(), carry: Carry::Yes },
2253 _ if PASSING.contains(&name) => {
2256 if n.args.iter().all(|a| self.carry(a, scope) == Carry::No) { plain() } else { any }
2257 }
2258 _ if PLAIN.contains(&name) => plain(),
2259 _ => any,
2260 }
2261 }
2262 "select" => if self.carry(n, scope) == Carry::No { plain() } else { any },
2265 "collate" | "pos" => n.left.as_deref().map_or(any, |l| self.json_fact(l, scope)),
2266 "case" => {
2267 let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
2268 let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
2269 match self.json_arms(results.chain(otherwise), false, scope) {
2270 Some(f) => JsonFact { non_null: self.type_of(n, scope).non_null, ..f },
2271 None => plain(),
2272 }
2273 }
2274 "cast" | "column" => if self.carry(n, scope) == Carry::No { plain() } else { any },
2276 _ => plain(),
2277 }
2278 }
2279
2280 fn json_arms<'n>(&self, arms: impl Iterator<Item = &'n Node>, coalesce: bool, scope: &ScopeStack) -> Option<JsonFact> {
2284 let mut facts: Vec<JsonFact> = Vec::new();
2285 for arm in arms.filter(|a| a.op != "null") {
2286 let f = self.json_fact(arm, scope);
2287 let last = coalesce && f.non_null;
2288 facts.push(f);
2289 if last {
2290 break;
2291 }
2292 }
2293 if facts.iter().all(|f| f.carry == Carry::No) {
2294 return None;
2295 }
2296 let non_null = facts.iter().any(|f| f.non_null);
2297 if !facts.iter().all(|f| f.carry == Carry::Yes) {
2298 return Some(JsonFact { ty: Ty::Unknown, non_null, carry: Carry::Maybe });
2299 }
2300 let types: Vec<&Ty> = facts.iter().map(|f| &f.ty).collect();
2301 let ty = if types.iter().all(|t| *t == types[0]) { types[0].clone() } else { same_json(&types).unwrap_or(Ty::Unknown) };
2302 Some(JsonFact { ty, non_null, carry: Carry::Yes })
2303 }
2304
2305 fn carry(&self, n: &Node, scope: &ScopeStack) -> Carry {
2307 match n.op.as_str() {
2308 "function" => {
2309 let Some(name) = self.builtin_name(n) else { return Carry::Maybe };
2310 let carry = match name {
2311 "coalesce" | "ifnull" => self.carries(n.args.iter(), scope),
2312 "nullif" | "likely" | "unlikely" | "likelihood" => self.carries(n.args.first().into_iter(), scope),
2313 "iif" | "if" => self.carries(iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i)), scope),
2314 "min" | "max" if n.args.len() == 1 && !n.window => self.carries(n.args.iter(), scope),
2315 _ if is_json_result(name) => if n.over { Carry::Maybe } else { Carry::Yes },
2316 _ if PASSING.contains(&name) => {
2317 if self.carries(n.args.iter(), scope) == Carry::No { Carry::No } else { Carry::Maybe }
2318 }
2319 _ if PLAIN.contains(&name) => Carry::No,
2320 _ => Carry::Maybe,
2321 };
2322 if carry != Carry::No && self.windowed_aggregate(n) { Carry::Maybe } else { carry }
2323 }
2324 "select" => {
2329 let Some(sub) = n.select.as_deref() else { return Carry::No };
2330 match self.select_carry(sub, 0, scope) {
2331 Carry::No => Carry::No,
2332 _ => Carry::Maybe,
2333 }
2334 }
2335 "collate" | "pos" => n.left.as_deref().map_or(Carry::No, |l| self.carry(l, scope)),
2336 "cast" => match n.left.as_deref().map_or(Carry::No, |l| self.carry(l, scope)) {
2337 Carry::No => Carry::No,
2338 _ => Carry::Maybe,
2339 },
2340 "case" => {
2341 let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
2342 let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
2343 self.carries(results.chain(otherwise), scope)
2344 }
2345 "column" => {
2349 for froms in scope.iter().rev() {
2350 if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
2351 if let Some(sub) = f.subquery.as_deref() {
2352 return if self.select_carry(sub, n.index.max(0) as usize, scope) == Carry::No { Carry::No } else { Carry::Maybe };
2353 }
2354 break;
2355 }
2356 }
2357 if n.subtype { Carry::Maybe } else { Carry::No }
2360 }
2361 _ => Carry::No,
2362 }
2363 }
2364
2365 fn select_carry(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> Carry {
2367 let mut carries = Vec::new();
2368 let mut s = Some(sel);
2369 while let Some(arm) = s {
2370 self.within(arm, scope, |inner| {
2371 for e in std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i))).flatten() {
2372 carries.push(self.carry(e, inner));
2373 }
2374 });
2375 s = arm.prior.as_deref();
2376 }
2377 combine(&carries)
2378 }
2379
2380 fn carries<'n>(&self, arms: impl Iterator<Item = &'n Node>, scope: &ScopeStack) -> Carry {
2382 let carries: Vec<Carry> = arms.filter(|a| a.op != "null").map(|a| self.carry(a, scope)).collect();
2383 combine(&carries)
2384 }
2385
2386 fn aggregated<T>(&self, n: &Node, f: impl FnOnce() -> T) -> T {
2389 if !(n.op == "function" && n.agg && !n.over) {
2390 return f();
2391 }
2392 let foreign = {
2395 let level = self.level.borrow();
2396 !n.window && !reads_cursor(n, &level.own)
2397 };
2398 {
2399 let mut level = self.level.borrow_mut();
2400 level.aggregating += 1;
2401 level.foreign += u32::from(foreign);
2402 }
2403 let out = f();
2404 let mut level = self.level.borrow_mut();
2405 level.aggregating -= 1;
2406 level.foreign -= u32::from(foreign);
2407 out
2408 }
2409
2410 fn windowed_aggregate(&self, n: &Node) -> bool {
2414 n.op == "function" && n.agg && !n.over && self.level.borrow().windowed
2415 }
2416
2417 fn level_within(&self, sel: &Sel) -> Level {
2420 let mut level = level_of(sel, self.extras);
2421 let outer = self.level.borrow();
2422 level.around = outer.around.clone();
2423 if outer.aggregating == 0 {
2424 level.around.extend(outer.lone.iter().copied());
2425 }
2426 level
2427 }
2428
2429 fn within<T>(&self, sel: &Sel, scope: &ScopeStack, f: impl FnOnce(&ScopeStack) -> T) -> T {
2431 let mut inner = scope.clone();
2432 inner.push(&sel.from);
2433 let outer = self.level.replace(self.level_within(sel));
2434 let out = f(&inner);
2435 self.level.replace(outer);
2436 out
2437 }
2438
2439 fn written_non_null(&self) -> HashSet<String> {
2450 let t = self.tree;
2451 let (Some(dml), Some(_)) = (&t.dml, &t.returning) else { return HashSet::new() };
2452 let events = match dml.kind.as_str() {
2453 "update" => TRIGGER_ROW_UPDATE,
2454 _ if dml.upserts.iter().any(|u| u.do_update) => TRIGGER_ROW_INSERT | TRIGGER_ROW_UPDATE,
2455 _ => TRIGGER_ROW_INSERT,
2456 };
2457 if self.skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & events != 0) {
2458 return HashSet::new();
2459 }
2460 let scope: ScopeStack = Vec::new();
2461 let non_null = |known: HashMap<String, bool>| -> HashSet<String> { known.into_iter().filter(|(_, n)| *n).map(|(c, _)| c).collect() };
2462 let assigned = |items: &[tree::SetItem]| -> HashSet<String> {
2463 let mut known: HashMap<String, bool> = HashMap::new();
2464 for item in items {
2465 let Some(column) = &item.column else { continue };
2466 *known.entry(column.to_ascii_lowercase()).or_insert(true) &= self.type_of(&item.expr, &scope).non_null;
2467 }
2468 non_null(known)
2469 };
2470 match dml.kind.as_str() {
2471 "update" => assigned(&dml.set),
2472 "insert" | "upsert" => {
2473 let mut known: HashMap<String, bool> = HashMap::new();
2474 for (i, column) in dml.columns.iter().enumerate() {
2475 let Some(column) = column else { continue };
2476 let fact = match (&dml.values, &t.statement) {
2477 (Some(values), _) => values.get(i).map(|v| self.type_of(v, &scope)),
2478 (None, Some(sel)) => Some(self.select_column(sel, i, &scope)),
2479 (None, None) => None,
2480 };
2481 *known.entry(column.to_ascii_lowercase()).or_insert(true) &= fact.is_some_and(|f| f.non_null);
2482 }
2483 let mut written = non_null(known);
2484 for upsert in dml.upserts.iter().filter(|u| u.do_update) {
2485 let updated = assigned(&upsert.set);
2486 written.retain(|c| updated.contains(c));
2487 }
2488 written
2489 }
2490 _ => HashSet::new(),
2491 }
2492 }
2493
2494 fn bare_nullable(&self) -> HashSet<String> {
2498 let t = self.tree;
2499 let Some(dml) = &t.dml else { return HashSet::new() };
2500 let mut fills: HashMap<String, bool> = HashMap::new();
2501 let mut fill = |v: &Node, column: Option<&str>| {
2502 let (Some(name), Some(column)) = (v.name.as_ref().filter(|_| v.op == "variable"), column) else { return };
2503 let Some(target) = self.table_column(&dml.table, column) else { return };
2504 let refuses = target.non_null || self.checked_not_null(&dml.table, column);
2505 *fills.entry(name.clone()).or_insert(true) &= !refuses;
2506 };
2507 if let (Some(sel), "insert" | "upsert") = (&t.statement, dml.kind.as_str()) {
2508 if sel.prior.is_none() {
2509 for (i, v) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
2510 fill(v, dml.columns.get(i).and_then(|c| c.as_deref()));
2511 }
2512 }
2513 }
2514 for (i, v) in dml.values.iter().flatten().enumerate() {
2515 fill(v, dml.columns.get(i).and_then(|c| c.as_deref()));
2516 }
2517 for item in dml.set.iter().chain(dml.upserts.iter().flat_map(|u| u.set.iter())) {
2518 fill(&item.expr, item.column.as_deref());
2519 }
2520 fills.into_iter().filter(|(_, nullable)| *nullable).map(|(name, _)| name).collect()
2521 }
2522
2523 fn params(&self, lexed: &Lexed) -> (Vec<Param>, Vec<(String, String, String)>) {
2529 let mut found: Vec<(String, Fact)> = Vec::new();
2530 let t = self.tree;
2531 let checked = |c: Option<&str>| t.dml.as_ref().zip(c).is_some_and(|(dml, c)| self.checked_not_null(&dml.table, c));
2532 let mut fills: HashMap<String, bool> = HashMap::new();
2537 let mut refused: Vec<(String, String, String)> = Vec::new();
2538 let mut fill = |v: &Node, target: &Option<Fact>, column: Option<&str>| {
2539 let Some(target) = target else { return };
2540 let refuses = target.non_null || checked(column);
2541 let bare = v.op == "variable";
2542 let Some(name) = (if bare { v.name.as_ref() } else { cast_variable(v, self.extras) }) else { return };
2543 if bare {
2544 *fills.entry(name.clone()).or_insert(true) &= !refuses;
2545 }
2546 if let (true, true, Some(column), Some(dml)) = (refuses, self.nullable_params.contains(name), column, t.dml.as_ref()) {
2547 refused.push((name.clone(), dml.table.clone(), column.to_string()));
2548 }
2549 };
2550 if let Some(sel) = &t.statement {
2551 let targets: Vec<Option<Fact>> = match &t.dml {
2552 Some(dml) if dml.kind == "insert" => dml.columns.iter().map(|c| c.as_deref().and_then(|c| self.table_column(&dml.table, c))).collect(),
2555 _ => Vec::new(),
2556 };
2557 if sel.prior.is_none() {
2560 for (i, v) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
2561 if let Some(target) = targets.get(i) {
2562 fill(v, target, t.dml.as_ref().and_then(|d| d.columns.get(i)).and_then(|c| c.as_deref()));
2563 }
2564 }
2565 }
2566 self.walk_select(sel, &Vec::new(), &targets, &mut found);
2567 }
2568 if let Some(dml) = &t.dml {
2569 let scope: ScopeStack = Vec::new();
2570 if let Some(values) = &dml.values {
2571 for (i, v) in values.iter().enumerate() {
2572 let target = dml.columns.get(i).and_then(|c| c.as_deref()).and_then(|c| self.table_column(&dml.table, c));
2573 fill(v, &target, dml.columns.get(i).and_then(|c| c.as_deref()));
2574 self.walk(v, Ctx::Typed(target), &scope, &mut found);
2575 }
2576 }
2577 for item in dml.set.iter().chain(dml.upserts.iter().flat_map(|u| u.set.iter())) {
2578 let target = item.column.as_deref().and_then(|c| self.table_column(&dml.table, c));
2579 fill(&item.expr, &target, item.column.as_deref());
2580 self.walk(&item.expr, Ctx::Typed(target), &scope, &mut found);
2581 }
2582 if let Some(w) = &dml.where_ {
2583 self.walk(w, Ctx::Bool, &scope, &mut found);
2584 }
2585 for w in dml.upserts.iter().filter_map(|u| u.where_.as_ref()) {
2586 self.walk(w, Ctx::Bool, &scope, &mut found);
2587 }
2588 }
2589 if let Some(returning) = &t.returning {
2590 for c in returning {
2591 self.walk(&c.expr, Ctx::None, &Vec::new(), &mut found);
2592 }
2593 }
2594 let mut typed: HashMap<&str, &Fact> = HashMap::new();
2597 for (name, fact) in found.iter().filter(|(_, f)| !matches!(f.ty, Ty::Unknown)) {
2598 typed.entry(name.as_str()).or_insert(fact);
2599 }
2600 let params = lexed
2601 .params
2602 .iter()
2603 .enumerate()
2604 .map(|(k, name)| {
2605 let numbered = format!("?{}", k + 1);
2606 let fact = typed.get(numbered.as_str()).map(|f| (*f).clone()).unwrap_or_else(Fact::unknown);
2607 let fact = Fact { ty: textual(&fact.ty), ..fact };
2609 let nullable = fills.get(&numbered).copied().unwrap_or(false) || self.nullable_params.contains(&numbered);
2610 Param { nullable, ..Param::new(name.clone(), descriptor(&fact.ty, None, false, false)) }
2611 })
2612 .collect();
2613 (params, refused)
2614 }
2615
2616 fn checked_not_null(&self, table: &str, column: &str) -> bool {
2620 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)
2621 }
2622
2623 fn table_column(&self, table: &str, column: &str) -> Option<Fact> {
2624 let info = self.tree.tables.get(table)?;
2625 let col = info.columns.iter().find(|c| c.name.eq_ignore_ascii_case(column))?;
2626 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)) })
2627 }
2628
2629 fn walk_select(&self, sel: &Sel, scope: &ScopeStack, targets: &[Option<Fact>], found: &mut Vec<(String, Fact)>) {
2630 let compound: Vec<Option<Fact>>;
2633 let targets = if targets.is_empty() && (sel.prior.is_some() || !sel.rows.is_empty()) {
2634 compound = (0..sel.columns.len())
2635 .map(|i| {
2636 let ty = self.select_column(sel, i, scope).ty;
2637 (!matches!(ty, Ty::Unknown)).then_some(Fact { ty, non_null: true })
2638 })
2639 .collect();
2640 compound.as_slice()
2641 } else {
2642 targets
2643 };
2644 let mut inner = scope.clone();
2645 inner.push(&sel.from);
2646 for (i, e) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
2647 self.walk(e, Ctx::Typed(targets.get(i).cloned().flatten()), &inner, found);
2648 }
2649 for f in &sel.from {
2650 if let Some(sub) = &f.subquery {
2651 self.walk_select(sub, &inner, &[], found);
2652 }
2653 if let Some(on) = &f.on {
2654 self.walk(on, Ctx::Bool, &inner, found);
2655 }
2656 let json = f.tab_func && matches!(f.table.as_deref(), Some("json_each" | "json_tree"));
2660 let top_k = f.tab_func && f.table.as_deref() == Some("vector_top_k");
2661 let series = f.tab_func && matches!(f.table.as_deref(), Some("generate_series" | "stats_seq"));
2663 for (i, a) in f.args.iter().enumerate() {
2664 let ctx = match i {
2665 0 | 1 if json || top_k => Ctx::Typed(Some(Fact::new("text", true))),
2666 2 if top_k => Ctx::Typed(Some(Fact::new("integer", true))),
2667 _ if series => Ctx::Typed(Some(Fact::new("integer", true))),
2668 _ => Ctx::None,
2669 };
2670 self.walk(a, ctx, &inner, found);
2671 }
2672 }
2673 if let Some(w) = &sel.where_ {
2674 self.walk(w, Ctx::Bool, &inner, found);
2675 }
2676 for g in &sel.group_by {
2677 self.walk(g, Ctx::None, &inner, found);
2678 }
2679 if let Some(h) = &sel.having {
2680 self.walk(h, Ctx::Bool, &inner, found);
2681 }
2682 for o in &sel.order_by {
2683 self.walk(o, Ctx::None, &inner, found);
2684 }
2685 for l in sel.limit.iter().chain(sel.offset.iter()) {
2686 self.walk(l, Ctx::Typed(Some(Fact::new("integer", true))), &inner, found);
2687 }
2688 if let Some(prior) = &sel.prior {
2689 self.walk_select(prior, scope, targets, found);
2690 }
2691 }
2692
2693 fn walk(&self, n: &Node, ctx: Ctx, scope: &ScopeStack, found: &mut Vec<(String, Fact)>) {
2695 if n.op == "variable" {
2696 let fact = match ctx {
2697 Ctx::Typed(Some(f)) => f,
2698 Ctx::Typed(None) | Ctx::Row(_) | Ctx::None => Fact::unknown(),
2699 Ctx::Bool => Fact::new("integer", false),
2700 };
2701 found.push((n.name.clone().unwrap_or_default(), fact));
2702 return;
2703 }
2704 let sibling = |other: &Option<Box<Node>>| other.as_deref().map(|o| self.type_of(o, scope));
2705 let case_results: std::cell::OnceCell<Ty> = std::cell::OnceCell::new();
2706 let child_ctx = |slot: Position| -> Ctx {
2707 match n.op.as_str() {
2708 "=" | "!=" | "<" | "<=" | ">" | ">=" | "is" | "is not" => {
2709 let (this, other) = match slot {
2710 Position::Left => (&n.left, &n.right),
2711 Position::Right => (&n.right, &n.left),
2712 _ => return Ctx::None,
2713 };
2714 match (this.as_deref(), other.as_deref().and_then(|o| self.row(o, scope))) {
2718 (Some(t), Some(row)) if matches!(t.op.as_str(), "vector" | "select") => Ctx::Row(row),
2719 _ => Ctx::Typed(sibling(other)),
2720 }
2721 }
2722 "in" => match slot {
2723 Position::Left if is_vector(&n.left) => n.select.as_deref().map_or(Ctx::None, |s| Ctx::Row(self.select_columns(s, scope))),
2726 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)))),
2727 Position::List(_) => Ctx::Typed(sibling(&n.left)),
2728 _ => Ctx::None,
2729 },
2730 "between" => match slot {
2731 Position::Left if is_vector(&n.left) => Ctx::Row(self.rows(&n.list.iter().collect::<Vec<_>>(), scope)),
2732 Position::Left => Ctx::Typed(n.list.first().map(|x| self.type_of(x, scope))),
2733 Position::List(_) => match n.left.as_deref().and_then(|l| self.row(l, scope)) {
2734 Some(row) if is_vector(&n.left) => Ctx::Row(row),
2735 _ => Ctx::Typed(sibling(&n.left)),
2736 },
2737 _ => Ctx::None,
2738 },
2739 "vector" => match (slot, &ctx) {
2741 (Position::List(i), Ctx::Row(row)) => Ctx::Typed(row.get(i).cloned().flatten()),
2742 _ => Ctx::None,
2743 },
2744 "select_column" => match (slot, &ctx) {
2746 (Position::Left, Ctx::Typed(Some(f))) => {
2747 let mut row = vec![None; n.index.max(0) as usize + 1];
2748 row[n.index.max(0) as usize] = Some(f.clone());
2749 Ctx::Row(row)
2750 }
2751 _ => Ctx::None,
2752 },
2753 "cast" => Ctx::Typed(Some(Fact::new(n.affinity.as_deref().unwrap_or("none"), true))),
2754 "+" | "-" | "*" | "/" | "%" => {
2755 let other = match slot {
2756 Position::Left => sibling(&n.right),
2757 _ => sibling(&n.left),
2758 };
2759 Ctx::Typed(Some(match other {
2760 Some(f) if is_numeric(&f.ty) => f,
2761 _ => Fact::new("real", true),
2762 }))
2763 }
2764 "||" => Ctx::Typed(Some(Fact::new("text", true))),
2765 "neg" | "~" | "&" | "|" | "<<" | ">>" => Ctx::Typed(Some(Fact::new("real", true))),
2766 "pos" | "collate" => ctx.clone(),
2769 "and" | "or" | "not" => Ctx::Bool,
2770 "case" => match slot {
2771 Position::List(i) if i % 2 == 0 && i + 1 < n.list.len() => match &n.left {
2775 Some(base) if base.op == "vector" => self.row(base, scope).map_or(Ctx::None, Ctx::Row),
2776 Some(base) => Ctx::Typed(Some(self.type_of(base, scope))),
2777 None => Ctx::Bool,
2778 },
2779 Position::List(_) => match case_results.get_or_init(|| {
2781 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();
2782 shared(&others.iter().collect::<Vec<_>>())
2783 }) {
2784 Ty::Unknown => outer_type(&ctx),
2785 ty => Ctx::Typed(Some(Fact { ty: ty.clone(), non_null: true })),
2786 },
2787 Position::Left if is_vector(&n.left) => {
2790 let values: Vec<&Node> = n.list.iter().enumerate().filter(|(j, _)| j % 2 == 0 && j + 1 < n.list.len()).map(|(_, x)| x).collect();
2791 Ctx::Row(self.rows(&values, scope))
2792 }
2793 Position::Left => {
2795 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();
2796 let refs: Vec<&Fact> = values.iter().collect();
2797 match shared(&refs) {
2798 Ty::Unknown => Ctx::None,
2799 ty => Ctx::Typed(Some(Fact { ty, non_null: true })),
2800 }
2801 }
2802 _ => Ctx::None,
2803 },
2804 "function" => match (slot, self.argument(n, i_of(slot), scope)) {
2807 (Position::Arg(_), Ctx::Typed(None) | Ctx::None) if matches!(n.name.as_deref(), Some("coalesce" | "ifnull" | "nullif" | "min" | "max")) && !n.agg => outer_type(&ctx),
2808 (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),
2809 (Position::Arg(_), c) => c,
2810 _ => Ctx::None,
2811 },
2812 _ => Ctx::None,
2813 }
2814 };
2815 if let Some(l) = &n.left {
2816 self.walk(l, child_ctx(Position::Left), scope, found);
2817 }
2818 if let Some(r) = &n.right {
2819 self.walk(r, child_ctx(Position::Right), scope, found);
2820 }
2821 for (i, x) in n.list.iter().enumerate() {
2822 self.walk(x, child_ctx(Position::List(i)), scope, found);
2823 }
2824 for (i, x) in n.args.iter().enumerate() {
2825 self.walk(x, child_ctx(Position::Arg(i)), scope, found);
2826 }
2827 if let Some(s) = &n.select {
2828 let targets: Vec<Option<Fact>> = match (n.op.as_str(), &ctx) {
2831 ("select", Ctx::Row(row)) => row.clone(),
2832 ("select", Ctx::Typed(Some(f))) => vec![Some(f.clone())],
2833 ("in", _) => match n.left.as_deref() {
2834 Some(l) if l.op == "vector" => self.row(l, scope).unwrap_or_default(),
2835 Some(l) => vec![Some(self.type_of(l, scope))],
2836 None => Vec::new(),
2837 },
2838 _ => Vec::new(),
2839 };
2840 self.walk_select(s, scope, &targets, found);
2841 }
2842 }
2843
2844 fn row(&self, n: &Node, scope: &ScopeStack) -> Option<Vec<Option<Fact>>> {
2846 match n.op.as_str() {
2847 "vector" => Some(n.list.iter().map(|x| Some(self.type_of(x, scope))).collect()),
2848 "select" => n.select.as_deref().map(|s| self.select_columns(s, scope)),
2849 _ => None,
2850 }
2851 }
2852
2853 fn select_columns(&self, sel: &Sel, scope: &ScopeStack) -> Vec<Option<Fact>> {
2854 (0..sel.columns.len()).map(|i| Some(self.select_column(sel, i, scope))).collect()
2855 }
2856
2857 fn rows(&self, values: &[&Node], scope: &ScopeStack) -> Vec<Option<Fact>> {
2860 let mut out: Vec<Option<Fact>> = Vec::new();
2861 for row in values.iter().filter_map(|v| self.row(v, scope)) {
2862 for (i, f) in row.into_iter().enumerate() {
2863 if i >= out.len() {
2864 out.push(None);
2865 }
2866 if out[i].as_ref().is_none_or(|known| matches!(known.ty, Ty::Unknown)) {
2867 out[i] = f;
2868 }
2869 }
2870 }
2871 out
2872 }
2873
2874 fn argument(&self, n: &Node, i: usize, scope: &ScopeStack) -> Ctx {
2876 let name = n.name.as_deref().unwrap_or("");
2877 if !n.agg && !n.window && self.extras.function(name, n.args.len()).is_some() {
2878 return Ctx::None;
2879 }
2880 let name = sqlean_alias(name);
2881 let text = || Ctx::Typed(Some(Fact::new("text", true)));
2882 let integer = || Ctx::Typed(Some(Fact::new("integer", true)));
2883 let real = || Ctx::Typed(Some(Fact::new("real", true)));
2884 let others = || {
2885 let facts: Vec<Fact> = n.args.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, a)| self.type_of(a, scope)).collect();
2886 let refs: Vec<&Fact> = facts.iter().collect();
2887 let ty = shared(&refs);
2888 Ctx::Typed(if matches!(ty, Ty::Unknown) { None } else { Some(Fact { ty, non_null: true }) })
2889 };
2890 match name {
2891 "like" | "glob" | "regexp" | "match" | "upper" | "lower" | "trim" | "ltrim" | "rtrim" | "length" | "hex" | "unicode" | "quote" | "instr" | "replace" | "soundex"
2892 | "printf" | "format" | "concat" | "concat_ws" | "date" | "time" | "datetime" | "strftime" | "julianday" | "unixepoch" | "timediff" | "json"
2893 | "json_extract" | "json_type" | "json_valid" | "json_array_length" | "json_quote" | "json_pretty" | "json_insert" | "json_replace" | "json_set"
2894 | "json_remove" | "json_patch" | "->" | "->>" => text(),
2895 "substr" | "substring" => {
2896 if i == 0 { text() } else { integer() }
2897 }
2898 "zeroblob" | "randomblob" | "char" => integer(),
2899 "abs" | "round" | "acos" | "acosh" | "asin" | "asinh" | "atan" | "atan2" | "atanh" | "ceil" | "ceiling" | "cos" | "cosh" | "degrees" | "exp"
2900 | "floor" | "ln" | "log" | "log10" | "log2" | "mod" | "pow" | "power" | "radians" | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc" => real(),
2901 "coalesce" | "ifnull" | "nullif" | "min" | "max" => others(),
2902 "lag" | "lead" if n.args.len() >= 3 && (i == 0 || i == 2) => {
2905 let other = self.type_of(&n.args[2 - i], scope);
2906 Ctx::Typed(if matches!(other.ty, Ty::Unknown) { None } else { Some(Fact { ty: other.ty, non_null: true }) })
2907 }
2908 "iif" | "if" => {
2910 let values = iif_values(n.args.len());
2911 if !values.contains(&i) {
2912 Ctx::Bool
2913 } else {
2914 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();
2915 let ty = shared(&facts.iter().collect::<Vec<_>>());
2916 Ctx::Typed(if matches!(ty, Ty::Unknown) { None } else { Some(Fact { ty, non_null: true }) })
2917 }
2918 }
2919 "sum" | "avg" | "total" => real(),
2920 "highlight" if i == 1 => integer(),
2923 "highlight" if i > 1 => text(),
2924 "bm25" if i > 0 => real(),
2925 "vector" | "vector32" | "vector64" | "vector1bit" | "vector8" | "vector16" | "vectorb16" | "vector_extract" | "vector_distance_cos" | "vector_distance_l2" => text(),
2927 _ => match name {
2929 "left" | "right" | "text_left" | "text_right" | "repeat" | "text_repeat" | "lpad" | "rpad" | "text_lpad" | "text_rpad" if i == 1 => integer(),
2932 "split_part" | "text_split" | "regexp_capture" if i == 2 => integer(),
2933 "text_slice" | "text_substring" if i > 0 => integer(),
2934 "text_replace" if i == 3 => integer(),
2935 "encode" if i == 0 => Ctx::None,
2937 "uuid_str" | "uuid_blob" | "uuid7_timestamp_ms" | "md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" | "encode" | "decode" | "levenshtein" | "dlevenshtein"
2938 | "edit_distance" | "osa_distance" | "hamming" | "jaro_winkler" | "caverphone" | "phonetic_hash" | "rsoundex" | "translit" | "script_code" | "bit_length"
2939 | "char_length" | "character_length" | "btrim" | "left" | "right" | "lpad" | "rpad" | "repeat" | "reverse" | "split_part" | "starts_with" | "strpos" | "translate"
2940 | "regexp_like" | "regexp_substr" | "regexp_capture" | "regexp_replace" => text(),
2941 t if t.starts_with("text_") => text(),
2942 "median" | "percentile" | "percentile_25" | "percentile_75" | "percentile_90" | "percentile_95" | "percentile_99" | "stddev" | "stddev_pop" | "stddev_samp" | "variance"
2944 | "var_pop" | "var_samp" => real(),
2945 _ => Ctx::None,
2946 },
2947 }
2948 }
2949
2950 fn cardinality(&self) -> (Cardinality, Option<String>) {
2953 let t = self.tree;
2954 if let Some(dml) = &t.dml {
2955 if t.returning.is_none() {
2956 return (Cardinality::None, None);
2957 }
2958 return match dml.kind.as_str() {
2959 "insert" => {
2960 if dml.rows == 1 {
2961 let triggered = |events: i32| self.skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & events != 0);
2962 let declared_ignore = dml.on_error == "default" && self.tree.tables.get(&dml.table).is_some_and(|t| t.ignores);
2964 let can_skip = dml.on_error == "ignore"
2965 || declared_ignore
2966 || dml.upserts.iter().any(|u| !u.do_update || u.where_.is_some() || triggered(TRIGGER_ROW_UPDATE))
2967 || triggered(TRIGGER_ROW_INSERT);
2968 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) }
2969 } else if dml.rows > 1 {
2970 (Cardinality::Many, Some(format!("a VALUES list of {} rows returns {} rows", dml.rows, dml.rows)))
2971 } else {
2972 (Cardinality::Many, Some("an INSERT ... SELECT returns a row per row it reads".into()))
2973 }
2974 }
2975 _ => {
2976 match self.pinned_by_name(&dml.table, dml.where_.as_ref()) {
2978 Ok(()) => (Cardinality::AtMostOne, None),
2979 Err(why) => (Cardinality::Many, Some(why)),
2980 }
2981 }
2982 };
2983 }
2984 let Some(sel) = &t.statement else { return (Cardinality::None, None) };
2985 match self.exactly_one(sel) {
2986 Ok(()) => (Cardinality::One, None),
2987 Err(one_why) => match self.at_most_one(sel) {
2988 Ok(()) => (Cardinality::AtMostOne, Some(one_why)),
2989 Err(why) => (Cardinality::Many, Some(why)),
2990 },
2991 }
2992 }
2993
2994 fn exactly_one(&self, sel: &Sel) -> Result<(), String> {
2995 let keeps = |n: &Node, least: i64| integer(n).is_some_and(|n| n >= least);
2998 if sel.limit.as_ref().is_some_and(|l| !keeps(l, 1)) || sel.offset.as_ref().is_some_and(|o| integer(o) != Some(0)) {
2999 return Err("a LIMIT or an OFFSET can remove the row (LIMIT 0, OFFSET 1)".into());
3000 }
3001 self.one_before_limit(sel)
3002 }
3003
3004 fn one_before_limit(&self, sel: &Sel) -> Result<(), String> {
3006 if sel.prior.is_some() {
3007 return Err("a set operation (UNION, INTERSECT, EXCEPT) returns any number of rows".into());
3008 }
3009 if sel.values && !sel.rows.is_empty() {
3010 return Err("a VALUES list returns a row per row it lists".into());
3011 }
3012 if sel.values {
3013 return Ok(());
3014 }
3015 if !sel.group_by.is_empty() {
3016 return Err("GROUP BY returns one row per group, and none when nothing matches".into());
3017 }
3018 if sel.having.is_some() {
3019 return Err("HAVING can remove the row".into());
3020 }
3021 if sel.aggregate && sel.columns.iter().any(|c| has_aggregate(&c.expr)) {
3025 return Ok(());
3026 }
3027 if sel.from.is_empty() && sel.where_.is_none() {
3028 return Ok(());
3029 }
3030 if !sel.from.is_empty() && self.never_empty(sel) && self.arm_at_most_one(sel).is_ok() {
3032 return Ok(());
3033 }
3034 Err("a FROM returns a row per row it matches, and only an aggregate with no GROUP BY collapses them to one".into())
3035 }
3036
3037 fn never_empty(&self, sel: &Sel) -> bool {
3044 let holds = |t: &Node| match (t.op.as_str(), t.left.as_deref().and_then(integer), t.right.as_deref().and_then(integer)) {
3045 ("=", Some(l), Some(r)) => l == r,
3046 _ => integer(t).is_some_and(|n| n != 0),
3047 };
3048 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())))
3049 && conjuncts(sel.where_.as_ref()).iter().all(|t| t.outer_on || holds(t))
3050 }
3051
3052 fn at_most_one(&self, sel: &Sel) -> Result<(), String> {
3053 if sel.limit.as_ref().and_then(integer).is_some_and(|n| (0..=1).contains(&n)) {
3054 return Ok(());
3055 }
3056 if !sel.values && self.one_before_limit(sel).is_ok() {
3059 return Ok(());
3060 }
3061 if let Some(prior) = &sel.prior {
3065 let drawn = match sel.op.as_deref() {
3066 Some("intersect") => self.at_most_one(prior).is_ok() || self.arm_at_most_one(sel).is_ok(),
3067 Some("except") => self.at_most_one(prior).is_ok(),
3068 _ => false,
3069 };
3070 return if drawn { Ok(()) } else { Err("a set operation (UNION, INTERSECT, EXCEPT) returns any number of rows".into()) };
3071 }
3072 self.arm_at_most_one(sel)
3073 }
3074
3075 fn arm_at_most_one(&self, sel: &Sel) -> Result<(), String> {
3080 if sel.values {
3081 return Err("a VALUES list returns a row per row it lists".into());
3082 }
3083 if !sel.group_by.is_empty() {
3084 if sel.from.iter().all(|f| !f.right) && self.determined(sel, false).iter().all(|d| *d) {
3085 return Ok(());
3086 }
3087 let constant = self.determined(sel, true);
3088 if sel.group_by.iter().all(|g| self.pinned(sel, g, &constant)) {
3089 return Ok(());
3090 }
3091 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());
3092 }
3093 if sel.having.is_some() {
3094 return Err("HAVING leaves a row per group".into());
3095 }
3096 if sel.from.is_empty() {
3097 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());
3098 }
3099 if sel.from.iter().any(|f| f.right) {
3102 return Err("a RIGHT or FULL JOIN returns a row for each side that matches nothing".into());
3103 }
3104 let determined = self.determined(sel, false);
3105 if determined.iter().all(|d| *d) {
3106 return Ok(());
3107 }
3108 if sel.distinct {
3109 let constant = self.determined(sel, true);
3110 if !sel.columns.is_empty() && sel.columns.iter().all(|c| self.pinned(sel, &c.expr, &constant)) {
3111 return Ok(());
3112 }
3113 }
3114 let i = determined.iter().position(|d| !d).unwrap_or(0);
3115 let f = &sel.from[i];
3116 let Some(table) = f.table.as_deref().filter(|_| f.subquery.is_none() && !f.tab_func) else {
3117 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("?")));
3118 };
3119 let keys = self.tree.tables.get(table).map(|t| t.unique_keys.clone()).unwrap_or_default();
3120 if keys.is_empty() {
3121 return Err(format!("`{table}` has no unique index the engine can read, so nothing bounds the rows a WHERE matches"));
3122 }
3123 let shown: Vec<String> = keys.iter().map(|k| format!("({})", k.join(", "))).collect();
3124 if sel.from.len() == 1 {
3125 Err(format!("the WHERE does not equate every column of a unique key of `{table}` — it has {}", shown.join(", ")))
3126 } else {
3127 let name = f.alias.as_deref().unwrap_or(table);
3128 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(", ")))
3129 }
3130 }
3131
3132 fn determined(&self, sel: &Sel, constant: bool) -> Vec<bool> {
3139 let derived = self.derived_keys(sel);
3140 self.determined_from(sel, vec![false; sel.from.len()], &derived, constant)
3141 }
3142
3143 fn derived_keys(&self, sel: &Sel) -> Vec<Vec<Vec<i64>>> {
3146 sel.from.iter().map(|f| f.subquery.as_ref().map(|sub| self.output_keys(sub)).unwrap_or_default()).collect()
3147 }
3148
3149 fn determined_from(&self, sel: &Sel, mut done: Vec<bool>, derived: &[Vec<Vec<i64>>], constant: bool) -> Vec<bool> {
3152 let n = sel.from.len();
3153 let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
3154 let terms = conjuncts(sel.where_.as_ref());
3155 loop {
3156 let mut changed = false;
3157 for i in 0..n {
3158 if done[i] {
3159 continue;
3160 }
3161 let f = &sel.from[i];
3162 let pinned = if let Some(sub) = &f.subquery {
3163 let usable: Vec<&Node> = terms.iter().copied().filter(|t| !t.outer_on || (!constant && t.join == f.cursor)).collect();
3164 !(constant && f.outer) && (self.at_most_one(sub).is_ok() || self.derived_pinned(&derived[i], f.cursor, &usable, &done, &index))
3165 } else if let (Some(table), false, false) = (f.table.as_deref(), f.tab_func, f.virtual_) {
3166 let usable: Vec<&Node> = terms.iter().copied().filter(|t| !t.outer_on || (!constant && t.join == f.cursor)).collect();
3169 self.key_pinned(table, f.cursor, &usable, &done, &index)
3170 } else {
3171 false
3172 };
3173 if pinned {
3174 done[i] = true;
3175 changed = true;
3176 }
3177 }
3178 if !changed {
3179 return done;
3180 }
3181 }
3182 }
3183
3184 fn key_pinned(&self, table: &str, cursor: i64, terms: &[&Node], done: &[bool], index: &HashMap<i64, usize>) -> bool {
3189 let Some(info) = self.tree.tables.get(table) else { return false };
3190 let pins: Vec<&str> = terms.iter().filter_map(|t| self.pins(t, cursor, done, index)).collect();
3191 info.unique_keys.iter().any(|key| !key.is_empty() && key.iter().all(|c| pins.iter().any(|p| p.eq_ignore_ascii_case(c))))
3192 }
3193
3194 fn derived_pinned(&self, keys: &[Vec<i64>], cursor: i64, terms: &[&Node], done: &[bool], index: &HashMap<i64, usize>) -> bool {
3197 let pinned: Vec<i64> = terms.iter().filter_map(|t| self.pinned_column(t, cursor, done, index)).map(|c| c.index).collect();
3198 keys.iter().any(|key| !key.is_empty() && key.iter().all(|p| pinned.contains(p)))
3199 }
3200
3201 fn output_keys(&self, sel: &Sel) -> Vec<Vec<i64>> {
3213 if let Some(prior) = &sel.prior {
3214 return self.compound_keys(sel, prior);
3215 }
3216 if sel.values {
3217 return Vec::new();
3218 }
3219 let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
3220 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);
3222 let mut keys = Vec::new();
3223 if !sel.group_by.is_empty() {
3224 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();
3225 keys.extend(key);
3226 return keys;
3227 }
3228 if sel.distinct && !sel.columns.is_empty() && sel.columns.iter().all(|c| c.expr.op == "column" && index.contains_key(&c.expr.cursor)) {
3229 keys.push((0..sel.columns.len() as i64).collect());
3230 }
3231 if sel.from.iter().any(|f| f.right) {
3234 return keys;
3235 }
3236 let derived = self.derived_keys(sel);
3237 let n = sel.from.len();
3238 for (r, f) in sel.from.iter().enumerate() {
3239 if f.tab_func || f.virtual_ {
3240 continue;
3241 }
3242 let mut seed = vec![false; n];
3243 seed[r] = true;
3244 if !self.determined_from(sel, seed, &derived, false).iter().all(|d| *d) {
3245 continue;
3246 }
3247 if f.subquery.is_some() {
3248 for key in &derived[r] {
3249 keys.extend(key.iter().map(|p| position(&|e: &Node| e.cursor == f.cursor && e.index == *p)).collect::<Option<Vec<i64>>>());
3250 }
3251 } else if let Some(info) = f.table.as_deref().and_then(|t| self.tree.tables.get(t)) {
3252 let fixed = |c: &str| {
3255 let none = vec![false; n];
3256 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)))
3257 };
3258 for key in info.unique_keys.iter().filter(|k| !k.is_empty()) {
3259 keys.extend(
3260 key.iter()
3261 .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))) {
3262 Some(p) => Some(Some(p)),
3263 None if fixed(c) => None,
3264 None => Some(None),
3265 })
3266 .collect::<Option<Vec<i64>>>(),
3267 );
3268 }
3269 }
3270 }
3271 keys
3272 }
3273
3274 fn compound_keys(&self, sel: &Sel, prior: &Sel) -> Vec<Vec<i64>> {
3280 let op = sel.op.as_deref().unwrap_or("");
3281 let mut keys = Vec::new();
3282 if op == "intersect" || op == "except" {
3283 keys.extend(self.output_keys(prior));
3284 }
3285 if op != "union all" {
3286 let mut arms = vec![sel];
3287 let mut at = Some(prior);
3288 while let Some(arm) = at {
3289 arms.push(arm);
3290 at = arm.prior.as_deref();
3291 }
3292 let width = sel.columns.len();
3293 let alike = width > 0
3294 && arms.iter().all(|arm| !arm.values && arm.columns.len() == width)
3295 && (0..width).all(|i| {
3296 let first = &sel.columns[i].expr;
3297 first.op == "column" && arms.iter().all(|arm| {
3298 let e = &arm.columns[i].expr;
3299 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"))
3300 })
3301 });
3302 if alike {
3303 keys.push((0..width as i64).collect());
3304 }
3305 }
3306 keys
3307 }
3308
3309 fn pins<'n>(&self, t: &'n Node, cursor: i64, done: &[bool], index: &HashMap<i64, usize>) -> Option<&'n str> {
3314 self.pinned_column(t, cursor, done, index).and_then(|col| col.column.as_deref())
3315 }
3316
3317 fn pinned_column<'n>(&self, t: &'n Node, cursor: i64, done: &[bool], index: &HashMap<i64, usize>) -> Option<&'n Node> {
3319 if t.op != "=" {
3320 return None;
3321 }
3322 let (l, r) = (t.left.as_deref()?, t.right.as_deref()?);
3323 let collation = column_of(l).or_else(|| column_of(r)).and_then(|c| c.coll.as_deref()).unwrap_or("BINARY");
3324 [(l, r), (r, l)].into_iter().find_map(|(col, other)| {
3325 let value = col.op == "column"
3326 && col.cursor == cursor
3327 && !has_op(other, "collate")
3328 && keeps_column(col, other)
3329 && (collation.eq_ignore_ascii_case("BINARY") || col.coll.as_deref().is_some_and(|c| c.eq_ignore_ascii_case(collation)))
3330 && !self.calls_volatile(other)
3331 && other.select.is_none()
3332 && cursors(other).is_some_and(|read| read.iter().all(|c| *c != cursor && index.get(c).is_none_or(|i| done[*i])));
3333 value.then_some(col)
3334 })
3335 }
3336
3337 fn pinned(&self, sel: &Sel, e: &Node, constant: &[bool]) -> bool {
3340 let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
3341 if e.op == "column" {
3342 if index.get(&e.cursor).is_some_and(|i| constant[*i]) {
3343 return true;
3344 }
3345 let terms = conjuncts(sel.where_.as_ref());
3346 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)));
3347 }
3348 e.select.is_none() && !self.calls_volatile(e) && cursors(e).is_some_and(|read| read.iter().all(|c| !index.contains_key(c)))
3349 }
3350
3351 fn pinned_by_name(&self, table: &str, where_: Option<&Node>) -> Result<(), String> {
3353 let equated = self.equated(where_);
3354 let Some(info) = self.tree.tables.get(table) else { return Err(format!("`{table}` is not a table the engine can read")) };
3355 let names: HashSet<String> = equated.iter().map(|(_, n)| n.to_ascii_lowercase()).collect();
3356 if info.unique_keys.iter().any(|key| !key.is_empty() && key.iter().all(|c| names.contains(&c.to_ascii_lowercase()))) {
3357 return Ok(());
3358 }
3359 if info.unique_keys.is_empty() {
3360 return Err(format!("`{table}` has no unique index the engine can read, so nothing bounds the rows a WHERE matches"));
3361 }
3362 let shown: Vec<String> = info.unique_keys.iter().map(|k| format!("({})", k.join(", "))).collect();
3363 Err(format!("the WHERE does not equate every column of a unique key of `{table}` — it has {}", shown.join(", ")))
3364 }
3365
3366 fn equated(&self, where_: Option<&Node>) -> HashSet<(i64, String)> {
3369 let mut out = HashSet::new();
3370 for n in conjuncts(where_) {
3371 if n.op != "=" || n.outer_on {
3372 continue;
3373 }
3374 if let (Some(l), Some(r)) = (n.left.as_deref(), n.right.as_deref()) {
3375 for (col, other) in [(l, r), (r, l)] {
3376 if col.op == "column" && !reads_column(other) && !has_op(other, "collate") && keeps_column(col, other) && !self.calls_volatile(other) {
3379 if let Some(name) = &col.column {
3380 out.insert((col.cursor, name.clone()));
3381 }
3382 }
3383 }
3384 }
3385 }
3386 out
3387 }
3388
3389 fn calls_volatile(&self, n: &Node) -> bool {
3395 const VOLATILE: &[&str] = &["random", "randomblob", "changes", "total_changes", "last_insert_rowid", "date", "time", "datetime", "julianday", "unixepoch", "strftime", "timediff"];
3396 if n.op == "function" {
3397 if n.agg || n.window || n.over {
3398 return true;
3399 }
3400 let name = n.name.as_deref().unwrap_or("").to_ascii_lowercase();
3401 if VOLATILE.contains(&name.as_str()) || self.extras.function(&name, n.args.len()).is_some() || !KNOWN_FUNCTIONS.contains(&name.as_str()) {
3402 return true;
3403 }
3404 }
3405 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))
3406 }
3407}
3408
3409fn keeps_column(col: &Node, other: &Node) -> bool {
3415 let numeric = |a: &str| matches!(a, "integer" | "real" | "numeric");
3416 let none = |a: &str| matches!(a, "blob" | "none");
3417 numeric(&col.aff) || none(&other.aff) || (col.aff == "text" && other.aff == "text")
3418}
3419
3420fn column_of(n: &Node) -> Option<&Node> {
3422 match n.op.as_str() {
3423 "column" => Some(n),
3424 "cast" | "pos" => n.left.as_deref().and_then(column_of),
3425 _ => None,
3426 }
3427}
3428
3429fn literal_text(n: &Node) -> Option<&str> {
3431 if n.op == "string" { n.value.as_deref() } else { None }
3432}
3433
3434fn iif_values(count: usize) -> Vec<usize> {
3437 let mut out: Vec<usize> = (1..count).step_by(2).collect();
3438 if count >= 3 && count % 2 == 1 {
3439 out.push(count - 1);
3440 }
3441 out
3442}
3443
3444fn holds_current_row(n: &Node) -> bool {
3454 let start = matches!(n.frame_start.as_deref(), Some("unbounded" | "preceding" | "current"));
3455 let end = matches!(n.frame_end.as_deref(), Some("unbounded" | "following" | "current"));
3456 let exclude = matches!(n.exclude.as_deref(), Some("no" | "ties"));
3457 n.over && !n.filter && start && end && exclude
3458}
3459
3460fn total_nulls(arg: &Fact) -> Nulls {
3463 if is_integral(&arg.ty) { Nulls::Never } else { Nulls::Always }
3464}
3465
3466fn current_time(args: &[Node]) -> bool {
3475 let Some((value, modifiers)) = args.split_first() else { return true };
3476 let now = literal_text(value).is_some_and(|v| v.eq_ignore_ascii_case("now"))
3477 || (value.op == "function" && value.args.is_empty() && matches!(value.name.as_deref(), Some("current_timestamp" | "current_date" | "current_time")));
3478 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 };
3479 let mut modifiers = modifiers.iter().map(literal_text).peekable();
3480 let julian_day = match number {
3481 Some(v) if modifiers.peek().is_some_and(|m| m.is_some_and(|m| m.eq_ignore_ascii_case("unixepoch"))) => {
3482 modifiers.next();
3483 v / 86_400.0 + 2_440_587.5
3484 }
3485 Some(v) => v,
3486 None if now => 0.0,
3487 None => return false,
3488 };
3489 let mut days = 0.0;
3491 for m in modifiers {
3492 let Some(m) = m else { return false };
3493 let m = m.to_ascii_lowercase();
3494 days += match m.as_str() {
3495 "subsec" | "subsecond" => 0.0,
3496 "localtime" | "utc" => 1.0,
3498 "start of day" | "start of month" | "start of year" => 366.0,
3499 _ if m.len() == 9 && m.starts_with("weekday ") && matches!(m.as_bytes()[8], b'0'..=b'6') => 7.0,
3500 _ => match shift_days(&m) {
3501 Some(d) => d,
3502 None => return false,
3503 },
3504 };
3505 }
3506 if now {
3507 days < 365_000.0
3508 } else {
3509 let margin = if days > 0.0 { days + 400.0 } else { 0.0 };
3511 julian_day - margin >= 0.0 && julian_day + margin < 5_373_484.0
3512 }
3513}
3514
3515fn shift_days(m: &str) -> Option<f64> {
3518 let (number, unit) = m.split_once(' ')?;
3519 let unit = unit.trim_start_matches(' ');
3520 let unit = unit.strip_suffix('s').unwrap_or(unit);
3521 let days = match unit {
3522 "second" => 1.0 / 86_400.0,
3523 "minute" => 1.0 / 1_440.0,
3524 "hour" => 1.0 / 24.0,
3525 "day" => 1.0,
3526 "month" => 31.0,
3527 "year" => 366.0,
3528 _ => return None,
3529 };
3530 let digits = number.strip_prefix(['+', '-']).unwrap_or(number);
3531 let (whole, fraction) = digits.split_once('.').unwrap_or((digits, "0"));
3532 let all_digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
3533 if !all_digits(whole) || !all_digits(fraction) {
3534 return None;
3535 }
3536 Some(digits.parse::<f64>().ok()? * days)
3537}
3538
3539fn printf_writes(format: &str) -> bool {
3545 let b = format.as_bytes();
3546 let at = |i: usize| b.get(i).copied().unwrap_or(0);
3547 let mut i = 0;
3548 loop {
3549 match at(i) {
3550 0 => return false,
3551 b'%' => {}
3552 _ => return true,
3553 }
3554 i += 1;
3555 if at(i) == 0 {
3557 return true;
3558 }
3559 let mut c = at(i);
3560 loop {
3561 match c {
3562 b'-' | b'+' | b' ' | b'#' | b'!' | b'0' | b',' => {}
3563 b'l' => {
3564 i += 1;
3565 if at(i) == b'l' {
3566 i += 1;
3567 }
3568 c = at(i);
3569 break;
3570 }
3571 b'1'..=b'9' => {
3572 while at(i + 1).is_ascii_digit() {
3573 i += 1;
3574 }
3575 if !matches!(at(i + 1), b'.' | b'l') {
3576 i += 1;
3577 c = at(i);
3578 break;
3579 }
3580 }
3581 b'*' => {
3582 if !matches!(at(i + 1), b'.' | b'l') {
3583 i += 1;
3584 c = at(i);
3585 break;
3586 }
3587 }
3588 b'.' => {
3589 i += 1;
3590 if at(i) == b'*' {
3591 i += 1;
3592 } else {
3593 while at(i).is_ascii_digit() {
3594 i += 1;
3595 }
3596 }
3597 if at(i) != b'l' {
3598 c = at(i);
3599 break;
3600 }
3601 i -= 1;
3602 }
3603 _ => break,
3604 }
3605 i += 1;
3606 c = at(i);
3607 if c == 0 {
3608 break;
3609 }
3610 }
3611 match c {
3612 b'%' => return true,
3613 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,
3615 _ => return false,
3616 }
3617 }
3618}
3619
3620fn strftime_format(format: &str) -> bool {
3624 let mut bytes = format.bytes();
3625 while let Some(b) = bytes.next() {
3626 if b == b'%' && !bytes.next().is_some_and(|c| b"deFfHkIljJmMpPRsSTuwWY%".contains(&c)) {
3627 return false;
3628 }
3629 }
3630 true
3631}
3632
3633fn sqlean_alias(name: &str) -> &str {
3636 match name {
3637 "fuzzy_caver" => "caverphone",
3638 "fuzzy_damlev" => "dlevenshtein",
3639 "fuzzy_editdist" => "edit_distance",
3640 "fuzzy_hamming" => "hamming",
3641 "fuzzy_jarowin" => "jaro_winkler",
3642 "fuzzy_leven" => "levenshtein",
3643 "fuzzy_osadist" => "osa_distance",
3644 "fuzzy_phonetic" => "phonetic_hash",
3645 "fuzzy_rsoundex" => "rsoundex",
3646 "fuzzy_script" => "script_code",
3647 "fuzzy_soundex" => "soundex",
3648 "fuzzy_translit" => "translit",
3649 "stats_median" => "median",
3650 "stats_perc" => "percentile",
3651 "stats_p25" => "percentile_25",
3652 "stats_p75" => "percentile_75",
3653 "stats_p90" => "percentile_90",
3654 "stats_p95" => "percentile_95",
3655 "stats_p99" => "percentile_99",
3656 "stats_stddev" => "stddev",
3657 "stats_stddev_pop" => "stddev_pop",
3658 "stats_stddev_samp" => "stddev_samp",
3659 "stats_var" => "variance",
3660 "stats_var_pop" => "var_pop",
3661 "stats_var_samp" => "var_samp",
3662 _ => match name.strip_prefix("crypto_").or_else(|| name.strip_prefix("math_")) {
3663 Some(base @ ("md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" | "encode" | "decode")) if name.starts_with("crypto_") => base,
3664 Some(
3665 base @ ("acos" | "acosh" | "asin" | "asinh" | "atan" | "atan2" | "atanh" | "ceil" | "cos" | "cosh" | "degrees" | "exp" | "floor" | "ln" | "log" | "log10" | "log2" | "mod" | "pi"
3666 | "pow" | "radians" | "round" | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc"),
3667 ) if name.starts_with("math_") => base,
3668 _ => name,
3669 },
3670 }
3671}
3672
3673const KNOWN_FUNCTIONS: &[&str] = &[
3675 "coalesce", "ifnull", "nullif", "iif", "if", "min", "max", "abs", "round", "length", "instr", "unicode", "json_array_length", "json_valid", "octet_length", "sign",
3676 "like", "glob", "regexp", "match", "likely", "unlikely", "likelihood", "upper", "lower", "trim", "ltrim", "rtrim", "substr", "substring", "replace", "char",
3677 "printf", "format", "concat", "concat_ws", "json", "jsonb", "json_array", "json_object", "json_insert", "json_replace", "json_set", "json_remove", "json_patch",
3678 "json_quote", "json_pretty", "json_type", "hex", "quote", "typeof", "soundex", "zeroblob", "json_extract", "jsonb_extract", "->", "->>", "acos", "acosh", "asin", "asinh",
3679 "atan", "atan2", "atanh", "ceil", "ceiling", "cos", "cosh", "degrees", "exp", "floor", "ln", "log", "log10", "log2", "mod", "pow", "power", "radians", "sin",
3680 "sinh", "sqrt", "tan", "tanh", "trunc", "pi",
3681];
3682
3683fn integer(n: &Node) -> Option<i64> {
3685 if n.op == "integer" { n.value.as_deref().and_then(|v| v.parse().ok()) } else { None }
3686}
3687
3688fn integer_literal_fits(n: &Node) -> bool {
3692 n.value.as_deref().is_none_or(|v| v.starts_with("0x") || v.starts_with("0X") || v.parse::<i64>().is_ok())
3693}
3694
3695fn is_two_to_the_63(n: &Node) -> bool {
3697 n.op == "integer" && n.value.as_deref().and_then(|v| v.parse::<u64>().ok()) == Some(1 << 63)
3698}
3699
3700fn conjuncts(n: Option<&Node>) -> Vec<&Node> {
3702 let mut out = Vec::new();
3703 let mut stack: Vec<&Node> = n.into_iter().collect();
3704 while let Some(n) = stack.pop() {
3705 if n.op == "and" {
3706 stack.extend(n.left.as_deref());
3707 stack.extend(n.right.as_deref());
3708 } else {
3709 out.push(n);
3710 }
3711 }
3712 out
3713}
3714
3715fn cursors(n: &Node) -> Option<Vec<i64>> {
3718 if n.select.is_some() {
3719 return None;
3720 }
3721 let mut out = Vec::new();
3722 if n.op == "column" {
3723 out.push(n.cursor);
3724 }
3725 for child in n.left.iter().chain(n.right.iter()).map(|b| b.as_ref()).chain(n.list.iter()).chain(n.args.iter()) {
3726 out.extend(cursors(child)?);
3727 }
3728 Some(out)
3729}
3730
3731fn arithmetic(l: &Ty, r: &Ty) -> Ty {
3733 match (scalar_name(l), scalar_name(r)) {
3734 (Some("integer" | "int8"), Some("integer" | "int8")) => Ty::Scalar { name: "integer".into() },
3735 _ => Ty::Scalar { name: "real".into() },
3736 }
3737}
3738
3739fn has_op(n: &Node, op: &str) -> bool {
3741 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))
3742}
3743
3744fn has_aggregate(n: &Node) -> bool {
3745 if n.op == "function" && n.agg && !n.window {
3746 return true;
3747 }
3748 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)
3749}
3750
3751fn reads_column(n: &Node) -> bool {
3753 if n.op == "column" {
3754 return true;
3755 }
3756 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()
3757}
3758
3759fn is_vector(n: &Option<Box<Node>>) -> bool {
3761 n.as_deref().is_some_and(|n| n.op == "vector")
3762}
3763
3764fn outer_type(ctx: &Ctx) -> Ctx {
3765 match ctx {
3766 Ctx::Typed(Some(f)) => Ctx::Typed(Some(f.clone())),
3767 _ => Ctx::None,
3768 }
3769}
3770
3771fn i_of(slot: Position) -> usize {
3773 match slot {
3774 Position::Arg(i) => i,
3775 _ => 0,
3776 }
3777}
3778
3779fn is_boolean_declared(declared: &str) -> bool {
3781 let d = declared.trim();
3782 d.eq_ignore_ascii_case("boolean") || d.eq_ignore_ascii_case("bool")
3783}
3784
3785pub fn affinity(declared: &str) -> &'static str {
3787 let d = declared.to_ascii_uppercase();
3788 if d.contains("INT") {
3789 "integer"
3790 } else if d.contains("CHAR") || d.contains("CLOB") || d.contains("TEXT") {
3791 "text"
3792 } else if d.contains("BLOB") || d.is_empty() {
3793 "blob"
3794 } else if d.contains("REAL") || d.contains("FLOA") || d.contains("DOUB") {
3795 "real"
3796 } else {
3797 "numeric"
3798 }
3799}
3800
3801#[derive(Clone)]
3803enum Ctx {
3804 Typed(Option<Fact>),
3805 Row(Vec<Option<Fact>>),
3807 Bool,
3808 None,
3809}
3810
3811#[derive(Clone, Copy)]
3812enum Position {
3813 Left,
3814 Right,
3815 List(usize),
3816 Arg(usize),
3817}
3818
3819#[cfg(test)]
3820mod tests {
3821 use super::*;
3822
3823 #[test]
3824 fn a_row_assigned_fewer_values_than_columns_is_the_database_s_error() {
3825 let ddl = vec!["create table t1 (a integer primary key, b, c, d)".to_string(), "create table t2 (w, x, y)".to_string()];
3826 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)"] {
3827 let a = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
3828 assert!(!a.diagnostics.is_empty(), "{sql}: {a:?}");
3829 }
3830 }
3831
3832 fn ddl() -> Vec<String> {
3833 vec![
3834 "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(),
3835 "create table posts (id integer primary key, user_id integer not null references users(id), title text not null, body text)".to_string(),
3836 ]
3837 }
3838
3839 fn analysis(sql: &str) -> Analysis {
3840 analyze_ddl(sql, &ddl(), &Extras::default()).analysis
3841 }
3842
3843 fn marked(sql: &str, ddl: &[String], names: &[&str]) -> Analysis {
3846 let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
3847 run(sql, &lex::lex(sql, Dialect::Sqlite).unwrap(), ddl, &Extras::default(), &names).analysis
3848 }
3849
3850 #[test]
3851 fn the_facts_are_read_for_every_table_the_statement_names_and_no_with_query() {
3852 let mut schema = ddl();
3853 schema.push("create table tags (id integer primary key, post_id integer)".into());
3854 schema.push("create view titles as select title from posts".into());
3855 let tables = |sql: &str| {
3856 let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
3857 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
3858 let mut t = a.tables.expect("the tree names its tables");
3859 t.read.sort();
3860 t.read.dedup();
3861 (t.read, t.write)
3862 };
3863 let names = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
3864 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![]));
3865 assert_eq!(tables("with recent as (select user_id from posts) select title from titles join recent on true"), (names(&["posts", "titles"]), vec![]));
3867 assert_eq!(tables("select value from json_each('[1]')"), (vec![], vec![]));
3868 assert_eq!(tables("select s.n from (select count(*) as n from posts) s join titles on true"), (names(&["posts", "titles"]), vec![]));
3869 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"])));
3870 assert_eq!(tables("insert into tags (post_id) select id from posts"), (names(&["posts"]), names(&["tags"])));
3872 assert_eq!(tables("update users set name = (select max(title) from posts) where id = 1"), (names(&["posts"]), names(&["users"])));
3873 assert_eq!(tables("delete from users where id in (select user_id from posts)"), (names(&["posts"]), names(&["users"])));
3874 }
3875
3876 #[test]
3877 fn a_key_declared_on_conflict_replace_is_read_from_sqlite_s_parse_however_the_ddl_spells_it() {
3878 let replaces = |clause: &str| {
3879 let ddl = vec![format!("create table p (id integer primary key, email text {clause})")];
3880 let t = tree::analyze(&ddl, "insert into p (email) values (?1)", "insert into p (email) values (?)", &[], None).expect("the tree parses");
3881 assert!(t.error.is_none(), "{clause}: {:?}", t.error);
3882 t.tables["p"].replaces
3883 };
3884 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"] {
3885 assert!(replaces(clause), "{clause}");
3886 }
3887 for clause in ["unique", "not null on conflict replace default '' unique", "unique on conflict ignore"] {
3889 assert!(!replaces(clause), "{clause}");
3890 }
3891 }
3892
3893 #[test]
3894 fn the_schema_replay_reaches_no_file_and_sets_no_pragma() {
3895 let dir = std::env::temp_dir().join(format!("reylo-sqlite-replay-test-{}", std::process::id()));
3898 std::fs::create_dir_all(&dir).unwrap();
3899 let (attached, vacuumed) = (dir.join("attached.db"), dir.join("vacuumed.db"));
3900 let ddl = vec![
3901 format!("create table t (a integer not null); attach '{}' as x; create table x.y (z)", attached.display()),
3902 format!("create table u (b); vacuum into '{}'", vacuumed.display()),
3903 "create table v (c); pragma hard_heap_limit = 1; create table w (d)".to_string(),
3904 ];
3905 let a = analyze_ddl("select a, b, c from t, u, v", &ddl, &Extras::default()).analysis;
3907 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
3908 assert!(!attached.exists() && !vacuumed.exists());
3909 for _ in 0..2 {
3912 let refused = analyze_ddl("select d from w", &ddl, &Extras::default()).analysis;
3913 let messages: Vec<&str> = refused.diagnostics.iter().map(|d| d.message.as_str()).collect();
3914 assert_eq!(messages.first(), Some(&"no such table: w"), "{messages:?}");
3915 assert!(messages.contains(&"The schema replay skipped statement 1: not authorized"), "{messages:?}");
3916 assert!(messages.contains(&"The schema replay skipped statement 3: not authorized"), "{messages:?}");
3917 }
3918 std::fs::remove_dir_all(&dir).unwrap();
3919 }
3920
3921 #[test]
3922 fn the_tree_describes_the_schema_tables_alone_and_no_with_query() {
3923 let described = |sql: &str| {
3927 let t = tree::analyze(&ddl(), sql, sql, &[], None).expect("the tree parses");
3928 assert!(t.error.is_none(), "{sql}: {:?}", t.error);
3929 let mut names = t.tables.into_keys().collect::<Vec<_>>();
3930 names.sort();
3931 names
3932 };
3933 assert_eq!(described("with recent as (select user_id from posts) select user_id from recent"), ["posts"]);
3934 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());
3935 assert_eq!(described("with users as (select id from main.users) select id from users"), ["users"]);
3936 let nested = "with recursive t (n, x, j) as (select 1, 'a', json_array('a') union all select n + 1, null, \
3937 (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) \
3938 from t where n < 3) select n, x, j from t";
3939 assert_eq!(described(nested), Vec::<String>::new());
3940 assert!(analysis(nested).diagnostics.is_empty());
3941 }
3942
3943 #[test]
3944 fn a_statement_as_deep_as_the_engine_reads_is_typed_and_one_level_past_it_is_an_error_at_the_bound() {
3945 let ddl = vec!["create table users (id integer primary key, name text not null, nick text)".to_string()];
3948 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());
3949 for (shape, n) in [("sum", 350), ("and_or", 348), ("case", 348), ("coalesce", 349), ("subquery", 23)] {
3951 let at = small(crate::stack::nested(shape, n));
3952 assert!(at.diagnostics.is_empty() && at.kind == Some(StatementKind::Select), "{shape} at {n}: {:?}", at.diagnostics);
3953 let past = small(crate::stack::nested(shape, n + 1));
3954 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);
3955 }
3956 let list = (0..5_000).map(|i| i.to_string()).collect::<Vec<_>>().join(", ");
3958 assert!(small(format!("select id from users where id in ({list})")).diagnostics.is_empty());
3959 }
3960
3961 fn col(a: &Analysis, name: &str) -> (String, bool) {
3962 let c = a.columns.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no column {name}"));
3963 (affinity_of(&c.ty).unwrap_or("unknown").to_string(), c.nullable)
3964 }
3965
3966 #[test]
3967 fn returning_reads_a_value_the_statement_wrote_to_the_row() {
3968 let nullable = |sql: &str| analysis(sql).columns.iter().map(|c| c.nullable).collect::<Vec<_>>();
3969 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]);
3972 assert_eq!(nullable("insert into users (name, email) values ('a', :e) returning email"), [true]);
3974 assert_eq!(nullable("update users set email = :e returning email"), [true]);
3975 assert_eq!(nullable("insert into users (name, email) values ('a', 'x'), ('b', null) returning email"), [true]);
3977 assert_eq!(nullable("insert into users (name, email) values ('a', 'x'), ('b', 'y') returning email"), [false]);
3978 assert_eq!(nullable("insert into users (name, email) select name, email from users returning email"), [true]);
3979 assert_eq!(nullable("insert into users (name, email) select name, name from users returning email"), [false]);
3980 assert_eq!(nullable("update users set email = 'x', score = coalesce(score, 0) where id = 1 returning email, score, avatar"), [false, false, true]);
3983 assert_eq!(nullable("update users set email = name returning email"), [false]);
3984 assert_eq!(nullable("update users set email = score returning email"), [true]);
3985 assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do update set email = 'y' returning email"), [false]);
3987 assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do update set name = 'b' returning email"), [true]);
3988 assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do nothing returning email"), [false]);
3989 let triggered = |sql: &str, trigger: &str| {
3992 let mut schema = ddl();
3993 schema.push(trigger.to_string());
3994 analyze_ddl(sql, &schema, &Extras::default()).analysis.columns.iter().map(|c| c.nullable).collect::<Vec<_>>()
3995 };
3996 assert_eq!(triggered("update users set email = 'x' returning email", "create trigger b before update on users begin select 1; end"), [true]);
3997 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]);
3998 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]);
3999 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]);
4000 assert_eq!(nullable("delete from users where id = 1 returning email"), [true]);
4002 assert_eq!(nullable("update users set email = 'x' returning (select email from users where id = 2) as other"), [true]);
4003 }
4004
4005 fn param(a: &Analysis, name: &str) -> String {
4006 let p = a.params.iter().find(|p| p.name == name).unwrap_or_else(|| panic!("no param {name}"));
4007 affinity_of(&p.ty).unwrap_or("unknown").to_string()
4008 }
4009
4010 #[test]
4011 fn the_full_text_functions_are_typed() {
4012 let mut schema = ddl();
4016 schema.push("CREATE VIRTUAL TABLE docs USING fts5(title, body)".into());
4017 schema.push("CREATE VIRTUAL TABLE notes USING fts4(body)".into());
4018 let a = |sql: &str| {
4019 let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
4020 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4021 a
4022 };
4023 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, \
4024 snippet(docs, -1, '<b>', '</b>', '…', 8) as excerpt from docs where docs match :q order by rank");
4025 assert_eq!(col(&fts5, "rank"), ("real".into(), false));
4026 assert_eq!(col(&fts5, "weighted"), ("real".into(), true));
4027 assert_eq!(col(&fts5, "hit"), ("text".into(), true));
4028 assert_eq!(col(&fts5, "excerpt"), ("text".into(), true));
4029 assert_eq!((param(&fts5, "w"), param(&fts5, "col"), param(&fts5, "open"), param(&fts5, "q")), ("real".into(), "integer".into(), "text".into(), "text".into()));
4030 let fts4 = a("select offsets(notes) as o, matchinfo(notes) as m, snippet(notes) as s from notes where notes match :q");
4031 assert_eq!(col(&fts4, "o"), ("text".into(), false));
4032 assert_eq!(col(&fts4, "m"), ("blob".into(), false));
4033 assert_eq!(col(&fts4, "s"), ("text".into(), true));
4034 let built = a("select json_object('hit', highlight(docs, 0, '<b>', '</b>'), 'rank', bm25(docs)) as j from docs where docs match :q");
4036 assert_eq!(shown(&built), "j: { hit: string | null; rank: number }");
4037 }
4038
4039 #[test]
4040 fn a_built_in_is_non_null_only_where_sqlite_never_answers_null_for_non_null_arguments() {
4041 let ddl = vec![
4043 "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(),
4044 "create table loose (id integer primary key, num numeric not null)".to_string(),
4045 ];
4046 let typed = |expr: &str| {
4047 let a = analyze_ddl(&format!("select {expr} as v from o, loose"), &ddl, &Extras::default()).analysis;
4048 assert!(a.diagnostics.is_empty(), "{expr}: {:?}", a.diagnostics);
4049 col(&a, "v")
4050 };
4051 let nullable = |expr: &str| typed(expr).1;
4052 for expr in [
4054 "date(placed_at)", "time(placed_at)", "datetime(placed_at)", "julianday(placed_at)", "unixepoch(placed_at)", "strftime('%Y', placed_at)",
4055 "date(placed_at, '+1 day')", "timediff(placed_at, 'now')", "date(n)", "date(x, 'unixepoch')", "date('2024-01-01')", "date(:d)",
4056 "date('now', 'weekday 7')", "date('now', 'unixepoch')", "date('now', 'julianday')", "date('now', '+8000 years')", "date('now', '+1 day ')",
4057 "date('now', '+600 years', '+600 years')", "date('now', fmt)", "date('now ')", "strftime('%Q', 'now')", "strftime('%Y%')", "strftime(fmt)",
4058 "date(5373485)", "datetime(1e18, 'unixepoch')", "date(0, '-1 day')", "date(1700000000, 'unixepoch', 'unixepoch')", "date(1, 'auto')", "date(-1)",
4059 ] {
4060 assert!(nullable(expr), "{expr}");
4061 }
4062 for expr in [
4064 "date()", "time()", "datetime()", "julianday()", "unixepoch()", "date('now')", "date('NOW')", "datetime('now', 'localtime')", "datetime('now', 'utc')",
4065 "date('now', 'start of month', '+1 month', '-1 day')", "date('now', 'weekday 0')", "datetime('now', '-7 days', '+1.5 hours', '+30 MINUTES')",
4066 "date('now', 'subsec')", "strftime('%Y-%m-%d %H:%M:%f %% %j', 'now')", "strftime('%s')", "strftime('')", "timediff('now', 'now')",
4067 "strftime('%Y', current_timestamp)", "date(current_date, '+1 month')", "datetime(0, 'unixepoch')", "date(2460000.5)", "date(1700000000, 'unixepoch', 'start of day', '+1 day')",
4068 ] {
4069 assert!(!nullable(expr), "{expr}");
4070 }
4071 assert_eq!(typed("unixepoch()"), ("integer".into(), false));
4072 assert_eq!(typed("unixepoch('now', 'subsec')"), ("real".into(), false));
4073 assert_eq!(typed("unixepoch('now', fmt)"), ("real".into(), true));
4074 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)"] {
4077 assert_eq!(typed(f), ("real".into(), true), "{f}");
4078 }
4079 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()"] {
4081 assert_eq!(typed(f), ("real".into(), false), "{f}");
4082 }
4083 assert_eq!(typed("sign(x)"), ("integer".into(), false));
4084 for f in ["sign(placed_at)", "sign(v)", "sign(num)", "ceil(placed_at)", "floor(b)", "exp(v)", "atan2(x, placed_at)", "sinh(num)"] {
4085 assert!(nullable(f), "{f}");
4086 }
4087 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('%-')"] {
4089 assert!(nullable(f), "{f}");
4090 }
4091 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')"] {
4092 assert!(!nullable(f), "{f}");
4093 }
4094 assert_eq!(typed("substr(placed_at, 2)"), ("text".into(), false));
4096 assert_eq!(typed("substr(n, 2, 1)"), ("text".into(), false));
4097 assert_eq!(typed("substr(:s, 2)"), ("text".into(), false));
4098 assert_eq!(typed("substr(b, 2)"), ("blob".into(), true));
4099 assert_eq!(typed("substring(v, 1, 2)"), ("unknown".into(), true));
4100 for f in ["json_type(doc, '$.a')", "json_array_length(doc, '$.a')", "json_remove(doc, '$')", "json_remove(doc, '$.a')"] {
4102 assert!(nullable(f), "{f}");
4103 }
4104 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)"] {
4105 assert!(!nullable(f), "{f}");
4106 }
4107 assert_eq!(typed("jsonb(doc)"), ("blob".into(), false));
4108 assert_eq!(typed("(select jsonb_group_array(id) from o)"), ("blob".into(), false));
4109 assert_eq!(typed("iif(n > 0, placed_at)"), ("text".into(), true));
4111 assert_eq!(typed("iif(n > 0, placed_at, n > 1, doc)"), ("text".into(), true));
4112 assert_eq!(typed("iif(n > 0, placed_at, n > 1, doc, fmt)"), ("text".into(), false));
4113 assert_eq!(typed("if(n > 0, x, n > 1, x, 1.5)"), ("real".into(), false));
4114 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");
4116 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");
4117 assert_eq!(typed("(select total(x) from o)"), ("real".into(), true));
4119 assert_eq!(typed("(select total(n) from o)"), ("real".into(), false));
4120 assert_eq!(typed("total(x) over ()"), ("real".into(), true));
4121 for f in [
4123 "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')",
4124 "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)",
4125 ] {
4126 assert!(!nullable(f), "{f}");
4127 }
4128 assert!(nullable("unicode(placed_at)"));
4129 }
4130
4131 #[test]
4132 fn the_postgres_nullability_rules_hold_on_sqlite() {
4133 let nullable_param = |sql: &str, name: &str| analysis(sql).params.iter().find(|p| p.name == name).is_some_and(|p| p.nullable);
4134 let marked_param = |sql: &str, name: &str| marked(sql, &ddl(), &[name]).params.iter().find(|p| p.name == name).is_some_and(|p| p.nullable);
4137 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"));
4138 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"));
4139 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"));
4140 assert!(!nullable_param("select id from users, (select :p as p) s where coalesce(s.p, score) = score", "p"));
4141 assert!(!nullable_param("with input as (select :p as p) select id from users, input where score = coalesce(input.p, score)", "p"));
4142 assert!(!nullable_param("with input as (select :p as p) select id from users, input where score > input.p", "p"));
4143 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"));
4144 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"));
4145 assert!(!nullable_param("select id from users where cast(:p as integer) is null", "p"));
4146 assert!(!nullable_param("select id from users where :p is not null", "p"));
4147 assert!(!nullable_param("select id from users where email is :p", "p"));
4148 assert!(!nullable_param("select id from users where :p is not email", "p"));
4149 assert!(!nullable_param("select id from users where :p isnull", "p"));
4150 assert!(!nullable_param("select id from users where score = coalesce(score, :p)", "p"));
4151 let sql = "select id from users where (:p is null or score > :p)";
4152 let repeated = analysis(sql);
4153 assert_eq!(repeated.diagnostics.iter().map(|d| (d.code, d.start, d.length)).collect::<Vec<_>>(), [(3, sql.rfind(":p").unwrap(), 2)]);
4154 assert!(!nullable_param("select coalesce(:s, 0) as x", "s"));
4155 assert!(!nullable_param("select id from users where score > :p", "p"));
4156 assert_eq!(col(&analysis("select upper(:s) as u"), "u"), ("text".into(), false));
4157 assert_eq!(col(&analysis("select email from users where email is not null"), "email"), ("text".into(), false));
4159 assert_eq!(col(&analysis("select email from users where lower(email) = :e or email like 'a%'"), "email").1, false);
4160 assert_eq!(col(&analysis("select email from users where email like 'a%' or id = 1"), "email").1, true);
4161 assert_eq!(col(&analysis("select email from users where lower(email) = :e and email like 'a%'"), "email").1, false);
4162 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");
4163 assert_eq!(col(&reduced, "name"), ("text".into(), false));
4164 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));
4165 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");
4168 assert_eq!((col(&right, "title").1, col(&right, "name").1), (true, true));
4169 assert_eq!(col(&analysis("select u.email from posts p join users u on u.email is not null"), "email").1, false);
4170 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));
4171 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");
4173 assert_eq!((col(&grouped, "t").1, col(&grouped, "m").1, col(&grouped, "g").1), (false, false, false));
4174 assert!(col(&analysis("select max(title) as t from posts"), "t").1);
4175 let concat = analysis("select concat(email, 'x') as c, concat_ws(',', email) as w, concat_ws(email, 'a') as n from users");
4177 assert_eq!((col(&concat, "c").1, col(&concat, "w").1, col(&concat, "n").1), (false, false, true));
4178 }
4179
4180 #[test]
4181 fn a_cast_parameter_is_its_casts_type_and_a_bare_one_its_columns() {
4182 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()];
4188 let types = |sql: &str| {
4189 let a = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
4190 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4191 a.params.iter().map(|p| format!("{}{}", p.name, if p.nullable { "?" } else { "" })).collect::<Vec<_>>().join(" ")
4192 };
4193 for (sql, want) in [
4194 ("insert into users (name, email) values (:name, :email) on conflict (email) do update set name = excluded.name returning id", "name email?"),
4195 ("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"),
4196 ("insert into users (name, email, score, n, doc, meta) values (:name, :email, :score, :n, :doc, :meta)", "name email? score? n? doc? meta"),
4197 ("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"),
4198 ("insert into users (name, email) values (:a, :b), (:c, CAST(:d AS TEXT))", "a b? c d"),
4199 ("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"),
4200 ("update users set (name, email) = (:name, :email) where id = :id", "name email? id"),
4201 ("update users set (name, email) = (CAST(:name AS TEXT), CAST(:email AS TEXT)) where id = CAST(:id AS INTEGER)", "name email id"),
4202 ("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"),
4203 ("update users set email = CAST(CAST(:e AS INTEGER) AS TEXT), meta = json(:m) where id = 1", "e m"),
4204 ("insert into users (name, nick, code, tag) values (:name, :nick, :code, :tag)", "name nick code tag?"),
4205 ("update users set nick = :nick, code = :code, tag = :tag where id = :id", "nick code tag? id"),
4206 ("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"),
4207 ("select id from users where (json(:doc) is null or doc = json(:d)) and :x is not null", "doc d x"),
4208 ("insert into users (name, email) select CAST(:name AS TEXT), CAST(:email AS TEXT)", "name email"),
4209 ("insert into users (name, email) select :name, :email", "name email?"),
4210 ] {
4211 assert_eq!(types(sql), want, "{sql}");
4212 }
4213 let ddl: Vec<String> = ddl.iter().map(|s| s.to_string()).collect();
4217 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))";
4218 let a = marked(sql, &ddl, &["name", "email", "nick", "doc", "meta"]);
4219 assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true; 5]);
4220 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.");
4221 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"))]);
4222 let sql = "insert into users (name, email) select CAST(:name AS TEXT), CAST(:email AS TEXT)";
4224 let a = marked(sql, &ddl, &["name", "email"]);
4225 assert_eq!(a.diagnostics.iter().map(|d| (&sql[d.start..d.start + d.length], d.message.clone())).collect::<Vec<_>>(), [(":name", said(":name", "name"))]);
4226 let a = marked("update users set email = CAST(:e AS TEXT), n = coalesce(CAST(:n AS INTEGER), n) where id = 1", &ddl, &["e", "n"]);
4227 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4228 assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true, true]);
4229 }
4230
4231 #[test]
4232 fn a_parameter_takes_the_type_its_call_case_or_compound_stands_in() {
4233 assert_eq!(param(&analysis("select id from users where name = coalesce(:a, :b)"), "a"), "text");
4234 assert_eq!(param(&analysis("select id from users where name = coalesce(:a, :b)"), "b"), "text");
4235 assert_eq!(param(&analysis("select id from users where name = case when id > 1 then :a else :b end"), "a"), "text");
4236 assert_eq!(param(&analysis("select id from users where name = iif(id > 1, :a, 'x')"), "a"), "text");
4237 assert_eq!(param(&analysis("select case :kind when 'a' then 1 else 2 end as k from users"), "kind"), "text");
4238 assert_eq!(param(&analysis("select name from users union all select :x"), "x"), "text");
4239 assert_eq!(param(&analysis("select :x union all select name from users"), "x"), "text");
4240 assert_eq!(param(&analysis("select id from users where name = printf(:f, 1)"), "f"), "text");
4242 assert_eq!(param(&analysis("select :x as v"), "x"), "unknown");
4243 }
4244
4245 #[test]
4246 fn an_outer_joins_on_term_pins_its_right_side_but_groups_nothing() {
4247 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");
4250 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");
4251 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");
4253 }
4254
4255 #[test]
4256 fn an_insert_returns_no_row_where_something_can_skip_it() {
4257 let count = |sql: &str, extra: &[&str]| {
4258 let mut schema = ddl();
4259 schema.extend(extra.iter().map(|s| s.to_string()));
4260 analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
4261 };
4262 let insert = "insert into users (name) values (:n) returning id";
4263 assert_eq!(count(insert, &[]), "one");
4264 assert_eq!(count(insert, &["create trigger skip before insert on users begin select raise(ignore) where new.name = 'x'; end"]), "at_most_one");
4266 assert_eq!(count(insert, &["create trigger untimed insert on users begin select 1; end"]), "at_most_one", "BEFORE is the default");
4267 assert_eq!(count(insert, &["create trigger later after insert on users begin select 1; end"]), "one");
4268 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");
4270 assert_eq!(count("insert into users (id, name) values (:id, :n) on conflict (id) do update set name = excluded.name returning id", &[]), "one");
4271 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");
4273 let declared = |sql: &str, table: &str| {
4276 let schema = vec![table.to_string()];
4277 analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
4278 };
4279 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");
4280 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");
4281 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");
4282 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");
4283 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");
4284 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");
4285 }
4286
4287 #[test]
4288 fn a_write_to_a_view_goes_through_its_instead_of_trigger() {
4289 let schema = vec![
4290 "create table w (id integer primary key, k text not null, v integer)".to_string(),
4291 "create view wv as select id, k, v from w".to_string(),
4292 "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(),
4293 "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(),
4294 ];
4295 let analysis = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
4296 let insert = analysis("insert into wv (k, v) values (42, 9) returning k");
4297 assert!(insert.diagnostics.is_empty(), "{:?}", insert.diagnostics);
4298 assert_eq!(col(&insert, "k"), ("unknown".into(), true));
4300 assert!(analysis("update wv set v = :v where id = :id").diagnostics.is_empty());
4301 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"));
4304 assert_eq!(analysis("delete from wv").diagnostics.first().map(|d| d.message.as_str()), Some("cannot modify wv because it is a view"));
4305 assert_eq!(instead_of_stub("create trigger t before insert on w begin select 1; end"), None);
4306 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"));
4307 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"));
4308 }
4309
4310 #[test]
4311 fn a_unique_key_bounds_only_a_comparison_under_its_own_collation() {
4312 let count = |sql: &str| {
4313 let mut schema = ddl();
4314 schema.push("create table c (id integer primary key, e text collate nocase, b text unique)".into());
4315 schema.push("create unique index c_e on c (e collate binary)".into());
4316 analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
4317 };
4318 assert_eq!(count("select id from c where e = :e"), "many");
4320 assert_eq!(count("select id from c where b = :b"), "at_most_one");
4321 assert_eq!(count("select id from c where b = :b collate nocase"), "many");
4322 assert_eq!(count("select e from c where id = :id"), "at_most_one");
4323 }
4324
4325 #[test]
4326 fn a_function_the_host_registers_over_a_built_in_proves_nothing_strict() {
4327 let lower = Extras { total: vec![TotalFunction { name: "lower".into(), arity: 1, returns: Affinity::Text }], host: None };
4328 let nullable = |extras: &Extras| col(&analyze_ddl("select email from users where lower(email) = :e", &ddl(), extras).analysis, "email").1;
4329 assert!(!nullable(&Extras::default()));
4330 assert!(nullable(&lower));
4331 }
4332
4333 #[test]
4334 fn a_strict_column_and_a_rowid_hold_their_declared_type_alone() {
4335 let ddl = [
4336 "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",
4337 "create table loose (id integer primary key, n integer not null, t text)",
4338 "create table desc_key (a integer primary key desc)",
4339 ]
4340 .map(String::from);
4341 let kinds = |sql: &str| {
4342 let analysis = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
4343 analysis.columns.iter().map(|c| serde_json::to_value(&c.ty).unwrap()["kind"].as_str().unwrap().to_string()).collect::<Vec<_>>().join(" ")
4344 };
4345 assert_eq!(kinds("select id, n, x, t, b, a from s"), "integer integer float text bytes unknown");
4346 assert_eq!(kinds("select id, n, t from loose"), "integer union union");
4347 assert_eq!(kinds("select a from desc_key"), "union");
4348 assert_eq!(kinds("select g from s"), "union");
4350 assert_eq!(kinds("select n, t from (select n, t from s)"), "integer text");
4352 assert_eq!(kinds("select n from s union all select id from loose"), "integer");
4353 assert_eq!(kinds("select n from s union all select n from loose"), "union");
4354 assert_eq!(kinds("select n from s union all values (1)"), "union");
4355 }
4356
4357 fn libsql_schema() -> Vec<String> {
4360 [
4361 "CREATE TABLE docs (id integer primary key, title text not null, emb F32_BLOB(3))",
4362 "CREATE TABLE libsql_vector_meta_shadow ( name TEXT PRIMARY KEY, metadata BLOB ) WITHOUT ROWID",
4363 "CREATE TABLE docs_emb_shadow (index_key INTEGER , data BLOB, PRIMARY KEY (index_key))",
4364 "CREATE INDEX docs_emb_shadow_idx ON docs_emb_shadow (index_key)",
4365 "CREATE INDEX docs_emb on docs (libsql_vector_idx(emb))",
4366 "CREATE TABLE words (k text primary key, e F32_BLOB(2)) WITHOUT ROWID",
4367 "CREATE INDEX words_e on words (libsql_vector_idx(e, 'metric=l2'))",
4368 ]
4369 .map(String::from)
4370 .to_vec()
4371 }
4372
4373 fn sqlite_host() -> Extras {
4375 Extras { total: vec![], host: Some(["lower", "upper", "length", "count"].map(|name| HostFunction { name: name.into(), arity: -1, kind: 's' }).to_vec()) }
4376 }
4377
4378 #[test]
4379 fn the_sqlean_functions_turso_cloud_loads_are_typed_whatever_the_host_lists() {
4380 let ddl = vec!["create table people (id integer primary key, name text not null, nick text, score real not null) strict".to_string()];
4382 for extras in [Extras::default(), sqlite_host()] {
4383 let a = |sql: &str| {
4384 let a = analyze_ddl(sql, &ddl, &extras).analysis;
4385 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4386 a
4387 };
4388 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");
4389 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)));
4390 assert_eq!(param(&fresh, "id"), "text");
4391 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");
4392 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)));
4393 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");
4394 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)));
4395 assert_eq!(param(&fuzzy, "q"), "text");
4396 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");
4397 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)));
4398 assert_eq!(param(&text, "n"), "integer");
4399 let tests = a("select starts_with(name, 'a') as a, text_contains(name, :part) as b, regexp_like(nick, '^a') as c from people");
4401 assert_eq!(["a", "b", "c"].map(|c| col(&tests, c)), [("bool", false), ("bool", false), ("bool", false)].map(|(t, n)| (t.to_string(), n)));
4402 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'");
4404 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)));
4405 let aliased = a("select math_floor(:x) as a, fuzzy_soundex(:s) as b, stats_perc(score, :p) as c from people");
4407 assert_eq!((param(&aliased, "x"), param(&aliased, "s"), param(&aliased, "p")), ("real".into(), "text".into(), "real".into()));
4408 let math = a("select math_floor(score) as a, math_sqrt(score) as b, math_pi() as c from people");
4410 assert_eq!(["a", "b", "c"].map(|c| col(&math, c)), [("real", false), ("real", true), ("real", false)].map(|(t, n)| (t.to_string(), n)));
4411 let stats = a("select stddev(score) as a, stats_p90(score) as b, variance(score) as c from people group by name");
4412 assert_eq!(["a", "b", "c"].map(|c| col(&stats, c)), [("real", true), ("real", true), ("real", true)].map(|(t, n)| (t.to_string(), n)));
4413 let series = a("select value from generate_series(1, :stop)");
4414 assert_eq!((col(&series, "value"), param(&series, "stop")), (("integer".to_string(), false), "integer".to_string()));
4415 assert_eq!(col(&a("select value from stats_seq(1, 3)"), "value"), ("integer".to_string(), false));
4416 assert!(!analyze_ddl("select value from generate_series", &ddl, &extras).analysis.diagnostics.is_empty());
4417 }
4418 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;
4421 assert_eq!(["a", "b", "c"].map(|c| col(&own, c)), [("text", true), ("text", false), ("real", true)].map(|(t, n)| (t.to_string(), n)));
4422 }
4423
4424 #[test]
4425 fn libsql_s_vector_functions_are_typed_whatever_the_host_lists() {
4426 for extras in [Extras::default(), sqlite_host()] {
4427 let a = |sql: &str| {
4428 let a = analyze_ddl(sql, &libsql_schema(), &extras).analysis;
4429 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4430 a
4431 };
4432 let plain = a("select id, title from docs where id = :id");
4434 assert_eq!((col(&plain, "id"), col(&plain, "title")), (("integer".into(), false), ("text".into(), false)));
4435 assert_eq!(a("select emb from docs").columns[0].nullable, true);
4437 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");
4438 assert_eq!((col(&distance, "d"), col(&distance, "l")), (("real".into(), true), ("real".into(), true)));
4439 assert_eq!((param(&distance, "q"), param(&distance, "r")), ("text".into(), "text".into()));
4440 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");
4441 for name in ["v", "a", "b", "c", "d", "e", "f"] {
4442 assert_eq!(col(&made, name), ("blob".into(), false), "{name}");
4443 }
4444 assert_eq!(col(&made, "text"), ("text".into(), false));
4445 let insert = a("insert into docs (title, emb) values (:title, vector(:v)) returning id");
4446 assert_eq!((param(&insert, "title"), param(&insert, "v")), ("text".into(), "text".into()));
4447 }
4448 }
4449
4450 #[test]
4451 fn vector_top_k_returns_the_key_of_its_index_s_table() {
4452 for extras in [Extras::default(), sqlite_host()] {
4453 let a = |sql: &str| {
4454 let a = analyze_ddl(sql, &libsql_schema(), &extras).analysis;
4455 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4456 a
4457 };
4458 let top = a("select id from vector_top_k('docs_emb', vector(:q), :k)");
4460 assert_eq!(col(&top, "id"), ("integer".into(), false));
4461 assert_eq!((param(&top, "q"), param(&top, "k")), ("text".into(), "integer".into()));
4462 assert_eq!(a("select * from vector_top_k('docs_emb', :q, 5)").columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id"]);
4463 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");
4464 assert_eq!(col(&joined, "title"), ("text".into(), false));
4465 assert_eq!(col(&a("select id from vector_top_k('words_e', :q, 3)"), "id"), ("unknown".into(), false));
4467 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));
4469 assert_eq!(a("select id from vector_top_k(:index, :q, 5)").columns[0].nullable, true);
4470 }
4471 }
4472
4473 #[test]
4474 fn libsql_s_alter_column_prepares_on_a_table_and_column_that_exist() {
4475 let a = |sql: &str| analyze_ddl(sql, &libsql_schema(), &Extras::default()).analysis;
4476 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"] {
4477 let altered = a(sql);
4478 assert!(altered.diagnostics.is_empty(), "{sql}: {:?}", altered.diagnostics);
4479 assert!(altered.columns.is_empty());
4480 assert_eq!(altered.cardinality, Cardinality::None);
4481 }
4482 let missing = a("alter table docs alter column nope to nope integer");
4483 assert!(missing.diagnostics.len() == 1 && missing.diagnostics[0].message.starts_with("no such column: \"nope\", so if it is a migration"), "{:?}", missing.diagnostics);
4484 assert!(!a("alter table nope alter column title to title text").diagnostics.is_empty());
4485 assert!(!a("alter table docs alter column title").diagnostics.is_empty());
4486 }
4487
4488 #[test]
4489 fn a_table_whose_check_calls_a_function_the_host_lacks_still_replays() {
4490 let ddl = vec!["create table docs (id integer primary key, doc text check (doc is null or jsonschema_matches('{\"type\":\"object\"}', doc)))".to_string()];
4493 let without = Extras { total: vec![], host: Some(vec![HostFunction { name: "lower".into(), arity: 1, kind: 's' }]) };
4494 for extras in [Extras::default(), without.clone()] {
4495 let read = analyze_ddl("select id, doc from docs", &ddl, &extras).analysis;
4496 assert!(read.diagnostics.is_empty(), "{:?}", read.diagnostics);
4497 assert_eq!(read.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "doc"]);
4498 let write = analyze_ddl("insert into docs (doc) values (:doc) returning id", &ddl, &extras).analysis;
4499 assert!(write.diagnostics.is_empty(), "{:?}", write.diagnostics);
4500 assert_eq!(param(&write, "doc"), "text");
4501 }
4502 let call = analyze_ddl("select jsonschema_matches('{}', doc) as m from docs", &ddl, &without).analysis;
4504 assert!(!call.diagnostics.is_empty());
4505 }
4506
4507 #[test]
4508 fn columns_from_provenance_and_rules() {
4509 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");
4510 assert_eq!(col(&a, "id"), ("integer".into(), false));
4511 assert_eq!(col(&a, "name"), ("text".into(), false));
4512 assert_eq!(col(&a, "email"), ("text".into(), true));
4513 assert_eq!(col(&a, "score"), ("real".into(), true));
4514 assert_eq!(col(&a, "l"), ("integer".into(), true));
4515 assert_eq!(col(&a, "e"), ("text".into(), false));
4516 assert_eq!(col(&a, "d"), ("integer".into(), false));
4517 assert_eq!(col(&a, "h"), ("integer".into(), false));
4518 assert_eq!(a.cardinality, "many");
4519 }
4520
4521 #[test]
4522 fn a_column_beside_an_aggregate_with_no_group_by_is_null_over_no_rows() {
4523 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'");
4526 assert_eq!(col(&a, "id"), ("integer".into(), true));
4527 assert_eq!(col(&a, "name"), ("text".into(), true));
4528 assert_eq!(col(&a, "e"), ("text".into(), false));
4529 assert_eq!(col(&a, "d"), ("integer".into(), true));
4530 assert_eq!(col(&a, "n"), ("integer".into(), false));
4531 assert_eq!(col(&a, "c"), ("integer".into(), false));
4532 assert_eq!(a.cardinality, "one");
4533 let a = analysis("select name, count(*) as n from users group by name");
4535 assert_eq!(col(&a, "name"), ("text".into(), false));
4536 }
4537
4538 #[test]
4539 fn outer_join_and_subquery_provenance() {
4540 let a = analysis("select u.id, p.title from users u left join posts p on p.user_id = u.id");
4541 assert_eq!(col(&a, "title"), ("text".into(), true));
4542 let a = analysis("select t.id, t.name from (select id, name from users) t where t.id = :id");
4543 assert_eq!(col(&a, "id"), ("integer".into(), false));
4544 assert_eq!(col(&a, "name"), ("text".into(), false));
4545 assert_eq!(param(&a, "id"), "integer");
4546 }
4547
4548 #[test]
4549 fn parameters_from_context() {
4550 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");
4551 assert_eq!(param(&a, "email"), "text");
4552 assert_eq!(param(&a, "min"), "real");
4553 assert_eq!(param(&a, "a"), "integer");
4554 assert_eq!(param(&a, "from"), "text");
4555 assert_eq!(param(&a, "q"), "text");
4556 assert_eq!(param(&a, "n"), "text");
4557 assert_eq!(param(&a, "lim"), "integer");
4558 assert_eq!(param(&a, "off"), "integer");
4559 let a = analysis("insert into users (email, name, score) values (:e, upper(:n), :s * 2) returning id");
4560 assert_eq!(param(&a, "e"), "text");
4561 assert_eq!(param(&a, "n"), "text");
4562 assert_eq!(param(&a, "s"), "integer");
4563 assert_eq!(a.cardinality, "one");
4564 let a = analysis("update users set name = :name, score = :score where id = :id returning id");
4565 assert_eq!(param(&a, "name"), "text");
4566 assert_eq!(param(&a, "score"), "real");
4567 assert_eq!(param(&a, "id"), "integer");
4568 assert_eq!(a.cardinality, "at_most_one");
4569 }
4570
4571 #[test]
4572 fn json_each_reads_text() {
4573 let a = analysis("select id from users where id in (select value from json_each(:ids))");
4575 assert_eq!(param(&a, "ids"), "text");
4576 assert!(!a.params.iter().find(|p| p.name == "ids").unwrap().nullable);
4577 let a = analysis("select key, value from json_tree(:doc, :path)");
4578 assert_eq!(param(&a, "doc"), "text");
4579 assert_eq!(param(&a, "path"), "text");
4580 assert_eq!(param(&analysis("select value from json_each(cast(:ids as text))"), "ids"), "text");
4581 let a = marked("select value from json_each(coalesce(CAST(:ids AS TEXT), '[]'))", &ddl(), &["ids"]);
4582 assert_eq!(param(&a, "ids"), "text");
4583 assert!(a.params.iter().find(|p| p.name == "ids").unwrap().nullable);
4584 let a = analysis("select users.id from users, json_each(:ids) j where users.id = j.value and users.name = :n");
4586 assert_eq!(param(&a, "ids"), "text");
4587 assert_eq!(param(&a, "n"), "text");
4588 }
4589
4590 #[test]
4591 fn cardinality_by_keys() {
4592 assert_eq!(analysis("select id from users where email = :email").cardinality, "at_most_one");
4593 assert_eq!(analysis("select id from users where name = :name").cardinality, "many");
4594 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");
4595 assert_eq!(analysis("select id from users limit 1").cardinality, "at_most_one");
4596 assert_eq!(analysis("insert or ignore into users (email, name) values (:e, :n) returning id").cardinality, "at_most_one");
4597 assert_eq!(analysis("insert into users (email, name) values (:e, :n)").cardinality, "none");
4598 assert_eq!(analysis("delete from users where id = :id returning id").cardinality, "at_most_one");
4599 assert_eq!(analysis("select id from users union all select user_id from posts").cardinality, "many");
4600 }
4601
4602 fn analyzed(sql: &str) -> Analysis {
4604 let ddl = [
4605 "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)",
4606 ];
4607 let rows = ddl.iter().map(|d| vec![serde_json::Value::String(d.to_string())]).collect();
4608 let answers = HashMap::from([(format!("query:{DDL_QUERY}|[]"), crate::api::Answer::Rows { rows }), (format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]))]);
4609 let host = Host::new(&answers);
4610 analyze(sql, &lex::lex(sql, Dialect::Sqlite).unwrap(), &host, &[]).expect("the schema and the functions were answered")
4611 }
4612
4613 fn listed(extra: &[(&str, i32, char)]) -> Vec<Vec<serde_json::Value>> {
4616 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')];
4617 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')];
4618 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()
4619 }
4620
4621 fn functions_answer(extra: &[(&str, i32, char)]) -> crate::api::Answer {
4622 crate::api::Answer::Rows { rows: listed(extra) }
4623 }
4624
4625 fn on_host(sql: &str, schema: &[String], extra: &[(&str, i32, char)], total: Vec<TotalFunction>) -> Analysis {
4627 analyze_ddl(sql, schema, &Extras { total, host: host_functions(&listed(extra)) }).analysis
4628 }
4629
4630 #[test]
4631 fn names_fold_ascii_case_as_sqlite_folds_them() {
4632 let schema: Vec<String> = [
4633 "create table Books (id integer primary key, Title text not null, ISBN text unique, note text)",
4634 "create table \"\u{c9}t\u{e9}\" (id integer primary key, v text)",
4635 "create table wr (K text primary key, v text) without rowid",
4636 "create table rt (RowId integer, v text)",
4637 "create table \"my table\" (id integer primary key, v text)",
4638 "create trigger \"skip one\" before insert on \"BOOKS\" begin select raise(ignore) where new.title = 'x'; end",
4639 "create trigger skip_two before insert on \"my table\" begin select raise(ignore) where new.v = 'x'; end",
4640 "create trigger [later] after update of \"on\", v on main . [my table] begin select 1; end",
4641 ]
4642 .iter()
4643 .map(|s| s.to_string())
4644 .collect();
4645 let a = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
4646 for sql in [
4649 "select * from books where id = :id",
4650 "select * from BOOKS where ID = :id",
4651 "select * from \"books\" where \"ID\" = :id",
4652 "select * from [BOOKS] b where B.Id = :id",
4653 "select b.* from main.bOOKS b join Books c on c.ID = b.id where C.id = :id",
4654 "select title from books where isbn = :i",
4655 "update BOOKS set TITLE = :t where ID = :id returning Title",
4656 "delete from books where Isbn = :i returning id",
4657 "select v from WR where k = :k",
4658 "select v from Rt where _ROWID_ = :r",
4659 ] {
4660 let got = a(sql);
4661 assert!(got.diagnostics.is_empty(), "{sql}: {:?}", got.diagnostics);
4662 assert_eq!(got.cardinality, "at_most_one", "{sql}: {:?}", got.cardinality_reason);
4663 }
4664 assert_eq!(a("select v from RT where ROWID = :r").cardinality, "many");
4667 assert_eq!(a("select v from wr where rowid = 1").diagnostics[0].message, "no such column: rowid");
4668 let insert = a("insert into BOOKS (TITLE, NOTE) values (:t, :n)");
4670 assert_eq!((param(&insert, "t"), param(&insert, "n")), ("text".into(), "text".into()));
4671 assert_eq!(insert.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [false, true]);
4672 assert_eq!(col(&a("select TITLE, Note from books"), "Title"), ("text".into(), false));
4673 assert_eq!(param(&a("insert into books (ROWID, title) values (:r, :t)"), "r"), "integer");
4675 assert_eq!(param(&a("insert into rt (_rowid_, v) values (:r, :v)"), "r"), "unknown");
4676 assert_eq!(a("select v from \"\u{c9}t\u{e9}\" where id = :id").cardinality, "at_most_one");
4678 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}");
4679 assert_eq!(param(&a("select value from JSON_EACH(:ids)"), "ids"), "text");
4681 assert_eq!(a("insert into books (title) values (:t) returning id").cardinality, "at_most_one");
4684 assert_eq!(a("insert into \"My Table\" (v) values (:v) returning id").cardinality, "at_most_one");
4685 assert_eq!(trigger_header(&schema[5]), Some(("before".into(), "insert".into(), "books".into())));
4686 assert_eq!(trigger_header(&schema[7]), Some(("after".into(), "update".into(), "my table".into())));
4687 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())));
4688 assert_eq!(trigger_header("create table trigger_log (\"on\" text)"), None);
4689 }
4690
4691 #[test]
4692 fn every_row_of_a_values_list_types_its_parameters() {
4693 let a = analysis("insert into users (id, name, email) values (:a, :b, :e), (:c, :d, :e2), (:f, upper(:g), 'x') returning id");
4694 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4695 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();
4696 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)];
4697 assert_eq!(got, want.map(|(n, t, null)| (n.to_string(), t.to_string(), null)));
4698 assert_eq!((a.cardinality.as_str(), a.cardinality_reason.as_deref()), ("many", Some("a VALUES list of 3 rows returns 3 rows")));
4699 let a = analysis("insert into users (name, email) values ('a', :x), (:w, 'b'), ('c', lower(:y))");
4702 assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true, false, false]);
4703 assert_eq!(a.cardinality, "none");
4704 let a = analysis("insert into users (name, email) values ('a', :x), (:x, 'b')");
4705 assert_eq!(a.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [3]);
4706 let a = analysis("with w as (select 1) insert into posts values (:id, :u, :t, :b), (:id2, :u2, :t2, :b2)");
4708 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));
4709 let rows: Vec<String> = (0..3000).map(|i| format!("(:n{i}, :e{i}, {i})")).collect();
4711 let a = analysis(&format!("insert into users (name, email, score) values {}", rows.join(", ")));
4712 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4713 assert_eq!((a.params.len(), param(&a, "n2999"), param(&a, "e2999")), (6000, "text".into(), "text".into()));
4714 let a = analysis("values (1, 'a', :p), (2, null, 3), (:q, 'c', 4.5)");
4717 assert_eq!((col(&a, "column1"), col(&a, "column2")), (("integer".into(), false), ("text".into(), true)));
4718 assert_eq!((param(&a, "p"), param(&a, "q"), a.cardinality.as_str()), ("real".into(), "integer".into(), "many"));
4719 assert_eq!(analysis("values (1, 'a')").cardinality, "one");
4720 assert_eq!(col(&analysis("values (1), ('a')"), "column1").0, "unknown");
4721 assert_eq!(analysis("select v.column1 from (values (1), (2)) v").cardinality, "many");
4722 assert_eq!(analysis("select 1 union all values (2), (3)").cardinality, "many");
4723 assert_eq!(col(&analysis("select (values (1), (2)) as x"), "x"), ("integer".into(), true));
4724 }
4725
4726 #[test]
4727 fn the_select_that_feeds_an_insert_types_its_parameters() {
4728 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()];
4729 let a = |sql: &str| {
4730 let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
4731 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4732 a
4733 };
4734 let params = |a: &Analysis| a.params.iter().map(|p| (affinity_of(&p.ty).unwrap_or("unknown").to_string(), p.nullable)).collect::<Vec<_>>();
4735 let typed = |types: &[&str]| types.iter().map(|t| (t.to_string(), false)).collect::<Vec<_>>();
4736 let got = a("insert into foo (name, meta) select name, ? from bar where ready = ?");
4740 assert_eq!((got.kind.map_or("", StatementKind::as_str), got.cardinality.as_str()), ("insert", "none"));
4741 assert_eq!(params(&got), [("text".to_string(), true), ("numeric".to_string(), false)]);
4742 assert_eq!(params(&a("select name from bar where ready = ?")), typed(&["numeric"]));
4743 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)]);
4746 assert_eq!(params(&a("insert into foo (k, name) select n + :d, upper(:u) from bar limit :l")), typed(&["integer", "text", "integer"]));
4747 assert_eq!(params(&a("insert into foo (name, k) select name, :a from bar union all select :b, n from bar")), typed(&["integer", "text"]));
4748 let returning = a("insert into foo (name, meta) select name, :m from bar where n > :n returning name, meta");
4749 assert_eq!((params(&returning), returning.cardinality.as_str()), (vec![("text".to_string(), true), ("integer".to_string(), false)], "many"));
4750 assert_eq!(params(&a("insert into foo (name, meta) select name, 'x' from bar returning (select :p) as p")), typed(&["unknown"]));
4755 assert_eq!(params(&a("insert into foo (name, k) values ('a', (select :p))")), typed(&["integer"]));
4756 let copy = a("insert into foo2 select * from foo");
4758 assert_eq!((copy.kind.map_or("", StatementKind::as_str), copy.cardinality.as_str()), ("insert", "none"));
4759 }
4760
4761 #[test]
4762 fn the_hosts_sqlite_decides_which_functions_exist() {
4763 let sql = "select id, ACOS(score) as a from users where name = :n";
4765 let a = on_host(sql, &ddl(), &[], Vec::new());
4766 assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
4767 assert_eq!(a.diagnostics[0].message, "no such function: ACOS on this database's SQLite");
4768 assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length, a.diagnostics[0].code), (sql.find("ACOS").unwrap(), 4, 6));
4769 assert!(a.columns.is_empty());
4770 let a = on_host(sql, &ddl(), &[("acos", 1, 's')], Vec::new());
4771 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4772 assert_eq!(col(&a, "a"), ("real".into(), true));
4773 let a = on_host("select soundex(name) as s from users where soundex(:x) = 'A000'", &ddl(), &[("SOUNDEX", 1, 's')], Vec::new());
4774 assert_eq!((col(&a, "s"), param(&a, "x")), (("text".into(), false), "text".into()));
4775 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");
4776 assert_eq!(col(&analysis("select acos(score) as a, soundex(name) as s from users"), "a"), ("real".into(), true));
4778 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());
4780 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4781 for sql in [
4783 "select row_number() over (order by sqrt(score)) as r from users",
4784 "select id from users where id in (select id from users where sqrt(score) > 1)",
4785 "with w as (select sqrt(score) as s from users) select s from w",
4786 "select id from users order by sqrt(score)",
4787 "update users set score = sqrt(score) where id = :id",
4788 "insert into users (name, score) values (:n, sqrt(:s))",
4789 "delete from users where id = :id returning sqrt(score) as s",
4790 ] {
4791 let a = on_host(sql, &ddl(), &[], Vec::new());
4792 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}");
4793 }
4794 let mut schema = ddl();
4797 schema.push("create view roots as select id, sqrt(score) as root from users".into());
4798 let sql = "select root from roots";
4799 let a = on_host(sql, &schema, &[], Vec::new());
4800 assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
4801 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()));
4802 assert_eq!(col(&on_host(sql, &schema, &[("sqrt", 1, 's')], Vec::new()), "root"), ("real".into(), true));
4803 assert!(on_host("select id from users", &schema, &[], Vec::new()).diagnostics.is_empty());
4804 let extra = [("host_only", 2, 's'), ("host_only", 3, 's'), ("host_agg", 1, 'a'), ("host_win", -1, 'w')];
4807 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());
4808 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4809 assert_eq!((col(&a, "two"), col(&a, "three"), a.cardinality.as_str()), (("unknown".into(), true), ("unknown".into(), true), "at_most_one"));
4810 assert_eq!(on_host("select name from users where id = host_only(1, 2)", &ddl(), &extra, Vec::new()).cardinality, "many");
4812 let a = on_host("select host_agg(score) as total from users", &ddl(), &extra, Vec::new());
4813 assert_eq!((col(&a, "total"), a.cardinality.as_str()), (("unknown".into(), true), "one"));
4814 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());
4815 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4816 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()");
4817 let html = vec![TotalFunction { name: "reylo_html".into(), arity: 1, returns: Affinity::Text }];
4819 assert_eq!(col(&on_host("select reylo_html(name) as h from users", &ddl(), &[], html), "h"), ("text".into(), false));
4820 assert_eq!(host_functions(&[]), None);
4822 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' }]));
4823 }
4824
4825 #[test]
4826 fn the_replay_asks_the_host_for_its_functions_with_the_schema() {
4827 let sql = "select acos(score) as a from users";
4828 let lexed = lex::lex(sql, Dialect::Sqlite).unwrap();
4829 let schema = crate::api::Answer::Rows { rows: ddl().iter().map(|d| vec![serde_json::Value::String(d.clone())]).collect() };
4830 let ask = |answers: &HashMap<String, crate::api::Answer>| {
4831 let host = Host::new(answers);
4832 let analysis = analyze(sql, &lexed, &host, &[]);
4833 let needs: Vec<String> = host
4834 .needs()
4835 .iter()
4836 .map(|n| match n {
4837 crate::api::Need::Query { sql, scope, .. } => format!("{sql} {scope:?}"),
4838 crate::api::Need::Describe { sql, .. } => format!("describe {sql}"),
4839 })
4840 .collect();
4841 (analysis, needs)
4842 };
4843 let mut answers = HashMap::new();
4845 let (analysis, needs) = ask(&answers);
4846 assert!(analysis.is_none());
4847 assert_eq!(needs, [format!("{DDL_QUERY} Session"), format!("{FUNCTIONS_QUERY} Session")]);
4848 answers.insert(format!("query:{DDL_QUERY}|[]"), schema);
4849 assert_eq!(ask(&answers).1, [format!("{FUNCTIONS_QUERY} Session")]);
4850 answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]));
4852 let (analysis, needs) = ask(&answers);
4853 assert!(needs.is_empty());
4854 assert_eq!(analysis.unwrap().diagnostics[0].message, "no such function: acos on this database's SQLite");
4855 answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[("acos", 1, 's')]));
4856 assert!(ask(&answers).0.unwrap().diagnostics.is_empty());
4857 answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), crate::api::Answer::Error { error: crate::api::DbError { message: "not authorized".into(), code: None, position: None } });
4859 assert_eq!(col(&ask(&answers).0.unwrap(), "a"), ("real".into(), true));
4860 answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), crate::api::Answer::Rows { rows: Vec::new() });
4861 assert_eq!(col(&ask(&answers).0.unwrap(), "a"), ("real".into(), true));
4862 }
4863
4864 #[test]
4865 fn a_table_in_an_attached_database_is_named_as_one() {
4866 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");
4867 for (sql, reference) in [
4868 ("select id, name from baz.users where id = :id", "baz.users"),
4869 ("select u.id from \"baz\".[users] u", "\"baz\".[users]"),
4870 ("select 1 from users join /* x */ baz . users b on b.id = users.id", "baz . users"),
4871 ("insert into baz.users (id) values (:id)", "baz.users"),
4872 ("update baz.users set name = :n where id = :id", "baz.users"),
4873 ("delete from baz.users where id = :id", "baz.users"),
4874 ] {
4875 let a = analysis(sql);
4876 assert_eq!(a.diagnostics.len(), 1, "{sql}: {:?}", a.diagnostics);
4877 assert_eq!(a.diagnostics[0].message, message("baz"), "{sql}");
4878 assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length), (sql.find(reference).unwrap(), reference.len()), "{sql}");
4879 }
4880 let sql = "select :auth.user_id as u, id from baz.users";
4882 assert_eq!(analysis(sql).diagnostics[0].start, sql.find("baz").unwrap());
4883 assert_eq!(analysis("select id from main.nope").diagnostics[0].message, "no such table: main.nope");
4885 assert_eq!(analysis("select id from temp.nope").diagnostics[0].message, "no such table: temp.nope");
4886 assert_eq!(analysis("select id from \"baz.users\"").diagnostics[0].message, "no such table: baz.users");
4887 assert_eq!(analysis("select id from nope").diagnostics[0].message, "no such table: nope");
4888 assert!(analysis("select main.users.id from main.users").diagnostics.is_empty());
4889 }
4890
4891 #[test]
4892 fn sqlites_own_tables_replay_without_a_note() {
4893 let schema: Vec<String> = [
4896 "CREATE TABLE t (id integer primary key autoincrement, v text)",
4897 "CREATE TABLE sqlite_sequence(name,seq)",
4898 "CREATE TABLE sqlite_stat1(tbl,idx,stat)",
4899 "CREATE VIRTUAL TABLE ft USING fts5(body)",
4900 "CREATE TABLE 'ft_data'(id INTEGER PRIMARY KEY, block BLOB)",
4901 "CREATE TABLE 'ft_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID",
4902 "CREATE TABLE 'ft_content'(id INTEGER PRIMARY KEY, c0)",
4903 "CREATE TABLE 'ft_docsize'(id INTEGER PRIMARY KEY, sz BLOB)",
4904 "CREATE TABLE 'ft_config'(k PRIMARY KEY, v) WITHOUT ROWID",
4905 "CREATE VIRTUAL TABLE rt USING rtree(id, minx, maxx)",
4906 "CREATE TABLE \"rt_rowid\"(rowid INTEGER PRIMARY KEY,nodeno)",
4907 "CREATE TABLE \"rt_node\"(nodeno INTEGER PRIMARY KEY,data)",
4908 "CREATE TABLE \"rt_parent\"(nodeno INTEGER PRIMARY KEY,parentnode)",
4909 "CREATE VIRTUAL TABLE f4 USING fts4(body)",
4910 "CREATE TABLE 'f4_content'(docid INTEGER PRIMARY KEY, 'c0body')",
4911 "CREATE TABLE 'f4_segments'(blockid INTEGER PRIMARY KEY, block BLOB)",
4912 "CREATE TABLE 'f4_segdir'(level INTEGER,idx INTEGER,start_block INTEGER,leaves_end_block INTEGER,end_block INTEGER,root BLOB,PRIMARY KEY(level, idx))",
4913 "CREATE TABLE 'f4_docsize'(docid INTEGER PRIMARY KEY, size BLOB)",
4914 "CREATE TABLE 'f4_stat'(id INTEGER PRIMARY KEY, value BLOB)",
4915 ]
4916 .iter()
4917 .map(|s| s.to_string())
4918 .collect();
4919 let a = |sql: &str, schema: &[String]| analyze_ddl(sql, schema, &Extras::default()).analysis;
4920 let failed = a("select nope from t", &schema);
4922 assert_eq!(failed.diagnostics.iter().map(|d| d.message.as_str()).collect::<Vec<_>>(), ["no such column: nope"]);
4923 for sql in [
4924 "select name, seq from sqlite_sequence where name = :n",
4925 "update sqlite_sequence set seq = :s where name = :n",
4926 "select tbl, idx, stat from sqlite_stat1",
4927 "select name, sql from sqlite_schema where type = 'table'",
4928 "select name from sqlite_master",
4929 "select rowid, body from ft where ft match :q",
4930 "select id from rt where minx > :x",
4931 "select docid from f4 where f4 match :q",
4932 "select block from ft_data where id = :id",
4933 "insert into t (v) values (:v) returning id",
4934 ] {
4935 let got = a(sql, &schema);
4936 assert!(got.diagnostics.is_empty(), "{sql}: {:?}", got.diagnostics);
4937 }
4938 assert_eq!(a("insert into t (v) values (:v) returning id", &schema).cardinality, "one");
4939 assert_eq!(a("delete from sqlite_schema", &schema).diagnostics[0].message, "table sqlite_master may not be modified");
4941 let later = vec!["CREATE TABLE sqlite_sequence(name,seq)".to_string(), "CREATE TABLE u (id integer primary key autoincrement, v text)".to_string()];
4943 assert!(a("select seq from sqlite_sequence", &later).diagnostics.is_empty());
4944 assert_eq!(a("insert into u (v) values (:v) returning id", &later).cardinality, "one");
4945 assert_eq!(a("select nope from u", &later).diagnostics.len(), 1);
4946 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()];
4948 let notes: Vec<String> = a("select nope from t", &broken).diagnostics.iter().map(|d| d.message.clone()).collect();
4949 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"]);
4950 }
4951
4952 #[test]
4953 fn a_double_quoted_word_that_names_no_column_is_refused_as_the_drivers_refuse_it() {
4954 let schema = vec!["create table t (id integer primary key, v text default \"none\" check (v <> \"bad\"))".to_string()];
4956 let a = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
4957 for sql in ["select \"hello\"", "select \"hello\" from t", "select id from t where v = \"x\""] {
4958 let messages: Vec<String> = a(sql).diagnostics.iter().map(|d| d.message.clone()).collect();
4959 assert_eq!(messages, [format!("no such column: \"{}\" - should this be a string literal in single-quotes?", if sql.contains("hello") { "hello" } else { "x" })], "{sql}");
4960 }
4961 for sql in ["select \"id\", \"v\" from t", "select 'hello'", "insert into t (id) values (1) returning v"] {
4962 assert!(a(sql).diagnostics.is_empty(), "{sql}: {:?}", a(sql).diagnostics);
4963 }
4964 }
4965
4966 #[test]
4967 fn the_version_reported_is_the_embedded_sqlites() {
4968 assert!(tree::version().starts_with("3.53."), "{}", tree::version());
4970 }
4971
4972 #[test]
4973 fn a_parameter_sqlite_reads_and_the_lexer_does_not_is_an_error_at_its_place() {
4974 let unbound = |sql: &str| analysis(sql).diagnostics.iter().filter(|d| d.code == 1).map(|d| (d.start, d.length, d.message.clone())).collect::<Vec<_>>();
4975 for written in [":été", ":1st", "@2x"] {
4978 let sql = format!("select id from users where name = :n and email = {written}");
4979 let found = unbound(&sql);
4980 assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(sql.find(written).unwrap(), written.len())], "{sql}");
4981 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"));
4982 }
4983 let sql = "select ':été' from users where name = :été";
4985 assert_eq!(unbound(sql).iter().map(|(s, _, _)| *s).collect::<Vec<_>>(), [sql.rfind(":été").unwrap()]);
4986 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)"] {
4989 assert!(unbound(sql).is_empty(), "{sql}");
4990 }
4991 assert_eq!(analysis("select id as [it's], :n as n from users").params.len(), 1);
4992 }
4993
4994 #[test]
4995 fn a_parameter_as_a_whole_sort_or_group_key_is_an_error_at_its_place() {
4996 let full = |sql: &str| {
4998 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)"];
4999 let rows = ddl.iter().map(|d| vec![serde_json::Value::String(d.to_string())]).collect();
5000 let answers = HashMap::from([(format!("query:{DDL_QUERY}|[]"), crate::api::Answer::Rows { rows }), (format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]))]);
5001 let host = Host::new(&answers);
5002 <crate::api::Sqlite as reylo_engine_core::database::Database>::analyze(sql, &host).expect("answered")
5003 };
5004 let keys = |sql: &str| full(sql).diagnostics.iter().filter(|d| d.code == 17).map(|d| (d.start, d.length, d.message.clone())).collect::<Vec<_>>();
5005 let at = |sql: &str, written: &str| sql.find(written).unwrap();
5006 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)] {
5008 let found = keys(sql);
5009 assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(at(sql, ":sort"), length)], "{sql}");
5010 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");
5011 }
5012 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")] {
5013 let found = keys(sql);
5014 assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(at(sql, written), written.len())], "{sql}");
5015 assert!(found[0].2.starts_with(&format!("order by {written} sorts every row")), "{sql}");
5016 }
5017 assert_eq!(keys("select id from users order by ?2, ?1").iter().map(|(s, ..)| *s).collect::<Vec<_>>(), [30, 34]);
5018 assert_eq!(keys("select id from users order by name, ?").len(), 1);
5019 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");
5021 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"));
5022 let sql = "select row_number() over (partition by :p order by :o) as n from users";
5024 let found = keys(sql);
5025 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())]);
5026 assert_eq!(keys("select row_number() over w as n from users window w as (order by :o)").len(), 1);
5027 assert_eq!(keys("select group_concat(name, ',' order by :o) as names from users").len(), 1);
5028 assert_eq!(keys("select id from (select id from users order by :s limit 3) t").len(), 1);
5031 assert_eq!(keys("with t as (select name from users group by :g, name) select a.name from t a, t b").len(), 1);
5032 assert_eq!(keys("select id from users where id in (select id from users order by :s limit 3)").len(), 1);
5033 let refused = full("select id from users union select id from users order by :s");
5035 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")]);
5036 assert_eq!(keys("insert into users (name) select name from users order by :s").len(), 1);
5037 for sql in [
5041 "select id, :tag as tag from users order by 2",
5042 "select id, :tag as tag from users order by tag",
5043 "select :tenant as tenant, name, count(*) as n from users group by 1, 2",
5044 "select id, name from users order by case :sort when 'name' then name end",
5045 "select id from users order by case when :desc then id end desc, id",
5046 "select id from users order by 1 limit :n",
5047 "select id from users order by lower(:x) || name",
5048 ] {
5049 assert_eq!(keys(sql), [], "{sql}");
5050 }
5051 let a = full("select id from users order by :sort::text");
5053 assert_eq!(a.columns.len(), 1);
5054 assert_eq!(affinity_of(&a.params[0].ty), Some("text"));
5055 }
5056
5057 #[test]
5058 fn names_a_column_as_the_statement_is_sent() {
5059 let names = |sql: &str| analysis(sql).columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>();
5061 assert_eq!(names("select id + cast(:a as integer), name from users"), ["id + cast(? as integer)", "name"]);
5062 assert_eq!(names("select * from (select id + cast(:a as integer) from users)"), ["id + cast(? as integer)"]);
5063 assert_eq!(names("update users set name = name returning id + cast(:a as integer)"), ["id + cast(? as integer)"]);
5064 assert_eq!(names("select cast(:a as integer) as a"), ["a"]);
5065 }
5066
5067 #[test]
5068 fn prepares_the_numbered_rewrite() {
5069 let a = analyzed("select name from users where email = :auth.email and id = :auth.id and score > :auth.email");
5071 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5072 assert_eq!(param(&a, "auth.email"), "text");
5073 assert_eq!(param(&a, "auth.id"), "integer");
5074 assert_eq!(a.rewritten.sql, "select name from users where email = ? and id = ? and score > ?");
5075 assert_eq!(a.rewritten.order, ["auth.email", "auth.id", "auth.email"]);
5076 assert_eq!(param(&analyzed("select name from users where id = ?3"), "3"), "integer");
5078 assert_eq!(param(&analyzed("select name from users where email = ?"), "1"), "text");
5079 let sql = "select :auth.user_id, nope from users";
5081 let a = analyzed(sql);
5082 assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
5083 assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length), (sql.find("nope").unwrap(), 4));
5084 }
5085
5086 #[test]
5087 fn a_column_declared_without_a_type_holds_any_value() {
5088 let ddl = vec!["CREATE TABLE t (a, b TEXT, c ANY)".to_string(), "CREATE TABLE s (x ANY, y INTEGER) STRICT".to_string()];
5089 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());
5090 let a = &r.analysis;
5091 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5092 assert_eq!(col(a, "a"), ("unknown".into(), false));
5094 assert_eq!(col(a, "b"), ("text".into(), true));
5095 assert_eq!(col(a, "x"), ("unknown".into(), false));
5096 assert_eq!(col(a, "y"), ("integer".into(), true));
5097 assert_eq!((param(a, "a"), param(a, "x")), ("unknown".into(), "unknown".into()));
5098 let r = analyze_ddl("SELECT c FROM t", &ddl, &Extras::default());
5100 assert_eq!(col(&r.analysis, "c"), ("numeric".into(), true));
5101 }
5102
5103 #[test]
5104 fn the_direct_entry_reads_a_schema_it_is_handed() {
5105 let ddl = vec![
5106 "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(),
5107 "CREATE INDEX todos_org ON todos (org_id)".to_string(),
5108 ];
5109 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";
5110 let r = analyze_ddl(sql, &ddl, &Extras::default());
5111 let a = &r.analysis;
5112 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5113 assert_eq!(a.kind, Some(StatementKind::Select));
5114 assert!(r.readonly);
5115 assert_eq!(col(a, "id"), ("numeric".into(), false));
5116 assert_eq!(col(a, "title"), ("text".into(), false));
5117 assert_eq!(col(a, "org_id"), ("numeric".into(), true));
5118 assert_eq!(col(a, "n"), ("integer".into(), false));
5119 assert_eq!(r.declared, [Some("uuid".to_string()), Some("varchar(200)".into()), Some("uuid".into()), Some("boolean".into()), None]);
5120 assert_eq!(param(a, "auth.user_id"), "text");
5121 assert_eq!(param(a, "title"), "text");
5122 assert_eq!(a.cardinality, "at_most_one");
5123 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 = ?");
5124 let r = analyze_ddl("INSERT INTO todos (id, owner_id, title) VALUES (:id, :owner, :title) RETURNING id, done", &ddl, &Extras::default());
5126 assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
5127 assert!(!r.readonly);
5128 assert_eq!((r.analysis.kind.map_or("", StatementKind::as_str), r.analysis.cardinality.as_str()), ("insert", "one"));
5129 assert_eq!(col(&r.analysis, "done"), ("bool".into(), false));
5132 assert_eq!(r.unique_keys.len(), 1, "{:?}", r.unique_keys);
5134 let mut keys = r.unique_keys["todos"].clone();
5135 keys.sort();
5136 assert_eq!(keys, [vec!["id".to_string()], vec!["owner_id".into(), "title".into()], vec!["rowid".into()]]);
5137 let r = analyze_ddl("SELECT id FROM todos WHERE id = :a AND title = ?", &ddl, &Extras::default());
5139 assert_eq!(r.analysis.diagnostics.len(), 1, "{:?}", r.analysis.diagnostics);
5140 assert!(r.declared.is_empty() && !r.readonly);
5141 }
5142
5143 #[test]
5144 fn the_unique_keys_of_every_table_read() {
5145 let mut schema = ddl();
5146 schema.push("create unique index users_lower_name on users (lower(name))".into());
5147 schema.push("create unique index posts_title on posts (title) where body is not null".into());
5148 schema.push("create table tags (label text not null, post_id integer not null, primary key (post_id, label)) without rowid".into());
5149 schema.push("create view titled as select p.id, p.title from posts p".into());
5150 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());
5151 assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
5152 let mut tables: Vec<&String> = r.unique_keys.keys().collect();
5153 tables.sort();
5154 assert_eq!(tables, ["posts", "tags", "users"]);
5156 assert_eq!(r.unique_keys["users"], [vec!["id".to_string()], vec!["email".into()]]);
5158 assert_eq!(r.unique_keys["posts"], [vec!["id".to_string()]]);
5160 assert_eq!(r.unique_keys["tags"], [vec!["post_id".to_string(), "label".into()]]);
5162 assert!(analyze_ddl("select nope from users", &schema, &Extras::default()).unique_keys.is_empty());
5164 }
5165
5166 fn html() -> Extras {
5167 Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: 1, returns: Affinity::Text }], host: None }
5168 }
5169
5170 #[test]
5171 fn a_host_function_prepares_and_is_typed_from_its_argument() {
5172 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());
5173 let a = &r.analysis;
5174 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5175 assert_eq!(col(a, "h"), ("text".into(), false));
5176 assert_eq!(col(a, "e"), ("text".into(), true));
5177 assert_eq!(col(a, "q"), ("text".into(), false));
5179 assert_eq!(r.declared, [None, None, None]);
5180 let sql = "select id, reylo_html(name) as h from users";
5183 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()")] {
5184 let a = analyze_ddl(sql, &ddl(), &extras).analysis;
5185 assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
5186 assert_eq!(a.diagnostics[0].message, message);
5187 assert_eq!((a.diagnostics[0].start, a.diagnostics[0].code), (sql.find("reylo_html").unwrap(), 6));
5188 assert!(a.columns.is_empty());
5189 }
5190 let any = Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: -1, returns: Affinity::Text }], host: None };
5192 let mut schema = ddl();
5193 schema.push("create view safe_users as select id, reylo_html(name) as name from users".into());
5194 let a = analyze_ddl("select name, reylo_html(name, name) as twice from safe_users", &schema, &any).analysis;
5195 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5196 assert_eq!(col(&a, "name"), ("text".into(), false));
5197 assert_eq!(col(&a, "twice"), ("text".into(), false));
5198 }
5199
5200 #[test]
5201 fn a_scalar_subquery_is_non_null_only_when_it_always_finds_one_row() {
5202 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");
5203 assert_eq!(col(&a, "n"), ("integer".into(), false));
5204 assert_eq!(col(&a, "top"), ("text".into(), true));
5205 assert_eq!(col(&a, "one"), ("text".into(), true));
5206 assert_eq!(col(&a, "g"), ("integer".into(), true));
5207 assert_eq!(col(&a, "k"), ("integer".into(), false));
5208 }
5209
5210 #[test]
5211 fn truth_values_are_marked_and_typed_boolean() {
5212 let r = analyze_ddl(
5213 "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",
5214 &ddl(),
5215 &Extras::default(),
5216 );
5217 assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
5218 assert_eq!(r.booleans, [true, true, true, true, true, true, true, false, false, true, false]);
5219 assert_eq!(col(&r.analysis, "a"), ("bool".into(), false));
5221 assert_eq!(col(&r.analysis, "b"), ("bool".into(), false));
5222 assert_eq!(col(&r.analysis, "h"), ("integer".into(), false));
5223 let r = analyze_ddl("select t.x, t.y from (select id > 1 as x, id as y from users) t", &ddl(), &Extras::default());
5225 assert_eq!(r.booleans, [true, false]);
5226 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());
5227 assert_eq!(r.booleans, [false]);
5228 let r = analyze_ddl("select id > 1 as x from users union all select email is null from users", &ddl(), &Extras::default());
5229 assert_eq!(r.booleans, [true]);
5230 let r = analyze_ddl("insert into users (name) values ('a') returning id, id > 0 as positive", &ddl(), &Extras::default());
5232 assert_eq!(r.booleans, [false, true]);
5233 assert!(analyze_ddl("select nope from users", &ddl(), &Extras::default()).booleans.is_empty());
5234 }
5235
5236 #[test]
5237 fn a_column_declared_boolean_is_typed_boolean_and_no_truth_value() {
5238 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()];
5239 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());
5240 assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
5241 let types: Vec<String> = r.analysis.columns.iter().map(|c| affinity_of(&c.ty).unwrap_or("?").to_string()).collect();
5242 assert_eq!(types, ["bool", "bool", "integer", "integer", "real", "bool", "numeric", "bool", "bool", "bool"]);
5244 assert_eq!(r.booleans, [false; 10]);
5246 let r = analyze_ddl("select done from v", &ddl, &Extras::default());
5248 assert_eq!(col(&r.analysis, "done"), ("bool".into(), false));
5249 let r = analyze_ddl("select done from flags union all select 5", &ddl, &Extras::default());
5250 assert_ne!(affinity_of(&r.analysis.columns[0].ty), Some("bool"));
5251 let r = analyze_ddl("select done from flags union all select id > 1 from flags", &ddl, &Extras::default());
5252 assert_eq!(affinity_of(&r.analysis.columns[0].ty), Some("bool"));
5253 }
5254
5255 fn ts(t: &Type, in_json: bool) -> String {
5258 let null = |s: String, nullable: bool| if nullable { format!("{s} | null") } else { s };
5259 let list = |s: String| if s.contains('|') { format!("({s})[]") } else { format!("{s}[]") };
5260 match &t.kind {
5261 Kind::Json(crate::types::JsonType { content: Some(c), .. }) => ts(&c.ty, true),
5262 Kind::Struct(r) => {
5263 let fields: Vec<String> = r.fields.iter().map(|f| format!("{}: {}", f.name, null(ts(&f.ty, true), f.nullable))).collect();
5264 if fields.is_empty() { "Record<never, never>".into() } else { format!("{{ {} }}", fields.join("; ")) }
5265 }
5266 Kind::Array(a) => list(null(ts(&a.element.ty, true), a.element.nullable)),
5267 Kind::Json(crate::types::JsonType { schema: Some(_), .. }) => schema_ts(&t.schema().unwrap_or(serde_json::Value::Bool(true))),
5268 _ => match (affinity_of(t).unwrap_or("?"), in_json) {
5269 ("integer" | "real", _) | ("int8", true) => "number".into(),
5270 ("int8", false) => "bigint".into(),
5271 ("text", _) => "string".into(),
5272 ("numeric", _) => "number | string".into(),
5273 ("blob", false) => "Uint8Array".into(),
5274 ("bool", _) => "boolean".into(),
5275 _ => "unknown".into(),
5276 },
5277 }
5278 }
5279
5280 fn affinity_of(t: &Type) -> Option<&'static str> {
5282 let name = t.label.as_deref().unwrap_or("");
5283 match &t.kind {
5284 Kind::Enum(e) => affinity_of(&e.ty),
5286 Kind::Boolean(_) => Some("bool"),
5287 Kind::Integer(_) if name == "BIGINT" => Some("int8"),
5288 Kind::Integer(_) => Some("integer"),
5289 Kind::Float(_) => Some("real"),
5290 Kind::Text(_) => Some("text"),
5291 Kind::Bytes(_) => Some("blob"),
5292 Kind::Union(_) if is_boolean_declared(name) => Some("bool"),
5293 Kind::Union(u) if u.members.len() == 2 => Some("text"),
5294 Kind::Union(u) if u.members.len() == 3 => Some("real"),
5295 Kind::Union(_) if affinity(name) == "integer" && is_int8_declared(name) => Some("int8"),
5296 Kind::Union(_) => Some(affinity(name)),
5297 _ => None,
5298 }
5299 }
5300
5301 fn schema_ts(s: &serde_json::Value) -> String {
5302 if let Some(any) = s["anyOf"].as_array() {
5303 return any.iter().map(schema_ts).collect::<Vec<_>>().join(" | ");
5304 }
5305 let kinds: Vec<&str> = match &s["type"] {
5306 serde_json::Value::String(k) => vec![k.as_str()],
5307 serde_json::Value::Array(ks) => ks.iter().filter_map(|k| k.as_str()).collect(),
5308 _ => return "unknown".into(),
5309 };
5310 let one = |kind: &str| match kind {
5311 "integer" | "number" => "number".to_string(),
5312 "string" => "string".into(),
5313 "null" => "null".into(),
5314 "array" => match s["prefixItems"].as_array() {
5315 Some(items) => format!("[{}]", items.iter().map(schema_ts).collect::<Vec<_>>().join(", ")),
5316 None if s["items"] == false => "[]".into(),
5317 None => {
5318 let item = schema_ts(&s["items"]);
5319 if item.contains('|') { format!("({item})[]") } else { format!("{item}[]") }
5320 }
5321 },
5322 "object" => match s["properties"].as_object() {
5323 _ if s["additionalProperties"] == false && s["properties"].as_object().is_none_or(|p| p.is_empty()) => "Record<never, never>".into(),
5324 Some(p) if !p.is_empty() => format!("{{ {} }}", p.iter().map(|(k, v)| format!("{k}: {}", schema_ts(v))).collect::<Vec<_>>().join("; ")),
5325 _ => format!("{{ [key: string]: {} }}", schema_ts(&s["additionalProperties"])),
5326 },
5327 _ => "unknown".into(),
5328 };
5329 kinds.into_iter().map(one).collect::<Vec<_>>().join(" | ")
5330 }
5331
5332 fn shown(a: &Analysis) -> String {
5334 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5335 a.columns.iter().map(|c| format!("{}: {}{}", c.name, ts(&c.ty, false), if c.nullable { " | null" } else { "" })).collect::<Vec<_>>().join("; ")
5336 }
5337
5338 fn json_ddl() -> Vec<String> {
5339 vec![
5340 "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(),
5341 "create table posts (id integer primary key, user_id integer not null references users(id), title text not null, body text) strict".to_string(),
5342 "create view titled as select id, json_object('id', id, 'title', title) as post from posts".to_string(),
5343 ]
5344 }
5345
5346 fn json_typed(sql: &str) -> String {
5347 shown(&analyze_ddl(sql, &json_ddl(), &Extras::default()).analysis)
5348 }
5349
5350 #[test]
5351 fn json_whose_subtype_is_out_of_sight_is_any_json() {
5352 assert_eq!(
5355 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"),
5356 "doc: { ids: unknown }; top: [unknown]; counted: { n: number }; total: number"
5357 );
5358 assert_eq!(json_typed("select json_object('ids', json_group_array(id)) as doc from posts group by user_id"), "doc: { ids: number[] }");
5359 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");
5361 assert_eq!(json_typed("select json(json((select json_object('a', 1) where 0))) as v"), "v: { a: number } | null");
5363 assert_eq!(json_typed("select json_object('k', json(jsonb((select json_object('a', 1) where 0)))) as w"), "w: { k: { a: number } | null }");
5364 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()];
5368 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]");
5369 assert_eq!(shown(&analyze_ddl("select json_object('j', j) as v from (select j from d)", &schema, &Extras::default()).analysis), "v: { j: unknown }");
5370 }
5371
5372 #[test]
5373 fn a_number_beside_a_numeric_value_is_a_number_or_text() {
5374 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()];
5375 let typed = |sql: &str| col(&analyze_ddl(sql, &schema, &Extras::default()).analysis, "v");
5376 assert_eq!(typed("select ifnull(dt, 0) as v from dts"), ("numeric".into(), false));
5378 assert_eq!(typed("select case when ok then d else 0 end as v from dts"), ("numeric".into(), false));
5379 assert_eq!(typed("select coalesce(dt, 1.5) as v from dts"), ("numeric".into(), false));
5380 assert_eq!(typed("select coalesce(n, 1.5) as v from dts"), ("integer".into(), false));
5381 assert_eq!(typed("select iif(ok, n, x) as v from dts"), ("real".into(), false));
5382 }
5383
5384 #[test]
5385 fn a_window_call_is_no_value_every_row_shares() {
5386 let count = |sql: &str| analyze_ddl(sql, &ddl(), &Extras::default()).analysis.cardinality;
5387 assert_eq!(count("select distinct min(1) over (order by id rows between 1 preceding and 1 preceding) as m from users"), "many");
5388 assert_eq!(count("select distinct max(1) filter (where id > 2) over (order by id) as m from users"), "many");
5389 assert_eq!(count("select distinct 1 as m from users"), "at_most_one");
5390 }
5391
5392 #[test]
5393 fn a_date_conversion_newer_than_libsql_s_sqlite_is_nullable() {
5394 let typed = |sql: &str| col(&analyze_ddl(sql, &ddl(), &Extras::default()).analysis, "v");
5395 assert_eq!(typed("select strftime('%Y-%m-%d', 'now') as v"), ("text".into(), false));
5398 assert_eq!(typed("select strftime('%G-W%V', 'now') as v"), ("text".into(), true));
5399 assert_eq!(typed("select date('now', 'start of month', '+1 month', 'floor') as v"), ("text".into(), true));
5400 }
5401
5402 #[test]
5403 fn a_json_constructor_is_typed_as_the_json_it_builds() {
5404 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";
5407 assert_eq!(json_typed(profile), "profile: { user: { id: number; name: string }; posts: { id: number; title: string }[] }");
5408 let bare = profile.replace("json((select", "((select");
5410 assert_eq!(json_typed(&bare), "profile: { user: { id: number; name: string }; posts: unknown }");
5411 assert_eq!(json_typed("select (select json_group_array(id) from posts) as ids"), "ids: number[]");
5413 assert_eq!(json_typed("select json((select json_object('n', name) from users where id = 1)) as u"), "u: { n: string } | null");
5414 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 }");
5415 let a = analyze_ddl(profile, &json_ddl(), &Extras::default()).analysis;
5416 assert_eq!((a.columns[0].ty.kind.name(), a.cardinality.as_str()), ("json", "at_most_one"));
5417 assert_eq!(
5422 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"),
5423 "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 }"
5424 );
5425 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>]");
5428 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 }");
5429 assert_eq!(json_typed("select json_object('k', id, 'k', name) as o from users"), "o: { k: string }");
5431 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 }");
5433 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)[]");
5436 assert_eq!(
5437 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"),
5439 "f: { f: unknown }; w: { w: unknown }"
5440 );
5441 assert_eq!(
5442 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"),
5443 "id: number; titles: string[]; grouped: string[] | null"
5444 );
5445 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] }");
5448 assert_eq!(json_typed("select jsonb(json_array(1)) as b, (select jsonb_group_array(id) from users) as g"), "b: Uint8Array; g: Uint8Array");
5449 assert_eq!(json_typed("select post from titled"), "post: { id: number; title: string }");
5451 assert_eq!(json_typed("with t as (select json_array(id) as x from users) select x from t"), "x: [number]");
5452 assert_eq!(json_typed("select max(json_array(id)) as m from users"), "m: [number] | null");
5453 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 }");
5454 }
5455
5456 #[test]
5457 fn a_value_nests_as_json_only_where_it_keeps_sqlites_json_subtype() {
5458 for (expr, ty) in [
5460 ("coalesce(json_array(id), 'x')", "[number]"),
5461 ("ifnull(json_array(id), 'x')", "[number]"),
5462 ("nullif(json_array(id), 'x')", "[number] | null"),
5463 ("iif(id > 1, json_array(id), json_array(0))", "[number]"),
5464 ("case when id > 1 then json_object('x', id) end", "{ x: number } | null"),
5465 ("json_array(id) collate nocase", "[number]"),
5466 ("+json_array(id)", "[number]"),
5467 ("likely(json_array(id))", "[number]"),
5468 ("json((select json_object('n', name) from users u2 where u2.id = users.id))", "{ n: string } | null"),
5470 ("json((select json_group_array(p.id) from posts p where p.user_id = users.id order by p.id))", "number[]"),
5471 ("json((select json_array(1)))", "[number]"),
5472 ("json_array((select name from users u2 where u2.id = users.id))", "[string | null]"),
5474 ("json_group_array((select name from users u2 where u2.id = users.id))", "(string | null)[]"),
5475 ("coalesce(json((select json_group_array(p.id) from posts p where p.user_id = users.id)), '[]')", "number[]"),
5477 ("coalesce(json_object('e', email), json_array())", "{ e: string | null }"),
5478 ("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[]"),
5479 ("doc", "string | null"),
5481 ("json_array(id) || ''", "string"),
5482 ("upper(json_array(id))", "string"),
5483 ("length(json_array(id))", "number"),
5484 ("json_type(json_array(id))", "string"),
5485 ("json_array_length(json_array(id))", "number"),
5486 ] {
5487 assert_eq!(json_typed(&format!("select json_object('a', {expr}) as o from users")), format!("o: {{ a: {ty} }}"), "{expr}");
5488 }
5489 for expr in [
5492 "x",
5493 "post",
5494 "(select json_object('n', name) from users u2 where u2.id = users.id)",
5496 "(select json_array(1))",
5497 "(select json_object('id', id) from users order by name limit 1)",
5498 "(select distinct json_array(id) from users)",
5499 "(select json_array(1) union all select json_array(2))",
5500 "lag(json_array(id)) over (order by id)",
5501 "max(json_array(id), json_array(0))",
5502 "cast(json_array(id) as text)",
5503 "doc ->> '$.a'",
5504 "json_pretty(json_array(1))",
5505 "case when id > 1 then json_array(id) else 'x' end",
5506 "case when id > 1 then json_array(id) else json_object('a', 1) end",
5507 ] {
5508 let sql = format!("select json_object('a', {expr}) as o from (select *, json_array(id) as x from users) users, (select post from titled)");
5509 assert_eq!(json_typed(&sql), "o: { a: unknown }", "{expr}");
5510 }
5511 for expr in ["json(doc)", "json_extract(doc, '$.a')", "doc -> '$.a'", "json_set(doc, '$.a', 1)", "json_quote(name)"] {
5514 assert_eq!(json_typed(&format!("select json_object('a', {expr}) as o from users")), "o: { a: unknown | null }", "{expr}");
5515 }
5516 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()];
5517 for (expr, ty) in [
5518 ("json_object('k', json(doc))", "{ k: unknown | null }"),
5519 ("json_object('k', doc -> '$')", "{ k: unknown | null }"),
5520 ("json_object('k', json_extract(doc, '$'))", "{ k: unknown | null }"),
5521 ("json_object('k', json(b))", "{ k: unknown | null }"),
5522 ("json_group_array(json(doc))", "(unknown | null)[]"),
5523 ] {
5524 assert_eq!(shown(&analyze_ddl(&format!("select {expr} as o from js"), ¬_null, &Extras::default()).analysis), format!("o: {ty}"), "{expr}");
5525 }
5526 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 };
5528 let a = analyze_ddl("select json_array(1) as a, json_object('b', html(name)) as b from users", &json_ddl(), &host).analysis;
5529 assert_eq!(shown(&a), "a: string; b: { b: unknown }");
5530 }
5531
5532 #[test]
5533 fn a_deep_constructor_is_read_once_per_node() {
5534 let ddl = vec!["create table users (id integer primary key, name text not null)".to_string()];
5537 let deep = |open: &str, close: &str, n: usize| format!("select {}id{} as o from users", open.repeat(n), close.repeat(n));
5538 let started = std::time::Instant::now();
5539 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)] {
5540 let a = crate::stack::run(|| analyze_ddl(&sql, &ddl, &Extras::default()).analysis);
5541 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5542 }
5543 assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
5544 }
5545
5546 #[test]
5547 fn built_json_beside_other_text_is_the_text_it_is() {
5548 assert_eq!(
5550 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"),
5551 "a: [number]; b: string; c: string; d: [number] | null"
5552 );
5553 assert_eq!(json_typed("select json_array(id) as a from users union all select 'x'"), "a: string");
5554 assert_eq!(json_typed("select json_array(id) as a from users union all select null"), "a: [number] | null");
5555 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"]);
5558 assert_eq!(shown(&a), "d: string; o: { a: unknown }");
5559 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"]);
5560 }
5561
5562 #[test]
5563 fn a_json_object_of_an_odd_count_of_arguments_is_built_in_alone() {
5564 let sql = "select json_object('id', id, 'name') as j from users";
5565 let odd = |extras: &Extras| analyze_ddl(sql, &ddl(), extras).analysis.diagnostics.iter().filter(|d| d.code == 15).count();
5566 assert_eq!(odd(&Extras::default()), 1);
5567 let listed = |arities: &[i32]| Extras { total: vec![], host: Some(arities.iter().map(|&arity| HostFunction { name: "json_object".into(), arity, kind: 's' }).collect()) };
5568 assert_eq!(odd(&listed(&[-1])), 1);
5569 assert_eq!(odd(&listed(&[-1, 3])), 0);
5571 assert_eq!(odd(&Extras { total: vec![TotalFunction { name: "JSON_OBJECT".into(), arity: 3, returns: Affinity::Text }], host: None }), 0);
5572 }
5573
5574 #[test]
5575 fn a_modulo_by_a_fractional_literal_under_one_is_nullable() {
5576 let schema = vec!["create table items (id integer primary key, qty integer not null)".to_string()];
5579 let typed = |sql: &str| {
5580 let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
5581 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
5582 col(&a, "r")
5583 };
5584 assert_eq!(typed("select qty % 0.5 as r from items"), ("real".into(), true));
5585 assert_eq!(typed("select qty % 0.99 as r from items"), ("real".into(), true));
5586 assert_eq!(typed("select qty % 1e-3 as r from items"), ("real".into(), true));
5587 assert_eq!(typed("select qty % 2.5 as r from items"), ("real".into(), false));
5588 assert_eq!(typed("select qty % 2 as r from items"), ("integer".into(), false));
5589 assert_eq!(typed("select qty % 1e999 as r from items"), ("real".into(), false));
5591 assert_eq!(typed("select qty / 0.5 as r from items"), ("real".into(), false));
5592 assert_eq!(typed("select qty / 0 as r from items"), ("integer".into(), true));
5593 }
5594
5595 #[test]
5596 fn sqlite_only_syntax_parses() {
5597 let a = analysis("select id from users limit :n, :m");
5598 assert_eq!(param(&a, "n"), "integer");
5599 assert_eq!(analysis("insert or replace into users (id, name) values (:id, :name) returning id").cardinality, "one");
5600 }
5601
5602 #[test]
5603 fn an_insert_that_leaves_out_a_required_column_is_an_error() {
5604 let schema = |extra: &[&str]| -> Vec<String> {
5605 let mut s: Vec<String> = [
5606 "create table req (id integer primary key not null, name text not null, email text not null, note text)",
5607 "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'))",
5608 "create table keyed (k text not null, v text, primary key (k)) without rowid",
5609 "create table plain_key (k int primary key, v text)",
5610 "create table ign (id integer primary key, name text not null on conflict ignore)",
5611 "create table rep (id integer primary key, name text not null on conflict replace)",
5612 ]
5613 .iter()
5614 .map(|s| s.to_string())
5615 .collect();
5616 s.extend(extra.iter().map(|s| s.to_string()));
5617 s
5618 };
5619 let said = |sql: &str, extra: &[&str]| -> Vec<(String, String)> {
5620 let a = analyze_ddl(sql, &schema(extra), &Extras::default()).analysis;
5621 a.diagnostics.iter().filter(|d| d.code == 16).map(|d| (sql[d.start..d.start + d.length].to_string(), d.message.clone())).collect()
5622 };
5623 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.");
5624 assert_eq!(said("insert into req (id, name) values (:id, :name)", &[]), [("req".to_string(), one("email", "req"))]);
5625 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())]);
5626 assert_eq!(said("insert into req default values", &[]).len(), 1);
5627 assert_eq!(said("insert into \"req\" (name) select 'a'", &[]).first().map(|d| d.0.as_str()), Some("\"req\""));
5628 assert_eq!(said("insert into main.req (name) select 'a' union all select 'b'", &[]).first().map(|d| d.0.as_str()), Some("main.req"));
5629 assert_eq!(said("insert or replace into req (name) values ('a')", &[]).len(), 1);
5631 assert_eq!(said("replace into req (name) values ('a')", &[]).len(), 1);
5632 assert_eq!(said("insert into req (id, name) values (1, 'a') on conflict do nothing", &[]).len(), 1);
5633 assert_eq!(said("insert into rep (id) values (1)", &[]), [("rep".to_string(), one("name", "rep"))]);
5634 assert_eq!(said("insert into dflt (id) values (1)", &[]), [("dflt".to_string(), one("nulled", "dflt"))]);
5636 assert_eq!(said("insert into keyed (v) values ('a')", &[]), [("keyed".to_string(), one("k", "keyed"))]);
5637 for sql in [
5639 "insert into req (name, email) values (:name, :email)",
5640 "insert into req values (1, 'a', 'b', null)",
5641 "insert into req (NAME, Email) values ('a', 'b'), ('c', 'd')",
5642 "insert into req select * from req",
5643 "insert into dflt (nulled) values ('a')",
5644 "insert into plain_key (v) values ('a')",
5645 "insert or ignore into req (id) values (1)",
5647 "insert into ign (id) values (1)",
5648 "select 1",
5649 "update req set name = 'a'",
5650 ] {
5651 assert_eq!(said(sql, &[]), Vec::<(String, String)>::new(), "{sql}");
5652 }
5653 assert!(said("insert into req (id) values (1)", &["create trigger skip before insert on req begin select raise(ignore); end"]).is_empty());
5655 assert!(said("insert into req (id) values (1)", &["create trigger skip insert on REQ begin select 1; end"]).is_empty());
5656 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());
5657 assert_eq!(said("insert into req (id) values (1)", &["create trigger later after insert on req begin select 1; end"]).len(), 1);
5658 assert_eq!(said("insert into req (id) values (1)", &["create trigger other before update on req begin select 1; end"]).len(), 1);
5659 assert_eq!(said("insert into uniq (tag) values ('x')", &["create table uniq (required text not null, tag text unique on conflict ignore)"]).len(), 1);
5661 assert_eq!(said("insert into plain (rowid, tag) values (1, 'x')", &["create table plain (required text not null, tag text)"]).len(), 1);
5662 assert_eq!(said("insert into ign (id, name) values (1, :name)", &[]).len(), 0);
5663 assert_eq!(said("insert into /* audit */ req default values", &[]).first().map(|d| d.0.as_str()), Some("req"));
5665 assert_eq!(said("insert into main . req default values", &[]).first().map(|d| d.0.as_str()), Some("main . req"));
5666 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"));
5667 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());
5669 assert!(said("explain insert into req (id) values (1)", &[]).is_empty());
5670 assert!(said("explain query plan insert into req (id) values (1)", &[]).is_empty());
5671 }
5672}