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 let nullable_params: HashSet<String> = lexed.params.iter().enumerate().filter(|(_, name)| marked.contains(name)).map(|(k, _)| format!("?{}", k + 1)).collect();
302 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()) };
303 let a = Analyzer { nullable_values: a.bare_nullable().into_iter().chain(a.nullable_params.iter().cloned()).collect(), ..a };
304 if let lex::Statement::Command(kind) = statement {
308 let columns: Vec<Column> = t.columns.iter().map(|c| Column::new(c.name.clone(), Type::unknown(), true)).collect();
309 let cardinality = if columns.is_empty() { Cardinality::None } else { Cardinality::Many };
310 let capabilities = crate::capabilities::of_command(&rewritten.sql, &kind);
311 let analysis = Analysis {
312 kind: Some(StatementKind::of(&kind)),
313 comment: None,
314 params: a.params(lexed).0,
315 columns,
316 cardinality,
317 cardinality_reason: None,
318 key: None,
319 unique: Vec::new(),
320 order: Vec::new(),
321 ordered: false,
322 value: false,
323 rewritten,
324 sql_mode: None,
325 style: lexed.style,
326 diagnostics,
327 unresolved: Vec::new(),
328 structured: Vec::new(),
329 errors: None,
330 capabilities: Some(capabilities),
331 read_only: false,
332 notes: Vec::new(),
333 tables: None,
334 domains: Default::default(),
335 };
336 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()] };
337 }
338 let (facts, kind) = a.columns();
339 let booleans = a.booleans();
340 let literals = a.literals();
341 let columns: Vec<Column> = facts
345 .into_iter()
346 .zip(a.flags())
347 .zip(&booleans)
348 .zip(&t.columns)
349 .zip(a.exacts())
350 .enumerate()
351 .map(|(i, (((((name, fact), flag), computed), public), exact))| {
352 let ty = if flag { Ty::Scalar { name: "bool".into() } } else { fact.ty };
353 let ty = descriptor(&ty, public.declared.as_deref(), *computed, exact);
354 let ty = match literals.get(i) {
355 Some(Some(written)) => reylo_engine_core::literal::narrow(&ty, written).unwrap_or(ty),
356 _ => ty,
357 };
358 Column::new(name, ty, !fact.non_null)
359 })
360 .collect();
361 let (params, refused) = a.params(lexed);
362 for (numbered, table, column) in refused {
365 let name = numbered.strip_prefix('?').and_then(|k| k.parse::<usize>().ok()).and_then(|k| lexed.params.get(k.checked_sub(1)?));
366 let Some(at) = name.and_then(|name| lexed.placeholders.iter().find(|p| &p.name == name)) else { continue };
367 let written = &sql[at.start..at.end];
368 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));
369 }
370 let (cardinality, reason) = a.cardinality();
371 let mut analysis = Analysis {
372 kind: (!kind.is_empty()).then(|| StatementKind::of(&kind)),
373 comment: None,
374 params,
375 columns,
376 cardinality,
377 cardinality_reason: reason,
378 key: None,
379 unique: Vec::new(),
380 order: Vec::new(),
381 ordered: false,
382 value: false,
383 rewritten,
384 sql_mode: None,
385 style: lexed.style,
386 diagnostics,
387 unresolved: Vec::new(),
388 structured: Vec::new(),
389 errors: None,
390 capabilities: Some(crate::capabilities::of_statement(&t)),
391 read_only: false,
392 notes: Vec::new(),
393 tables: Some(tables(&t)),
394 domains: Default::default(),
395 };
396 crate::analysis::names(sql, Dialect::Sqlite, &mut analysis, result_targets(&t).as_deref(), &|_| None);
397 let unique_keys = t.tables.iter().map(|(name, info)| (name.clone(), info.unique_keys.clone())).collect();
398 SqliteAnalysis { analysis, declared: t.columns.iter().map(|c| c.declared.clone()).collect(), readonly: t.readonly, unique_keys, booleans }
399}
400
401fn replayed(ddl: &[String]) -> (Vec<String>, Vec<String>) {
406 let (triggers, mut replay): (Vec<String>, Vec<String>) = ddl.iter().cloned().partition(|s| trigger_header(s).is_some());
407 replay.extend(triggers.iter().filter_map(|s| instead_of_stub(s)));
408 (triggers, replay)
409}
410
411fn listed(host: Option<&[HostFunction]>) -> Option<Vec<tree::Listed<'_>>> {
413 host.map(|host| host.iter().map(|f| (f.name.as_str(), f.arity, f.kind)).collect())
414}
415
416pub(crate) fn declares_replace(analysis: &Analysis, host: &Host) -> Lazy<bool> {
423 let schema = host.query(DDL_QUERY, Vec::new(), Scope::Session);
424 let functions = host.query(FUNCTIONS_QUERY, Vec::new(), Scope::Session);
425 let (Ok(rows), functions) = (schema?, functions?) else { return Some(true) };
426 let ddl: Vec<String> = rows.iter().filter_map(|r| r.first().and_then(as_str)).map(String::from).collect();
427 let host_functions = functions.ok().and_then(|rows| host_functions(&rows));
428 let (_, replay) = replayed(&ddl);
429 let sql = &analysis.rewritten.sql;
430 let Ok(t) = tree::analyze(&replay, sql, sql, &[], listed(host_functions.as_deref()).as_deref()) else { return Some(true) };
431 Some(t.dml.as_ref().and_then(|dml| t.tables.get(&dml.table)).is_none_or(|info| info.replaces))
432}
433
434fn reads_itself(sel: &Sel) -> bool {
437 let mut arm = Some(sel);
438 while let Some(a) = arm {
439 if a.from.iter().any(|f| f.recursive) {
440 return true;
441 }
442 arm = a.prior.as_deref();
443 }
444 false
445}
446
447fn tables(t: &Tree) -> Tables {
455 #[derive(Default)]
456 struct Walk {
457 read: Vec<String>,
458 ctes: Vec<String>,
459 }
460 impl Walk {
461 fn node(&mut self, n: &Node) {
462 if let Some(q) = &n.select {
463 self.sel(q);
464 }
465 for child in n.left.iter().chain(&n.right) {
466 self.node(child);
467 }
468 for child in n.list.iter().chain(&n.args) {
469 self.node(child);
470 }
471 }
472 fn sel(&mut self, s: &Sel) {
473 for c in &s.columns {
474 self.node(&c.expr);
475 }
476 for f in &s.from {
477 if f.cte {
478 self.ctes.extend(f.table.clone());
479 }
480 if f.cte || f.subquery.is_some() && f.table.is_none() {
481 if let Some(q) = &f.subquery {
482 self.sel(q);
483 }
484 } else if !f.tab_func {
485 self.read.extend(f.table.clone());
486 }
487 for n in f.args.iter().chain(&f.on) {
488 self.node(n);
489 }
490 }
491 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) {
492 self.node(n);
493 }
494 if let Some(prior) = &s.prior {
495 self.sel(prior);
496 }
497 }
498 }
499 let mut walk = Walk::default();
500 if let Some(s) = &t.statement {
501 walk.sel(s);
502 }
503 for c in t.returning.iter().flatten() {
504 walk.node(&c.expr);
505 }
506 let mut write = Vec::new();
507 if let Some(dml) = &t.dml {
508 write.push(dml.table.clone());
509 let upsert = dml.upserts.iter().flat_map(|u| u.set.iter().map(|s| &s.expr).chain(&u.where_));
510 for n in dml.values.iter().flatten().chain(dml.set.iter().map(|s| &s.expr)).chain(&dml.where_).chain(upsert) {
511 walk.node(n);
512 }
513 }
514 let Walk { mut read, ctes } = walk;
515 read.retain(|table| !ctes.iter().any(|cte| cte.eq_ignore_ascii_case(table)));
516 Tables { read, write, ..Default::default() }
517}
518
519fn lexed_parameter(p: &tree::PublicParam, lexed: &Lexed) -> bool {
522 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))
523}
524
525fn constant_keys(sql: &str, lexed: &Lexed, t: &Tree) -> Vec<crate::api::Diagnostic> {
530 fn param(n: &Node) -> Option<i64> {
531 match n.op.as_str() {
532 "variable" => Some(n.index),
533 "cast" | "collate" => n.left.as_deref().and_then(param),
534 _ => None,
535 }
536 }
537 fn reads(n: &Node, out: &mut HashSet<i64>) {
539 if n.op == "variable" {
540 out.insert(n.index);
541 }
542 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) {
543 reads(child, out);
544 }
545 }
546 #[derive(Default)]
547 struct Walk {
548 found: Vec<(i64, KeyClause, bool)>,
549 }
550 impl Walk {
551 fn keys(&mut self, list: &[Node], clause: KeyClause) {
552 self.found.extend(list.iter().filter_map(param).map(|index| (index, clause, list.len() == 1)));
553 }
554 fn select_keys(&mut self, s: &Sel) {
559 let mut listed = HashSet::new();
560 s.columns.iter().for_each(|c| reads(&c.expr, &mut listed));
561 for (list, clause) in [(&s.group_by, KeyClause::GroupBy), (&s.order_by, KeyClause::OrderBy)] {
562 let alone = list.len() == 1;
563 self.found.extend(list.iter().filter_map(param).filter(|index| !listed.contains(index)).map(|index| (index, clause, alone)));
564 }
565 }
566 fn node(&mut self, n: &Node) {
567 self.keys(&n.order_by, KeyClause::OrderBy);
568 self.keys(&n.partition_by, KeyClause::PartitionBy);
569 if let Some(q) = &n.select {
570 self.sel(q);
571 }
572 for child in n.left.iter().chain(&n.right) {
573 self.node(child);
574 }
575 for child in n.list.iter().chain(&n.args).chain(&n.order_by).chain(&n.partition_by) {
576 self.node(child);
577 }
578 }
579 fn sel(&mut self, s: &Sel) {
580 self.select_keys(s);
581 for c in &s.columns {
582 self.node(&c.expr);
583 }
584 for f in &s.from {
585 if let Some(q) = &f.subquery {
586 self.sel(q);
587 }
588 for n in f.args.iter().chain(&f.on) {
589 self.node(n);
590 }
591 }
592 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) {
593 self.node(n);
594 }
595 if let Some(prior) = &s.prior {
596 self.sel(prior);
597 }
598 }
599 }
600 let mut walk = Walk::default();
601 if let Some(s) = &t.statement {
602 walk.sel(s);
603 }
604 for c in t.returning.iter().flatten() {
605 walk.node(&c.expr);
606 }
607 if let Some(dml) = &t.dml {
608 let upsert = dml.upserts.iter().flat_map(|u| u.set.iter().map(|s| &s.expr).chain(&u.where_));
609 for n in dml.values.iter().flatten().chain(dml.set.iter().map(|s| &s.expr)).chain(&dml.where_).chain(upsert) {
610 walk.node(n);
611 }
612 }
613 let mut out: Vec<_> = walk
615 .found
616 .into_iter()
617 .filter_map(|(index, clause, alone)| {
618 let name = lexed.params.get(usize::try_from(index).ok()?.checked_sub(1)?)?;
619 let p = lexed.placeholders.iter().find(|p| &p.name == name)?;
620 Some(constant_key(sql, p.start, p.end, clause, alone))
621 })
622 .collect();
623 out.sort_by_key(|d| d.start);
624 out.dedup_by_key(|d| d.start);
625 out
626}
627
628fn token_len(rest: &str) -> usize {
629 rest.trim_start().chars().take_while(|c| c.is_alphanumeric() || *c == '_' || *c == ':' || *c == '$' || *c == '@' || *c == '?').count().max(1)
630}
631
632#[derive(Debug, Clone)]
634struct Fact {
635 ty: Ty,
636 non_null: bool,
637}
638
639impl Fact {
640 fn new(aff: &str, non_null: bool) -> Fact {
641 Fact { ty: affinity_type(aff), non_null }
642 }
643 fn unknown() -> Fact {
644 Fact { ty: Ty::Unknown, non_null: false }
645 }
646}
647
648fn int64() -> Type {
651 Type::integer(64)
652}
653fn real() -> Type {
654 Type::new(Kind::Float(FloatType { exponent_bits: 11, mantissa_bits: 52, infinity: true, ..FloatType::default() }))
655}
656fn text() -> Type {
657 Type::new(Kind::Text(TextType { encoding: Some("UTF-8".into()), ill_formed: true, ..TextType::default() }))
658}
659
660fn stored(aff: &str) -> Type {
663 let members = match aff {
664 "real" => vec![real(), text(), Type::bytes()],
665 "text" => vec![text(), Type::bytes()],
666 _ => vec![int64(), real(), text(), Type::bytes()],
667 };
668 Type::union(members)
669}
670
671fn descriptor(ty: &Ty, declared: Option<&str>, computed: bool, exact: bool) -> Type {
679 let declared = declared.map(str::trim).filter(|d| !d.is_empty()).filter(|d| match ty {
682 Ty::Scalar { name } if name == "bool" => is_boolean_declared(d),
683 Ty::Scalar { .. } => !is_boolean_declared(d) && column_type(d, affinity(d), false) == *ty,
684 _ => false,
685 });
686 match ty {
687 Ty::Scalar { name } if name == "bool" && computed => Type::boolean(),
688 Ty::Scalar { name } if name == "bool" => stored("numeric").named(declared.unwrap_or("BOOLEAN")),
689 Ty::Scalar { name } => match (declared, name.as_str()) {
690 (Some(d), "integer" | "int8") if exact => int64().named(d),
691 (Some(d), "real") if exact => real().named(d),
692 (Some(d), "text") if exact => text().named(d),
693 (Some(d), "blob") if exact => Type::bytes().named(d),
694 (Some(d), aff) => stored(if aff == "int8" { "integer" } else { aff }).named(d),
695 (None, "integer") => int64(),
696 (None, "int8") => int64().named("BIGINT"),
697 (None, "real") => real(),
698 (None, "text") => text(),
699 (None, "blob") => Type::bytes(),
700 (None, "numeric") => stored("numeric").named("NUMERIC"),
701 _ => Type::unknown(),
702 },
703 Ty::Object { .. } | Ty::List { .. } => Type::json_of(crate::types::Slot::non_null(content(ty))),
704 Ty::Json { schema: Some(schema) } => Type::json_schema_of(schema.clone()),
705 Ty::Json { schema: None } => Type::json(),
706 Ty::Unknown => Type::unknown(),
707 }
708}
709
710fn literals_of(n: &Node) -> Option<Vec<reylo_engine_core::literal::Literal>> {
714 use reylo_engine_core::literal::Literal;
715 match n.op.as_str() {
716 "null" => Some(Vec::new()),
717 "string" => Some(vec![Literal::Text(n.value.clone()?)]),
718 "integer" | "float" => Some(vec![Literal::Number(n.value.clone()?)]),
719 "truefalse" => Some(vec![Literal::Boolean(n.value.as_deref()?.eq_ignore_ascii_case("true"))]),
720 "neg" => match literals_of(n.left.as_deref()?)?.as_slice() {
721 [Literal::Number(v)] => Some(vec![Literal::Number(match v.strip_prefix('-') {
722 Some(positive) => positive.to_string(),
723 None => format!("-{v}"),
724 })]),
725 _ => None,
726 },
727 "pos" | "collate" => literals_of(n.left.as_deref()?),
728 "case" => {
729 let mut values = Vec::new();
731 for pair in n.list.chunks(2) {
732 values.extend(literals_of(pair.last()?)?);
733 }
734 Some(values)
735 }
736 _ => None,
737 }
738}
739
740fn content(ty: &Ty) -> Type {
743 match ty {
744 Ty::Object { fields } => Type::structure(fields.iter().map(|f| Field::new(f.name.clone(), content(&f.ty), f.nullable)).collect()),
745 Ty::List { of, nullable_items } => Type::array(crate::types::Slot::new(content(of), *nullable_items)),
746 other => descriptor(other, None, false, false),
747 }
748}
749
750fn column_type(declared: &str, aff: &str, strict: bool) -> Ty {
756 let declared = declared.trim();
757 if declared.is_empty() || (strict && declared.eq_ignore_ascii_case("any")) {
758 Ty::Unknown
759 } else if aff == "integer" && is_int8_declared(declared) {
760 Ty::Scalar { name: "int8".into() }
761 } else {
762 affinity_type(aff)
763 }
764}
765
766fn is_int8_declared(declared: &str) -> bool {
772 let base = declared.split('(').next().unwrap_or("").split_whitespace().map(str::to_ascii_lowercase).collect::<Vec<_>>().join(" ");
773 matches!(base.as_str(), "bigint" | "int8" | "unsigned big int")
774}
775
776fn affinity_type(aff: &str) -> Ty {
778 match aff {
779 "integer" | "real" | "text" | "blob" | "numeric" => Ty::Scalar { name: aff.to_string() },
780 _ => Ty::Unknown,
781 }
782}
783
784fn scalar_name(t: &Ty) -> Option<&str> {
785 match t {
786 Ty::Scalar { name } => Some(name.as_str()),
787 _ => None,
788 }
789}
790
791fn is_numeric(t: &Ty) -> bool {
792 matches!(scalar_name(t), Some("integer" | "int8" | "real" | "numeric"))
793}
794
795fn is_integral(t: &Ty) -> bool {
797 matches!(scalar_name(t), Some("integer" | "int8"))
798}
799
800fn computed(t: Ty) -> Ty {
805 if scalar_name(&t) == Some("int8") {
806 Ty::Scalar { name: "integer".into() }
807 } else {
808 t
809 }
810}
811
812fn shared(facts: &[&Fact]) -> Ty {
816 let known: Vec<&Ty> = facts.iter().map(|f| &f.ty).filter(|t| !matches!(t, Ty::Unknown)).collect();
817 let Some(first) = known.first() else { return Ty::Unknown };
818 if known.len() < facts.len() && known.iter().any(|t| is_built(t)) {
821 return Ty::Scalar { name: "text".into() };
822 }
823 if known.iter().all(|t| t == first) {
824 return (*first).clone();
825 }
826 if let Some(ty) = same_json(&known) {
827 return ty;
828 }
829 let known: Vec<Ty> = known.iter().map(|t| textual(t)).collect();
830 let known: Vec<&Ty> = known.iter().collect();
831 let first = known[0];
832 if known.iter().all(|t| *t == first) {
833 return first.clone();
834 }
835 if known.iter().all(|t| is_integral(t)) {
836 return Ty::Scalar { name: "int8".into() };
837 }
838 if known.iter().all(|t| is_numeric(t)) {
839 let numeric = known.iter().any(|t| scalar_name(t) == Some("numeric"));
842 return Ty::Scalar { name: if numeric { "numeric" } else { "real" }.into() };
843 }
844 Ty::Unknown
845}
846
847fn reached(args: &[Fact]) -> &[Fact] {
850 let count = args.iter().position(|f| f.non_null).map_or(args.len(), |i| i + 1);
851 &args[..count]
852}
853
854fn values_type(values: &[(&Node, &Fact)]) -> Ty {
860 let valued: Vec<&Fact> = values.iter().filter(|(e, _)| e.op != "null").map(|(_, f)| *f).collect();
861 if values.iter().any(|(e, f)| matches!(f.ty, Ty::Unknown) && e.op != "null" && e.op != "variable") {
862 return Ty::Unknown;
863 }
864 shared(&valued)
865}
866
867fn is_built(t: &Ty) -> bool {
869 matches!(t, Ty::Object { .. } | Ty::List { .. } | Ty::Json { .. })
870}
871
872fn textual(t: &Ty) -> Ty {
874 if is_built(t) { Ty::Scalar { name: "text".into() } } else { t.clone() }
875}
876
877fn same_json(types: &[&Ty]) -> Option<Ty> {
880 let empty = |t: &Ty| matches!(t, Ty::Json { schema: Some(s) } if s.get("prefixItems").is_none() && s["type"] == "array" && s["items"] == false);
881 let lists: Vec<&Ty> = types.iter().copied().filter(|t| !empty(t)).collect();
882 let first = lists.first()?;
883 (matches!(first, Ty::List { .. }) && lists.iter().all(|t| t == first)).then(|| (*first).clone())
884}
885
886#[derive(Debug, Clone, Copy, PartialEq, Eq)]
894enum Carry {
895 No,
897 Yes,
899 Maybe,
901}
902
903fn combine(carries: &[Carry]) -> Carry {
905 if carries.iter().all(|c| *c == Carry::No) {
906 Carry::No
907 } else if carries.iter().all(|c| *c == Carry::Yes) {
908 Carry::Yes
909 } else {
910 Carry::Maybe
911 }
912}
913
914struct JsonFact {
916 ty: Ty,
917 non_null: bool,
918 carry: Carry,
919}
920
921fn is_json_result(name: &str) -> bool {
926 name.starts_with("jsonb")
927 || matches!(
928 name,
929 "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"
930 )
931}
932
933const PASSING: &[&str] = &["min", "max", "lag", "lead", "first_value", "last_value", "nth_value"];
935
936const PLAIN: &[&str] = &[
938 "row_number", "rank", "dense_rank", "ntile", "percent_rank", "cume_dist", "count", "total", "sum", "avg", "group_concat", "string_agg", "abs", "round", "length", "instr",
939 "json_valid", "octet_length", "json_array_length", "json_type", "unicode", "like", "glob", "regexp", "match", "concat", "concat_ws", "substr", "substring", "printf", "format",
940 "upper", "lower", "trim", "ltrim", "rtrim", "replace", "char", "date", "time", "datetime", "julianday", "unixepoch", "strftime", "timediff", "hex", "quote", "typeof",
941 "soundex", "sqlite_version", "sqlite_source_id", "current_date", "current_time", "current_timestamp", "random", "last_insert_rowid", "changes", "total_changes",
942 "randomblob", "zeroblob", "->>", "atan", "atan2", "asinh", "sinh", "cosh", "tanh", "exp", "degrees", "radians", "ceil", "ceiling", "floor", "trunc", "sign", "acos", "acosh",
943 "asin", "atanh", "cos", "sin", "tan", "ln", "log", "log10", "log2", "mod", "pow", "power", "sqrt", "pi",
944 "bm25", "highlight", "snippet", "offsets", "matchinfo",
945];
946
947fn in_json(t: &Ty) -> Ty {
952 match scalar_name(t) {
953 Some("integer" | "int8" | "real" | "text" | "numeric") => t.clone(),
954 _ => Ty::Unknown,
955 }
956}
957
958fn nullable_in_json(f: &JsonFact) -> bool {
963 match f.ty {
964 Ty::Unknown => false,
965 Ty::Json { schema: None } => true,
966 _ => !f.non_null,
967 }
968}
969
970fn value_schema(t: &Ty, nullable: bool) -> serde_json::Value {
973 use serde_json::json;
974 let schema = match t {
975 Ty::Scalar { name } => match name.as_str() {
976 "integer" | "int8" => json!({"type": "integer", "format": "int64"}),
977 "real" => json!({"type": "number", "format": "double"}),
978 "text" => json!({"type": "string"}),
979 "numeric" => json!({"type": ["number", "string"]}),
980 _ => json!({}),
981 },
982 Ty::Object { fields } => {
983 let properties: serde_json::Map<String, serde_json::Value> = fields.iter().map(|f| (f.name.clone(), value_schema(&f.ty, f.nullable))).collect();
984 json!({"type": "object", "properties": properties, "required": fields.iter().map(|f| f.name.clone()).collect::<Vec<_>>(), "additionalProperties": false})
985 }
986 Ty::List { of, nullable_items } => json!({"type": "array", "items": value_schema(of, *nullable_items)}),
987 Ty::Json { schema: Some(schema) } => schema.clone(),
988 _ => json!({}),
989 };
990 if nullable { reylo_engine_core::schema::nullable(schema) } else { schema }
991}
992
993fn record(values: Vec<serde_json::Value>) -> Ty {
995 let mut distinct: Vec<serde_json::Value> = Vec::new();
996 for v in values {
997 if !distinct.contains(&v) {
998 distinct.push(v);
999 }
1000 }
1001 let rest = if distinct.len() == 1 { distinct.pop().unwrap_or_default() } else { serde_json::json!({"anyOf": distinct}) };
1002 Ty::Json { schema: Some(serde_json::json!({"type": "object", "additionalProperties": rest})) }
1003}
1004
1005type ScopeStack<'a> = Vec<&'a [From]>;
1007
1008struct Analyzer<'a> {
1009 tree: &'a Tree,
1010 extras: &'a Extras,
1011 skipping: &'a HashMap<String, i32>,
1014 nullable_params: HashSet<String>,
1018 nullable_values: HashSet<String>,
1022 written: std::cell::RefCell<HashSet<String>>,
1025 level: std::cell::RefCell<Level>,
1027 shapes: std::cell::RefCell<HashMap<usize, Option<Ty>>>,
1029 recursion: std::cell::RefCell<Vec<(String, Vec<Fact>)>>,
1032 settled: std::cell::RefCell<HashMap<usize, Vec<Fact>>>,
1034}
1035
1036#[derive(Debug, Clone, Default)]
1038struct Level {
1039 narrowed: HashSet<(i64, String)>,
1041 reduced: HashSet<i64>,
1043 grouped: bool,
1045 lone: HashSet<i64>,
1049 aggregating: u32,
1052 own: HashSet<i64>,
1054 around: HashSet<i64>,
1058 foreign: u32,
1063 windowed: bool,
1068}
1069
1070fn cast_variable<'n>(n: &'n Node, extras: &Extras) -> Option<&'n String> {
1073 let inner = match n.op.as_str() {
1074 "cast" => n.left.as_deref(),
1075 "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(),
1076 _ => None,
1077 }?;
1078 inner.name.as_ref().filter(|_| inner.op == "variable")
1079}
1080
1081fn level_of(sel: &Sel, extras: &Extras) -> Level {
1084 let own: HashSet<i64> = sel.from.iter().map(|f| f.cursor).collect();
1085 let outer: HashSet<i64> = sel.from.iter().filter(|f| f.outer).map(|f| f.cursor).collect();
1086 let extended: HashSet<i64> = sel.from.iter().filter(|f| f.left_of_right).map(|f| f.cursor).collect();
1089 let mut narrowed = HashSet::new();
1090 for term in conjuncts(sel.where_.as_ref()).into_iter().filter(|t| !t.outer_on) {
1091 narrowed.extend(strict_in(term, extras).into_iter().filter(|(cursor, _)| own.contains(cursor) && !(term.inner_on && extended.contains(cursor))));
1092 }
1093 let reduced = narrowed.iter().map(|(cursor, _)| *cursor).filter(|c| outer.contains(c)).collect();
1094 let lone = if sel.aggregate && sel.group_by.is_empty() { own.clone() } else { HashSet::new() };
1095 Level { narrowed, reduced, grouped: !sel.group_by.is_empty(), lone, aggregating: 0, own, around: HashSet::new(), foreign: 0, windowed: sel.window }
1096}
1097
1098fn reads_cursor(n: &Node, cursors: &HashSet<i64>) -> bool {
1101 if (n.op == "column" && cursors.contains(&n.cursor)) || n.select.is_some() {
1102 return true;
1103 }
1104 n.left.as_deref().is_some_and(|x| reads_cursor(x, cursors))
1105 || n.right.as_deref().is_some_and(|x| reads_cursor(x, cursors))
1106 || n.list.iter().chain(&n.args).chain(&n.order_by).chain(&n.partition_by).any(|x| reads_cursor(x, cursors))
1107}
1108
1109fn strict_in(n: &Node, extras: &Extras) -> HashSet<(i64, String)> {
1114 let nulls = |x: &Node| nulls_with(x, extras);
1115 match n.op.as_str() {
1116 "and" => n.left.iter().chain(n.right.iter()).flat_map(|x| strict_in(x, extras)).collect(),
1117 "or" => {
1118 let (Some(l), Some(r)) = (n.left.as_deref(), n.right.as_deref()) else { return HashSet::new() };
1119 let right = strict_in(r, extras);
1120 strict_in(l, extras).into_iter().filter(|c| right.contains(c)).collect()
1121 }
1122 "notnull" | "in" | "between" => n.left.as_deref().map(nulls).unwrap_or_default(),
1123 "=" | "!=" | "<" | "<=" | ">" | ">=" => n.left.iter().chain(n.right.iter()).flat_map(|x| nulls(x)).collect(),
1124 "not" => match n.left.as_deref() {
1125 Some(inner) if inner.op == "isnull" => inner.left.as_deref().map(nulls).unwrap_or_default(),
1126 Some(inner) => strict_in(inner, extras).into_iter().filter(|_| matches!(inner.op.as_str(), "=" | "!=" | "<" | "<=" | ">" | ">=" | "between") || (inner.op == "in" && inner.select.is_none())).collect(),
1129 None => HashSet::new(),
1130 },
1131 "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() => {
1132 n.args.iter().flat_map(nulls).collect()
1133 }
1134 "column" => nulls(n),
1135 _ => HashSet::new(),
1136 }
1137}
1138
1139fn nulls_with(n: &Node, extras: &Extras) -> HashSet<(i64, String)> {
1143 const STRICT: &[&str] = &["upper", "lower", "length", "abs", "trim", "ltrim", "rtrim", "substr", "substring", "replace", "round", "instr", "unicode", "sign", "octet_length"];
1144 match n.op.as_str() {
1145 "column" => n.column.clone().map(|c| HashSet::from([(n.cursor, c)])).unwrap_or_default(),
1146 "+" | "-" | "*" | "/" | "%" | "||" => n.left.iter().chain(n.right.iter()).flat_map(|x| nulls_with(x, extras)).collect(),
1147 "neg" | "pos" | "cast" | "collate" => n.left.as_deref().map(|x| nulls_with(x, extras)).unwrap_or_default(),
1148 "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(),
1149 _ => HashSet::new(),
1150 }
1151}
1152
1153fn alter_column(sql: &str) -> Option<(String, usize)> {
1158 let words = words(sql);
1159 let keyword = |i: usize, want: &str| words.get(i).is_some_and(|(w, quoted, _)| !quoted && w.eq_ignore_ascii_case(want));
1160 if !keyword(0, "alter") || !keyword(1, "table") {
1161 return None;
1162 }
1163 let alter = if keyword(3, ".") { 5 } else { 3 };
1165 if !keyword(alter, "alter") {
1166 return None;
1167 }
1168 let column = if keyword(alter + 1, "column") { alter + 2 } else { alter + 1 };
1169 if !keyword(column + 1, "to") {
1170 return None;
1171 }
1172 let byte = |chars: usize| sql.char_indices().nth(chars).map_or(sql.len(), |(at, _)| at);
1174 let at = byte(words[alter].2);
1175 let to = byte(words[column + 1].2) + 2;
1176 Some((format!("{}rename{} \"reylo libsql column\"", &sql[..at], &sql[at + 5..to]), at + 6))
1177}
1178
1179fn words(sql: &str) -> Vec<(String, bool, usize)> {
1184 let chars: Vec<char> = sql.chars().collect();
1185 let mut out = Vec::new();
1186 let mut i = 0;
1187 while i < chars.len() {
1188 let c = chars[i];
1189 if c.is_whitespace() {
1190 i += 1;
1191 } else if c == '-' && chars.get(i + 1) == Some(&'-') {
1192 i += chars[i..].iter().position(|c| *c == '\n').unwrap_or(chars.len() - i);
1193 } else if c == '/' && chars.get(i + 1) == Some(&'*') {
1194 i += 2;
1195 while i < chars.len() && !(chars[i] == '*' && chars.get(i + 1) == Some(&'/')) {
1196 i += 1;
1197 }
1198 i += 2;
1199 } else if matches!(c, '"' | '`' | '\'' | '[') {
1200 let close = if c == '[' { ']' } else { c };
1202 let mut name = String::new();
1203 let at = i;
1204 i += 1;
1205 while i < chars.len() {
1206 if chars[i] == close {
1207 if close != ']' && chars.get(i + 1) == Some(&close) {
1208 i += 1;
1209 } else {
1210 break;
1211 }
1212 }
1213 name.push(chars[i]);
1214 i += 1;
1215 }
1216 i += 1;
1217 out.push((name, true, at));
1218 } else if c.is_alphanumeric() || c == '_' || c == '$' || !c.is_ascii() {
1219 let end = chars[i..].iter().position(|c| !(c.is_alphanumeric() || *c == '_' || *c == '$' || !c.is_ascii())).map_or(chars.len(), |n| i + n);
1220 out.push((chars[i..end].iter().collect(), false, i));
1221 i = end;
1222 } else {
1223 out.push((c.to_string(), false, i));
1224 i += 1;
1225 }
1226 }
1227 out
1228}
1229
1230fn trigger_header(sql: &str) -> Option<(String, String, String)> {
1234 if !sql.as_bytes().windows(7).any(|w| w.eq_ignore_ascii_case(b"trigger")) {
1236 return None;
1237 }
1238 let words = words(sql);
1239 let keyword = |i: usize| words.get(i).filter(|(_, quoted, _)| !quoted).map(|(w, _, _)| w.to_ascii_lowercase());
1240 let take = |i: &mut usize, want: &[&str]| {
1242 let hit = keyword(*i).is_some_and(|w| want.contains(&w.as_str()));
1243 if hit {
1244 *i += 1;
1245 }
1246 hit
1247 };
1248 let mut i = 0;
1249 if !take(&mut i, &["create"]) {
1250 return None;
1251 }
1252 take(&mut i, &["temp", "temporary"]);
1253 if !take(&mut i, &["trigger"]) {
1254 return None;
1255 }
1256 if take(&mut i, &["if"]) {
1257 take(&mut i, &["not"]);
1258 take(&mut i, &["exists"]);
1259 }
1260 i += 1;
1262 if take(&mut i, &["."]) {
1263 i += 1;
1264 }
1265 let timing = if take(&mut i, &["before"]) {
1266 "before"
1267 } else if take(&mut i, &["after"]) {
1268 "after"
1269 } else if take(&mut i, &["instead"]) {
1270 take(&mut i, &["of"]);
1271 "instead"
1272 } else {
1273 "before"
1275 };
1276 let event = keyword(i)?;
1277 let on = (i..words.len()).find(|j| keyword(*j).as_deref() == Some("on"))?;
1279 let mut table = &words.get(on + 1)?.0;
1280 if keyword(on + 2).as_deref() == Some(".") {
1281 table = &words.get(on + 3)?.0;
1282 }
1283 Some((timing.to_string(), event, table.to_ascii_lowercase()))
1284}
1285
1286fn instead_of_stub(sql: &str) -> Option<String> {
1292 let (timing, _, _) = trigger_header(sql)?;
1293 if timing != "instead" {
1294 return None;
1295 }
1296 let words = words(sql);
1297 let keyword = |w: &(String, bool, usize)| !w.1 && (w.0.eq_ignore_ascii_case("when") || w.0.eq_ignore_ascii_case("begin"));
1298 let on = words.iter().position(|w| !w.1 && w.0.eq_ignore_ascii_case("on"))?;
1299 let after = if words.get(on + 2).is_some_and(|w| !w.1 && w.0 == ".") { on + 4 } else { on + 2 };
1301 let body = words.iter().skip(after).find(|w| keyword(w))?.2;
1302 let header: String = sql.chars().take(body).collect();
1303 Some(format!("{}\nBEGIN SELECT 1; END", header.trim_end()))
1305}
1306
1307const TRIGGER_ROW_INSERT: i32 = 4;
1310const TRIGGER_ROW_DELETE: i32 = 8;
1311const TRIGGER_ROW_UPDATE: i32 = 16;
1312
1313fn skipping_triggers(triggers: &[String]) -> HashMap<String, i32> {
1315 let mut out: HashMap<String, i32> = HashMap::new();
1316 for sql in triggers {
1317 let Some((timing, event, table)) = trigger_header(sql) else { continue };
1318 if timing == "after" {
1319 continue;
1320 }
1321 let bit = match event.as_str() {
1322 "insert" => TRIGGER_ROW_INSERT,
1323 "update" => TRIGGER_ROW_UPDATE,
1324 "delete" => TRIGGER_ROW_DELETE,
1325 _ => TRIGGER_ROW_INSERT | TRIGGER_ROW_UPDATE | TRIGGER_ROW_DELETE,
1326 };
1327 *out.entry(table).or_default() |= bit;
1328 }
1329 out
1330}
1331
1332#[derive(Clone, Copy)]
1334enum Nulls {
1335 Never,
1337 IfArgs,
1339 Always,
1341}
1342
1343impl Analyzer<'_> {
1344 fn columns(&self) -> (Vec<(String, Fact)>, String) {
1347 let t = self.tree;
1348 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() });
1349 let facts: Vec<Fact> = if let Some(returning) = &t.returning {
1350 let written = self.written_non_null();
1351 *self.written.borrow_mut() = written;
1352 returning.iter().map(|c| self.type_of(&c.expr, &Vec::new())).collect()
1353 } else if let (Some(sel), None) = (&t.statement, &t.dml) {
1354 (0..sel.columns.len()).map(|i| self.select_column(sel, i, &Vec::new())).collect()
1355 } else {
1356 Vec::new()
1357 };
1358 let columns = t
1359 .columns
1360 .iter()
1361 .enumerate()
1362 .map(|(i, public)| {
1363 (public.name.clone(), facts.get(i).cloned().unwrap_or_else(Fact::unknown))
1364 })
1365 .collect();
1366 (columns, kind)
1367 }
1368
1369 fn literals(&self) -> Vec<Option<Vec<reylo_engine_core::literal::Literal>>> {
1373 let t = self.tree;
1374 if let Some(returning) = &t.returning {
1375 return returning.iter().map(|c| literals_of(&c.expr)).collect();
1376 }
1377 let (Some(sel), None) = (&t.statement, &t.dml) else { return Vec::new() };
1378 let mut arms: Vec<&Sel> = Vec::new();
1379 let mut s = Some(sel);
1380 while let Some(arm) = s {
1381 arms.push(arm);
1382 s = arm.prior.as_deref();
1383 }
1384 arms.reverse();
1385 (0..sel.columns.len())
1386 .map(|i| {
1387 let mut values = Vec::new();
1388 for (k, arm) in arms.iter().enumerate() {
1389 if k > 0 && matches!(arm.op.as_deref(), Some("intersect" | "except")) {
1390 continue;
1391 }
1392 for e in std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i))) {
1393 values.extend(literals_of(e?)?);
1394 }
1395 }
1396 Some(values)
1397 })
1398 .collect()
1399 }
1400
1401 fn booleans(&self) -> Vec<bool> {
1403 self.result_truths(false)
1404 }
1405
1406 fn flags(&self) -> Vec<bool> {
1412 self.result_truths(true)
1413 }
1414
1415 fn result_truths(&self, declared: bool) -> Vec<bool> {
1416 let t = self.tree;
1417 let truths: Vec<bool> = if let Some(returning) = &t.returning {
1418 returning.iter().map(|c| self.truth(&c.expr, &Vec::new(), declared)).collect()
1419 } else if let (Some(sel), None) = (&t.statement, &t.dml) {
1420 (0..sel.columns.len()).map(|i| self.select_truth(sel, i, &Vec::new(), declared)).collect()
1421 } else {
1422 Vec::new()
1423 };
1424 (0..t.columns.len()).map(|i| truths.get(i).copied().unwrap_or(false)).collect()
1425 }
1426
1427 fn exacts(&self) -> Vec<bool> {
1430 let t = self.tree;
1431 let exact: Vec<bool> = if let Some(returning) = &t.returning {
1432 returning.iter().map(|c| self.exact(&c.expr, &Vec::new())).collect()
1433 } else if let (Some(sel), None) = (&t.statement, &t.dml) {
1434 (0..sel.columns.len()).map(|i| self.select_exact(sel, i, &Vec::new())).collect()
1435 } else {
1436 Vec::new()
1437 };
1438 (0..t.columns.len()).map(|i| exact.get(i).copied().unwrap_or(false)).collect()
1439 }
1440
1441 fn select_exact(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> bool {
1442 let mut s = Some(sel);
1443 while let Some(arm) = s {
1444 let mut inner = scope.clone();
1445 inner.push(&arm.from);
1446 if !arm.columns.get(i).is_some_and(|c| self.exact(&c.expr, &inner)) || !arm.rows.is_empty() {
1447 return false;
1448 }
1449 s = arm.prior.as_deref();
1450 }
1451 true
1452 }
1453
1454 fn exact(&self, n: &Node, scope: &ScopeStack) -> bool {
1455 if n.op != "column" {
1456 return false;
1457 }
1458 for froms in scope.iter().rev() {
1459 if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
1460 if let Some(sub) = f.subquery.as_deref() {
1461 return self.select_exact(sub, n.index.max(0) as usize, scope);
1462 }
1463 break;
1464 }
1465 }
1466 (n.strict && !n.generated) || n.rowid
1469 }
1470
1471 fn select_truth(&self, sel: &Sel, i: usize, scope: &ScopeStack, declared: bool) -> bool {
1473 let mut s = Some(sel);
1474 while let Some(arm) = s {
1475 let mut inner = scope.clone();
1476 inner.push(&arm.from);
1477 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))) {
1478 return false;
1479 }
1480 s = arm.prior.as_deref();
1481 }
1482 true
1483 }
1484
1485 fn truth(&self, n: &Node, scope: &ScopeStack, declared: bool) -> bool {
1490 let every = |nodes: &mut dyn Iterator<Item = &Node>| {
1491 let mut any = false;
1492 for x in nodes {
1493 if x.op == "null" {
1494 continue;
1495 }
1496 if !self.truth(x, scope, declared) {
1497 return false;
1498 }
1499 any = true;
1500 }
1501 any
1502 };
1503 match n.op.as_str() {
1504 "=" | "!=" | "<" | "<=" | ">" | ">=" | "is" | "is not" | "isnull" | "notnull" | "in" | "between" | "exists" | "and" | "or" | "not" | "truefalse" => true,
1505 "collate" => n.left.as_deref().is_some_and(|l| self.truth(l, scope, declared)),
1506 "function" if !n.agg && !n.window => match n.name.as_deref().unwrap_or("") {
1507 "like" | "glob" | "regexp" | "match" => self.extras.function(n.name.as_deref().unwrap_or(""), n.args.len()).is_none(),
1508 "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(),
1510 "likely" | "unlikely" | "likelihood" => n.args.first().is_some_and(|a| self.truth(a, scope, declared)),
1511 "coalesce" | "ifnull" => every(&mut n.args.iter()),
1512 "iif" | "if" => every(&mut iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i))),
1513 _ => false,
1514 },
1515 "case" => {
1517 let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
1518 let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
1519 every(&mut results.chain(otherwise))
1520 }
1521 "select" => n.select.as_deref().is_some_and(|sub| self.select_truth(sub, 0, scope, declared)),
1522 "column" => {
1523 for froms in scope.iter().rev() {
1524 if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
1525 if let Some(sub) = f.subquery.as_deref() {
1526 return self.select_truth(sub, n.index.max(0) as usize, scope, declared);
1527 }
1528 break;
1529 }
1530 }
1531 declared && !n.rowid && n.declared.as_deref().is_some_and(is_boolean_declared)
1532 }
1533 _ => false,
1534 }
1535 }
1536
1537 fn select_column(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> Fact {
1540 let mut arms: Vec<&Sel> = Vec::new();
1541 let mut s = Some(sel);
1542 while let Some(arm) = s {
1543 arms.push(arm);
1544 s = arm.prior.as_deref();
1545 }
1546 arms.reverse();
1547 let facts: Vec<(Option<&Node>, Fact)> = arms
1549 .iter()
1550 .flat_map(|arm| {
1551 let mut inner = scope.clone();
1552 inner.push(&arm.from);
1553 let outer = self.level.replace(self.level_within(arm));
1554 let rows = std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i)));
1555 let facts: Vec<(Option<&Node>, Fact)> = rows.map(|e| (e, e.map(|e| self.type_of(e, &inner)).unwrap_or_else(Fact::unknown))).collect();
1556 self.level.replace(outer);
1557 facts
1558 })
1559 .collect();
1560 let Some((_, first)) = facts.first() else { return Fact::unknown() };
1561 let values: Option<Vec<(&Node, &Fact)>> = facts.iter().map(|(e, f)| Some(((*e)?, f))).collect();
1562 let ty = match values {
1563 _ if facts.iter().all(|(_, f)| f.ty == first.ty) => first.ty.clone(),
1564 Some(values) => values_type(&values),
1565 None => Ty::Unknown,
1566 };
1567 Fact { ty, non_null: facts.iter().all(|(_, f)| f.non_null) }
1568 }
1569
1570 fn recursive_column(&self, name: &str, sub: &Sel, i: usize, scope: &ScopeStack) -> Fact {
1579 let key = sub as *const Sel as usize;
1580 if let Some(facts) = self.settled.borrow().get(&key) {
1581 return facts.get(i).cloned().unwrap_or_else(Fact::unknown);
1582 }
1583 let mut first = sub;
1584 while let Some(prior) = first.prior.as_deref() {
1585 first = prior;
1586 }
1587 let width = first.columns.len();
1588 let mut inner = scope.clone();
1589 inner.push(&first.from);
1590 let outer = self.level.replace(self.level_within(first));
1591 let mut assumed: Vec<Fact> = first.columns.iter().map(|c| Fact { ty: self.type_of(&c.expr, &inner).ty, non_null: true }).collect();
1592 self.level.replace(outer);
1593 let shapes = self.shapes.borrow().clone();
1597 let nested = self.settled.borrow().clone();
1598 let mut settled = None;
1599 for _ in 0..=width + 1 {
1600 *self.shapes.borrow_mut() = shapes.clone();
1601 *self.settled.borrow_mut() = nested.clone();
1602 self.recursion.borrow_mut().push((name.to_string(), assumed.clone()));
1603 let got: Vec<Fact> = (0..width).map(|k| self.select_column(sub, k, scope)).collect();
1604 self.recursion.borrow_mut().pop();
1605 if got.iter().zip(&assumed).all(|(g, a)| g.ty == a.ty && g.non_null == a.non_null) {
1606 settled = Some(got);
1607 break;
1608 }
1609 assumed = got.iter().zip(&assumed).map(|(g, a)| Fact { ty: g.ty.clone(), non_null: g.non_null && a.non_null }).collect();
1610 }
1611 if settled.is_none() {
1612 *self.shapes.borrow_mut() = shapes;
1613 *self.settled.borrow_mut() = nested;
1614 }
1615 let facts = settled.unwrap_or_else(|| vec![Fact::unknown(); width]);
1616 let fact = facts.get(i).cloned().unwrap_or_else(Fact::unknown);
1617 self.settled.borrow_mut().insert(key, facts);
1618 fact
1619 }
1620
1621 fn column_ref(&self, n: &Node, scope: &ScopeStack) -> Fact {
1623 if n.register && !n.view && !n.generated && n.column.as_ref().is_some_and(|c| self.written.borrow().contains(&c.to_ascii_lowercase())) {
1628 let aff = n.affinity.as_deref().unwrap_or(&n.aff);
1629 let ty = match &n.declared {
1630 Some(declared) if !n.rowid => column_type(declared, aff, n.strict),
1631 _ => affinity_type(aff),
1632 };
1633 return Fact { ty, non_null: true };
1634 }
1635 let (narrowed, reduced, lone) = {
1638 let level = self.level.borrow();
1639 (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)))
1640 };
1641 for froms in scope.iter().rev() {
1642 if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
1643 let index = n.index.max(0) as usize;
1644 let inner = match (&f.subquery, f.table.as_deref()) {
1645 (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),
1646 (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)),
1649 (Some(sub), Some(name)) if f.cte && reads_itself(sub) => Some(self.recursive_column(name, sub, index, scope)),
1650 (Some(sub), _) => Some(self.select_column(sub, index, scope)),
1651 (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)),
1653 _ => None,
1654 };
1655 if let Some(inner) = inner {
1656 return Fact { ty: inner.ty, non_null: !lone && (narrowed || (inner.non_null && ((!f.outer && !n.outer) || reduced))) };
1657 }
1658 break;
1659 }
1660 }
1661 if n.view && self.tree.dml.as_ref().is_some_and(|d| d.kind == "insert") {
1664 return Fact::unknown();
1665 }
1666 let aff = n.affinity.as_deref().unwrap_or(&n.aff);
1667 let ty = match &n.declared {
1668 Some(declared) if !n.rowid => column_type(declared, aff, n.strict),
1669 _ => affinity_type(aff),
1670 };
1671 Fact { ty, non_null: !lone && (narrowed || ((n.not_null || n.rowid) && (!n.outer || reduced))) }
1672 }
1673
1674 fn vector_key(&self, f: &From) -> Option<Fact> {
1681 let table = self.tree.tables.get(f.vector_table.as_deref()?)?;
1682 Some(if table.without_rowid { Fact { ty: Ty::Unknown, non_null: true } } else { Fact::new("integer", true) })
1683 }
1684
1685 fn call(&self, n: &Node, scope: &ScopeStack) -> Fact {
1690 if let Some(ty) = self.built_text(n, scope) {
1692 return Fact { ty, non_null: self.built_non_null(n, scope) };
1693 }
1694 let args: Vec<Fact> = n.args.iter().map(|a| self.type_of(a, scope)).collect();
1695 self.function(n, &args)
1696 }
1697
1698 fn built_non_null(&self, n: &Node, scope: &ScopeStack) -> bool {
1702 match (self.builtin_name(n), n.args.as_slice()) {
1703 (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) },
1704 _ => true,
1705 }
1706 }
1707
1708 fn type_of(&self, n: &Node, scope: &ScopeStack) -> Fact {
1709 let arg = |x: &Option<Box<Node>>| x.as_deref().map(|x| self.type_of(x, scope)).unwrap_or_else(Fact::unknown);
1710 match n.op.as_str() {
1711 "column" => self.column_ref(n, scope),
1712 "integer" => Fact::new(if integer_literal_fits(n) { "integer" } else { "real" }, true),
1713 "truefalse" => Fact::new("integer", true),
1714 "float" => Fact::new("real", true),
1715 "string" => Fact::new("text", true),
1716 "blob" => Fact::new("blob", true),
1717 "null" => Fact::unknown(),
1718 "variable" => Fact { ty: Ty::Unknown, non_null: n.name.as_ref().is_some_and(|name| !self.nullable_values.contains(name)) },
1720 "function" => {
1721 self.aggregated(n, || self.call(n, scope))
1722 }
1723 "+" | "-" | "*" => {
1724 let (l, r) = (arg(&n.left), arg(&n.right));
1725 Fact { ty: arithmetic(&l.ty, &r.ty), non_null: l.non_null && r.non_null }
1726 }
1727 "/" | "%" => {
1728 let (l, r) = (arg(&n.left), arg(&n.right));
1732 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());
1733 let literal_divisor = divisor.is_some_and(|v| if n.op == "%" { v as i64 != 0 } else { v != 0.0 });
1734 Fact { ty: arithmetic(&l.ty, &r.ty), non_null: l.non_null && r.non_null && literal_divisor }
1735 }
1736 "||" => {
1737 let (l, r) = (arg(&n.left), arg(&n.right));
1738 Fact::new("text", l.non_null && r.non_null)
1739 }
1740 "=" | "!=" | "<" | "<=" | ">" | ">=" | "and" | "or" | "in" | "between" | "&" | "|" | "<<" | ">>" => {
1741 let (l, r) = (arg(&n.left), arg(&n.right));
1742 let list_non_null = n.list.iter().all(|x| self.type_of(x, scope).non_null);
1743 let right_non_null = if n.right.is_some() { r.non_null } else { list_non_null && n.select.is_none() };
1744 Fact::new("integer", l.non_null && right_non_null)
1745 }
1746 "is" | "is not" | "isnull" | "notnull" | "exists" => Fact::new("integer", true),
1747 "not" | "~" => {
1748 let l = arg(&n.left);
1749 Fact::new("integer", l.non_null)
1750 }
1751 "neg" if n.left.as_deref().is_some_and(is_two_to_the_63) => Fact::new("integer", true),
1754 "neg" => {
1755 let l = arg(&n.left);
1756 Fact { ty: if is_numeric(&l.ty) { computed(l.ty) } else { Ty::Scalar { name: "real".into() } }, non_null: l.non_null }
1757 }
1758 "pos" => arg(&n.left),
1761 "cast" => {
1762 let l = arg(&n.left);
1763 Fact::new(n.affinity.as_deref().unwrap_or("none"), l.non_null)
1764 }
1765 "collate" => arg(&n.left),
1766 "case" => {
1767 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();
1769 let otherwise = if n.list.len() % 2 == 1 { n.list.last().map(|e| (e, self.type_of(e, scope))) } else { None };
1770 let mut all: Vec<&(&Node, Fact)> = results.iter().collect();
1771 if let Some(o) = &otherwise {
1772 all.push(o);
1773 }
1774 let values: Vec<(&Node, &Fact)> = all.iter().map(|(e, f)| (*e, f)).collect();
1775 Fact { ty: values_type(&values), non_null: otherwise.is_some() && all.iter().all(|(_, f)| f.non_null) }
1776 }
1777 "select" => {
1778 let Some(sub) = n.select.as_deref() else { return Fact::unknown() };
1782 let inner = self.select_column(sub, 0, scope);
1783 Fact { ty: inner.ty, non_null: inner.non_null && self.exactly_one(sub).is_ok() }
1784 }
1785 _ => Fact::unknown(),
1786 }
1787 }
1788
1789 fn function(&self, n: &Node, args: &[Fact]) -> Fact {
1791 let name = n.name.as_deref().unwrap_or("");
1792 let all_non_null = args.iter().all(|a| a.non_null);
1793 let first = args.first().cloned().unwrap_or_else(Fact::unknown);
1794 let done = |aff: &str, nulls: Nulls| {
1795 let non_null = match nulls {
1796 Nulls::Never => true,
1797 Nulls::IfArgs => all_non_null,
1798 Nulls::Always => false,
1799 };
1800 Fact::new(aff, non_null)
1801 };
1802 let typed = |ty: Ty, nulls: Nulls| Fact { ty, non_null: matches!(nulls, Nulls::Never) || (matches!(nulls, Nulls::IfArgs) && all_non_null) };
1803 if !n.agg && !n.window {
1804 if let Some(f) = self.extras.function(name, args.len()) {
1805 return done(f.returns.name(), Nulls::IfArgs);
1806 }
1807 }
1808 let name = sqlean_alias(name);
1809 if n.window {
1810 let has_a_row = holds_current_row(n);
1815 return match name {
1816 "row_number" | "rank" | "dense_rank" | "ntile" => done("integer", Nulls::Never),
1817 "percent_rank" | "cume_dist" => done("real", Nulls::Never),
1818 "count" => done("integer", Nulls::Never),
1819 "total" => done("real", total_nulls(&first)),
1820 "sum" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::Always),
1821 "avg" => done("real", Nulls::Always),
1822 "lag" | "lead" if args.len() >= 3 => typed(values_type(&[(&n.args[0], &args[0]), (&n.args[2], &args[2])]), Nulls::Always),
1824 "min" | "max" => typed(first.ty.clone(), if has_a_row { Nulls::IfArgs } else { Nulls::Always }),
1825 "lag" | "lead" | "first_value" | "last_value" | "nth_value" => typed(first.ty.clone(), Nulls::Always),
1826 "group_concat" | "string_agg" => done("text", Nulls::Always),
1827 _ => Fact::unknown(),
1828 };
1829 }
1830 if n.agg {
1831 let grouped = self.level.borrow().grouped;
1836 return match name {
1837 "count" => done("integer", Nulls::Never),
1838 "total" => done("real", total_nulls(&first)),
1839 "sum" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::Always),
1840 "avg" => done("real", Nulls::Always),
1841 "min" | "max" => typed(first.ty.clone(), if grouped { Nulls::IfArgs } else { Nulls::Always }),
1842 "group_concat" | "string_agg" => done("text", if grouped { Nulls::IfArgs } else { Nulls::Always }),
1843 "json_group_array" | "json_group_object" => done("text", Nulls::Never),
1844 "jsonb_group_array" | "jsonb_group_object" => done("blob", Nulls::Never),
1845 "median" | "percentile" | "percentile_25" | "percentile_75" | "percentile_90" | "percentile_95" | "percentile_99" => done("real", Nulls::Always),
1848 "stddev" | "stddev_pop" | "stddev_samp" | "variance" | "var_pop" | "var_samp" => done("real", Nulls::Always),
1850 _ => Fact::unknown(),
1851 };
1852 }
1853 let numbers = all_non_null && args.iter().all(|a| matches!(scalar_name(&a.ty), Some("integer" | "int8" | "real")));
1856 match name {
1857 "coalesce" | "ifnull" => Fact { ty: values_type(&n.args.iter().zip(reached(args)).collect::<Vec<_>>()), non_null: args.iter().any(|a| a.non_null) },
1860 "nullif" => Fact { ty: first.ty.clone(), non_null: false },
1861 "iif" | "if" => {
1864 let values = iif_values(args.len());
1865 let arms: Vec<(&Node, &Fact)> = values.iter().filter_map(|i| Some((n.args.get(*i)?, args.get(*i)?))).collect();
1866 Fact { ty: values_type(&arms), non_null: args.len() >= 3 && args.len() % 2 == 1 && arms.iter().all(|(_, a)| a.non_null) }
1867 }
1868 "min" | "max" => Fact { ty: values_type(&n.args.iter().zip(args).collect::<Vec<_>>()), non_null: all_non_null },
1869 "abs" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::IfArgs),
1871 "round" => done("real", Nulls::IfArgs),
1872 "length" | "instr" | "json_valid" | "octet_length" => done("integer", Nulls::IfArgs),
1873 "json_array_length" => done("integer", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
1875 "json_type" => done("text", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
1876 "json_remove" => done("text", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
1878 "unicode" => done("integer", Nulls::Always),
1880 "like" | "glob" | "regexp" | "match" | "likely" | "unlikely" | "likelihood" => {
1881 if matches!(name, "likely" | "unlikely" | "likelihood") { first.clone() } else { done("integer", Nulls::IfArgs) }
1882 }
1883 "concat" => done("text", Nulls::Never),
1886 "concat_ws" => Fact::new("text", first.non_null),
1887 "substr" | "substring" => {
1890 let blob = matches!(scalar_name(&first.ty), Some("blob"));
1891 let any = matches!(first.ty, Ty::Unknown) && n.args.first().is_some_and(|a| a.op != "variable");
1892 let ty = if blob { first.ty.clone() } else if any { Ty::Unknown } else { Ty::Scalar { name: "text".into() } };
1893 Fact { ty, non_null: all_non_null && !blob && !any }
1894 }
1895 "printf" | "format" => Fact::new("text", n.args.first().and_then(literal_text).is_some_and(printf_writes)),
1898 "upper" | "lower" | "trim" | "ltrim" | "rtrim" | "replace" | "json" | "json_patch" | "json_pretty" => done("text", Nulls::IfArgs),
1899 "char" | "json_array" | "json_object" | "json_quote" => done("text", Nulls::Never),
1901 "json_insert" | "json_replace" | "json_set" => Fact::new("text", first.non_null),
1902 "jsonb" => done("blob", Nulls::IfArgs),
1903 "date" | "time" | "datetime" => Fact::new("text", current_time(&n.args)),
1907 "julianday" => Fact::new("real", current_time(&n.args)),
1908 "unixepoch" => {
1910 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")));
1911 Fact::new(if whole { "integer" } else { "real" }, current_time(&n.args))
1912 }
1913 "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())),
1915 "timediff" => Fact::new("text", n.args.len() == 2 && current_time(&n.args[..1]) && current_time(&n.args[1..])),
1916 "hex" | "quote" | "typeof" => done("text", Nulls::Never),
1918 "soundex" => done("text", Nulls::IfArgs),
1921 "sqlite_version" | "sqlite_source_id" | "current_date" | "current_time" | "current_timestamp" => done("text", Nulls::Never),
1922 "random" | "last_insert_rowid" | "changes" | "total_changes" => done("integer", Nulls::Never),
1923 "randomblob" | "zeroblob" => done("blob", Nulls::IfArgs),
1924 "json_extract" | "jsonb_extract" | "->" | "->>" => Fact::unknown(),
1925 "atan" | "atan2" | "asinh" | "sinh" | "cosh" | "tanh" | "exp" | "degrees" | "radians" | "ceil" | "ceiling" | "floor" | "trunc" => Fact::new("real", numbers),
1928 "sign" => Fact::new("integer", numbers),
1929 "acos" | "acosh" | "asin" | "atanh" | "cos" | "sin" | "tan" | "ln" | "log" | "log10" | "log2" | "mod" | "pow" | "power" | "sqrt" => done("real", Nulls::Always),
1932 "pi" => done("real", Nulls::Never),
1933 "bm25" => done("real", if n.args.len() == 1 { Nulls::Never } else { Nulls::Always }),
1941 "highlight" | "snippet" => done("text", Nulls::Always),
1942 "offsets" => done("text", Nulls::Never),
1943 "matchinfo" => done("blob", Nulls::Never),
1944 "vector" | "vector32" | "vector64" | "vector1bit" | "vector8" | "vector16" | "vectorb16" => done("blob", Nulls::Never),
1948 "vector_extract" => done("text", Nulls::Never),
1949 "vector_distance_cos" | "vector_distance_l2" => done("real", Nulls::Always),
1952 "libsql_vector_idx" => Fact { ty: Ty::Unknown, non_null: first.non_null },
1955 "uuid4" | "gen_random_uuid" | "uuid7" => done("text", Nulls::Never),
1959 "uuid_str" => done("text", Nulls::Always),
1960 "uuid_blob" => done("blob", Nulls::Always),
1961 "uuid7_timestamp_ms" => done("integer", Nulls::Always),
1962 "md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" => done("blob", Nulls::IfArgs),
1965 "encode" => Fact::new("text", first.non_null),
1966 "decode" => Fact::new("blob", first.non_null),
1967 "levenshtein" | "dlevenshtein" | "edit_distance" | "osa_distance" | "hamming" => done("integer", Nulls::Never),
1970 "jaro_winkler" => done("real", Nulls::Never),
1971 "caverphone" | "phonetic_hash" | "rsoundex" => done("text", Nulls::IfArgs),
1972 "translit" => done("text", Nulls::Never),
1973 "script_code" => done("integer", Nulls::Never),
1974 "bit_length" | "char_length" | "character_length" | "text_size" | "text_bitsize" | "text_length" => done("integer", Nulls::IfArgs),
1976 "strpos" | "text_index" | "text_last_index" | "text_count" => done("integer", Nulls::IfArgs),
1977 "starts_with" | "text_has_prefix" | "text_has_suffix" | "text_contains" | "text_like" => done("integer", Nulls::IfArgs),
1978 "btrim" | "left" | "right" | "lpad" | "rpad" | "repeat" | "reverse" | "split_part" | "translate" | "text_trim" | "text_ltrim" | "text_rtrim" | "text_left" | "text_right"
1979 | "text_lpad" | "text_rpad" | "text_repeat" | "text_reverse" | "text_split" | "text_translate" | "text_title" | "text_casefold" | "text_lower" | "text_upper"
1980 | "text_replace" | "text_slice" | "text_substring" => done("text", Nulls::IfArgs),
1981 "text_concat" => done("text", Nulls::Never),
1983 "text_join" => Fact::new("text", first.non_null),
1984 "regexp_like" => done("integer", Nulls::Never),
1986 "regexp_substr" | "regexp_capture" => done("text", Nulls::Always),
1987 "regexp_replace" => Fact { ty: if scalar_name(&first.ty) == Some("text") { first.ty.clone() } else { Ty::Unknown }, non_null: first.non_null },
1990 _ => Fact::unknown(),
1991 }
1992 }
1993
1994 fn built_text(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
2009 match self.builtin_name(n)? {
2010 "json_object" | "json_array" | "json_group_array" | "json_group_object" => self.shape(n, scope),
2011 "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)),
2012 _ => None,
2013 }
2014 }
2015
2016 fn subquery_shape(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
2020 if n.op != "select" {
2021 return None;
2022 }
2023 let sub = n.select.as_deref()?;
2024 if sub.columns.len() != 1 || sub.prior.is_some() || !sub.rows.is_empty() || sub.values {
2025 return None;
2026 }
2027 let col = sub.columns.first()?;
2028 self.within(sub, scope, |inner| self.built_text(&col.expr, inner))
2029 }
2030
2031 fn builtin_name<'n>(&self, n: &'n Node) -> Option<&'n str> {
2034 let name = n.name.as_deref().filter(|_| n.op == "function")?;
2035 (n.agg || n.window || self.extras.function(name, n.args.len()).is_none()).then_some(name)
2036 }
2037
2038 fn shape(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
2042 let key = n as *const Node as usize;
2043 if let Some(found) = self.shapes.borrow().get(&key) {
2044 return found.clone();
2045 }
2046 let shape = self.aggregated(n, || self.shape_here(n, scope));
2047 self.shapes.borrow_mut().insert(key, shape.clone());
2048 shape
2049 }
2050
2051 fn shape_here(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
2052 let name = self.builtin_name(n)?;
2053 let aggregate = n.agg || n.window;
2054 let value = |x: &Node| {
2056 let f = self.json_fact(x, scope);
2057 let nullable = nullable_in_json(&f);
2058 (f.ty, nullable)
2059 };
2060 match name {
2061 "json_object" | "jsonb_object" if !aggregate => {
2062 if n.args.len() % 2 != 0 {
2064 return Some(Ty::Json { schema: None });
2065 }
2066 let mut fields: Vec<TyField> = Vec::new();
2067 let mut dynamic = false;
2068 for pair in n.args.chunks(2) {
2069 let (ty, nullable) = value(&pair[1]);
2070 match literal_text(&pair[0]) {
2071 Some(key) => match fields.iter_mut().find(|f| f.name == key) {
2073 Some(f) => {
2074 f.ty = ty;
2075 f.nullable = nullable;
2076 }
2077 None => fields.push(TyField { name: key.to_string(), ty, nullable }),
2078 },
2079 None => {
2080 dynamic = true;
2081 fields.push(TyField { name: String::new(), ty, nullable });
2082 }
2083 }
2084 }
2085 if dynamic {
2087 return Some(record(fields.iter().map(|f| value_schema(&f.ty, f.nullable)).collect()));
2088 }
2089 Some(Ty::Object { fields })
2090 }
2091 "json_array" | "jsonb_array" if !aggregate => {
2093 let items: Vec<serde_json::Value> = n.args.iter().map(|x| {
2094 let (ty, nullable) = value(x);
2095 value_schema(&ty, nullable)
2096 }).collect();
2097 let mut schema = serde_json::json!({"type": "array", "items": false});
2098 if !items.is_empty() {
2099 schema["minItems"] = serde_json::json!(items.len());
2100 schema["prefixItems"] = serde_json::Value::Array(items);
2101 }
2102 Some(Ty::Json { schema: Some(schema) })
2103 }
2104 "json_group_array" | "jsonb_group_array" if aggregate && n.args.len() == 1 => {
2106 let (ty, nullable) = value(&n.args[0]);
2107 Some(Ty::List { of: Box::new(ty), nullable_items: nullable })
2108 }
2109 "json_group_object" | "jsonb_group_object" if aggregate && n.args.len() == 2 => {
2111 let (ty, nullable) = value(&n.args[1]);
2112 Some(record(vec![value_schema(&ty, nullable)]))
2113 }
2114 "json" | "jsonb" if !aggregate && n.args.len() == 1 => self.shape(&n.args[0], scope).or_else(|| self.subquery_shape(&n.args[0], scope)),
2115 _ => None,
2116 }
2117 }
2118
2119 fn json_fact(&self, n: &Node, scope: &ScopeStack) -> JsonFact {
2124 let plain = || {
2125 let f = self.type_of(n, scope);
2126 JsonFact { ty: in_json(&f.ty), non_null: f.non_null, carry: Carry::No }
2127 };
2128 let any = JsonFact { ty: Ty::Unknown, non_null: false, carry: Carry::Maybe };
2129 match n.op.as_str() {
2130 "function" => {
2131 let Some(name) = self.builtin_name(n) else { return any };
2133 if n.over && is_json_result(name) {
2136 return any;
2137 }
2138 if self.windowed_aggregate(n) && self.carry(n, scope) != Carry::No {
2140 return any;
2141 }
2142 if let Some(ty) = self.shape(n, scope) {
2143 let non_null = self.built_non_null(n, scope);
2144 return JsonFact { ty, non_null, carry: Carry::Yes };
2145 }
2146 let first = n.args.first().into_iter();
2147 let non_null = || self.type_of(n, scope).non_null;
2148 match name {
2149 "coalesce" | "ifnull" => self.json_arms(n.args.iter(), true, scope).map(|f| JsonFact { non_null: f.non_null, ..f }).unwrap_or_else(plain),
2150 "nullif" => self.json_arms(first, false, scope).map(|f| JsonFact { non_null: false, ..f }).unwrap_or_else(plain),
2151 "likely" | "unlikely" | "likelihood" => self.json_arms(first, false, scope).unwrap_or_else(plain),
2152 "iif" | "if" => {
2153 let arms = iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i));
2154 self.json_arms(arms, false, scope).map(|f| JsonFact { non_null: non_null(), ..f }).unwrap_or_else(plain)
2155 }
2156 "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),
2158 _ if is_json_result(name) => JsonFact { ty: Ty::Json { schema: None }, non_null: non_null(), carry: Carry::Yes },
2159 _ if PASSING.contains(&name) => {
2162 if n.args.iter().all(|a| self.carry(a, scope) == Carry::No) { plain() } else { any }
2163 }
2164 _ if PLAIN.contains(&name) => plain(),
2165 _ => any,
2166 }
2167 }
2168 "select" => if self.carry(n, scope) == Carry::No { plain() } else { any },
2171 "collate" | "pos" => n.left.as_deref().map_or(any, |l| self.json_fact(l, scope)),
2172 "case" => {
2173 let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
2174 let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
2175 match self.json_arms(results.chain(otherwise), false, scope) {
2176 Some(f) => JsonFact { non_null: self.type_of(n, scope).non_null, ..f },
2177 None => plain(),
2178 }
2179 }
2180 "cast" | "column" => if self.carry(n, scope) == Carry::No { plain() } else { any },
2182 _ => plain(),
2183 }
2184 }
2185
2186 fn json_arms<'n>(&self, arms: impl Iterator<Item = &'n Node>, coalesce: bool, scope: &ScopeStack) -> Option<JsonFact> {
2190 let mut facts: Vec<JsonFact> = Vec::new();
2191 for arm in arms.filter(|a| a.op != "null") {
2192 let f = self.json_fact(arm, scope);
2193 let last = coalesce && f.non_null;
2194 facts.push(f);
2195 if last {
2196 break;
2197 }
2198 }
2199 if facts.iter().all(|f| f.carry == Carry::No) {
2200 return None;
2201 }
2202 let non_null = facts.iter().any(|f| f.non_null);
2203 if !facts.iter().all(|f| f.carry == Carry::Yes) {
2204 return Some(JsonFact { ty: Ty::Unknown, non_null, carry: Carry::Maybe });
2205 }
2206 let types: Vec<&Ty> = facts.iter().map(|f| &f.ty).collect();
2207 let ty = if types.iter().all(|t| *t == types[0]) { types[0].clone() } else { same_json(&types).unwrap_or(Ty::Unknown) };
2208 Some(JsonFact { ty, non_null, carry: Carry::Yes })
2209 }
2210
2211 fn carry(&self, n: &Node, scope: &ScopeStack) -> Carry {
2213 match n.op.as_str() {
2214 "function" => {
2215 let Some(name) = self.builtin_name(n) else { return Carry::Maybe };
2216 let carry = match name {
2217 "coalesce" | "ifnull" => self.carries(n.args.iter(), scope),
2218 "nullif" | "likely" | "unlikely" | "likelihood" => self.carries(n.args.first().into_iter(), scope),
2219 "iif" | "if" => self.carries(iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i)), scope),
2220 "min" | "max" if n.args.len() == 1 && !n.window => self.carries(n.args.iter(), scope),
2221 _ if is_json_result(name) => if n.over { Carry::Maybe } else { Carry::Yes },
2222 _ if PASSING.contains(&name) => {
2223 if self.carries(n.args.iter(), scope) == Carry::No { Carry::No } else { Carry::Maybe }
2224 }
2225 _ if PLAIN.contains(&name) => Carry::No,
2226 _ => Carry::Maybe,
2227 };
2228 if carry != Carry::No && self.windowed_aggregate(n) { Carry::Maybe } else { carry }
2229 }
2230 "select" => {
2235 let Some(sub) = n.select.as_deref() else { return Carry::No };
2236 match self.select_carry(sub, 0, scope) {
2237 Carry::No => Carry::No,
2238 _ => Carry::Maybe,
2239 }
2240 }
2241 "collate" | "pos" => n.left.as_deref().map_or(Carry::No, |l| self.carry(l, scope)),
2242 "cast" => match n.left.as_deref().map_or(Carry::No, |l| self.carry(l, scope)) {
2243 Carry::No => Carry::No,
2244 _ => Carry::Maybe,
2245 },
2246 "case" => {
2247 let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
2248 let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
2249 self.carries(results.chain(otherwise), scope)
2250 }
2251 "column" => {
2255 for froms in scope.iter().rev() {
2256 if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
2257 if let Some(sub) = f.subquery.as_deref() {
2258 return if self.select_carry(sub, n.index.max(0) as usize, scope) == Carry::No { Carry::No } else { Carry::Maybe };
2259 }
2260 break;
2261 }
2262 }
2263 if n.subtype { Carry::Maybe } else { Carry::No }
2266 }
2267 _ => Carry::No,
2268 }
2269 }
2270
2271 fn select_carry(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> Carry {
2273 let mut carries = Vec::new();
2274 let mut s = Some(sel);
2275 while let Some(arm) = s {
2276 self.within(arm, scope, |inner| {
2277 for e in std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i))).flatten() {
2278 carries.push(self.carry(e, inner));
2279 }
2280 });
2281 s = arm.prior.as_deref();
2282 }
2283 combine(&carries)
2284 }
2285
2286 fn carries<'n>(&self, arms: impl Iterator<Item = &'n Node>, scope: &ScopeStack) -> Carry {
2288 let carries: Vec<Carry> = arms.filter(|a| a.op != "null").map(|a| self.carry(a, scope)).collect();
2289 combine(&carries)
2290 }
2291
2292 fn aggregated<T>(&self, n: &Node, f: impl FnOnce() -> T) -> T {
2295 if !(n.op == "function" && n.agg && !n.over) {
2296 return f();
2297 }
2298 let foreign = {
2301 let level = self.level.borrow();
2302 !n.window && !reads_cursor(n, &level.own)
2303 };
2304 {
2305 let mut level = self.level.borrow_mut();
2306 level.aggregating += 1;
2307 level.foreign += u32::from(foreign);
2308 }
2309 let out = f();
2310 let mut level = self.level.borrow_mut();
2311 level.aggregating -= 1;
2312 level.foreign -= u32::from(foreign);
2313 out
2314 }
2315
2316 fn windowed_aggregate(&self, n: &Node) -> bool {
2320 n.op == "function" && n.agg && !n.over && self.level.borrow().windowed
2321 }
2322
2323 fn level_within(&self, sel: &Sel) -> Level {
2326 let mut level = level_of(sel, self.extras);
2327 let outer = self.level.borrow();
2328 level.around = outer.around.clone();
2329 if outer.aggregating == 0 {
2330 level.around.extend(outer.lone.iter().copied());
2331 }
2332 level
2333 }
2334
2335 fn within<T>(&self, sel: &Sel, scope: &ScopeStack, f: impl FnOnce(&ScopeStack) -> T) -> T {
2337 let mut inner = scope.clone();
2338 inner.push(&sel.from);
2339 let outer = self.level.replace(self.level_within(sel));
2340 let out = f(&inner);
2341 self.level.replace(outer);
2342 out
2343 }
2344
2345 fn written_non_null(&self) -> HashSet<String> {
2356 let t = self.tree;
2357 let (Some(dml), Some(_)) = (&t.dml, &t.returning) else { return HashSet::new() };
2358 let events = match dml.kind.as_str() {
2359 "update" => TRIGGER_ROW_UPDATE,
2360 _ if dml.upserts.iter().any(|u| u.do_update) => TRIGGER_ROW_INSERT | TRIGGER_ROW_UPDATE,
2361 _ => TRIGGER_ROW_INSERT,
2362 };
2363 if self.skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & events != 0) {
2364 return HashSet::new();
2365 }
2366 let scope: ScopeStack = Vec::new();
2367 let non_null = |known: HashMap<String, bool>| -> HashSet<String> { known.into_iter().filter(|(_, n)| *n).map(|(c, _)| c).collect() };
2368 let assigned = |items: &[tree::SetItem]| -> HashSet<String> {
2369 let mut known: HashMap<String, bool> = HashMap::new();
2370 for item in items {
2371 let Some(column) = &item.column else { continue };
2372 *known.entry(column.to_ascii_lowercase()).or_insert(true) &= self.type_of(&item.expr, &scope).non_null;
2373 }
2374 non_null(known)
2375 };
2376 match dml.kind.as_str() {
2377 "update" => assigned(&dml.set),
2378 "insert" | "upsert" => {
2379 let mut known: HashMap<String, bool> = HashMap::new();
2380 for (i, column) in dml.columns.iter().enumerate() {
2381 let Some(column) = column else { continue };
2382 let fact = match (&dml.values, &t.statement) {
2383 (Some(values), _) => values.get(i).map(|v| self.type_of(v, &scope)),
2384 (None, Some(sel)) => Some(self.select_column(sel, i, &scope)),
2385 (None, None) => None,
2386 };
2387 *known.entry(column.to_ascii_lowercase()).or_insert(true) &= fact.is_some_and(|f| f.non_null);
2388 }
2389 let mut written = non_null(known);
2390 for upsert in dml.upserts.iter().filter(|u| u.do_update) {
2391 let updated = assigned(&upsert.set);
2392 written.retain(|c| updated.contains(c));
2393 }
2394 written
2395 }
2396 _ => HashSet::new(),
2397 }
2398 }
2399
2400 fn bare_nullable(&self) -> HashSet<String> {
2404 let t = self.tree;
2405 let Some(dml) = &t.dml else { return HashSet::new() };
2406 let mut fills: HashMap<String, bool> = HashMap::new();
2407 let mut fill = |v: &Node, column: Option<&str>| {
2408 let (Some(name), Some(column)) = (v.name.as_ref().filter(|_| v.op == "variable"), column) else { return };
2409 let Some(target) = self.table_column(&dml.table, column) else { return };
2410 let refuses = target.non_null || self.checked_not_null(&dml.table, column);
2411 *fills.entry(name.clone()).or_insert(true) &= !refuses;
2412 };
2413 if let (Some(sel), "insert" | "upsert") = (&t.statement, dml.kind.as_str()) {
2414 if sel.prior.is_none() {
2415 for (i, v) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
2416 fill(v, dml.columns.get(i).and_then(|c| c.as_deref()));
2417 }
2418 }
2419 }
2420 for (i, v) in dml.values.iter().flatten().enumerate() {
2421 fill(v, dml.columns.get(i).and_then(|c| c.as_deref()));
2422 }
2423 for item in dml.set.iter().chain(dml.upserts.iter().flat_map(|u| u.set.iter())) {
2424 fill(&item.expr, item.column.as_deref());
2425 }
2426 fills.into_iter().filter(|(_, nullable)| *nullable).map(|(name, _)| name).collect()
2427 }
2428
2429 fn params(&self, lexed: &Lexed) -> (Vec<Param>, Vec<(String, String, String)>) {
2435 let mut found: Vec<(String, Fact)> = Vec::new();
2436 let t = self.tree;
2437 let checked = |c: Option<&str>| t.dml.as_ref().zip(c).is_some_and(|(dml, c)| self.checked_not_null(&dml.table, c));
2438 let mut fills: HashMap<String, bool> = HashMap::new();
2443 let mut refused: Vec<(String, String, String)> = Vec::new();
2444 let mut fill = |v: &Node, target: &Option<Fact>, column: Option<&str>| {
2445 let Some(target) = target else { return };
2446 let refuses = target.non_null || checked(column);
2447 let bare = v.op == "variable";
2448 let Some(name) = (if bare { v.name.as_ref() } else { cast_variable(v, self.extras) }) else { return };
2449 if bare {
2450 *fills.entry(name.clone()).or_insert(true) &= !refuses;
2451 }
2452 if let (true, true, Some(column), Some(dml)) = (refuses, self.nullable_params.contains(name), column, t.dml.as_ref()) {
2453 refused.push((name.clone(), dml.table.clone(), column.to_string()));
2454 }
2455 };
2456 if let Some(sel) = &t.statement {
2457 let targets: Vec<Option<Fact>> = match &t.dml {
2458 Some(dml) if dml.kind == "insert" => dml.columns.iter().map(|c| c.as_deref().and_then(|c| self.table_column(&dml.table, c))).collect(),
2461 _ => Vec::new(),
2462 };
2463 if sel.prior.is_none() {
2466 for (i, v) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
2467 if let Some(target) = targets.get(i) {
2468 fill(v, target, t.dml.as_ref().and_then(|d| d.columns.get(i)).and_then(|c| c.as_deref()));
2469 }
2470 }
2471 }
2472 self.walk_select(sel, &Vec::new(), &targets, &mut found);
2473 }
2474 if let Some(dml) = &t.dml {
2475 let scope: ScopeStack = Vec::new();
2476 if let Some(values) = &dml.values {
2477 for (i, v) in values.iter().enumerate() {
2478 let target = dml.columns.get(i).and_then(|c| c.as_deref()).and_then(|c| self.table_column(&dml.table, c));
2479 fill(v, &target, dml.columns.get(i).and_then(|c| c.as_deref()));
2480 self.walk(v, Ctx::Typed(target), &scope, &mut found);
2481 }
2482 }
2483 for item in dml.set.iter().chain(dml.upserts.iter().flat_map(|u| u.set.iter())) {
2484 let target = item.column.as_deref().and_then(|c| self.table_column(&dml.table, c));
2485 fill(&item.expr, &target, item.column.as_deref());
2486 self.walk(&item.expr, Ctx::Typed(target), &scope, &mut found);
2487 }
2488 if let Some(w) = &dml.where_ {
2489 self.walk(w, Ctx::Bool, &scope, &mut found);
2490 }
2491 for w in dml.upserts.iter().filter_map(|u| u.where_.as_ref()) {
2492 self.walk(w, Ctx::Bool, &scope, &mut found);
2493 }
2494 }
2495 if let Some(returning) = &t.returning {
2496 for c in returning {
2497 self.walk(&c.expr, Ctx::None, &Vec::new(), &mut found);
2498 }
2499 }
2500 let mut typed: HashMap<&str, &Fact> = HashMap::new();
2503 for (name, fact) in found.iter().filter(|(_, f)| !matches!(f.ty, Ty::Unknown)) {
2504 typed.entry(name.as_str()).or_insert(fact);
2505 }
2506 let params = lexed
2507 .params
2508 .iter()
2509 .enumerate()
2510 .map(|(k, name)| {
2511 let numbered = format!("?{}", k + 1);
2512 let fact = typed.get(numbered.as_str()).map(|f| (*f).clone()).unwrap_or_else(Fact::unknown);
2513 let fact = Fact { ty: textual(&fact.ty), ..fact };
2515 let nullable = fills.get(&numbered).copied().unwrap_or(false) || self.nullable_params.contains(&numbered);
2516 Param { nullable, ..Param::new(name.clone(), descriptor(&fact.ty, None, false, false)) }
2517 })
2518 .collect();
2519 (params, refused)
2520 }
2521
2522 fn checked_not_null(&self, table: &str, column: &str) -> bool {
2526 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)
2527 }
2528
2529 fn table_column(&self, table: &str, column: &str) -> Option<Fact> {
2530 let info = self.tree.tables.get(table)?;
2531 let col = info.columns.iter().find(|c| c.name.eq_ignore_ascii_case(column))?;
2532 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)) })
2533 }
2534
2535 fn walk_select(&self, sel: &Sel, scope: &ScopeStack, targets: &[Option<Fact>], found: &mut Vec<(String, Fact)>) {
2536 let compound: Vec<Option<Fact>>;
2539 let targets = if targets.is_empty() && (sel.prior.is_some() || !sel.rows.is_empty()) {
2540 compound = (0..sel.columns.len())
2541 .map(|i| {
2542 let ty = self.select_column(sel, i, scope).ty;
2543 (!matches!(ty, Ty::Unknown)).then_some(Fact { ty, non_null: true })
2544 })
2545 .collect();
2546 compound.as_slice()
2547 } else {
2548 targets
2549 };
2550 let mut inner = scope.clone();
2551 inner.push(&sel.from);
2552 for (i, e) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
2553 self.walk(e, Ctx::Typed(targets.get(i).cloned().flatten()), &inner, found);
2554 }
2555 for f in &sel.from {
2556 if let Some(sub) = &f.subquery {
2557 self.walk_select(sub, &inner, &[], found);
2558 }
2559 if let Some(on) = &f.on {
2560 self.walk(on, Ctx::Bool, &inner, found);
2561 }
2562 let json = f.tab_func && matches!(f.table.as_deref(), Some("json_each" | "json_tree"));
2566 let top_k = f.tab_func && f.table.as_deref() == Some("vector_top_k");
2567 let series = f.tab_func && matches!(f.table.as_deref(), Some("generate_series" | "stats_seq"));
2569 for (i, a) in f.args.iter().enumerate() {
2570 let ctx = match i {
2571 0 | 1 if json || top_k => Ctx::Typed(Some(Fact::new("text", true))),
2572 2 if top_k => Ctx::Typed(Some(Fact::new("integer", true))),
2573 _ if series => Ctx::Typed(Some(Fact::new("integer", true))),
2574 _ => Ctx::None,
2575 };
2576 self.walk(a, ctx, &inner, found);
2577 }
2578 }
2579 if let Some(w) = &sel.where_ {
2580 self.walk(w, Ctx::Bool, &inner, found);
2581 }
2582 for g in &sel.group_by {
2583 self.walk(g, Ctx::None, &inner, found);
2584 }
2585 if let Some(h) = &sel.having {
2586 self.walk(h, Ctx::Bool, &inner, found);
2587 }
2588 for o in &sel.order_by {
2589 self.walk(o, Ctx::None, &inner, found);
2590 }
2591 for l in sel.limit.iter().chain(sel.offset.iter()) {
2592 self.walk(l, Ctx::Typed(Some(Fact::new("integer", true))), &inner, found);
2593 }
2594 if let Some(prior) = &sel.prior {
2595 self.walk_select(prior, scope, targets, found);
2596 }
2597 }
2598
2599 fn walk(&self, n: &Node, ctx: Ctx, scope: &ScopeStack, found: &mut Vec<(String, Fact)>) {
2601 if n.op == "variable" {
2602 let fact = match ctx {
2603 Ctx::Typed(Some(f)) => f,
2604 Ctx::Typed(None) | Ctx::Row(_) | Ctx::None => Fact::unknown(),
2605 Ctx::Bool => Fact::new("integer", false),
2606 };
2607 found.push((n.name.clone().unwrap_or_default(), fact));
2608 return;
2609 }
2610 let sibling = |other: &Option<Box<Node>>| other.as_deref().map(|o| self.type_of(o, scope));
2611 let case_results: std::cell::OnceCell<Ty> = std::cell::OnceCell::new();
2612 let child_ctx = |slot: Position| -> Ctx {
2613 match n.op.as_str() {
2614 "=" | "!=" | "<" | "<=" | ">" | ">=" | "is" | "is not" => {
2615 let (this, other) = match slot {
2616 Position::Left => (&n.left, &n.right),
2617 Position::Right => (&n.right, &n.left),
2618 _ => return Ctx::None,
2619 };
2620 match (this.as_deref(), other.as_deref().and_then(|o| self.row(o, scope))) {
2624 (Some(t), Some(row)) if matches!(t.op.as_str(), "vector" | "select") => Ctx::Row(row),
2625 _ => Ctx::Typed(sibling(other)),
2626 }
2627 }
2628 "in" => match slot {
2629 Position::Left if is_vector(&n.left) => n.select.as_deref().map_or(Ctx::None, |s| Ctx::Row(self.select_columns(s, scope))),
2632 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)))),
2633 Position::List(_) => Ctx::Typed(sibling(&n.left)),
2634 _ => Ctx::None,
2635 },
2636 "between" => match slot {
2637 Position::Left if is_vector(&n.left) => Ctx::Row(self.rows(&n.list.iter().collect::<Vec<_>>(), scope)),
2638 Position::Left => Ctx::Typed(n.list.first().map(|x| self.type_of(x, scope))),
2639 Position::List(_) => match n.left.as_deref().and_then(|l| self.row(l, scope)) {
2640 Some(row) if is_vector(&n.left) => Ctx::Row(row),
2641 _ => Ctx::Typed(sibling(&n.left)),
2642 },
2643 _ => Ctx::None,
2644 },
2645 "vector" => match (slot, &ctx) {
2647 (Position::List(i), Ctx::Row(row)) => Ctx::Typed(row.get(i).cloned().flatten()),
2648 _ => Ctx::None,
2649 },
2650 "select_column" => match (slot, &ctx) {
2652 (Position::Left, Ctx::Typed(Some(f))) => {
2653 let mut row = vec![None; n.index.max(0) as usize + 1];
2654 row[n.index.max(0) as usize] = Some(f.clone());
2655 Ctx::Row(row)
2656 }
2657 _ => Ctx::None,
2658 },
2659 "cast" => Ctx::Typed(Some(Fact::new(n.affinity.as_deref().unwrap_or("none"), true))),
2660 "+" | "-" | "*" | "/" | "%" => {
2661 let other = match slot {
2662 Position::Left => sibling(&n.right),
2663 _ => sibling(&n.left),
2664 };
2665 Ctx::Typed(Some(match other {
2666 Some(f) if is_numeric(&f.ty) => f,
2667 _ => Fact::new("real", true),
2668 }))
2669 }
2670 "||" => Ctx::Typed(Some(Fact::new("text", true))),
2671 "neg" | "~" | "&" | "|" | "<<" | ">>" => Ctx::Typed(Some(Fact::new("real", true))),
2672 "pos" | "collate" => ctx.clone(),
2675 "and" | "or" | "not" => Ctx::Bool,
2676 "case" => match slot {
2677 Position::List(i) if i % 2 == 0 && i + 1 < n.list.len() => match &n.left {
2681 Some(base) if base.op == "vector" => self.row(base, scope).map_or(Ctx::None, Ctx::Row),
2682 Some(base) => Ctx::Typed(Some(self.type_of(base, scope))),
2683 None => Ctx::Bool,
2684 },
2685 Position::List(_) => match case_results.get_or_init(|| {
2687 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();
2688 shared(&others.iter().collect::<Vec<_>>())
2689 }) {
2690 Ty::Unknown => outer_type(&ctx),
2691 ty => Ctx::Typed(Some(Fact { ty: ty.clone(), non_null: true })),
2692 },
2693 Position::Left if is_vector(&n.left) => {
2696 let values: Vec<&Node> = n.list.iter().enumerate().filter(|(j, _)| j % 2 == 0 && j + 1 < n.list.len()).map(|(_, x)| x).collect();
2697 Ctx::Row(self.rows(&values, scope))
2698 }
2699 Position::Left => {
2701 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();
2702 let refs: Vec<&Fact> = values.iter().collect();
2703 match shared(&refs) {
2704 Ty::Unknown => Ctx::None,
2705 ty => Ctx::Typed(Some(Fact { ty, non_null: true })),
2706 }
2707 }
2708 _ => Ctx::None,
2709 },
2710 "function" => match (slot, self.argument(n, i_of(slot), scope)) {
2713 (Position::Arg(_), Ctx::Typed(None) | Ctx::None) if matches!(n.name.as_deref(), Some("coalesce" | "ifnull" | "nullif" | "min" | "max")) && !n.agg => outer_type(&ctx),
2714 (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),
2715 (Position::Arg(_), c) => c,
2716 _ => Ctx::None,
2717 },
2718 _ => Ctx::None,
2719 }
2720 };
2721 if let Some(l) = &n.left {
2722 self.walk(l, child_ctx(Position::Left), scope, found);
2723 }
2724 if let Some(r) = &n.right {
2725 self.walk(r, child_ctx(Position::Right), scope, found);
2726 }
2727 for (i, x) in n.list.iter().enumerate() {
2728 self.walk(x, child_ctx(Position::List(i)), scope, found);
2729 }
2730 for (i, x) in n.args.iter().enumerate() {
2731 self.walk(x, child_ctx(Position::Arg(i)), scope, found);
2732 }
2733 if let Some(s) = &n.select {
2734 let targets: Vec<Option<Fact>> = match (n.op.as_str(), &ctx) {
2737 ("select", Ctx::Row(row)) => row.clone(),
2738 ("select", Ctx::Typed(Some(f))) => vec![Some(f.clone())],
2739 ("in", _) => match n.left.as_deref() {
2740 Some(l) if l.op == "vector" => self.row(l, scope).unwrap_or_default(),
2741 Some(l) => vec![Some(self.type_of(l, scope))],
2742 None => Vec::new(),
2743 },
2744 _ => Vec::new(),
2745 };
2746 self.walk_select(s, scope, &targets, found);
2747 }
2748 }
2749
2750 fn row(&self, n: &Node, scope: &ScopeStack) -> Option<Vec<Option<Fact>>> {
2752 match n.op.as_str() {
2753 "vector" => Some(n.list.iter().map(|x| Some(self.type_of(x, scope))).collect()),
2754 "select" => n.select.as_deref().map(|s| self.select_columns(s, scope)),
2755 _ => None,
2756 }
2757 }
2758
2759 fn select_columns(&self, sel: &Sel, scope: &ScopeStack) -> Vec<Option<Fact>> {
2760 (0..sel.columns.len()).map(|i| Some(self.select_column(sel, i, scope))).collect()
2761 }
2762
2763 fn rows(&self, values: &[&Node], scope: &ScopeStack) -> Vec<Option<Fact>> {
2766 let mut out: Vec<Option<Fact>> = Vec::new();
2767 for row in values.iter().filter_map(|v| self.row(v, scope)) {
2768 for (i, f) in row.into_iter().enumerate() {
2769 if i >= out.len() {
2770 out.push(None);
2771 }
2772 if out[i].as_ref().is_none_or(|known| matches!(known.ty, Ty::Unknown)) {
2773 out[i] = f;
2774 }
2775 }
2776 }
2777 out
2778 }
2779
2780 fn argument(&self, n: &Node, i: usize, scope: &ScopeStack) -> Ctx {
2782 let name = n.name.as_deref().unwrap_or("");
2783 if !n.agg && !n.window && self.extras.function(name, n.args.len()).is_some() {
2784 return Ctx::None;
2785 }
2786 let name = sqlean_alias(name);
2787 let text = || Ctx::Typed(Some(Fact::new("text", true)));
2788 let integer = || Ctx::Typed(Some(Fact::new("integer", true)));
2789 let real = || Ctx::Typed(Some(Fact::new("real", true)));
2790 let others = || {
2791 let facts: Vec<Fact> = n.args.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, a)| self.type_of(a, scope)).collect();
2792 let refs: Vec<&Fact> = facts.iter().collect();
2793 let ty = shared(&refs);
2794 Ctx::Typed(if matches!(ty, Ty::Unknown) { None } else { Some(Fact { ty, non_null: true }) })
2795 };
2796 match name {
2797 "like" | "glob" | "regexp" | "match" | "upper" | "lower" | "trim" | "ltrim" | "rtrim" | "length" | "hex" | "unicode" | "quote" | "instr" | "replace" | "soundex"
2798 | "printf" | "format" | "concat" | "concat_ws" | "date" | "time" | "datetime" | "strftime" | "julianday" | "unixepoch" | "timediff" | "json"
2799 | "json_extract" | "json_type" | "json_valid" | "json_array_length" | "json_quote" | "json_pretty" | "json_insert" | "json_replace" | "json_set"
2800 | "json_remove" | "json_patch" | "->" | "->>" => text(),
2801 "substr" | "substring" => {
2802 if i == 0 { text() } else { integer() }
2803 }
2804 "zeroblob" | "randomblob" | "char" => integer(),
2805 "abs" | "round" | "acos" | "acosh" | "asin" | "asinh" | "atan" | "atan2" | "atanh" | "ceil" | "ceiling" | "cos" | "cosh" | "degrees" | "exp"
2806 | "floor" | "ln" | "log" | "log10" | "log2" | "mod" | "pow" | "power" | "radians" | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc" => real(),
2807 "coalesce" | "ifnull" | "nullif" | "min" | "max" => others(),
2808 "lag" | "lead" if n.args.len() >= 3 && (i == 0 || i == 2) => {
2811 let other = self.type_of(&n.args[2 - i], scope);
2812 Ctx::Typed(if matches!(other.ty, Ty::Unknown) { None } else { Some(Fact { ty: other.ty, non_null: true }) })
2813 }
2814 "iif" | "if" => {
2816 let values = iif_values(n.args.len());
2817 if !values.contains(&i) {
2818 Ctx::Bool
2819 } else {
2820 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();
2821 let ty = shared(&facts.iter().collect::<Vec<_>>());
2822 Ctx::Typed(if matches!(ty, Ty::Unknown) { None } else { Some(Fact { ty, non_null: true }) })
2823 }
2824 }
2825 "sum" | "avg" | "total" => real(),
2826 "highlight" if i == 1 => integer(),
2829 "highlight" if i > 1 => text(),
2830 "bm25" if i > 0 => real(),
2831 "vector" | "vector32" | "vector64" | "vector1bit" | "vector8" | "vector16" | "vectorb16" | "vector_extract" | "vector_distance_cos" | "vector_distance_l2" => text(),
2833 _ => match name {
2835 "left" | "right" | "text_left" | "text_right" | "repeat" | "text_repeat" | "lpad" | "rpad" | "text_lpad" | "text_rpad" if i == 1 => integer(),
2838 "split_part" | "text_split" | "regexp_capture" if i == 2 => integer(),
2839 "text_slice" | "text_substring" if i > 0 => integer(),
2840 "text_replace" if i == 3 => integer(),
2841 "encode" if i == 0 => Ctx::None,
2843 "uuid_str" | "uuid_blob" | "uuid7_timestamp_ms" | "md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" | "encode" | "decode" | "levenshtein" | "dlevenshtein"
2844 | "edit_distance" | "osa_distance" | "hamming" | "jaro_winkler" | "caverphone" | "phonetic_hash" | "rsoundex" | "translit" | "script_code" | "bit_length"
2845 | "char_length" | "character_length" | "btrim" | "left" | "right" | "lpad" | "rpad" | "repeat" | "reverse" | "split_part" | "starts_with" | "strpos" | "translate"
2846 | "regexp_like" | "regexp_substr" | "regexp_capture" | "regexp_replace" => text(),
2847 t if t.starts_with("text_") => text(),
2848 "median" | "percentile" | "percentile_25" | "percentile_75" | "percentile_90" | "percentile_95" | "percentile_99" | "stddev" | "stddev_pop" | "stddev_samp" | "variance"
2850 | "var_pop" | "var_samp" => real(),
2851 _ => Ctx::None,
2852 },
2853 }
2854 }
2855
2856 fn cardinality(&self) -> (Cardinality, Option<String>) {
2859 let t = self.tree;
2860 if let Some(dml) = &t.dml {
2861 if t.returning.is_none() {
2862 return (Cardinality::None, None);
2863 }
2864 return match dml.kind.as_str() {
2865 "insert" => {
2866 if dml.rows == 1 {
2867 let triggered = |events: i32| self.skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & events != 0);
2868 let declared_ignore = dml.on_error == "default" && self.tree.tables.get(&dml.table).is_some_and(|t| t.ignores);
2870 let can_skip = dml.on_error == "ignore"
2871 || declared_ignore
2872 || dml.upserts.iter().any(|u| !u.do_update || u.where_.is_some() || triggered(TRIGGER_ROW_UPDATE))
2873 || triggered(TRIGGER_ROW_INSERT);
2874 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) }
2875 } else if dml.rows > 1 {
2876 (Cardinality::Many, Some(format!("a VALUES list of {} rows returns {} rows", dml.rows, dml.rows)))
2877 } else {
2878 (Cardinality::Many, Some("an INSERT ... SELECT returns a row per row it reads".into()))
2879 }
2880 }
2881 _ => {
2882 match self.pinned_by_name(&dml.table, dml.where_.as_ref()) {
2884 Ok(()) => (Cardinality::AtMostOne, None),
2885 Err(why) => (Cardinality::Many, Some(why)),
2886 }
2887 }
2888 };
2889 }
2890 let Some(sel) = &t.statement else { return (Cardinality::None, None) };
2891 match self.exactly_one(sel) {
2892 Ok(()) => (Cardinality::One, None),
2893 Err(one_why) => match self.at_most_one(sel) {
2894 Ok(()) => (Cardinality::AtMostOne, Some(one_why)),
2895 Err(why) => (Cardinality::Many, Some(why)),
2896 },
2897 }
2898 }
2899
2900 fn exactly_one(&self, sel: &Sel) -> Result<(), String> {
2901 let keeps = |n: &Node, least: i64| integer(n).is_some_and(|n| n >= least);
2904 if sel.limit.as_ref().is_some_and(|l| !keeps(l, 1)) || sel.offset.as_ref().is_some_and(|o| integer(o) != Some(0)) {
2905 return Err("a LIMIT or an OFFSET can remove the row (LIMIT 0, OFFSET 1)".into());
2906 }
2907 self.one_before_limit(sel)
2908 }
2909
2910 fn one_before_limit(&self, sel: &Sel) -> Result<(), String> {
2912 if sel.prior.is_some() {
2913 return Err("a set operation (UNION, INTERSECT, EXCEPT) returns any number of rows".into());
2914 }
2915 if sel.values && !sel.rows.is_empty() {
2916 return Err("a VALUES list returns a row per row it lists".into());
2917 }
2918 if sel.values {
2919 return Ok(());
2920 }
2921 if !sel.group_by.is_empty() {
2922 return Err("GROUP BY returns one row per group, and none when nothing matches".into());
2923 }
2924 if sel.having.is_some() {
2925 return Err("HAVING can remove the row".into());
2926 }
2927 if sel.aggregate && sel.columns.iter().any(|c| has_aggregate(&c.expr)) {
2931 return Ok(());
2932 }
2933 if sel.from.is_empty() && sel.where_.is_none() {
2934 return Ok(());
2935 }
2936 if !sel.from.is_empty() && self.never_empty(sel) && self.arm_at_most_one(sel).is_ok() {
2938 return Ok(());
2939 }
2940 Err("a FROM returns a row per row it matches, and only an aggregate with no GROUP BY collapses them to one".into())
2941 }
2942
2943 fn never_empty(&self, sel: &Sel) -> bool {
2950 let holds = |t: &Node| match (t.op.as_str(), t.left.as_deref().and_then(integer), t.right.as_deref().and_then(integer)) {
2951 ("=", Some(l), Some(r)) => l == r,
2952 _ => integer(t).is_some_and(|n| n != 0),
2953 };
2954 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())))
2955 && conjuncts(sel.where_.as_ref()).iter().all(|t| t.outer_on || holds(t))
2956 }
2957
2958 fn at_most_one(&self, sel: &Sel) -> Result<(), String> {
2959 if sel.limit.as_ref().and_then(integer).is_some_and(|n| (0..=1).contains(&n)) {
2960 return Ok(());
2961 }
2962 if !sel.values && self.one_before_limit(sel).is_ok() {
2965 return Ok(());
2966 }
2967 if let Some(prior) = &sel.prior {
2971 let drawn = match sel.op.as_deref() {
2972 Some("intersect") => self.at_most_one(prior).is_ok() || self.arm_at_most_one(sel).is_ok(),
2973 Some("except") => self.at_most_one(prior).is_ok(),
2974 _ => false,
2975 };
2976 return if drawn { Ok(()) } else { Err("a set operation (UNION, INTERSECT, EXCEPT) returns any number of rows".into()) };
2977 }
2978 self.arm_at_most_one(sel)
2979 }
2980
2981 fn arm_at_most_one(&self, sel: &Sel) -> Result<(), String> {
2986 if sel.values {
2987 return Err("a VALUES list returns a row per row it lists".into());
2988 }
2989 if !sel.group_by.is_empty() {
2990 if sel.from.iter().all(|f| !f.right) && self.determined(sel, false).iter().all(|d| *d) {
2991 return Ok(());
2992 }
2993 let constant = self.determined(sel, true);
2994 if sel.group_by.iter().all(|g| self.pinned(sel, g, &constant)) {
2995 return Ok(());
2996 }
2997 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());
2998 }
2999 if sel.having.is_some() {
3000 return Err("HAVING leaves a row per group".into());
3001 }
3002 if sel.from.is_empty() {
3003 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());
3004 }
3005 if sel.from.iter().any(|f| f.right) {
3008 return Err("a RIGHT or FULL JOIN returns a row for each side that matches nothing".into());
3009 }
3010 let determined = self.determined(sel, false);
3011 if determined.iter().all(|d| *d) {
3012 return Ok(());
3013 }
3014 if sel.distinct {
3015 let constant = self.determined(sel, true);
3016 if !sel.columns.is_empty() && sel.columns.iter().all(|c| self.pinned(sel, &c.expr, &constant)) {
3017 return Ok(());
3018 }
3019 }
3020 let i = determined.iter().position(|d| !d).unwrap_or(0);
3021 let f = &sel.from[i];
3022 let Some(table) = f.table.as_deref().filter(|_| f.subquery.is_none() && !f.tab_func) else {
3023 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("?")));
3024 };
3025 let keys = self.tree.tables.get(table).map(|t| t.unique_keys.clone()).unwrap_or_default();
3026 if keys.is_empty() {
3027 return Err(format!("`{table}` has no unique index the engine can read, so nothing bounds the rows a WHERE matches"));
3028 }
3029 let shown: Vec<String> = keys.iter().map(|k| format!("({})", k.join(", "))).collect();
3030 if sel.from.len() == 1 {
3031 Err(format!("the WHERE does not equate every column of a unique key of `{table}` — it has {}", shown.join(", ")))
3032 } else {
3033 let name = f.alias.as_deref().unwrap_or(table);
3034 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(", ")))
3035 }
3036 }
3037
3038 fn determined(&self, sel: &Sel, constant: bool) -> Vec<bool> {
3045 let derived = self.derived_keys(sel);
3046 self.determined_from(sel, vec![false; sel.from.len()], &derived, constant)
3047 }
3048
3049 fn derived_keys(&self, sel: &Sel) -> Vec<Vec<Vec<i64>>> {
3052 sel.from.iter().map(|f| f.subquery.as_ref().map(|sub| self.output_keys(sub)).unwrap_or_default()).collect()
3053 }
3054
3055 fn determined_from(&self, sel: &Sel, mut done: Vec<bool>, derived: &[Vec<Vec<i64>>], constant: bool) -> Vec<bool> {
3058 let n = sel.from.len();
3059 let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
3060 let terms = conjuncts(sel.where_.as_ref());
3061 loop {
3062 let mut changed = false;
3063 for i in 0..n {
3064 if done[i] {
3065 continue;
3066 }
3067 let f = &sel.from[i];
3068 let pinned = if let Some(sub) = &f.subquery {
3069 let usable: Vec<&Node> = terms.iter().copied().filter(|t| !t.outer_on || (!constant && t.join == f.cursor)).collect();
3070 !(constant && f.outer) && (self.at_most_one(sub).is_ok() || self.derived_pinned(&derived[i], f.cursor, &usable, &done, &index))
3071 } else if let (Some(table), false, false) = (f.table.as_deref(), f.tab_func, f.virtual_) {
3072 let usable: Vec<&Node> = terms.iter().copied().filter(|t| !t.outer_on || (!constant && t.join == f.cursor)).collect();
3075 self.key_pinned(table, f.cursor, &usable, &done, &index)
3076 } else {
3077 false
3078 };
3079 if pinned {
3080 done[i] = true;
3081 changed = true;
3082 }
3083 }
3084 if !changed {
3085 return done;
3086 }
3087 }
3088 }
3089
3090 fn key_pinned(&self, table: &str, cursor: i64, terms: &[&Node], done: &[bool], index: &HashMap<i64, usize>) -> bool {
3095 let Some(info) = self.tree.tables.get(table) else { return false };
3096 let pins: Vec<&str> = terms.iter().filter_map(|t| self.pins(t, cursor, done, index)).collect();
3097 info.unique_keys.iter().any(|key| !key.is_empty() && key.iter().all(|c| pins.iter().any(|p| p.eq_ignore_ascii_case(c))))
3098 }
3099
3100 fn derived_pinned(&self, keys: &[Vec<i64>], cursor: i64, terms: &[&Node], done: &[bool], index: &HashMap<i64, usize>) -> bool {
3103 let pinned: Vec<i64> = terms.iter().filter_map(|t| self.pinned_column(t, cursor, done, index)).map(|c| c.index).collect();
3104 keys.iter().any(|key| !key.is_empty() && key.iter().all(|p| pinned.contains(p)))
3105 }
3106
3107 fn output_keys(&self, sel: &Sel) -> Vec<Vec<i64>> {
3119 if let Some(prior) = &sel.prior {
3120 return self.compound_keys(sel, prior);
3121 }
3122 if sel.values {
3123 return Vec::new();
3124 }
3125 let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
3126 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);
3128 let mut keys = Vec::new();
3129 if !sel.group_by.is_empty() {
3130 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();
3131 keys.extend(key);
3132 return keys;
3133 }
3134 if sel.distinct && !sel.columns.is_empty() && sel.columns.iter().all(|c| c.expr.op == "column" && index.contains_key(&c.expr.cursor)) {
3135 keys.push((0..sel.columns.len() as i64).collect());
3136 }
3137 if sel.from.iter().any(|f| f.right) {
3140 return keys;
3141 }
3142 let derived = self.derived_keys(sel);
3143 let n = sel.from.len();
3144 for (r, f) in sel.from.iter().enumerate() {
3145 if f.tab_func || f.virtual_ {
3146 continue;
3147 }
3148 let mut seed = vec![false; n];
3149 seed[r] = true;
3150 if !self.determined_from(sel, seed, &derived, false).iter().all(|d| *d) {
3151 continue;
3152 }
3153 if f.subquery.is_some() {
3154 for key in &derived[r] {
3155 keys.extend(key.iter().map(|p| position(&|e: &Node| e.cursor == f.cursor && e.index == *p)).collect::<Option<Vec<i64>>>());
3156 }
3157 } else if let Some(info) = f.table.as_deref().and_then(|t| self.tree.tables.get(t)) {
3158 let fixed = |c: &str| {
3161 let none = vec![false; n];
3162 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)))
3163 };
3164 for key in info.unique_keys.iter().filter(|k| !k.is_empty()) {
3165 keys.extend(
3166 key.iter()
3167 .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))) {
3168 Some(p) => Some(Some(p)),
3169 None if fixed(c) => None,
3170 None => Some(None),
3171 })
3172 .collect::<Option<Vec<i64>>>(),
3173 );
3174 }
3175 }
3176 }
3177 keys
3178 }
3179
3180 fn compound_keys(&self, sel: &Sel, prior: &Sel) -> Vec<Vec<i64>> {
3186 let op = sel.op.as_deref().unwrap_or("");
3187 let mut keys = Vec::new();
3188 if op == "intersect" || op == "except" {
3189 keys.extend(self.output_keys(prior));
3190 }
3191 if op != "union all" {
3192 let mut arms = vec![sel];
3193 let mut at = Some(prior);
3194 while let Some(arm) = at {
3195 arms.push(arm);
3196 at = arm.prior.as_deref();
3197 }
3198 let width = sel.columns.len();
3199 let alike = width > 0
3200 && arms.iter().all(|arm| !arm.values && arm.columns.len() == width)
3201 && (0..width).all(|i| {
3202 let first = &sel.columns[i].expr;
3203 first.op == "column" && arms.iter().all(|arm| {
3204 let e = &arm.columns[i].expr;
3205 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"))
3206 })
3207 });
3208 if alike {
3209 keys.push((0..width as i64).collect());
3210 }
3211 }
3212 keys
3213 }
3214
3215 fn pins<'n>(&self, t: &'n Node, cursor: i64, done: &[bool], index: &HashMap<i64, usize>) -> Option<&'n str> {
3220 self.pinned_column(t, cursor, done, index).and_then(|col| col.column.as_deref())
3221 }
3222
3223 fn pinned_column<'n>(&self, t: &'n Node, cursor: i64, done: &[bool], index: &HashMap<i64, usize>) -> Option<&'n Node> {
3225 if t.op != "=" {
3226 return None;
3227 }
3228 let (l, r) = (t.left.as_deref()?, t.right.as_deref()?);
3229 let collation = column_of(l).or_else(|| column_of(r)).and_then(|c| c.coll.as_deref()).unwrap_or("BINARY");
3230 [(l, r), (r, l)].into_iter().find_map(|(col, other)| {
3231 let value = col.op == "column"
3232 && col.cursor == cursor
3233 && !has_op(other, "collate")
3234 && keeps_column(col, other)
3235 && (collation.eq_ignore_ascii_case("BINARY") || col.coll.as_deref().is_some_and(|c| c.eq_ignore_ascii_case(collation)))
3236 && !self.calls_volatile(other)
3237 && other.select.is_none()
3238 && cursors(other).is_some_and(|read| read.iter().all(|c| *c != cursor && index.get(c).is_none_or(|i| done[*i])));
3239 value.then_some(col)
3240 })
3241 }
3242
3243 fn pinned(&self, sel: &Sel, e: &Node, constant: &[bool]) -> bool {
3246 let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
3247 if e.op == "column" {
3248 if index.get(&e.cursor).is_some_and(|i| constant[*i]) {
3249 return true;
3250 }
3251 let terms = conjuncts(sel.where_.as_ref());
3252 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)));
3253 }
3254 e.select.is_none() && !self.calls_volatile(e) && cursors(e).is_some_and(|read| read.iter().all(|c| !index.contains_key(c)))
3255 }
3256
3257 fn pinned_by_name(&self, table: &str, where_: Option<&Node>) -> Result<(), String> {
3259 let equated = self.equated(where_);
3260 let Some(info) = self.tree.tables.get(table) else { return Err(format!("`{table}` is not a table the engine can read")) };
3261 let names: HashSet<String> = equated.iter().map(|(_, n)| n.to_ascii_lowercase()).collect();
3262 if info.unique_keys.iter().any(|key| !key.is_empty() && key.iter().all(|c| names.contains(&c.to_ascii_lowercase()))) {
3263 return Ok(());
3264 }
3265 if info.unique_keys.is_empty() {
3266 return Err(format!("`{table}` has no unique index the engine can read, so nothing bounds the rows a WHERE matches"));
3267 }
3268 let shown: Vec<String> = info.unique_keys.iter().map(|k| format!("({})", k.join(", "))).collect();
3269 Err(format!("the WHERE does not equate every column of a unique key of `{table}` — it has {}", shown.join(", ")))
3270 }
3271
3272 fn equated(&self, where_: Option<&Node>) -> HashSet<(i64, String)> {
3275 let mut out = HashSet::new();
3276 for n in conjuncts(where_) {
3277 if n.op != "=" || n.outer_on {
3278 continue;
3279 }
3280 if let (Some(l), Some(r)) = (n.left.as_deref(), n.right.as_deref()) {
3281 for (col, other) in [(l, r), (r, l)] {
3282 if col.op == "column" && !reads_column(other) && !has_op(other, "collate") && keeps_column(col, other) && !self.calls_volatile(other) {
3285 if let Some(name) = &col.column {
3286 out.insert((col.cursor, name.clone()));
3287 }
3288 }
3289 }
3290 }
3291 }
3292 out
3293 }
3294
3295 fn calls_volatile(&self, n: &Node) -> bool {
3301 const VOLATILE: &[&str] = &["random", "randomblob", "changes", "total_changes", "last_insert_rowid", "date", "time", "datetime", "julianday", "unixepoch", "strftime", "timediff"];
3302 if n.op == "function" {
3303 if n.agg || n.window || n.over {
3304 return true;
3305 }
3306 let name = n.name.as_deref().unwrap_or("").to_ascii_lowercase();
3307 if VOLATILE.contains(&name.as_str()) || self.extras.function(&name, n.args.len()).is_some() || !KNOWN_FUNCTIONS.contains(&name.as_str()) {
3308 return true;
3309 }
3310 }
3311 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))
3312 }
3313}
3314
3315fn keeps_column(col: &Node, other: &Node) -> bool {
3321 let numeric = |a: &str| matches!(a, "integer" | "real" | "numeric");
3322 let none = |a: &str| matches!(a, "blob" | "none");
3323 numeric(&col.aff) || none(&other.aff) || (col.aff == "text" && other.aff == "text")
3324}
3325
3326fn column_of(n: &Node) -> Option<&Node> {
3328 match n.op.as_str() {
3329 "column" => Some(n),
3330 "cast" | "pos" => n.left.as_deref().and_then(column_of),
3331 _ => None,
3332 }
3333}
3334
3335fn literal_text(n: &Node) -> Option<&str> {
3337 if n.op == "string" { n.value.as_deref() } else { None }
3338}
3339
3340fn iif_values(count: usize) -> Vec<usize> {
3343 let mut out: Vec<usize> = (1..count).step_by(2).collect();
3344 if count >= 3 && count % 2 == 1 {
3345 out.push(count - 1);
3346 }
3347 out
3348}
3349
3350fn holds_current_row(n: &Node) -> bool {
3360 let start = matches!(n.frame_start.as_deref(), Some("unbounded" | "preceding" | "current"));
3361 let end = matches!(n.frame_end.as_deref(), Some("unbounded" | "following" | "current"));
3362 let exclude = matches!(n.exclude.as_deref(), Some("no" | "ties"));
3363 n.over && !n.filter && start && end && exclude
3364}
3365
3366fn total_nulls(arg: &Fact) -> Nulls {
3369 if is_integral(&arg.ty) { Nulls::Never } else { Nulls::Always }
3370}
3371
3372fn current_time(args: &[Node]) -> bool {
3381 let Some((value, modifiers)) = args.split_first() else { return true };
3382 let now = literal_text(value).is_some_and(|v| v.eq_ignore_ascii_case("now"))
3383 || (value.op == "function" && value.args.is_empty() && matches!(value.name.as_deref(), Some("current_timestamp" | "current_date" | "current_time")));
3384 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 };
3385 let mut modifiers = modifiers.iter().map(literal_text).peekable();
3386 let julian_day = match number {
3387 Some(v) if modifiers.peek().is_some_and(|m| m.is_some_and(|m| m.eq_ignore_ascii_case("unixepoch"))) => {
3388 modifiers.next();
3389 v / 86_400.0 + 2_440_587.5
3390 }
3391 Some(v) => v,
3392 None if now => 0.0,
3393 None => return false,
3394 };
3395 let mut days = 0.0;
3397 for m in modifiers {
3398 let Some(m) = m else { return false };
3399 let m = m.to_ascii_lowercase();
3400 days += match m.as_str() {
3401 "subsec" | "subsecond" => 0.0,
3402 "localtime" | "utc" => 1.0,
3404 "start of day" | "start of month" | "start of year" => 366.0,
3405 _ if m.len() == 9 && m.starts_with("weekday ") && matches!(m.as_bytes()[8], b'0'..=b'6') => 7.0,
3406 _ => match shift_days(&m) {
3407 Some(d) => d,
3408 None => return false,
3409 },
3410 };
3411 }
3412 if now {
3413 days < 365_000.0
3414 } else {
3415 let margin = if days > 0.0 { days + 400.0 } else { 0.0 };
3417 julian_day - margin >= 0.0 && julian_day + margin < 5_373_484.0
3418 }
3419}
3420
3421fn shift_days(m: &str) -> Option<f64> {
3424 let (number, unit) = m.split_once(' ')?;
3425 let unit = unit.trim_start_matches(' ');
3426 let unit = unit.strip_suffix('s').unwrap_or(unit);
3427 let days = match unit {
3428 "second" => 1.0 / 86_400.0,
3429 "minute" => 1.0 / 1_440.0,
3430 "hour" => 1.0 / 24.0,
3431 "day" => 1.0,
3432 "month" => 31.0,
3433 "year" => 366.0,
3434 _ => return None,
3435 };
3436 let digits = number.strip_prefix(['+', '-']).unwrap_or(number);
3437 let (whole, fraction) = digits.split_once('.').unwrap_or((digits, "0"));
3438 let all_digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
3439 if !all_digits(whole) || !all_digits(fraction) {
3440 return None;
3441 }
3442 Some(digits.parse::<f64>().ok()? * days)
3443}
3444
3445fn printf_writes(format: &str) -> bool {
3451 let b = format.as_bytes();
3452 let at = |i: usize| b.get(i).copied().unwrap_or(0);
3453 let mut i = 0;
3454 loop {
3455 match at(i) {
3456 0 => return false,
3457 b'%' => {}
3458 _ => return true,
3459 }
3460 i += 1;
3461 if at(i) == 0 {
3463 return true;
3464 }
3465 let mut c = at(i);
3466 loop {
3467 match c {
3468 b'-' | b'+' | b' ' | b'#' | b'!' | b'0' | b',' => {}
3469 b'l' => {
3470 i += 1;
3471 if at(i) == b'l' {
3472 i += 1;
3473 }
3474 c = at(i);
3475 break;
3476 }
3477 b'1'..=b'9' => {
3478 while at(i + 1).is_ascii_digit() {
3479 i += 1;
3480 }
3481 if !matches!(at(i + 1), b'.' | b'l') {
3482 i += 1;
3483 c = at(i);
3484 break;
3485 }
3486 }
3487 b'*' => {
3488 if !matches!(at(i + 1), b'.' | b'l') {
3489 i += 1;
3490 c = at(i);
3491 break;
3492 }
3493 }
3494 b'.' => {
3495 i += 1;
3496 if at(i) == b'*' {
3497 i += 1;
3498 } else {
3499 while at(i).is_ascii_digit() {
3500 i += 1;
3501 }
3502 }
3503 if at(i) != b'l' {
3504 c = at(i);
3505 break;
3506 }
3507 i -= 1;
3508 }
3509 _ => break,
3510 }
3511 i += 1;
3512 c = at(i);
3513 if c == 0 {
3514 break;
3515 }
3516 }
3517 match c {
3518 b'%' => return true,
3519 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,
3521 _ => return false,
3522 }
3523 }
3524}
3525
3526fn strftime_format(format: &str) -> bool {
3530 let mut bytes = format.bytes();
3531 while let Some(b) = bytes.next() {
3532 if b == b'%' && !bytes.next().is_some_and(|c| b"deFfHkIljJmMpPRsSTuwWY%".contains(&c)) {
3533 return false;
3534 }
3535 }
3536 true
3537}
3538
3539fn sqlean_alias(name: &str) -> &str {
3542 match name {
3543 "fuzzy_caver" => "caverphone",
3544 "fuzzy_damlev" => "dlevenshtein",
3545 "fuzzy_editdist" => "edit_distance",
3546 "fuzzy_hamming" => "hamming",
3547 "fuzzy_jarowin" => "jaro_winkler",
3548 "fuzzy_leven" => "levenshtein",
3549 "fuzzy_osadist" => "osa_distance",
3550 "fuzzy_phonetic" => "phonetic_hash",
3551 "fuzzy_rsoundex" => "rsoundex",
3552 "fuzzy_script" => "script_code",
3553 "fuzzy_soundex" => "soundex",
3554 "fuzzy_translit" => "translit",
3555 "stats_median" => "median",
3556 "stats_perc" => "percentile",
3557 "stats_p25" => "percentile_25",
3558 "stats_p75" => "percentile_75",
3559 "stats_p90" => "percentile_90",
3560 "stats_p95" => "percentile_95",
3561 "stats_p99" => "percentile_99",
3562 "stats_stddev" => "stddev",
3563 "stats_stddev_pop" => "stddev_pop",
3564 "stats_stddev_samp" => "stddev_samp",
3565 "stats_var" => "variance",
3566 "stats_var_pop" => "var_pop",
3567 "stats_var_samp" => "var_samp",
3568 _ => match name.strip_prefix("crypto_").or_else(|| name.strip_prefix("math_")) {
3569 Some(base @ ("md5" | "sha1" | "sha256" | "sha384" | "sha512" | "blake3" | "encode" | "decode")) if name.starts_with("crypto_") => base,
3570 Some(
3571 base @ ("acos" | "acosh" | "asin" | "asinh" | "atan" | "atan2" | "atanh" | "ceil" | "cos" | "cosh" | "degrees" | "exp" | "floor" | "ln" | "log" | "log10" | "log2" | "mod" | "pi"
3572 | "pow" | "radians" | "round" | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc"),
3573 ) if name.starts_with("math_") => base,
3574 _ => name,
3575 },
3576 }
3577}
3578
3579const KNOWN_FUNCTIONS: &[&str] = &[
3581 "coalesce", "ifnull", "nullif", "iif", "if", "min", "max", "abs", "round", "length", "instr", "unicode", "json_array_length", "json_valid", "octet_length", "sign",
3582 "like", "glob", "regexp", "match", "likely", "unlikely", "likelihood", "upper", "lower", "trim", "ltrim", "rtrim", "substr", "substring", "replace", "char",
3583 "printf", "format", "concat", "concat_ws", "json", "jsonb", "json_array", "json_object", "json_insert", "json_replace", "json_set", "json_remove", "json_patch",
3584 "json_quote", "json_pretty", "json_type", "hex", "quote", "typeof", "soundex", "zeroblob", "json_extract", "jsonb_extract", "->", "->>", "acos", "acosh", "asin", "asinh",
3585 "atan", "atan2", "atanh", "ceil", "ceiling", "cos", "cosh", "degrees", "exp", "floor", "ln", "log", "log10", "log2", "mod", "pow", "power", "radians", "sin",
3586 "sinh", "sqrt", "tan", "tanh", "trunc", "pi",
3587];
3588
3589fn integer(n: &Node) -> Option<i64> {
3591 if n.op == "integer" { n.value.as_deref().and_then(|v| v.parse().ok()) } else { None }
3592}
3593
3594fn integer_literal_fits(n: &Node) -> bool {
3598 n.value.as_deref().is_none_or(|v| v.starts_with("0x") || v.starts_with("0X") || v.parse::<i64>().is_ok())
3599}
3600
3601fn is_two_to_the_63(n: &Node) -> bool {
3603 n.op == "integer" && n.value.as_deref().and_then(|v| v.parse::<u64>().ok()) == Some(1 << 63)
3604}
3605
3606fn conjuncts(n: Option<&Node>) -> Vec<&Node> {
3608 let mut out = Vec::new();
3609 let mut stack: Vec<&Node> = n.into_iter().collect();
3610 while let Some(n) = stack.pop() {
3611 if n.op == "and" {
3612 stack.extend(n.left.as_deref());
3613 stack.extend(n.right.as_deref());
3614 } else {
3615 out.push(n);
3616 }
3617 }
3618 out
3619}
3620
3621fn cursors(n: &Node) -> Option<Vec<i64>> {
3624 if n.select.is_some() {
3625 return None;
3626 }
3627 let mut out = Vec::new();
3628 if n.op == "column" {
3629 out.push(n.cursor);
3630 }
3631 for child in n.left.iter().chain(n.right.iter()).map(|b| b.as_ref()).chain(n.list.iter()).chain(n.args.iter()) {
3632 out.extend(cursors(child)?);
3633 }
3634 Some(out)
3635}
3636
3637fn arithmetic(l: &Ty, r: &Ty) -> Ty {
3639 match (scalar_name(l), scalar_name(r)) {
3640 (Some("integer" | "int8"), Some("integer" | "int8")) => Ty::Scalar { name: "integer".into() },
3641 _ => Ty::Scalar { name: "real".into() },
3642 }
3643}
3644
3645fn has_op(n: &Node, op: &str) -> bool {
3647 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))
3648}
3649
3650fn has_aggregate(n: &Node) -> bool {
3651 if n.op == "function" && n.agg && !n.window {
3652 return true;
3653 }
3654 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)
3655}
3656
3657fn reads_column(n: &Node) -> bool {
3659 if n.op == "column" {
3660 return true;
3661 }
3662 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()
3663}
3664
3665fn is_vector(n: &Option<Box<Node>>) -> bool {
3667 n.as_deref().is_some_and(|n| n.op == "vector")
3668}
3669
3670fn outer_type(ctx: &Ctx) -> Ctx {
3671 match ctx {
3672 Ctx::Typed(Some(f)) => Ctx::Typed(Some(f.clone())),
3673 _ => Ctx::None,
3674 }
3675}
3676
3677fn i_of(slot: Position) -> usize {
3679 match slot {
3680 Position::Arg(i) => i,
3681 _ => 0,
3682 }
3683}
3684
3685fn is_boolean_declared(declared: &str) -> bool {
3687 let d = declared.trim();
3688 d.eq_ignore_ascii_case("boolean") || d.eq_ignore_ascii_case("bool")
3689}
3690
3691pub fn affinity(declared: &str) -> &'static str {
3693 let d = declared.to_ascii_uppercase();
3694 if d.contains("INT") {
3695 "integer"
3696 } else if d.contains("CHAR") || d.contains("CLOB") || d.contains("TEXT") {
3697 "text"
3698 } else if d.contains("BLOB") || d.is_empty() {
3699 "blob"
3700 } else if d.contains("REAL") || d.contains("FLOA") || d.contains("DOUB") {
3701 "real"
3702 } else {
3703 "numeric"
3704 }
3705}
3706
3707#[derive(Clone)]
3709enum Ctx {
3710 Typed(Option<Fact>),
3711 Row(Vec<Option<Fact>>),
3713 Bool,
3714 None,
3715}
3716
3717#[derive(Clone, Copy)]
3718enum Position {
3719 Left,
3720 Right,
3721 List(usize),
3722 Arg(usize),
3723}
3724
3725#[cfg(test)]
3726mod tests {
3727 use super::*;
3728
3729 #[test]
3730 fn a_row_assigned_fewer_values_than_columns_is_the_database_s_error() {
3731 let ddl = vec!["create table t1 (a integer primary key, b, c, d)".to_string(), "create table t2 (w, x, y)".to_string()];
3732 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)"] {
3733 let a = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
3734 assert!(!a.diagnostics.is_empty(), "{sql}: {a:?}");
3735 }
3736 }
3737
3738 fn ddl() -> Vec<String> {
3739 vec![
3740 "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(),
3741 "create table posts (id integer primary key, user_id integer not null references users(id), title text not null, body text)".to_string(),
3742 ]
3743 }
3744
3745 fn analysis(sql: &str) -> Analysis {
3746 analyze_ddl(sql, &ddl(), &Extras::default()).analysis
3747 }
3748
3749 fn marked(sql: &str, ddl: &[String], names: &[&str]) -> Analysis {
3752 let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
3753 run(sql, &lex::lex(sql, Dialect::Sqlite).unwrap(), ddl, &Extras::default(), &names).analysis
3754 }
3755
3756 #[test]
3757 fn the_facts_are_read_for_every_table_the_statement_names_and_no_with_query() {
3758 let mut schema = ddl();
3759 schema.push("create table tags (id integer primary key, post_id integer)".into());
3760 schema.push("create view titles as select title from posts".into());
3761 let tables = |sql: &str| {
3762 let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
3763 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
3764 let mut t = a.tables.expect("the tree names its tables");
3765 t.read.sort();
3766 t.read.dedup();
3767 (t.read, t.write)
3768 };
3769 let names = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
3770 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![]));
3771 assert_eq!(tables("with recent as (select user_id from posts) select title from titles join recent on true"), (names(&["posts", "titles"]), vec![]));
3773 assert_eq!(tables("select value from json_each('[1]')"), (vec![], vec![]));
3774 assert_eq!(tables("select s.n from (select count(*) as n from posts) s join titles on true"), (names(&["posts", "titles"]), vec![]));
3775 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"])));
3776 assert_eq!(tables("insert into tags (post_id) select id from posts"), (names(&["posts"]), names(&["tags"])));
3778 assert_eq!(tables("update users set name = (select max(title) from posts) where id = 1"), (names(&["posts"]), names(&["users"])));
3779 assert_eq!(tables("delete from users where id in (select user_id from posts)"), (names(&["posts"]), names(&["users"])));
3780 }
3781
3782 #[test]
3783 fn a_key_declared_on_conflict_replace_is_read_from_sqlite_s_parse_however_the_ddl_spells_it() {
3784 let replaces = |clause: &str| {
3785 let ddl = vec![format!("create table p (id integer primary key, email text {clause})")];
3786 let t = tree::analyze(&ddl, "insert into p (email) values (?1)", "insert into p (email) values (?)", &[], None).expect("the tree parses");
3787 assert!(t.error.is_none(), "{clause}: {:?}", t.error);
3788 t.tables["p"].replaces
3789 };
3790 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"] {
3791 assert!(replaces(clause), "{clause}");
3792 }
3793 for clause in ["unique", "not null on conflict replace default '' unique", "unique on conflict ignore"] {
3795 assert!(!replaces(clause), "{clause}");
3796 }
3797 }
3798
3799 #[test]
3800 fn the_schema_replay_reaches_no_file_and_sets_no_pragma() {
3801 let dir = std::env::temp_dir().join(format!("reylo-sqlite-replay-test-{}", std::process::id()));
3804 std::fs::create_dir_all(&dir).unwrap();
3805 let (attached, vacuumed) = (dir.join("attached.db"), dir.join("vacuumed.db"));
3806 let ddl = vec![
3807 format!("create table t (a integer not null); attach '{}' as x; create table x.y (z)", attached.display()),
3808 format!("create table u (b); vacuum into '{}'", vacuumed.display()),
3809 "create table v (c); pragma hard_heap_limit = 1; create table w (d)".to_string(),
3810 ];
3811 let a = analyze_ddl("select a, b, c from t, u, v", &ddl, &Extras::default()).analysis;
3813 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
3814 assert!(!attached.exists() && !vacuumed.exists());
3815 for _ in 0..2 {
3818 let refused = analyze_ddl("select d from w", &ddl, &Extras::default()).analysis;
3819 let messages: Vec<&str> = refused.diagnostics.iter().map(|d| d.message.as_str()).collect();
3820 assert_eq!(messages.first(), Some(&"no such table: w"), "{messages:?}");
3821 assert!(messages.contains(&"The schema replay skipped statement 1: not authorized"), "{messages:?}");
3822 assert!(messages.contains(&"The schema replay skipped statement 3: not authorized"), "{messages:?}");
3823 }
3824 std::fs::remove_dir_all(&dir).unwrap();
3825 }
3826
3827 #[test]
3828 fn the_tree_describes_the_schema_tables_alone_and_no_with_query() {
3829 let described = |sql: &str| {
3833 let t = tree::analyze(&ddl(), sql, sql, &[], None).expect("the tree parses");
3834 assert!(t.error.is_none(), "{sql}: {:?}", t.error);
3835 let mut names = t.tables.into_keys().collect::<Vec<_>>();
3836 names.sort();
3837 names
3838 };
3839 assert_eq!(described("with recent as (select user_id from posts) select user_id from recent"), ["posts"]);
3840 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());
3841 assert_eq!(described("with users as (select id from main.users) select id from users"), ["users"]);
3842 let nested = "with recursive t (n, x, j) as (select 1, 'a', json_array('a') union all select n + 1, null, \
3843 (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) \
3844 from t where n < 3) select n, x, j from t";
3845 assert_eq!(described(nested), Vec::<String>::new());
3846 assert!(analysis(nested).diagnostics.is_empty());
3847 }
3848
3849 #[test]
3850 fn a_statement_as_deep_as_the_engine_reads_is_typed_and_one_level_past_it_is_an_error_at_the_bound() {
3851 let ddl = vec!["create table users (id integer primary key, name text not null, nick text)".to_string()];
3854 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());
3855 for (shape, n) in [("sum", 350), ("and_or", 348), ("case", 348), ("coalesce", 349), ("subquery", 23)] {
3857 let at = small(crate::stack::nested(shape, n));
3858 assert!(at.diagnostics.is_empty() && at.kind == Some(StatementKind::Select), "{shape} at {n}: {:?}", at.diagnostics);
3859 let past = small(crate::stack::nested(shape, n + 1));
3860 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);
3861 }
3862 let list = (0..5_000).map(|i| i.to_string()).collect::<Vec<_>>().join(", ");
3864 assert!(small(format!("select id from users where id in ({list})")).diagnostics.is_empty());
3865 }
3866
3867 fn col(a: &Analysis, name: &str) -> (String, bool) {
3868 let c = a.columns.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no column {name}"));
3869 (affinity_of(&c.ty).unwrap_or("unknown").to_string(), c.nullable)
3870 }
3871
3872 #[test]
3873 fn returning_reads_a_value_the_statement_wrote_to_the_row() {
3874 let nullable = |sql: &str| analysis(sql).columns.iter().map(|c| c.nullable).collect::<Vec<_>>();
3875 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]);
3878 assert_eq!(nullable("insert into users (name, email) values ('a', :e) returning email"), [true]);
3880 assert_eq!(nullable("update users set email = :e returning email"), [true]);
3881 assert_eq!(nullable("insert into users (name, email) values ('a', 'x'), ('b', null) returning email"), [true]);
3883 assert_eq!(nullable("insert into users (name, email) values ('a', 'x'), ('b', 'y') returning email"), [false]);
3884 assert_eq!(nullable("insert into users (name, email) select name, email from users returning email"), [true]);
3885 assert_eq!(nullable("insert into users (name, email) select name, name from users returning email"), [false]);
3886 assert_eq!(nullable("update users set email = 'x', score = coalesce(score, 0) where id = 1 returning email, score, avatar"), [false, false, true]);
3889 assert_eq!(nullable("update users set email = name returning email"), [false]);
3890 assert_eq!(nullable("update users set email = score returning email"), [true]);
3891 assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do update set email = 'y' returning email"), [false]);
3893 assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do update set name = 'b' returning email"), [true]);
3894 assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do nothing returning email"), [false]);
3895 let triggered = |sql: &str, trigger: &str| {
3898 let mut schema = ddl();
3899 schema.push(trigger.to_string());
3900 analyze_ddl(sql, &schema, &Extras::default()).analysis.columns.iter().map(|c| c.nullable).collect::<Vec<_>>()
3901 };
3902 assert_eq!(triggered("update users set email = 'x' returning email", "create trigger b before update on users begin select 1; end"), [true]);
3903 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]);
3904 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]);
3905 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]);
3906 assert_eq!(nullable("delete from users where id = 1 returning email"), [true]);
3908 assert_eq!(nullable("update users set email = 'x' returning (select email from users where id = 2) as other"), [true]);
3909 }
3910
3911 fn param(a: &Analysis, name: &str) -> String {
3912 let p = a.params.iter().find(|p| p.name == name).unwrap_or_else(|| panic!("no param {name}"));
3913 affinity_of(&p.ty).unwrap_or("unknown").to_string()
3914 }
3915
3916 #[test]
3917 fn the_full_text_functions_are_typed() {
3918 let mut schema = ddl();
3922 schema.push("CREATE VIRTUAL TABLE docs USING fts5(title, body)".into());
3923 schema.push("CREATE VIRTUAL TABLE notes USING fts4(body)".into());
3924 let a = |sql: &str| {
3925 let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
3926 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
3927 a
3928 };
3929 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, \
3930 snippet(docs, -1, '<b>', '</b>', '…', 8) as excerpt from docs where docs match :q order by rank");
3931 assert_eq!(col(&fts5, "rank"), ("real".into(), false));
3932 assert_eq!(col(&fts5, "weighted"), ("real".into(), true));
3933 assert_eq!(col(&fts5, "hit"), ("text".into(), true));
3934 assert_eq!(col(&fts5, "excerpt"), ("text".into(), true));
3935 assert_eq!((param(&fts5, "w"), param(&fts5, "col"), param(&fts5, "open"), param(&fts5, "q")), ("real".into(), "integer".into(), "text".into(), "text".into()));
3936 let fts4 = a("select offsets(notes) as o, matchinfo(notes) as m, snippet(notes) as s from notes where notes match :q");
3937 assert_eq!(col(&fts4, "o"), ("text".into(), false));
3938 assert_eq!(col(&fts4, "m"), ("blob".into(), false));
3939 assert_eq!(col(&fts4, "s"), ("text".into(), true));
3940 let built = a("select json_object('hit', highlight(docs, 0, '<b>', '</b>'), 'rank', bm25(docs)) as j from docs where docs match :q");
3942 assert_eq!(shown(&built), "j: { hit: string | null; rank: number }");
3943 }
3944
3945 #[test]
3946 fn a_built_in_is_non_null_only_where_sqlite_never_answers_null_for_non_null_arguments() {
3947 let ddl = vec![
3949 "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(),
3950 "create table loose (id integer primary key, num numeric not null)".to_string(),
3951 ];
3952 let typed = |expr: &str| {
3953 let a = analyze_ddl(&format!("select {expr} as v from o, loose"), &ddl, &Extras::default()).analysis;
3954 assert!(a.diagnostics.is_empty(), "{expr}: {:?}", a.diagnostics);
3955 col(&a, "v")
3956 };
3957 let nullable = |expr: &str| typed(expr).1;
3958 for expr in [
3960 "date(placed_at)", "time(placed_at)", "datetime(placed_at)", "julianday(placed_at)", "unixepoch(placed_at)", "strftime('%Y', placed_at)",
3961 "date(placed_at, '+1 day')", "timediff(placed_at, 'now')", "date(n)", "date(x, 'unixepoch')", "date('2024-01-01')", "date(:d)",
3962 "date('now', 'weekday 7')", "date('now', 'unixepoch')", "date('now', 'julianday')", "date('now', '+8000 years')", "date('now', '+1 day ')",
3963 "date('now', '+600 years', '+600 years')", "date('now', fmt)", "date('now ')", "strftime('%Q', 'now')", "strftime('%Y%')", "strftime(fmt)",
3964 "date(5373485)", "datetime(1e18, 'unixepoch')", "date(0, '-1 day')", "date(1700000000, 'unixepoch', 'unixepoch')", "date(1, 'auto')", "date(-1)",
3965 ] {
3966 assert!(nullable(expr), "{expr}");
3967 }
3968 for expr in [
3970 "date()", "time()", "datetime()", "julianday()", "unixepoch()", "date('now')", "date('NOW')", "datetime('now', 'localtime')", "datetime('now', 'utc')",
3971 "date('now', 'start of month', '+1 month', '-1 day')", "date('now', 'weekday 0')", "datetime('now', '-7 days', '+1.5 hours', '+30 MINUTES')",
3972 "date('now', 'subsec')", "strftime('%Y-%m-%d %H:%M:%f %% %j', 'now')", "strftime('%s')", "strftime('')", "timediff('now', 'now')",
3973 "strftime('%Y', current_timestamp)", "date(current_date, '+1 month')", "datetime(0, 'unixepoch')", "date(2460000.5)", "date(1700000000, 'unixepoch', 'start of day', '+1 day')",
3974 ] {
3975 assert!(!nullable(expr), "{expr}");
3976 }
3977 assert_eq!(typed("unixepoch()"), ("integer".into(), false));
3978 assert_eq!(typed("unixepoch('now', 'subsec')"), ("real".into(), false));
3979 assert_eq!(typed("unixepoch('now', fmt)"), ("real".into(), true));
3980 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)"] {
3983 assert_eq!(typed(f), ("real".into(), true), "{f}");
3984 }
3985 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()"] {
3987 assert_eq!(typed(f), ("real".into(), false), "{f}");
3988 }
3989 assert_eq!(typed("sign(x)"), ("integer".into(), false));
3990 for f in ["sign(placed_at)", "sign(v)", "sign(num)", "ceil(placed_at)", "floor(b)", "exp(v)", "atan2(x, placed_at)", "sinh(num)"] {
3991 assert!(nullable(f), "{f}");
3992 }
3993 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('%-')"] {
3995 assert!(nullable(f), "{f}");
3996 }
3997 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')"] {
3998 assert!(!nullable(f), "{f}");
3999 }
4000 assert_eq!(typed("substr(placed_at, 2)"), ("text".into(), false));
4002 assert_eq!(typed("substr(n, 2, 1)"), ("text".into(), false));
4003 assert_eq!(typed("substr(:s, 2)"), ("text".into(), false));
4004 assert_eq!(typed("substr(b, 2)"), ("blob".into(), true));
4005 assert_eq!(typed("substring(v, 1, 2)"), ("unknown".into(), true));
4006 for f in ["json_type(doc, '$.a')", "json_array_length(doc, '$.a')", "json_remove(doc, '$')", "json_remove(doc, '$.a')"] {
4008 assert!(nullable(f), "{f}");
4009 }
4010 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)"] {
4011 assert!(!nullable(f), "{f}");
4012 }
4013 assert_eq!(typed("jsonb(doc)"), ("blob".into(), false));
4014 assert_eq!(typed("(select jsonb_group_array(id) from o)"), ("blob".into(), false));
4015 assert_eq!(typed("iif(n > 0, placed_at)"), ("text".into(), true));
4017 assert_eq!(typed("iif(n > 0, placed_at, n > 1, doc)"), ("text".into(), true));
4018 assert_eq!(typed("iif(n > 0, placed_at, n > 1, doc, fmt)"), ("text".into(), false));
4019 assert_eq!(typed("if(n > 0, x, n > 1, x, 1.5)"), ("real".into(), false));
4020 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");
4022 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");
4023 assert_eq!(typed("(select total(x) from o)"), ("real".into(), true));
4025 assert_eq!(typed("(select total(n) from o)"), ("real".into(), false));
4026 assert_eq!(typed("total(x) over ()"), ("real".into(), true));
4027 for f in [
4029 "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')",
4030 "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)",
4031 ] {
4032 assert!(!nullable(f), "{f}");
4033 }
4034 assert!(nullable("unicode(placed_at)"));
4035 }
4036
4037 #[test]
4038 fn the_postgres_nullability_rules_hold_on_sqlite() {
4039 let nullable_param = |sql: &str, name: &str| analysis(sql).params.iter().find(|p| p.name == name).is_some_and(|p| p.nullable);
4040 let marked_param = |sql: &str, name: &str| marked(sql, &ddl(), &[name]).params.iter().find(|p| p.name == name).is_some_and(|p| p.nullable);
4043 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"));
4044 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"));
4045 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"));
4046 assert!(!nullable_param("select id from users, (select :p as p) s where coalesce(s.p, score) = score", "p"));
4047 assert!(!nullable_param("with input as (select :p as p) select id from users, input where score = coalesce(input.p, score)", "p"));
4048 assert!(!nullable_param("with input as (select :p as p) select id from users, input where score > input.p", "p"));
4049 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"));
4050 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"));
4051 assert!(!nullable_param("select id from users where cast(:p as integer) is null", "p"));
4052 assert!(!nullable_param("select id from users where :p is not null", "p"));
4053 assert!(!nullable_param("select id from users where email is :p", "p"));
4054 assert!(!nullable_param("select id from users where :p is not email", "p"));
4055 assert!(!nullable_param("select id from users where :p isnull", "p"));
4056 assert!(!nullable_param("select id from users where score = coalesce(score, :p)", "p"));
4057 let sql = "select id from users where (:p is null or score > :p)";
4058 let repeated = analysis(sql);
4059 assert_eq!(repeated.diagnostics.iter().map(|d| (d.code, d.start, d.length)).collect::<Vec<_>>(), [(3, sql.rfind(":p").unwrap(), 2)]);
4060 assert!(!nullable_param("select coalesce(:s, 0) as x", "s"));
4061 assert!(!nullable_param("select id from users where score > :p", "p"));
4062 assert_eq!(col(&analysis("select upper(:s) as u"), "u"), ("text".into(), false));
4063 assert_eq!(col(&analysis("select email from users where email is not null"), "email"), ("text".into(), false));
4065 assert_eq!(col(&analysis("select email from users where lower(email) = :e or email like 'a%'"), "email").1, false);
4066 assert_eq!(col(&analysis("select email from users where email like 'a%' or id = 1"), "email").1, true);
4067 assert_eq!(col(&analysis("select email from users where lower(email) = :e and email like 'a%'"), "email").1, false);
4068 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");
4069 assert_eq!(col(&reduced, "name"), ("text".into(), false));
4070 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));
4071 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");
4074 assert_eq!((col(&right, "title").1, col(&right, "name").1), (true, true));
4075 assert_eq!(col(&analysis("select u.email from posts p join users u on u.email is not null"), "email").1, false);
4076 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));
4077 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");
4079 assert_eq!((col(&grouped, "t").1, col(&grouped, "m").1, col(&grouped, "g").1), (false, false, false));
4080 assert!(col(&analysis("select max(title) as t from posts"), "t").1);
4081 let concat = analysis("select concat(email, 'x') as c, concat_ws(',', email) as w, concat_ws(email, 'a') as n from users");
4083 assert_eq!((col(&concat, "c").1, col(&concat, "w").1, col(&concat, "n").1), (false, false, true));
4084 }
4085
4086 #[test]
4087 fn a_cast_parameter_is_its_casts_type_and_a_bare_one_its_columns() {
4088 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()];
4094 let types = |sql: &str| {
4095 let a = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
4096 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4097 a.params.iter().map(|p| format!("{}{}", p.name, if p.nullable { "?" } else { "" })).collect::<Vec<_>>().join(" ")
4098 };
4099 for (sql, want) in [
4100 ("insert into users (name, email) values (:name, :email) on conflict (email) do update set name = excluded.name returning id", "name email?"),
4101 ("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"),
4102 ("insert into users (name, email, score, n, doc, meta) values (:name, :email, :score, :n, :doc, :meta)", "name email? score? n? doc? meta"),
4103 ("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"),
4104 ("insert into users (name, email) values (:a, :b), (:c, CAST(:d AS TEXT))", "a b? c d"),
4105 ("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"),
4106 ("update users set (name, email) = (:name, :email) where id = :id", "name email? id"),
4107 ("update users set (name, email) = (CAST(:name AS TEXT), CAST(:email AS TEXT)) where id = CAST(:id AS INTEGER)", "name email id"),
4108 ("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"),
4109 ("update users set email = CAST(CAST(:e AS INTEGER) AS TEXT), meta = json(:m) where id = 1", "e m"),
4110 ("insert into users (name, nick, code, tag) values (:name, :nick, :code, :tag)", "name nick code tag?"),
4111 ("update users set nick = :nick, code = :code, tag = :tag where id = :id", "nick code tag? id"),
4112 ("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"),
4113 ("select id from users where (json(:doc) is null or doc = json(:d)) and :x is not null", "doc d x"),
4114 ("insert into users (name, email) select CAST(:name AS TEXT), CAST(:email AS TEXT)", "name email"),
4115 ("insert into users (name, email) select :name, :email", "name email?"),
4116 ] {
4117 assert_eq!(types(sql), want, "{sql}");
4118 }
4119 let ddl: Vec<String> = ddl.iter().map(|s| s.to_string()).collect();
4123 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))";
4124 let a = marked(sql, &ddl, &["name", "email", "nick", "doc", "meta"]);
4125 assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true; 5]);
4126 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.");
4127 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"))]);
4128 let sql = "insert into users (name, email) select CAST(:name AS TEXT), CAST(:email AS TEXT)";
4130 let a = marked(sql, &ddl, &["name", "email"]);
4131 assert_eq!(a.diagnostics.iter().map(|d| (&sql[d.start..d.start + d.length], d.message.clone())).collect::<Vec<_>>(), [(":name", said(":name", "name"))]);
4132 let a = marked("update users set email = CAST(:e AS TEXT), n = coalesce(CAST(:n AS INTEGER), n) where id = 1", &ddl, &["e", "n"]);
4133 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4134 assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true, true]);
4135 }
4136
4137 #[test]
4138 fn a_parameter_takes_the_type_its_call_case_or_compound_stands_in() {
4139 assert_eq!(param(&analysis("select id from users where name = coalesce(:a, :b)"), "a"), "text");
4140 assert_eq!(param(&analysis("select id from users where name = coalesce(:a, :b)"), "b"), "text");
4141 assert_eq!(param(&analysis("select id from users where name = case when id > 1 then :a else :b end"), "a"), "text");
4142 assert_eq!(param(&analysis("select id from users where name = iif(id > 1, :a, 'x')"), "a"), "text");
4143 assert_eq!(param(&analysis("select case :kind when 'a' then 1 else 2 end as k from users"), "kind"), "text");
4144 assert_eq!(param(&analysis("select name from users union all select :x"), "x"), "text");
4145 assert_eq!(param(&analysis("select :x union all select name from users"), "x"), "text");
4146 assert_eq!(param(&analysis("select id from users where name = printf(:f, 1)"), "f"), "text");
4148 assert_eq!(param(&analysis("select :x as v"), "x"), "unknown");
4149 }
4150
4151 #[test]
4152 fn an_outer_joins_on_term_pins_its_right_side_but_groups_nothing() {
4153 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");
4156 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");
4157 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");
4159 }
4160
4161 #[test]
4162 fn an_insert_returns_no_row_where_something_can_skip_it() {
4163 let count = |sql: &str, extra: &[&str]| {
4164 let mut schema = ddl();
4165 schema.extend(extra.iter().map(|s| s.to_string()));
4166 analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
4167 };
4168 let insert = "insert into users (name) values (:n) returning id";
4169 assert_eq!(count(insert, &[]), "one");
4170 assert_eq!(count(insert, &["create trigger skip before insert on users begin select raise(ignore) where new.name = 'x'; end"]), "at_most_one");
4172 assert_eq!(count(insert, &["create trigger untimed insert on users begin select 1; end"]), "at_most_one", "BEFORE is the default");
4173 assert_eq!(count(insert, &["create trigger later after insert on users begin select 1; end"]), "one");
4174 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");
4176 assert_eq!(count("insert into users (id, name) values (:id, :n) on conflict (id) do update set name = excluded.name returning id", &[]), "one");
4177 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");
4179 let declared = |sql: &str, table: &str| {
4182 let schema = vec![table.to_string()];
4183 analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
4184 };
4185 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");
4186 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");
4187 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");
4188 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");
4189 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");
4190 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");
4191 }
4192
4193 #[test]
4194 fn a_write_to_a_view_goes_through_its_instead_of_trigger() {
4195 let schema = vec![
4196 "create table w (id integer primary key, k text not null, v integer)".to_string(),
4197 "create view wv as select id, k, v from w".to_string(),
4198 "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(),
4199 "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(),
4200 ];
4201 let analysis = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
4202 let insert = analysis("insert into wv (k, v) values (42, 9) returning k");
4203 assert!(insert.diagnostics.is_empty(), "{:?}", insert.diagnostics);
4204 assert_eq!(col(&insert, "k"), ("unknown".into(), true));
4206 assert!(analysis("update wv set v = :v where id = :id").diagnostics.is_empty());
4207 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"));
4210 assert_eq!(analysis("delete from wv").diagnostics.first().map(|d| d.message.as_str()), Some("cannot modify wv because it is a view"));
4211 assert_eq!(instead_of_stub("create trigger t before insert on w begin select 1; end"), None);
4212 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"));
4213 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"));
4214 }
4215
4216 #[test]
4217 fn a_unique_key_bounds_only_a_comparison_under_its_own_collation() {
4218 let count = |sql: &str| {
4219 let mut schema = ddl();
4220 schema.push("create table c (id integer primary key, e text collate nocase, b text unique)".into());
4221 schema.push("create unique index c_e on c (e collate binary)".into());
4222 analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
4223 };
4224 assert_eq!(count("select id from c where e = :e"), "many");
4226 assert_eq!(count("select id from c where b = :b"), "at_most_one");
4227 assert_eq!(count("select id from c where b = :b collate nocase"), "many");
4228 assert_eq!(count("select e from c where id = :id"), "at_most_one");
4229 }
4230
4231 #[test]
4232 fn a_function_the_host_registers_over_a_built_in_proves_nothing_strict() {
4233 let lower = Extras { total: vec![TotalFunction { name: "lower".into(), arity: 1, returns: Affinity::Text }], host: None };
4234 let nullable = |extras: &Extras| col(&analyze_ddl("select email from users where lower(email) = :e", &ddl(), extras).analysis, "email").1;
4235 assert!(!nullable(&Extras::default()));
4236 assert!(nullable(&lower));
4237 }
4238
4239 #[test]
4240 fn a_strict_column_and_a_rowid_hold_their_declared_type_alone() {
4241 let ddl = [
4242 "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",
4243 "create table loose (id integer primary key, n integer not null, t text)",
4244 "create table desc_key (a integer primary key desc)",
4245 ]
4246 .map(String::from);
4247 let kinds = |sql: &str| {
4248 let analysis = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
4249 analysis.columns.iter().map(|c| serde_json::to_value(&c.ty).unwrap()["kind"].as_str().unwrap().to_string()).collect::<Vec<_>>().join(" ")
4250 };
4251 assert_eq!(kinds("select id, n, x, t, b, a from s"), "integer integer float text bytes unknown");
4252 assert_eq!(kinds("select id, n, t from loose"), "integer union union");
4253 assert_eq!(kinds("select a from desc_key"), "union");
4254 assert_eq!(kinds("select g from s"), "union");
4256 assert_eq!(kinds("select n, t from (select n, t from s)"), "integer text");
4258 assert_eq!(kinds("select n from s union all select id from loose"), "integer");
4259 assert_eq!(kinds("select n from s union all select n from loose"), "union");
4260 assert_eq!(kinds("select n from s union all values (1)"), "union");
4261 }
4262
4263 fn libsql_schema() -> Vec<String> {
4266 [
4267 "CREATE TABLE docs (id integer primary key, title text not null, emb F32_BLOB(3))",
4268 "CREATE TABLE libsql_vector_meta_shadow ( name TEXT PRIMARY KEY, metadata BLOB ) WITHOUT ROWID",
4269 "CREATE TABLE docs_emb_shadow (index_key INTEGER , data BLOB, PRIMARY KEY (index_key))",
4270 "CREATE INDEX docs_emb_shadow_idx ON docs_emb_shadow (index_key)",
4271 "CREATE INDEX docs_emb on docs (libsql_vector_idx(emb))",
4272 "CREATE TABLE words (k text primary key, e F32_BLOB(2)) WITHOUT ROWID",
4273 "CREATE INDEX words_e on words (libsql_vector_idx(e, 'metric=l2'))",
4274 ]
4275 .map(String::from)
4276 .to_vec()
4277 }
4278
4279 fn sqlite_host() -> Extras {
4281 Extras { total: vec![], host: Some(["lower", "upper", "length", "count"].map(|name| HostFunction { name: name.into(), arity: -1, kind: 's' }).to_vec()) }
4282 }
4283
4284 #[test]
4285 fn the_sqlean_functions_turso_cloud_loads_are_typed_whatever_the_host_lists() {
4286 let ddl = vec!["create table people (id integer primary key, name text not null, nick text, score real not null) strict".to_string()];
4288 for extras in [Extras::default(), sqlite_host()] {
4289 let a = |sql: &str| {
4290 let a = analyze_ddl(sql, &ddl, &extras).analysis;
4291 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4292 a
4293 };
4294 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");
4295 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)));
4296 assert_eq!(param(&fresh, "id"), "text");
4297 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");
4298 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)));
4299 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");
4300 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)));
4301 assert_eq!(param(&fuzzy, "q"), "text");
4302 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");
4303 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)));
4304 assert_eq!(param(&text, "n"), "integer");
4305 let tests = a("select starts_with(name, 'a') as a, text_contains(name, :part) as b, regexp_like(nick, '^a') as c from people");
4307 assert_eq!(["a", "b", "c"].map(|c| col(&tests, c)), [("bool", false), ("bool", false), ("bool", false)].map(|(t, n)| (t.to_string(), n)));
4308 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'");
4310 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)));
4311 let aliased = a("select math_floor(:x) as a, fuzzy_soundex(:s) as b, stats_perc(score, :p) as c from people");
4313 assert_eq!((param(&aliased, "x"), param(&aliased, "s"), param(&aliased, "p")), ("real".into(), "text".into(), "real".into()));
4314 let math = a("select math_floor(score) as a, math_sqrt(score) as b, math_pi() as c from people");
4316 assert_eq!(["a", "b", "c"].map(|c| col(&math, c)), [("real", false), ("real", true), ("real", false)].map(|(t, n)| (t.to_string(), n)));
4317 let stats = a("select stddev(score) as a, stats_p90(score) as b, variance(score) as c from people group by name");
4318 assert_eq!(["a", "b", "c"].map(|c| col(&stats, c)), [("real", true), ("real", true), ("real", true)].map(|(t, n)| (t.to_string(), n)));
4319 let series = a("select value from generate_series(1, :stop)");
4320 assert_eq!((col(&series, "value"), param(&series, "stop")), (("integer".to_string(), false), "integer".to_string()));
4321 assert_eq!(col(&a("select value from stats_seq(1, 3)"), "value"), ("integer".to_string(), false));
4322 assert!(!analyze_ddl("select value from generate_series", &ddl, &extras).analysis.diagnostics.is_empty());
4323 }
4324 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;
4327 assert_eq!(["a", "b", "c"].map(|c| col(&own, c)), [("text", true), ("text", false), ("real", true)].map(|(t, n)| (t.to_string(), n)));
4328 }
4329
4330 #[test]
4331 fn libsql_s_vector_functions_are_typed_whatever_the_host_lists() {
4332 for extras in [Extras::default(), sqlite_host()] {
4333 let a = |sql: &str| {
4334 let a = analyze_ddl(sql, &libsql_schema(), &extras).analysis;
4335 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4336 a
4337 };
4338 let plain = a("select id, title from docs where id = :id");
4340 assert_eq!((col(&plain, "id"), col(&plain, "title")), (("integer".into(), false), ("text".into(), false)));
4341 assert_eq!(a("select emb from docs").columns[0].nullable, true);
4343 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");
4344 assert_eq!((col(&distance, "d"), col(&distance, "l")), (("real".into(), true), ("real".into(), true)));
4345 assert_eq!((param(&distance, "q"), param(&distance, "r")), ("text".into(), "text".into()));
4346 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");
4347 for name in ["v", "a", "b", "c", "d", "e", "f"] {
4348 assert_eq!(col(&made, name), ("blob".into(), false), "{name}");
4349 }
4350 assert_eq!(col(&made, "text"), ("text".into(), false));
4351 let insert = a("insert into docs (title, emb) values (:title, vector(:v)) returning id");
4352 assert_eq!((param(&insert, "title"), param(&insert, "v")), ("text".into(), "text".into()));
4353 }
4354 }
4355
4356 #[test]
4357 fn vector_top_k_returns_the_key_of_its_index_s_table() {
4358 for extras in [Extras::default(), sqlite_host()] {
4359 let a = |sql: &str| {
4360 let a = analyze_ddl(sql, &libsql_schema(), &extras).analysis;
4361 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4362 a
4363 };
4364 let top = a("select id from vector_top_k('docs_emb', vector(:q), :k)");
4366 assert_eq!(col(&top, "id"), ("integer".into(), false));
4367 assert_eq!((param(&top, "q"), param(&top, "k")), ("text".into(), "integer".into()));
4368 assert_eq!(a("select * from vector_top_k('docs_emb', :q, 5)").columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id"]);
4369 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");
4370 assert_eq!(col(&joined, "title"), ("text".into(), false));
4371 assert_eq!(col(&a("select id from vector_top_k('words_e', :q, 3)"), "id"), ("unknown".into(), false));
4373 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));
4375 assert_eq!(a("select id from vector_top_k(:index, :q, 5)").columns[0].nullable, true);
4376 }
4377 }
4378
4379 #[test]
4380 fn libsql_s_alter_column_prepares_on_a_table_and_column_that_exist() {
4381 let a = |sql: &str| analyze_ddl(sql, &libsql_schema(), &Extras::default()).analysis;
4382 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"] {
4383 let altered = a(sql);
4384 assert!(altered.diagnostics.is_empty(), "{sql}: {:?}", altered.diagnostics);
4385 assert!(altered.columns.is_empty());
4386 assert_eq!(altered.cardinality, Cardinality::None);
4387 }
4388 let missing = a("alter table docs alter column nope to nope integer");
4389 assert!(missing.diagnostics.len() == 1 && missing.diagnostics[0].message.starts_with("no such column: \"nope\", so if it is a migration"), "{:?}", missing.diagnostics);
4390 assert!(!a("alter table nope alter column title to title text").diagnostics.is_empty());
4391 assert!(!a("alter table docs alter column title").diagnostics.is_empty());
4392 }
4393
4394 #[test]
4395 fn a_table_whose_check_calls_a_function_the_host_lacks_still_replays() {
4396 let ddl = vec!["create table docs (id integer primary key, doc text check (doc is null or jsonschema_matches('{\"type\":\"object\"}', doc)))".to_string()];
4399 let without = Extras { total: vec![], host: Some(vec![HostFunction { name: "lower".into(), arity: 1, kind: 's' }]) };
4400 for extras in [Extras::default(), without.clone()] {
4401 let read = analyze_ddl("select id, doc from docs", &ddl, &extras).analysis;
4402 assert!(read.diagnostics.is_empty(), "{:?}", read.diagnostics);
4403 assert_eq!(read.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "doc"]);
4404 let write = analyze_ddl("insert into docs (doc) values (:doc) returning id", &ddl, &extras).analysis;
4405 assert!(write.diagnostics.is_empty(), "{:?}", write.diagnostics);
4406 assert_eq!(param(&write, "doc"), "text");
4407 }
4408 let call = analyze_ddl("select jsonschema_matches('{}', doc) as m from docs", &ddl, &without).analysis;
4410 assert!(!call.diagnostics.is_empty());
4411 }
4412
4413 #[test]
4414 fn columns_from_provenance_and_rules() {
4415 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");
4416 assert_eq!(col(&a, "id"), ("integer".into(), false));
4417 assert_eq!(col(&a, "name"), ("text".into(), false));
4418 assert_eq!(col(&a, "email"), ("text".into(), true));
4419 assert_eq!(col(&a, "score"), ("real".into(), true));
4420 assert_eq!(col(&a, "l"), ("integer".into(), true));
4421 assert_eq!(col(&a, "e"), ("text".into(), false));
4422 assert_eq!(col(&a, "d"), ("integer".into(), false));
4423 assert_eq!(col(&a, "h"), ("integer".into(), false));
4424 assert_eq!(a.cardinality, "many");
4425 }
4426
4427 #[test]
4428 fn a_column_beside_an_aggregate_with_no_group_by_is_null_over_no_rows() {
4429 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'");
4432 assert_eq!(col(&a, "id"), ("integer".into(), true));
4433 assert_eq!(col(&a, "name"), ("text".into(), true));
4434 assert_eq!(col(&a, "e"), ("text".into(), false));
4435 assert_eq!(col(&a, "d"), ("integer".into(), true));
4436 assert_eq!(col(&a, "n"), ("integer".into(), false));
4437 assert_eq!(col(&a, "c"), ("integer".into(), false));
4438 assert_eq!(a.cardinality, "one");
4439 let a = analysis("select name, count(*) as n from users group by name");
4441 assert_eq!(col(&a, "name"), ("text".into(), false));
4442 }
4443
4444 #[test]
4445 fn outer_join_and_subquery_provenance() {
4446 let a = analysis("select u.id, p.title from users u left join posts p on p.user_id = u.id");
4447 assert_eq!(col(&a, "title"), ("text".into(), true));
4448 let a = analysis("select t.id, t.name from (select id, name from users) t where t.id = :id");
4449 assert_eq!(col(&a, "id"), ("integer".into(), false));
4450 assert_eq!(col(&a, "name"), ("text".into(), false));
4451 assert_eq!(param(&a, "id"), "integer");
4452 }
4453
4454 #[test]
4455 fn parameters_from_context() {
4456 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");
4457 assert_eq!(param(&a, "email"), "text");
4458 assert_eq!(param(&a, "min"), "real");
4459 assert_eq!(param(&a, "a"), "integer");
4460 assert_eq!(param(&a, "from"), "text");
4461 assert_eq!(param(&a, "q"), "text");
4462 assert_eq!(param(&a, "n"), "text");
4463 assert_eq!(param(&a, "lim"), "integer");
4464 assert_eq!(param(&a, "off"), "integer");
4465 let a = analysis("insert into users (email, name, score) values (:e, upper(:n), :s * 2) returning id");
4466 assert_eq!(param(&a, "e"), "text");
4467 assert_eq!(param(&a, "n"), "text");
4468 assert_eq!(param(&a, "s"), "integer");
4469 assert_eq!(a.cardinality, "one");
4470 let a = analysis("update users set name = :name, score = :score where id = :id returning id");
4471 assert_eq!(param(&a, "name"), "text");
4472 assert_eq!(param(&a, "score"), "real");
4473 assert_eq!(param(&a, "id"), "integer");
4474 assert_eq!(a.cardinality, "at_most_one");
4475 }
4476
4477 #[test]
4478 fn json_each_reads_text() {
4479 let a = analysis("select id from users where id in (select value from json_each(:ids))");
4481 assert_eq!(param(&a, "ids"), "text");
4482 assert!(!a.params.iter().find(|p| p.name == "ids").unwrap().nullable);
4483 let a = analysis("select key, value from json_tree(:doc, :path)");
4484 assert_eq!(param(&a, "doc"), "text");
4485 assert_eq!(param(&a, "path"), "text");
4486 assert_eq!(param(&analysis("select value from json_each(cast(:ids as text))"), "ids"), "text");
4487 let a = marked("select value from json_each(coalesce(CAST(:ids AS TEXT), '[]'))", &ddl(), &["ids"]);
4488 assert_eq!(param(&a, "ids"), "text");
4489 assert!(a.params.iter().find(|p| p.name == "ids").unwrap().nullable);
4490 let a = analysis("select users.id from users, json_each(:ids) j where users.id = j.value and users.name = :n");
4492 assert_eq!(param(&a, "ids"), "text");
4493 assert_eq!(param(&a, "n"), "text");
4494 }
4495
4496 #[test]
4497 fn cardinality_by_keys() {
4498 assert_eq!(analysis("select id from users where email = :email").cardinality, "at_most_one");
4499 assert_eq!(analysis("select id from users where name = :name").cardinality, "many");
4500 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");
4501 assert_eq!(analysis("select id from users limit 1").cardinality, "at_most_one");
4502 assert_eq!(analysis("insert or ignore into users (email, name) values (:e, :n) returning id").cardinality, "at_most_one");
4503 assert_eq!(analysis("insert into users (email, name) values (:e, :n)").cardinality, "none");
4504 assert_eq!(analysis("delete from users where id = :id returning id").cardinality, "at_most_one");
4505 assert_eq!(analysis("select id from users union all select user_id from posts").cardinality, "many");
4506 }
4507
4508 fn analyzed(sql: &str) -> Analysis {
4510 let ddl = [
4511 "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)",
4512 ];
4513 let rows = ddl.iter().map(|d| vec![serde_json::Value::String(d.to_string())]).collect();
4514 let answers = HashMap::from([(format!("query:{DDL_QUERY}|[]"), crate::api::Answer::Rows { rows }), (format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]))]);
4515 let host = Host::new(&answers);
4516 analyze(sql, &lex::lex(sql, Dialect::Sqlite).unwrap(), &host, &[]).expect("the schema and the functions were answered")
4517 }
4518
4519 fn listed(extra: &[(&str, i32, char)]) -> Vec<Vec<serde_json::Value>> {
4522 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')];
4523 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')];
4524 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()
4525 }
4526
4527 fn functions_answer(extra: &[(&str, i32, char)]) -> crate::api::Answer {
4528 crate::api::Answer::Rows { rows: listed(extra) }
4529 }
4530
4531 fn on_host(sql: &str, schema: &[String], extra: &[(&str, i32, char)], total: Vec<TotalFunction>) -> Analysis {
4533 analyze_ddl(sql, schema, &Extras { total, host: host_functions(&listed(extra)) }).analysis
4534 }
4535
4536 #[test]
4537 fn names_fold_ascii_case_as_sqlite_folds_them() {
4538 let schema: Vec<String> = [
4539 "create table Books (id integer primary key, Title text not null, ISBN text unique, note text)",
4540 "create table \"\u{c9}t\u{e9}\" (id integer primary key, v text)",
4541 "create table wr (K text primary key, v text) without rowid",
4542 "create table rt (RowId integer, v text)",
4543 "create table \"my table\" (id integer primary key, v text)",
4544 "create trigger \"skip one\" before insert on \"BOOKS\" begin select raise(ignore) where new.title = 'x'; end",
4545 "create trigger skip_two before insert on \"my table\" begin select raise(ignore) where new.v = 'x'; end",
4546 "create trigger [later] after update of \"on\", v on main . [my table] begin select 1; end",
4547 ]
4548 .iter()
4549 .map(|s| s.to_string())
4550 .collect();
4551 let a = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
4552 for sql in [
4555 "select * from books where id = :id",
4556 "select * from BOOKS where ID = :id",
4557 "select * from \"books\" where \"ID\" = :id",
4558 "select * from [BOOKS] b where B.Id = :id",
4559 "select b.* from main.bOOKS b join Books c on c.ID = b.id where C.id = :id",
4560 "select title from books where isbn = :i",
4561 "update BOOKS set TITLE = :t where ID = :id returning Title",
4562 "delete from books where Isbn = :i returning id",
4563 "select v from WR where k = :k",
4564 "select v from Rt where _ROWID_ = :r",
4565 ] {
4566 let got = a(sql);
4567 assert!(got.diagnostics.is_empty(), "{sql}: {:?}", got.diagnostics);
4568 assert_eq!(got.cardinality, "at_most_one", "{sql}: {:?}", got.cardinality_reason);
4569 }
4570 assert_eq!(a("select v from RT where ROWID = :r").cardinality, "many");
4573 assert_eq!(a("select v from wr where rowid = 1").diagnostics[0].message, "no such column: rowid");
4574 let insert = a("insert into BOOKS (TITLE, NOTE) values (:t, :n)");
4576 assert_eq!((param(&insert, "t"), param(&insert, "n")), ("text".into(), "text".into()));
4577 assert_eq!(insert.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [false, true]);
4578 assert_eq!(col(&a("select TITLE, Note from books"), "Title"), ("text".into(), false));
4579 assert_eq!(param(&a("insert into books (ROWID, title) values (:r, :t)"), "r"), "integer");
4581 assert_eq!(param(&a("insert into rt (_rowid_, v) values (:r, :v)"), "r"), "unknown");
4582 assert_eq!(a("select v from \"\u{c9}t\u{e9}\" where id = :id").cardinality, "at_most_one");
4584 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}");
4585 assert_eq!(param(&a("select value from JSON_EACH(:ids)"), "ids"), "text");
4587 assert_eq!(a("insert into books (title) values (:t) returning id").cardinality, "at_most_one");
4590 assert_eq!(a("insert into \"My Table\" (v) values (:v) returning id").cardinality, "at_most_one");
4591 assert_eq!(trigger_header(&schema[5]), Some(("before".into(), "insert".into(), "books".into())));
4592 assert_eq!(trigger_header(&schema[7]), Some(("after".into(), "update".into(), "my table".into())));
4593 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())));
4594 assert_eq!(trigger_header("create table trigger_log (\"on\" text)"), None);
4595 }
4596
4597 #[test]
4598 fn every_row_of_a_values_list_types_its_parameters() {
4599 let a = analysis("insert into users (id, name, email) values (:a, :b, :e), (:c, :d, :e2), (:f, upper(:g), 'x') returning id");
4600 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4601 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();
4602 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)];
4603 assert_eq!(got, want.map(|(n, t, null)| (n.to_string(), t.to_string(), null)));
4604 assert_eq!((a.cardinality.as_str(), a.cardinality_reason.as_deref()), ("many", Some("a VALUES list of 3 rows returns 3 rows")));
4605 let a = analysis("insert into users (name, email) values ('a', :x), (:w, 'b'), ('c', lower(:y))");
4608 assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true, false, false]);
4609 assert_eq!(a.cardinality, "none");
4610 let a = analysis("insert into users (name, email) values ('a', :x), (:x, 'b')");
4611 assert_eq!(a.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [3]);
4612 let a = analysis("with w as (select 1) insert into posts values (:id, :u, :t, :b), (:id2, :u2, :t2, :b2)");
4614 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));
4615 let rows: Vec<String> = (0..3000).map(|i| format!("(:n{i}, :e{i}, {i})")).collect();
4617 let a = analysis(&format!("insert into users (name, email, score) values {}", rows.join(", ")));
4618 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4619 assert_eq!((a.params.len(), param(&a, "n2999"), param(&a, "e2999")), (6000, "text".into(), "text".into()));
4620 let a = analysis("values (1, 'a', :p), (2, null, 3), (:q, 'c', 4.5)");
4623 assert_eq!((col(&a, "column1"), col(&a, "column2")), (("integer".into(), false), ("text".into(), true)));
4624 assert_eq!((param(&a, "p"), param(&a, "q"), a.cardinality.as_str()), ("real".into(), "integer".into(), "many"));
4625 assert_eq!(analysis("values (1, 'a')").cardinality, "one");
4626 assert_eq!(col(&analysis("values (1), ('a')"), "column1").0, "unknown");
4627 assert_eq!(analysis("select v.column1 from (values (1), (2)) v").cardinality, "many");
4628 assert_eq!(analysis("select 1 union all values (2), (3)").cardinality, "many");
4629 assert_eq!(col(&analysis("select (values (1), (2)) as x"), "x"), ("integer".into(), true));
4630 }
4631
4632 #[test]
4633 fn the_select_that_feeds_an_insert_types_its_parameters() {
4634 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()];
4635 let a = |sql: &str| {
4636 let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
4637 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4638 a
4639 };
4640 let params = |a: &Analysis| a.params.iter().map(|p| (affinity_of(&p.ty).unwrap_or("unknown").to_string(), p.nullable)).collect::<Vec<_>>();
4641 let typed = |types: &[&str]| types.iter().map(|t| (t.to_string(), false)).collect::<Vec<_>>();
4642 let got = a("insert into foo (name, meta) select name, ? from bar where ready = ?");
4646 assert_eq!((got.kind.map_or("", StatementKind::as_str), got.cardinality.as_str()), ("insert", "none"));
4647 assert_eq!(params(&got), [("text".to_string(), true), ("numeric".to_string(), false)]);
4648 assert_eq!(params(&a("select name from bar where ready = ?")), typed(&["numeric"]));
4649 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)]);
4652 assert_eq!(params(&a("insert into foo (k, name) select n + :d, upper(:u) from bar limit :l")), typed(&["integer", "text", "integer"]));
4653 assert_eq!(params(&a("insert into foo (name, k) select name, :a from bar union all select :b, n from bar")), typed(&["integer", "text"]));
4654 let returning = a("insert into foo (name, meta) select name, :m from bar where n > :n returning name, meta");
4655 assert_eq!((params(&returning), returning.cardinality.as_str()), (vec![("text".to_string(), true), ("integer".to_string(), false)], "many"));
4656 assert_eq!(params(&a("insert into foo (name, meta) select name, 'x' from bar returning (select :p) as p")), typed(&["unknown"]));
4661 assert_eq!(params(&a("insert into foo (name, k) values ('a', (select :p))")), typed(&["integer"]));
4662 let copy = a("insert into foo2 select * from foo");
4664 assert_eq!((copy.kind.map_or("", StatementKind::as_str), copy.cardinality.as_str()), ("insert", "none"));
4665 }
4666
4667 #[test]
4668 fn the_hosts_sqlite_decides_which_functions_exist() {
4669 let sql = "select id, ACOS(score) as a from users where name = :n";
4671 let a = on_host(sql, &ddl(), &[], Vec::new());
4672 assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
4673 assert_eq!(a.diagnostics[0].message, "no such function: ACOS on this database's SQLite");
4674 assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length, a.diagnostics[0].code), (sql.find("ACOS").unwrap(), 4, 6));
4675 assert!(a.columns.is_empty());
4676 let a = on_host(sql, &ddl(), &[("acos", 1, 's')], Vec::new());
4677 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4678 assert_eq!(col(&a, "a"), ("real".into(), true));
4679 let a = on_host("select soundex(name) as s from users where soundex(:x) = 'A000'", &ddl(), &[("SOUNDEX", 1, 's')], Vec::new());
4680 assert_eq!((col(&a, "s"), param(&a, "x")), (("text".into(), false), "text".into()));
4681 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");
4682 assert_eq!(col(&analysis("select acos(score) as a, soundex(name) as s from users"), "a"), ("real".into(), true));
4684 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());
4686 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4687 for sql in [
4689 "select row_number() over (order by sqrt(score)) as r from users",
4690 "select id from users where id in (select id from users where sqrt(score) > 1)",
4691 "with w as (select sqrt(score) as s from users) select s from w",
4692 "select id from users order by sqrt(score)",
4693 "update users set score = sqrt(score) where id = :id",
4694 "insert into users (name, score) values (:n, sqrt(:s))",
4695 "delete from users where id = :id returning sqrt(score) as s",
4696 ] {
4697 let a = on_host(sql, &ddl(), &[], Vec::new());
4698 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}");
4699 }
4700 let mut schema = ddl();
4703 schema.push("create view roots as select id, sqrt(score) as root from users".into());
4704 let sql = "select root from roots";
4705 let a = on_host(sql, &schema, &[], Vec::new());
4706 assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
4707 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()));
4708 assert_eq!(col(&on_host(sql, &schema, &[("sqrt", 1, 's')], Vec::new()), "root"), ("real".into(), true));
4709 assert!(on_host("select id from users", &schema, &[], Vec::new()).diagnostics.is_empty());
4710 let extra = [("host_only", 2, 's'), ("host_only", 3, 's'), ("host_agg", 1, 'a'), ("host_win", -1, 'w')];
4713 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());
4714 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4715 assert_eq!((col(&a, "two"), col(&a, "three"), a.cardinality.as_str()), (("unknown".into(), true), ("unknown".into(), true), "at_most_one"));
4716 assert_eq!(on_host("select name from users where id = host_only(1, 2)", &ddl(), &extra, Vec::new()).cardinality, "many");
4718 let a = on_host("select host_agg(score) as total from users", &ddl(), &extra, Vec::new());
4719 assert_eq!((col(&a, "total"), a.cardinality.as_str()), (("unknown".into(), true), "one"));
4720 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());
4721 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4722 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()");
4723 let html = vec![TotalFunction { name: "reylo_html".into(), arity: 1, returns: Affinity::Text }];
4725 assert_eq!(col(&on_host("select reylo_html(name) as h from users", &ddl(), &[], html), "h"), ("text".into(), false));
4726 assert_eq!(host_functions(&[]), None);
4728 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' }]));
4729 }
4730
4731 #[test]
4732 fn the_replay_asks_the_host_for_its_functions_with_the_schema() {
4733 let sql = "select acos(score) as a from users";
4734 let lexed = lex::lex(sql, Dialect::Sqlite).unwrap();
4735 let schema = crate::api::Answer::Rows { rows: ddl().iter().map(|d| vec![serde_json::Value::String(d.clone())]).collect() };
4736 let ask = |answers: &HashMap<String, crate::api::Answer>| {
4737 let host = Host::new(answers);
4738 let analysis = analyze(sql, &lexed, &host, &[]);
4739 let needs: Vec<String> = host
4740 .needs()
4741 .iter()
4742 .map(|n| match n {
4743 crate::api::Need::Query { sql, scope, .. } => format!("{sql} {scope:?}"),
4744 crate::api::Need::Describe { sql, .. } => format!("describe {sql}"),
4745 })
4746 .collect();
4747 (analysis, needs)
4748 };
4749 let mut answers = HashMap::new();
4751 let (analysis, needs) = ask(&answers);
4752 assert!(analysis.is_none());
4753 assert_eq!(needs, [format!("{DDL_QUERY} Session"), format!("{FUNCTIONS_QUERY} Session")]);
4754 answers.insert(format!("query:{DDL_QUERY}|[]"), schema);
4755 assert_eq!(ask(&answers).1, [format!("{FUNCTIONS_QUERY} Session")]);
4756 answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]));
4758 let (analysis, needs) = ask(&answers);
4759 assert!(needs.is_empty());
4760 assert_eq!(analysis.unwrap().diagnostics[0].message, "no such function: acos on this database's SQLite");
4761 answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[("acos", 1, 's')]));
4762 assert!(ask(&answers).0.unwrap().diagnostics.is_empty());
4763 answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), crate::api::Answer::Error { error: crate::api::DbError { message: "not authorized".into(), code: None, position: None } });
4765 assert_eq!(col(&ask(&answers).0.unwrap(), "a"), ("real".into(), true));
4766 answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), crate::api::Answer::Rows { rows: Vec::new() });
4767 assert_eq!(col(&ask(&answers).0.unwrap(), "a"), ("real".into(), true));
4768 }
4769
4770 #[test]
4771 fn a_table_in_an_attached_database_is_named_as_one() {
4772 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");
4773 for (sql, reference) in [
4774 ("select id, name from baz.users where id = :id", "baz.users"),
4775 ("select u.id from \"baz\".[users] u", "\"baz\".[users]"),
4776 ("select 1 from users join /* x */ baz . users b on b.id = users.id", "baz . users"),
4777 ("insert into baz.users (id) values (:id)", "baz.users"),
4778 ("update baz.users set name = :n where id = :id", "baz.users"),
4779 ("delete from baz.users where id = :id", "baz.users"),
4780 ] {
4781 let a = analysis(sql);
4782 assert_eq!(a.diagnostics.len(), 1, "{sql}: {:?}", a.diagnostics);
4783 assert_eq!(a.diagnostics[0].message, message("baz"), "{sql}");
4784 assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length), (sql.find(reference).unwrap(), reference.len()), "{sql}");
4785 }
4786 let sql = "select :auth.user_id as u, id from baz.users";
4788 assert_eq!(analysis(sql).diagnostics[0].start, sql.find("baz").unwrap());
4789 assert_eq!(analysis("select id from main.nope").diagnostics[0].message, "no such table: main.nope");
4791 assert_eq!(analysis("select id from temp.nope").diagnostics[0].message, "no such table: temp.nope");
4792 assert_eq!(analysis("select id from \"baz.users\"").diagnostics[0].message, "no such table: baz.users");
4793 assert_eq!(analysis("select id from nope").diagnostics[0].message, "no such table: nope");
4794 assert!(analysis("select main.users.id from main.users").diagnostics.is_empty());
4795 }
4796
4797 #[test]
4798 fn sqlites_own_tables_replay_without_a_note() {
4799 let schema: Vec<String> = [
4802 "CREATE TABLE t (id integer primary key autoincrement, v text)",
4803 "CREATE TABLE sqlite_sequence(name,seq)",
4804 "CREATE TABLE sqlite_stat1(tbl,idx,stat)",
4805 "CREATE VIRTUAL TABLE ft USING fts5(body)",
4806 "CREATE TABLE 'ft_data'(id INTEGER PRIMARY KEY, block BLOB)",
4807 "CREATE TABLE 'ft_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID",
4808 "CREATE TABLE 'ft_content'(id INTEGER PRIMARY KEY, c0)",
4809 "CREATE TABLE 'ft_docsize'(id INTEGER PRIMARY KEY, sz BLOB)",
4810 "CREATE TABLE 'ft_config'(k PRIMARY KEY, v) WITHOUT ROWID",
4811 "CREATE VIRTUAL TABLE rt USING rtree(id, minx, maxx)",
4812 "CREATE TABLE \"rt_rowid\"(rowid INTEGER PRIMARY KEY,nodeno)",
4813 "CREATE TABLE \"rt_node\"(nodeno INTEGER PRIMARY KEY,data)",
4814 "CREATE TABLE \"rt_parent\"(nodeno INTEGER PRIMARY KEY,parentnode)",
4815 "CREATE VIRTUAL TABLE f4 USING fts4(body)",
4816 "CREATE TABLE 'f4_content'(docid INTEGER PRIMARY KEY, 'c0body')",
4817 "CREATE TABLE 'f4_segments'(blockid INTEGER PRIMARY KEY, block BLOB)",
4818 "CREATE TABLE 'f4_segdir'(level INTEGER,idx INTEGER,start_block INTEGER,leaves_end_block INTEGER,end_block INTEGER,root BLOB,PRIMARY KEY(level, idx))",
4819 "CREATE TABLE 'f4_docsize'(docid INTEGER PRIMARY KEY, size BLOB)",
4820 "CREATE TABLE 'f4_stat'(id INTEGER PRIMARY KEY, value BLOB)",
4821 ]
4822 .iter()
4823 .map(|s| s.to_string())
4824 .collect();
4825 let a = |sql: &str, schema: &[String]| analyze_ddl(sql, schema, &Extras::default()).analysis;
4826 let failed = a("select nope from t", &schema);
4828 assert_eq!(failed.diagnostics.iter().map(|d| d.message.as_str()).collect::<Vec<_>>(), ["no such column: nope"]);
4829 for sql in [
4830 "select name, seq from sqlite_sequence where name = :n",
4831 "update sqlite_sequence set seq = :s where name = :n",
4832 "select tbl, idx, stat from sqlite_stat1",
4833 "select name, sql from sqlite_schema where type = 'table'",
4834 "select name from sqlite_master",
4835 "select rowid, body from ft where ft match :q",
4836 "select id from rt where minx > :x",
4837 "select docid from f4 where f4 match :q",
4838 "select block from ft_data where id = :id",
4839 "insert into t (v) values (:v) returning id",
4840 ] {
4841 let got = a(sql, &schema);
4842 assert!(got.diagnostics.is_empty(), "{sql}: {:?}", got.diagnostics);
4843 }
4844 assert_eq!(a("insert into t (v) values (:v) returning id", &schema).cardinality, "one");
4845 assert_eq!(a("delete from sqlite_schema", &schema).diagnostics[0].message, "table sqlite_master may not be modified");
4847 let later = vec!["CREATE TABLE sqlite_sequence(name,seq)".to_string(), "CREATE TABLE u (id integer primary key autoincrement, v text)".to_string()];
4849 assert!(a("select seq from sqlite_sequence", &later).diagnostics.is_empty());
4850 assert_eq!(a("insert into u (v) values (:v) returning id", &later).cardinality, "one");
4851 assert_eq!(a("select nope from u", &later).diagnostics.len(), 1);
4852 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()];
4854 let notes: Vec<String> = a("select nope from t", &broken).diagnostics.iter().map(|d| d.message.clone()).collect();
4855 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"]);
4856 }
4857
4858 #[test]
4859 fn a_double_quoted_word_that_names_no_column_is_refused_as_the_drivers_refuse_it() {
4860 let schema = vec!["create table t (id integer primary key, v text default \"none\" check (v <> \"bad\"))".to_string()];
4862 let a = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
4863 for sql in ["select \"hello\"", "select \"hello\" from t", "select id from t where v = \"x\""] {
4864 let messages: Vec<String> = a(sql).diagnostics.iter().map(|d| d.message.clone()).collect();
4865 assert_eq!(messages, [format!("no such column: \"{}\" - should this be a string literal in single-quotes?", if sql.contains("hello") { "hello" } else { "x" })], "{sql}");
4866 }
4867 for sql in ["select \"id\", \"v\" from t", "select 'hello'", "insert into t (id) values (1) returning v"] {
4868 assert!(a(sql).diagnostics.is_empty(), "{sql}: {:?}", a(sql).diagnostics);
4869 }
4870 }
4871
4872 #[test]
4873 fn the_version_reported_is_the_embedded_sqlites() {
4874 assert!(tree::version().starts_with("3.53."), "{}", tree::version());
4876 }
4877
4878 #[test]
4879 fn a_parameter_sqlite_reads_and_the_lexer_does_not_is_an_error_at_its_place() {
4880 let unbound = |sql: &str| analysis(sql).diagnostics.iter().filter(|d| d.code == 1).map(|d| (d.start, d.length, d.message.clone())).collect::<Vec<_>>();
4881 for written in [":été", ":1st", "@2x"] {
4884 let sql = format!("select id from users where name = :n and email = {written}");
4885 let found = unbound(&sql);
4886 assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(sql.find(written).unwrap(), written.len())], "{sql}");
4887 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"));
4888 }
4889 let sql = "select ':été' from users where name = :été";
4891 assert_eq!(unbound(sql).iter().map(|(s, _, _)| *s).collect::<Vec<_>>(), [sql.rfind(":été").unwrap()]);
4892 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)"] {
4895 assert!(unbound(sql).is_empty(), "{sql}");
4896 }
4897 assert_eq!(analysis("select id as [it's], :n as n from users").params.len(), 1);
4898 }
4899
4900 #[test]
4901 fn a_parameter_as_a_whole_sort_or_group_key_is_an_error_at_its_place() {
4902 let full = |sql: &str| {
4904 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)"];
4905 let rows = ddl.iter().map(|d| vec![serde_json::Value::String(d.to_string())]).collect();
4906 let answers = HashMap::from([(format!("query:{DDL_QUERY}|[]"), crate::api::Answer::Rows { rows }), (format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]))]);
4907 let host = Host::new(&answers);
4908 <crate::api::Sqlite as reylo_engine_core::database::Database>::analyze(sql, &host).expect("answered")
4909 };
4910 let keys = |sql: &str| full(sql).diagnostics.iter().filter(|d| d.code == 17).map(|d| (d.start, d.length, d.message.clone())).collect::<Vec<_>>();
4911 let at = |sql: &str, written: &str| sql.find(written).unwrap();
4912 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)] {
4914 let found = keys(sql);
4915 assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(at(sql, ":sort"), length)], "{sql}");
4916 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");
4917 }
4918 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")] {
4919 let found = keys(sql);
4920 assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(at(sql, written), written.len())], "{sql}");
4921 assert!(found[0].2.starts_with(&format!("order by {written} sorts every row")), "{sql}");
4922 }
4923 assert_eq!(keys("select id from users order by ?2, ?1").iter().map(|(s, ..)| *s).collect::<Vec<_>>(), [30, 34]);
4924 assert_eq!(keys("select id from users order by name, ?").len(), 1);
4925 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");
4927 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"));
4928 let sql = "select row_number() over (partition by :p order by :o) as n from users";
4930 let found = keys(sql);
4931 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())]);
4932 assert_eq!(keys("select row_number() over w as n from users window w as (order by :o)").len(), 1);
4933 assert_eq!(keys("select group_concat(name, ',' order by :o) as names from users").len(), 1);
4934 assert_eq!(keys("select id from (select id from users order by :s limit 3) t").len(), 1);
4937 assert_eq!(keys("with t as (select name from users group by :g, name) select a.name from t a, t b").len(), 1);
4938 assert_eq!(keys("select id from users where id in (select id from users order by :s limit 3)").len(), 1);
4939 let refused = full("select id from users union select id from users order by :s");
4941 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")]);
4942 assert_eq!(keys("insert into users (name) select name from users order by :s").len(), 1);
4943 for sql in [
4947 "select id, :tag as tag from users order by 2",
4948 "select id, :tag as tag from users order by tag",
4949 "select :tenant as tenant, name, count(*) as n from users group by 1, 2",
4950 "select id, name from users order by case :sort when 'name' then name end",
4951 "select id from users order by case when :desc then id end desc, id",
4952 "select id from users order by 1 limit :n",
4953 "select id from users order by lower(:x) || name",
4954 ] {
4955 assert_eq!(keys(sql), [], "{sql}");
4956 }
4957 let a = full("select id from users order by :sort::text");
4959 assert_eq!(a.columns.len(), 1);
4960 assert_eq!(affinity_of(&a.params[0].ty), Some("text"));
4961 }
4962
4963 #[test]
4964 fn names_a_column_as_the_statement_is_sent() {
4965 let names = |sql: &str| analysis(sql).columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>();
4967 assert_eq!(names("select id + cast(:a as integer), name from users"), ["id + cast(? as integer)", "name"]);
4968 assert_eq!(names("select * from (select id + cast(:a as integer) from users)"), ["id + cast(? as integer)"]);
4969 assert_eq!(names("update users set name = name returning id + cast(:a as integer)"), ["id + cast(? as integer)"]);
4970 assert_eq!(names("select cast(:a as integer) as a"), ["a"]);
4971 }
4972
4973 #[test]
4974 fn prepares_the_numbered_rewrite() {
4975 let a = analyzed("select name from users where email = :auth.email and id = :auth.id and score > :auth.email");
4977 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4978 assert_eq!(param(&a, "auth.email"), "text");
4979 assert_eq!(param(&a, "auth.id"), "integer");
4980 assert_eq!(a.rewritten.sql, "select name from users where email = ? and id = ? and score > ?");
4981 assert_eq!(a.rewritten.order, ["auth.email", "auth.id", "auth.email"]);
4982 assert_eq!(param(&analyzed("select name from users where id = ?3"), "3"), "integer");
4984 assert_eq!(param(&analyzed("select name from users where email = ?"), "1"), "text");
4985 let sql = "select :auth.user_id, nope from users";
4987 let a = analyzed(sql);
4988 assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
4989 assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length), (sql.find("nope").unwrap(), 4));
4990 }
4991
4992 #[test]
4993 fn a_column_declared_without_a_type_holds_any_value() {
4994 let ddl = vec!["CREATE TABLE t (a, b TEXT, c ANY)".to_string(), "CREATE TABLE s (x ANY, y INTEGER) STRICT".to_string()];
4995 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());
4996 let a = &r.analysis;
4997 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4998 assert_eq!(col(a, "a"), ("unknown".into(), false));
5000 assert_eq!(col(a, "b"), ("text".into(), true));
5001 assert_eq!(col(a, "x"), ("unknown".into(), false));
5002 assert_eq!(col(a, "y"), ("integer".into(), true));
5003 assert_eq!((param(a, "a"), param(a, "x")), ("unknown".into(), "unknown".into()));
5004 let r = analyze_ddl("SELECT c FROM t", &ddl, &Extras::default());
5006 assert_eq!(col(&r.analysis, "c"), ("numeric".into(), true));
5007 }
5008
5009 #[test]
5010 fn the_direct_entry_reads_a_schema_it_is_handed() {
5011 let ddl = vec![
5012 "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(),
5013 "CREATE INDEX todos_org ON todos (org_id)".to_string(),
5014 ];
5015 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";
5016 let r = analyze_ddl(sql, &ddl, &Extras::default());
5017 let a = &r.analysis;
5018 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5019 assert_eq!(a.kind, Some(StatementKind::Select));
5020 assert!(r.readonly);
5021 assert_eq!(col(a, "id"), ("numeric".into(), false));
5022 assert_eq!(col(a, "title"), ("text".into(), false));
5023 assert_eq!(col(a, "org_id"), ("numeric".into(), true));
5024 assert_eq!(col(a, "n"), ("integer".into(), false));
5025 assert_eq!(r.declared, [Some("uuid".to_string()), Some("varchar(200)".into()), Some("uuid".into()), Some("boolean".into()), None]);
5026 assert_eq!(param(a, "auth.user_id"), "text");
5027 assert_eq!(param(a, "title"), "text");
5028 assert_eq!(a.cardinality, "at_most_one");
5029 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 = ?");
5030 let r = analyze_ddl("INSERT INTO todos (id, owner_id, title) VALUES (:id, :owner, :title) RETURNING id, done", &ddl, &Extras::default());
5032 assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
5033 assert!(!r.readonly);
5034 assert_eq!((r.analysis.kind.map_or("", StatementKind::as_str), r.analysis.cardinality.as_str()), ("insert", "one"));
5035 assert_eq!(col(&r.analysis, "done"), ("bool".into(), false));
5038 assert_eq!(r.unique_keys.len(), 1, "{:?}", r.unique_keys);
5040 let mut keys = r.unique_keys["todos"].clone();
5041 keys.sort();
5042 assert_eq!(keys, [vec!["id".to_string()], vec!["owner_id".into(), "title".into()], vec!["rowid".into()]]);
5043 let r = analyze_ddl("SELECT id FROM todos WHERE id = :a AND title = ?", &ddl, &Extras::default());
5045 assert_eq!(r.analysis.diagnostics.len(), 1, "{:?}", r.analysis.diagnostics);
5046 assert!(r.declared.is_empty() && !r.readonly);
5047 }
5048
5049 #[test]
5050 fn the_unique_keys_of_every_table_read() {
5051 let mut schema = ddl();
5052 schema.push("create unique index users_lower_name on users (lower(name))".into());
5053 schema.push("create unique index posts_title on posts (title) where body is not null".into());
5054 schema.push("create table tags (label text not null, post_id integer not null, primary key (post_id, label)) without rowid".into());
5055 schema.push("create view titled as select p.id, p.title from posts p".into());
5056 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());
5057 assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
5058 let mut tables: Vec<&String> = r.unique_keys.keys().collect();
5059 tables.sort();
5060 assert_eq!(tables, ["posts", "tags", "users"]);
5062 assert_eq!(r.unique_keys["users"], [vec!["id".to_string()], vec!["email".into()]]);
5064 assert_eq!(r.unique_keys["posts"], [vec!["id".to_string()]]);
5066 assert_eq!(r.unique_keys["tags"], [vec!["post_id".to_string(), "label".into()]]);
5068 assert!(analyze_ddl("select nope from users", &schema, &Extras::default()).unique_keys.is_empty());
5070 }
5071
5072 fn html() -> Extras {
5073 Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: 1, returns: Affinity::Text }], host: None }
5074 }
5075
5076 #[test]
5077 fn a_host_function_prepares_and_is_typed_from_its_argument() {
5078 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());
5079 let a = &r.analysis;
5080 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5081 assert_eq!(col(a, "h"), ("text".into(), false));
5082 assert_eq!(col(a, "e"), ("text".into(), true));
5083 assert_eq!(col(a, "q"), ("text".into(), false));
5085 assert_eq!(r.declared, [None, None, None]);
5086 let sql = "select id, reylo_html(name) as h from users";
5089 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()")] {
5090 let a = analyze_ddl(sql, &ddl(), &extras).analysis;
5091 assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
5092 assert_eq!(a.diagnostics[0].message, message);
5093 assert_eq!((a.diagnostics[0].start, a.diagnostics[0].code), (sql.find("reylo_html").unwrap(), 6));
5094 assert!(a.columns.is_empty());
5095 }
5096 let any = Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: -1, returns: Affinity::Text }], host: None };
5098 let mut schema = ddl();
5099 schema.push("create view safe_users as select id, reylo_html(name) as name from users".into());
5100 let a = analyze_ddl("select name, reylo_html(name, name) as twice from safe_users", &schema, &any).analysis;
5101 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5102 assert_eq!(col(&a, "name"), ("text".into(), false));
5103 assert_eq!(col(&a, "twice"), ("text".into(), false));
5104 }
5105
5106 #[test]
5107 fn a_scalar_subquery_is_non_null_only_when_it_always_finds_one_row() {
5108 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");
5109 assert_eq!(col(&a, "n"), ("integer".into(), false));
5110 assert_eq!(col(&a, "top"), ("text".into(), true));
5111 assert_eq!(col(&a, "one"), ("text".into(), true));
5112 assert_eq!(col(&a, "g"), ("integer".into(), true));
5113 assert_eq!(col(&a, "k"), ("integer".into(), false));
5114 }
5115
5116 #[test]
5117 fn truth_values_are_marked_and_typed_boolean() {
5118 let r = analyze_ddl(
5119 "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",
5120 &ddl(),
5121 &Extras::default(),
5122 );
5123 assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
5124 assert_eq!(r.booleans, [true, true, true, true, true, true, true, false, false, true, false]);
5125 assert_eq!(col(&r.analysis, "a"), ("bool".into(), false));
5127 assert_eq!(col(&r.analysis, "b"), ("bool".into(), false));
5128 assert_eq!(col(&r.analysis, "h"), ("integer".into(), false));
5129 let r = analyze_ddl("select t.x, t.y from (select id > 1 as x, id as y from users) t", &ddl(), &Extras::default());
5131 assert_eq!(r.booleans, [true, false]);
5132 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());
5133 assert_eq!(r.booleans, [false]);
5134 let r = analyze_ddl("select id > 1 as x from users union all select email is null from users", &ddl(), &Extras::default());
5135 assert_eq!(r.booleans, [true]);
5136 let r = analyze_ddl("insert into users (name) values ('a') returning id, id > 0 as positive", &ddl(), &Extras::default());
5138 assert_eq!(r.booleans, [false, true]);
5139 assert!(analyze_ddl("select nope from users", &ddl(), &Extras::default()).booleans.is_empty());
5140 }
5141
5142 #[test]
5143 fn a_column_declared_boolean_is_typed_boolean_and_no_truth_value() {
5144 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()];
5145 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());
5146 assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
5147 let types: Vec<String> = r.analysis.columns.iter().map(|c| affinity_of(&c.ty).unwrap_or("?").to_string()).collect();
5148 assert_eq!(types, ["bool", "bool", "integer", "integer", "real", "bool", "numeric", "bool", "bool", "bool"]);
5150 assert_eq!(r.booleans, [false; 10]);
5152 let r = analyze_ddl("select done from v", &ddl, &Extras::default());
5154 assert_eq!(col(&r.analysis, "done"), ("bool".into(), false));
5155 let r = analyze_ddl("select done from flags union all select 5", &ddl, &Extras::default());
5156 assert_ne!(affinity_of(&r.analysis.columns[0].ty), Some("bool"));
5157 let r = analyze_ddl("select done from flags union all select id > 1 from flags", &ddl, &Extras::default());
5158 assert_eq!(affinity_of(&r.analysis.columns[0].ty), Some("bool"));
5159 }
5160
5161 fn ts(t: &Type, in_json: bool) -> String {
5164 let null = |s: String, nullable: bool| if nullable { format!("{s} | null") } else { s };
5165 let list = |s: String| if s.contains('|') { format!("({s})[]") } else { format!("{s}[]") };
5166 match &t.kind {
5167 Kind::Json(crate::types::JsonType { content: Some(c), .. }) => ts(&c.ty, true),
5168 Kind::Struct(r) => {
5169 let fields: Vec<String> = r.fields.iter().map(|f| format!("{}: {}", f.name, null(ts(&f.ty, true), f.nullable))).collect();
5170 if fields.is_empty() { "Record<never, never>".into() } else { format!("{{ {} }}", fields.join("; ")) }
5171 }
5172 Kind::Array(a) => list(null(ts(&a.element.ty, true), a.element.nullable)),
5173 Kind::Json(crate::types::JsonType { schema: Some(_), .. }) => schema_ts(&t.schema().unwrap_or(serde_json::Value::Bool(true))),
5174 _ => match (affinity_of(t).unwrap_or("?"), in_json) {
5175 ("integer" | "real", _) | ("int8", true) => "number".into(),
5176 ("int8", false) => "bigint".into(),
5177 ("text", _) => "string".into(),
5178 ("numeric", _) => "number | string".into(),
5179 ("blob", false) => "Uint8Array".into(),
5180 ("bool", _) => "boolean".into(),
5181 _ => "unknown".into(),
5182 },
5183 }
5184 }
5185
5186 fn affinity_of(t: &Type) -> Option<&'static str> {
5188 let name = t.label.as_deref().unwrap_or("");
5189 match &t.kind {
5190 Kind::Enum(e) => affinity_of(&e.ty),
5192 Kind::Boolean(_) => Some("bool"),
5193 Kind::Integer(_) if name == "BIGINT" => Some("int8"),
5194 Kind::Integer(_) => Some("integer"),
5195 Kind::Float(_) => Some("real"),
5196 Kind::Text(_) => Some("text"),
5197 Kind::Bytes(_) => Some("blob"),
5198 Kind::Union(_) if is_boolean_declared(name) => Some("bool"),
5199 Kind::Union(u) if u.members.len() == 2 => Some("text"),
5200 Kind::Union(u) if u.members.len() == 3 => Some("real"),
5201 Kind::Union(_) if affinity(name) == "integer" && is_int8_declared(name) => Some("int8"),
5202 Kind::Union(_) => Some(affinity(name)),
5203 _ => None,
5204 }
5205 }
5206
5207 fn schema_ts(s: &serde_json::Value) -> String {
5208 if let Some(any) = s["anyOf"].as_array() {
5209 return any.iter().map(schema_ts).collect::<Vec<_>>().join(" | ");
5210 }
5211 let kinds: Vec<&str> = match &s["type"] {
5212 serde_json::Value::String(k) => vec![k.as_str()],
5213 serde_json::Value::Array(ks) => ks.iter().filter_map(|k| k.as_str()).collect(),
5214 _ => return "unknown".into(),
5215 };
5216 let one = |kind: &str| match kind {
5217 "integer" | "number" => "number".to_string(),
5218 "string" => "string".into(),
5219 "null" => "null".into(),
5220 "array" => match s["prefixItems"].as_array() {
5221 Some(items) => format!("[{}]", items.iter().map(schema_ts).collect::<Vec<_>>().join(", ")),
5222 None if s["items"] == false => "[]".into(),
5223 None => {
5224 let item = schema_ts(&s["items"]);
5225 if item.contains('|') { format!("({item})[]") } else { format!("{item}[]") }
5226 }
5227 },
5228 "object" => match s["properties"].as_object() {
5229 _ if s["additionalProperties"] == false && s["properties"].as_object().is_none_or(|p| p.is_empty()) => "Record<never, never>".into(),
5230 Some(p) if !p.is_empty() => format!("{{ {} }}", p.iter().map(|(k, v)| format!("{k}: {}", schema_ts(v))).collect::<Vec<_>>().join("; ")),
5231 _ => format!("{{ [key: string]: {} }}", schema_ts(&s["additionalProperties"])),
5232 },
5233 _ => "unknown".into(),
5234 };
5235 kinds.into_iter().map(one).collect::<Vec<_>>().join(" | ")
5236 }
5237
5238 fn shown(a: &Analysis) -> String {
5240 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5241 a.columns.iter().map(|c| format!("{}: {}{}", c.name, ts(&c.ty, false), if c.nullable { " | null" } else { "" })).collect::<Vec<_>>().join("; ")
5242 }
5243
5244 fn json_ddl() -> Vec<String> {
5245 vec![
5246 "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(),
5247 "create table posts (id integer primary key, user_id integer not null references users(id), title text not null, body text) strict".to_string(),
5248 "create view titled as select id, json_object('id', id, 'title', title) as post from posts".to_string(),
5249 ]
5250 }
5251
5252 fn json_typed(sql: &str) -> String {
5253 shown(&analyze_ddl(sql, &json_ddl(), &Extras::default()).analysis)
5254 }
5255
5256 #[test]
5257 fn json_whose_subtype_is_out_of_sight_is_any_json() {
5258 assert_eq!(
5261 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"),
5262 "doc: { ids: unknown }; top: [unknown]; counted: { n: number }; total: number"
5263 );
5264 assert_eq!(json_typed("select json_object('ids', json_group_array(id)) as doc from posts group by user_id"), "doc: { ids: number[] }");
5265 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");
5267 assert_eq!(json_typed("select json(json((select json_object('a', 1) where 0))) as v"), "v: { a: number } | null");
5269 assert_eq!(json_typed("select json_object('k', json(jsonb((select json_object('a', 1) where 0)))) as w"), "w: { k: { a: number } | null }");
5270 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()];
5274 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]");
5275 assert_eq!(shown(&analyze_ddl("select json_object('j', j) as v from (select j from d)", &schema, &Extras::default()).analysis), "v: { j: unknown }");
5276 }
5277
5278 #[test]
5279 fn a_number_beside_a_numeric_value_is_a_number_or_text() {
5280 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()];
5281 let typed = |sql: &str| col(&analyze_ddl(sql, &schema, &Extras::default()).analysis, "v");
5282 assert_eq!(typed("select ifnull(dt, 0) as v from dts"), ("numeric".into(), false));
5284 assert_eq!(typed("select case when ok then d else 0 end as v from dts"), ("numeric".into(), false));
5285 assert_eq!(typed("select coalesce(dt, 1.5) as v from dts"), ("numeric".into(), false));
5286 assert_eq!(typed("select coalesce(n, 1.5) as v from dts"), ("integer".into(), false));
5287 assert_eq!(typed("select iif(ok, n, x) as v from dts"), ("real".into(), false));
5288 }
5289
5290 #[test]
5291 fn a_window_call_is_no_value_every_row_shares() {
5292 let count = |sql: &str| analyze_ddl(sql, &ddl(), &Extras::default()).analysis.cardinality;
5293 assert_eq!(count("select distinct min(1) over (order by id rows between 1 preceding and 1 preceding) as m from users"), "many");
5294 assert_eq!(count("select distinct max(1) filter (where id > 2) over (order by id) as m from users"), "many");
5295 assert_eq!(count("select distinct 1 as m from users"), "at_most_one");
5296 }
5297
5298 #[test]
5299 fn a_date_conversion_newer_than_libsql_s_sqlite_is_nullable() {
5300 let typed = |sql: &str| col(&analyze_ddl(sql, &ddl(), &Extras::default()).analysis, "v");
5301 assert_eq!(typed("select strftime('%Y-%m-%d', 'now') as v"), ("text".into(), false));
5304 assert_eq!(typed("select strftime('%G-W%V', 'now') as v"), ("text".into(), true));
5305 assert_eq!(typed("select date('now', 'start of month', '+1 month', 'floor') as v"), ("text".into(), true));
5306 }
5307
5308 #[test]
5309 fn a_json_constructor_is_typed_as_the_json_it_builds() {
5310 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";
5313 assert_eq!(json_typed(profile), "profile: { user: { id: number; name: string }; posts: { id: number; title: string }[] }");
5314 let bare = profile.replace("json((select", "((select");
5316 assert_eq!(json_typed(&bare), "profile: { user: { id: number; name: string }; posts: unknown }");
5317 assert_eq!(json_typed("select (select json_group_array(id) from posts) as ids"), "ids: number[]");
5319 assert_eq!(json_typed("select json((select json_object('n', name) from users where id = 1)) as u"), "u: { n: string } | null");
5320 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 }");
5321 let a = analyze_ddl(profile, &json_ddl(), &Extras::default()).analysis;
5322 assert_eq!((a.columns[0].ty.kind.name(), a.cardinality.as_str()), ("json", "at_most_one"));
5323 assert_eq!(
5328 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"),
5329 "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 }"
5330 );
5331 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>]");
5334 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 }");
5335 assert_eq!(json_typed("select json_object('k', id, 'k', name) as o from users"), "o: { k: string }");
5337 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 }");
5339 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)[]");
5342 assert_eq!(
5343 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"),
5345 "f: { f: unknown }; w: { w: unknown }"
5346 );
5347 assert_eq!(
5348 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"),
5349 "id: number; titles: string[]; grouped: string[] | null"
5350 );
5351 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] }");
5354 assert_eq!(json_typed("select jsonb(json_array(1)) as b, (select jsonb_group_array(id) from users) as g"), "b: Uint8Array; g: Uint8Array");
5355 assert_eq!(json_typed("select post from titled"), "post: { id: number; title: string }");
5357 assert_eq!(json_typed("with t as (select json_array(id) as x from users) select x from t"), "x: [number]");
5358 assert_eq!(json_typed("select max(json_array(id)) as m from users"), "m: [number] | null");
5359 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 }");
5360 }
5361
5362 #[test]
5363 fn a_value_nests_as_json_only_where_it_keeps_sqlites_json_subtype() {
5364 for (expr, ty) in [
5366 ("coalesce(json_array(id), 'x')", "[number]"),
5367 ("ifnull(json_array(id), 'x')", "[number]"),
5368 ("nullif(json_array(id), 'x')", "[number] | null"),
5369 ("iif(id > 1, json_array(id), json_array(0))", "[number]"),
5370 ("case when id > 1 then json_object('x', id) end", "{ x: number } | null"),
5371 ("json_array(id) collate nocase", "[number]"),
5372 ("+json_array(id)", "[number]"),
5373 ("likely(json_array(id))", "[number]"),
5374 ("json((select json_object('n', name) from users u2 where u2.id = users.id))", "{ n: string } | null"),
5376 ("json((select json_group_array(p.id) from posts p where p.user_id = users.id order by p.id))", "number[]"),
5377 ("json((select json_array(1)))", "[number]"),
5378 ("json_array((select name from users u2 where u2.id = users.id))", "[string | null]"),
5380 ("json_group_array((select name from users u2 where u2.id = users.id))", "(string | null)[]"),
5381 ("coalesce(json((select json_group_array(p.id) from posts p where p.user_id = users.id)), '[]')", "number[]"),
5383 ("coalesce(json_object('e', email), json_array())", "{ e: string | null }"),
5384 ("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[]"),
5385 ("doc", "string | null"),
5387 ("json_array(id) || ''", "string"),
5388 ("upper(json_array(id))", "string"),
5389 ("length(json_array(id))", "number"),
5390 ("json_type(json_array(id))", "string"),
5391 ("json_array_length(json_array(id))", "number"),
5392 ] {
5393 assert_eq!(json_typed(&format!("select json_object('a', {expr}) as o from users")), format!("o: {{ a: {ty} }}"), "{expr}");
5394 }
5395 for expr in [
5398 "x",
5399 "post",
5400 "(select json_object('n', name) from users u2 where u2.id = users.id)",
5402 "(select json_array(1))",
5403 "(select json_object('id', id) from users order by name limit 1)",
5404 "(select distinct json_array(id) from users)",
5405 "(select json_array(1) union all select json_array(2))",
5406 "lag(json_array(id)) over (order by id)",
5407 "max(json_array(id), json_array(0))",
5408 "cast(json_array(id) as text)",
5409 "doc ->> '$.a'",
5410 "json_pretty(json_array(1))",
5411 "case when id > 1 then json_array(id) else 'x' end",
5412 "case when id > 1 then json_array(id) else json_object('a', 1) end",
5413 ] {
5414 let sql = format!("select json_object('a', {expr}) as o from (select *, json_array(id) as x from users) users, (select post from titled)");
5415 assert_eq!(json_typed(&sql), "o: { a: unknown }", "{expr}");
5416 }
5417 for expr in ["json(doc)", "json_extract(doc, '$.a')", "doc -> '$.a'", "json_set(doc, '$.a', 1)", "json_quote(name)"] {
5420 assert_eq!(json_typed(&format!("select json_object('a', {expr}) as o from users")), "o: { a: unknown | null }", "{expr}");
5421 }
5422 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()];
5423 for (expr, ty) in [
5424 ("json_object('k', json(doc))", "{ k: unknown | null }"),
5425 ("json_object('k', doc -> '$')", "{ k: unknown | null }"),
5426 ("json_object('k', json_extract(doc, '$'))", "{ k: unknown | null }"),
5427 ("json_object('k', json(b))", "{ k: unknown | null }"),
5428 ("json_group_array(json(doc))", "(unknown | null)[]"),
5429 ] {
5430 assert_eq!(shown(&analyze_ddl(&format!("select {expr} as o from js"), ¬_null, &Extras::default()).analysis), format!("o: {ty}"), "{expr}");
5431 }
5432 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 };
5434 let a = analyze_ddl("select json_array(1) as a, json_object('b', html(name)) as b from users", &json_ddl(), &host).analysis;
5435 assert_eq!(shown(&a), "a: string; b: { b: unknown }");
5436 }
5437
5438 #[test]
5439 fn a_deep_constructor_is_read_once_per_node() {
5440 let ddl = vec!["create table users (id integer primary key, name text not null)".to_string()];
5443 let deep = |open: &str, close: &str, n: usize| format!("select {}id{} as o from users", open.repeat(n), close.repeat(n));
5444 let started = std::time::Instant::now();
5445 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)] {
5446 let a = crate::stack::run(|| analyze_ddl(&sql, &ddl, &Extras::default()).analysis);
5447 assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5448 }
5449 assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
5450 }
5451
5452 #[test]
5453 fn built_json_beside_other_text_is_the_text_it_is() {
5454 assert_eq!(
5456 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"),
5457 "a: [number]; b: string; c: string; d: [number] | null"
5458 );
5459 assert_eq!(json_typed("select json_array(id) as a from users union all select 'x'"), "a: string");
5460 assert_eq!(json_typed("select json_array(id) as a from users union all select null"), "a: [number] | null");
5461 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"]);
5464 assert_eq!(shown(&a), "d: string; o: { a: unknown }");
5465 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"]);
5466 }
5467
5468 #[test]
5469 fn a_json_object_of_an_odd_count_of_arguments_is_built_in_alone() {
5470 let sql = "select json_object('id', id, 'name') as j from users";
5471 let odd = |extras: &Extras| analyze_ddl(sql, &ddl(), extras).analysis.diagnostics.iter().filter(|d| d.code == 15).count();
5472 assert_eq!(odd(&Extras::default()), 1);
5473 let listed = |arities: &[i32]| Extras { total: vec![], host: Some(arities.iter().map(|&arity| HostFunction { name: "json_object".into(), arity, kind: 's' }).collect()) };
5474 assert_eq!(odd(&listed(&[-1])), 1);
5475 assert_eq!(odd(&listed(&[-1, 3])), 0);
5477 assert_eq!(odd(&Extras { total: vec![TotalFunction { name: "JSON_OBJECT".into(), arity: 3, returns: Affinity::Text }], host: None }), 0);
5478 }
5479
5480 #[test]
5481 fn a_modulo_by_a_fractional_literal_under_one_is_nullable() {
5482 let schema = vec!["create table items (id integer primary key, qty integer not null)".to_string()];
5485 let typed = |sql: &str| {
5486 let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
5487 assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
5488 col(&a, "r")
5489 };
5490 assert_eq!(typed("select qty % 0.5 as r from items"), ("real".into(), true));
5491 assert_eq!(typed("select qty % 0.99 as r from items"), ("real".into(), true));
5492 assert_eq!(typed("select qty % 1e-3 as r from items"), ("real".into(), true));
5493 assert_eq!(typed("select qty % 2.5 as r from items"), ("real".into(), false));
5494 assert_eq!(typed("select qty % 2 as r from items"), ("integer".into(), false));
5495 assert_eq!(typed("select qty % 1e999 as r from items"), ("real".into(), false));
5497 assert_eq!(typed("select qty / 0.5 as r from items"), ("real".into(), false));
5498 assert_eq!(typed("select qty / 0 as r from items"), ("integer".into(), true));
5499 }
5500
5501 #[test]
5502 fn sqlite_only_syntax_parses() {
5503 let a = analysis("select id from users limit :n, :m");
5504 assert_eq!(param(&a, "n"), "integer");
5505 assert_eq!(analysis("insert or replace into users (id, name) values (:id, :name) returning id").cardinality, "one");
5506 }
5507}
5508