Skip to main content

reylo_engine_sqlite/
sqlite.rs

1//! The SQLite analysis, over SQLite's own resolved tree ([`crate::sqlite_tree`], produced by
2//! `csrc/reylo_sqlite.c` from a patched amalgamation). SQLite resolves the names, the join sides,
3//! every parameter's context and the DML target columns itself, and reports each expression's
4//! affinity. What SQLite has no facts for stays here, as explicit tables: the result type and
5//! nullability of the built-in functions, the type a function gives its arguments, the arithmetic
6//! rule, and the row-count proof from the unique keys. The host runs two queries, one for the
7//! schema DDL and one for the functions its SQLite has; everything else happens inside the engine.
8//!
9//! Two entries share the code: [`analyze`], replayed through the [`Host`] like every dialect, and
10//! [`analyze_ddl`], for a host that holds a live connection and runs [`DDL_QUERY`] and
11//! [`FUNCTIONS_QUERY`] on it itself, with [`Extras`] naming the scalar functions it registers there.
12
13use 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/// What the analysis reasons in: a value's storage class by the affinity name SQLite gives it
23/// (`integer`, `real`, `text`, `blob`, `numeric`; `int8` for a value a column declared 64 bits wide
24/// holds, `bool` for a truth value or a column declared BOOLEAN), the JSON a constructor builds,
25/// or nothing known. The analysis hands each result column and parameter on as the format's type
26/// ([`descriptor`]).
27#[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
44/// The schema, as SQLite stores it: its `sql` column is the DDL the engine replays into its
45/// in-memory copy. The replayed entry asks the host for it; a host with a connection of its own
46/// runs it there and hands the rows to [`analyze_ddl`].
47pub 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
49/// The functions the host's SQLite has, which decide what a statement may call: SQLite builds
50/// differ in them (the math functions, `soundex`, a newer release's additions), and the embedded
51/// one has every optional family, so it alone would accept a call the host then refuses to run.
52/// The replayed entry asks the host for it; a host with a connection of its own runs it there and
53/// hands the rows to [`Extras::host`] through [`host_functions`]. A SQLite that cannot answer (an
54/// old one whose pragma lacks these columns, or a service that refuses the pragma) is taken to
55/// have what the embedded one has.
56pub const FUNCTIONS_QUERY: &str = "select name, narg, type from pragma_function_list";
57
58/// One row of [`FUNCTIONS_QUERY`].
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct HostFunction {
61    pub name: String,
62    /// The argument count as SQLite keeps it: -1 for any number.
63    pub arity: i32,
64    /// `s` for a scalar function, `a` for an aggregate, `w` for a window function.
65    pub kind: char,
66}
67
68/// The rows of [`FUNCTIONS_QUERY`] as the host's function list; `None` when there is none to
69/// read, since every SQLite has functions and an empty list would refuse every call.
70pub 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/// A scalar function the host registers on its own connection, which the engine's replay cannot
84/// see: the replay registers a stub under the same name and argument count, so a statement calling
85/// it prepares, and the function table types a call as `returns`, NULL only when an argument is.
86/// A function the host vouches for as total, Postgres's `Trust::total` in SQLite's terms: NULL only
87/// when an argument is, with the argument count SQLite resolves a call by.
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct TotalFunction {
90    pub name: String,
91    /// How many arguments it takes; -1 for any number.
92    pub arity: i32,
93    /// The storage class its value lands in.
94    pub returns: Affinity,
95}
96
97/// A storage class a value lands in, as SQLite names a column's affinity.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99pub enum Affinity {
100    Integer,
101    Real,
102    Text,
103    Blob,
104    Numeric,
105    /// Any storage class: SQLite's "none".
106    Any,
107}
108
109impl Affinity {
110    /// The affinity's name, as the tree and the type model spell it.
111    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/// What a host says of the SQLite on its own connection: the functions it registers there, and
124/// the functions that SQLite has ([`FUNCTIONS_QUERY`]; `None` when it cannot list them).
125#[derive(Debug, Clone, Default)]
126pub struct Extras {
127    pub total: Vec<TotalFunction>,
128    pub host: Option<Vec<HostFunction>>,
129}
130
131impl Extras {
132    /// The registration a call resolves to: SQLite prefers a host function over a built-in of the
133    /// same name and argument count.
134    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/// [`analyze_ddl`]'s answer: the analysis, and what the tree adds for a host that types a result
140/// column by the spelling its table declares.
141#[derive(Debug, Clone)]
142pub struct SqliteAnalysis {
143    pub analysis: Analysis,
144    /// Per result column, the declared type of the table column it reads
145    /// (`sqlite3_column_decltype`, through subqueries and views); `None` for an expression. Empty
146    /// when the statement did not prepare.
147    pub declared: Vec<Option<String>>,
148    /// `sqlite3_stmt_readonly`; false when the statement did not prepare.
149    pub readonly: bool,
150    /// The unique keys of every table the statement reads or writes (through views and
151    /// subqueries), by the table's name as its DDL spells it: every unique, non-partial index over
152    /// plain columns, the `INTEGER PRIMARY KEY`, and `rowid` for a rowid table without one. What
153    /// the row-count proof reads, for a host that runs that proof over text of its own. Empty when
154    /// the statement did not prepare.
155    pub unique_keys: HashMap<String, Vec<Vec<String>>>,
156    /// Per result column, whether it is a truth value: a comparison, `IN`, `BETWEEN`, `EXISTS`,
157    /// `IS`, `IS NULL`, `NOT`, `AND`, `OR`, `TRUE` or `FALSE`, a `like`, `glob`, `regexp` or `match`
158    /// call, or a `CASE`, `coalesce`, `ifnull`, `iif`, scalar subquery or subquery column whose
159    /// every value is one. SQLite stores one as the integer 0 or 1, and its type stays `integer`;
160    /// a host that types by meaning reads it as a boolean. Empty when the
161    /// statement did not prepare.
162    pub booleans: Vec<bool>,
163}
164
165/// The replayed entry: the host answers [`DDL_QUERY`] and [`FUNCTIONS_QUERY`] (session-scoped,
166/// asked in one round), the rest is [`run`]. `marked` names the parameters cast to `nullable(…)`.
167pub 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    // A host that cannot list its functions keeps the embedded SQLite's.
176    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
180/// The direct entry, for a host with a connection of its own: `ddl` is the `sql` column of
181/// [`DDL_QUERY`] run there, `extras` the functions it registers there. No round trip; a lex
182/// error, a prepare error (SQLite's own message, at its offset) and a replay failure come back as
183/// diagnostics, as on the replayed path.
184pub 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
195/// How the statement writes its result columns: a write's `RETURNING`, or a query's select list, the
196/// first arm's of a compound, whose names are the result's. SQLite has expanded each `*` by now, into
197/// columns it names. `None` for a write without `RETURNING`.
198fn result_targets(t: &Tree) -> Option<Vec<ResultTarget>> {
199    // `RETURNING`'s names are not resolved yet where the serializer reads them.
200    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    // `values (1, 2)`: named column1 and column2 by SQLite, by nothing in the statement.
209    if first.values {
210        return Some(vec![ResultTarget::Unnamed(None); first.columns.len()]);
211    }
212    Some(first.columns.iter().map(target).collect())
213}
214
215/// The statements the SQLite analysis reads; any other is a command ([`lex::Statement`]).
216const 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    // SQLite prepares the `?n` rewrite, not the author's text: its own `:name` ends at the first
225    // dot, so `:auth.user_id` survives only as a number. `?n` is the lexer's n-th parameter, which
226    // is how `params` matches them back, and an error offset maps back through the rewrite.
227    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    // libSQL's `ALTER TABLE t ALTER COLUMN c TO <definition>` is prepared as the RENAME COLUMN of
234    // the same column, which SQLite has, to a name no table has: it prepares where libSQL's does,
235    // on an existing table and column, and the definition is libSQL's to read when it runs.
236    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        // An offset into the stand-in past its RENAME is one character past the ALTER it replaced.
248        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            // The embedded SQLite has the function; the SQLite the statement will run on does not.
260            (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            // The replay holds the database file's own schema. An ATTACH is an act of the
265            // application's connection at run time, and nothing in the file names it.
266            (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        // A statement that fails against the replayed schema often fails because a replay step did.
272        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    // SQLite prepared the `?n` rewrite, so each of its parameters is one the lexer numbered. Any
282    // other is one SQLite reads and the lexer does not (`:été`, whose name the lexer ends before):
283    // it stayed in the text, takes no value and would run as NULL. An error where it stands.
284    for p in t.params.iter().filter(|p| !lexed_parameter(p, lexed)) {
285        // Where it stands: the first place its name is written outside a string, a quoted name or a comment.
286        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    // A JSON object of an odd count of arguments, which SQLite prepares and refuses when it runs;
293    // only the built-in constructors, which a function the host registers under the name overrides
294    // (`Extras::function`). The host's list names the built-ins with any argument count (-1).
295    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    // A parameter as a whole sort or group key is an error; the rest is typed all the same.
299    diagnostics.extend(constant_keys(sql, lexed, &t));
300    // The parameters cast to `nullable(…)`, by the `?n` the tree names each by.
301    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    // A command (DDL, a PRAGMA, a transaction's control) has no tree to read: SQLite's prepare
305    // says what it takes and returns, and nothing says where a column comes from, so each is of
306    // no known type and may be NULL. One that returns no rows runs as a write does.
307    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    // A truth value SQLite computes is a boolean, which the oracle holds to 0 and 1; a column
342    // declared BOOLEAN, read or passed through, holds whatever was stored in it, and the loader's
343    // run time reads it as a truth value by its name, refusing any other value (src/values.ts).
344    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    // A parameter cast to `nullable(…)` and written whole to a column that refuses null would be
363    // refused at run time for the null its type allows: an error at the parameter.
364    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
401/// The schema's triggers, and what the engine replays of the schema. Triggers are not replayed (a
402/// body may call a function only the application registers); their headers say which statements a
403/// trigger can skip a row of. An INSTEAD OF trigger is replayed with an empty body, which is what
404/// lets a write to its view through.
405fn 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
411/// The host's functions as the walker takes them.
412fn 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
416/// Whether the table an INSERT writes declares its PRIMARY KEY or a UNIQUE ON CONFLICT REPLACE, as
417/// the embedded SQLite parsed the schema ([`tree::TableInfo::replaces`]), however its DDL spells
418/// the clause: the INSERT, with no OR clause of its own, then deletes the row it conflicts with,
419/// and a foreign key's action follows the delete. The statement is prepared again on the replay
420/// the analysis made, from the same answers. True where it does not prepare, or writes no table
421/// the tree describes.
422pub(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
434/// Whether a WITH query reads itself: an arm of its statement has a FROM item SQLite marks as the
435/// query's recursive read of itself.
436fn 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
447/// The tables the statement names, as SQLite resolved them, for its errors pass: each table
448/// and view a FROM clause reads, in subqueries, WITH queries and expressions too, and the table it
449/// writes. A view is named, never what it reads; a WITH query, a subquery and a table-valued
450/// function are no table. SQLite expands a view into a subquery as it does a derived table, and
451/// marks both a view: a view keeps the name the statement writes, a derived table has none. A
452/// recursive WITH query's reference to itself is marked as nothing at all, so a name the statement
453/// gives a WITH query is no table anywhere in it.
454fn 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
519/// Whether SQLite's parameter is one the lexer read: the statement is prepared as its `?n` rewrite,
520/// which names the lexer's parameters `?1` to `?N`.
521fn 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
525/// The error of each parameter that is, bare or under casts and collations, a whole key of an
526/// ORDER BY (a statement's, a window's or an aggregate's), a GROUP BY or a window's PARTITION BY,
527/// anywhere in the statement, at the placeholder as the author wrote it. A key that only holds a
528/// parameter (`case :sort when 'name' then name end`) is none.
529fn 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    /// Every parameter an expression reads, at any depth.
538    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        /// A select's own ORDER BY and GROUP BY. SQLite resolves a key that is a position or a
555        /// result column's alias (`order by 2`, `group by tag`) to a copy of that column's
556        /// expression, so a key that is a parameter the select list reads is such a copy: the
557        /// author writes each parameter once.
558        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    // SQLite prepared the `?n` rewrite, whose n is the lexer's n-th parameter, which appears once.
614    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/// What an expression is: its affinity as the type model, and whether it can be NULL.
633#[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
648/// SQLite's storage classes as the format's types: a 64-bit integer, a double that holds the
649/// infinities (a NaN is stored as NULL), text that is never validated as UTF-8, and bytes.
650fn 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
660/// What a column of an affinity holds outside a STRICT table: an INTEGER or NUMERIC one any
661/// storage class, a REAL one a float, text or bytes, a TEXT one text or bytes.
662fn 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
671/// The format's type of a value the analysis typed `ty` ([`Ty`]). A column read as it is
672/// (`declared`, the type its table declares, through subqueries and views) holds what its affinity
673/// stores, under that name: SQLite keeps what it cannot convert as it is. One that is `exact`, in a
674/// STRICT table or a rowid, holds its declared type alone ([`Analyzer::exacts`]). A value the statement
675/// computes is the storage class the analysis gives it, a 64-bit column's under `BIGINT` and a
676/// column declared BOOLEAN's under `BOOLEAN`, the names a client reads it by; a truth value SQLite
677/// computes (`computed`) is a boolean, delivered as 1 or 0.
678fn descriptor(ty: &Ty, declared: Option<&str>, computed: bool, exact: bool) -> Type {
679    // SQLite gives a compound's column the first arm's declared type: it names the value only
680    // where the value is what a column of that type holds.
681    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
710/// The values an expression is one of, where it writes them all: a string, which SQLite reads as
711/// written, a number in decimal, `TRUE` and `FALSE`, a number's negation, and a `CASE` whose every
712/// result is one, through a unary plus and a `COLLATE`. NULL is none.
713fn 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            // `list` alternates WHEN and THEN; an odd tail is the ELSE.
730            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
740/// A value inside a document SQLite built: an object's fields and an array's items, each the
741/// value SQLite wrote there.
742fn 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
750/// The type of a table column's values: its affinity, except that a column declared with no type,
751/// or `ANY` in a STRICT table, holds a value of any storage class, and that a column declared with
752/// a 64-bit integer's name ([`is_int8_declared`]) is `int8`, the type Postgres's `int8` and MySQL's
753/// `BIGINT` are: the declared width decides, on every database (wiki/driver-decoding.md). (`ANY` in
754/// a table that is not STRICT is a declared type like any other, with NUMERIC affinity.)
755fn 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
766/// Whether a declared type names a 64-bit integer: `BIGINT`, `INT8` or `UNSIGNED BIG INT`, the
767/// names SQLite's own documentation lists for one, in any case, with any spacing between words and
768/// a size after it ignored (`bigint(20)`, as a MySQL dump writes it). `INTEGER`, `INT` and the
769/// other integer names are SQLite's INTEGER, a `number`; so is the rowid, whatever its alias is
770/// declared, since only `INTEGER PRIMARY KEY` is one.
771fn 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
776/// An affinity name as the type model; `none` is unknown.
777fn 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
795/// Whether a type is an integer's: SQLite's INTEGER, or a column declared 64 bits wide.
796fn is_integral(t: &Ty) -> bool {
797    matches!(scalar_name(t), Some("integer" | "int8"))
798}
799
800/// The type of a value computed from one of type `t`: a 64-bit column's value passes through
801/// unchanged only as itself (a column, a subquery's or view's column, `min`, `max`, `coalesce`, a
802/// `CASE` arm, a window's `lag`), and what SQLite computes from it (`-id`, `abs(id)`, `sum(id)`,
803/// `id + 1`) is SQLite's INTEGER, as `count(*)` is.
804fn computed(t: Ty) -> Ty {
805    if scalar_name(&t) == Some("int8") {
806        Ty::Scalar { name: "integer".into() }
807    } else {
808        t
809    }
810}
811
812/// The type several arms share: one type when they agree, `int8` for a mix of integers of which
813/// one is a 64-bit column's (`coalesce(user_id, 0)`: any integer is exact as a BigInt), `numeric`
814/// for a mix with a NUMERIC value, `real` for another mix of numbers, unknown otherwise.
815fn 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    // Built JSON is text to SQLite: beside a value of no known type (a parameter:
819    // `coalesce(:doc, json_array())`), or another type, it is the text it is.
820    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        // A NUMERIC value is a number or the text it could not convert (a DATE's '2024-01-01'),
840        // beside a number too.
841        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
847/// The arguments of `coalesce` or `ifnull` it can hand back: each up to the first that is never
848/// NULL, after which none is reached.
849fn 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
854/// The type of a value SQLite hands back from one of `values` (a compound's arms, `CASE`'s results,
855/// `coalesce`'s arguments): the type [`shared`] finds over them. A value of no known type that is no
856/// parameter, such as a column declared without a type or `json_extract`, may be of any storage
857/// class, so the result is unknown too; a parameter takes the others' type, and a NULL literal says
858/// nothing of the type.
859fn 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
867/// Whether a type is JSON a constructor built, which SQLite returns as text.
868fn is_built(t: &Ty) -> bool {
869    matches!(t, Ty::Object { .. } | Ty::List { .. } | Ty::Json { .. })
870}
871
872/// A type as SQLite's storage class: built JSON is text.
873fn textual(t: &Ty) -> Ty {
874    if is_built(t) { Ty::Scalar { name: "text".into() } } else { t.clone() }
875}
876
877/// The one JSON shape several types are, where they differ only in that one is an empty array
878/// (`json_array()`) and the others one list: the list.
879fn 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/// Whether a value carries SQLite's JSON subtype, which makes a JSON function that reads it nest
887/// it as JSON, where text without it is a string. Every JSON function sets it on what it returns,
888/// and a `jsonb_*` blob is read as JSON alike. On SQLite 3.53.4 it passed through `coalesce`,
889/// `ifnull`, `nullif`, `iif`, `CASE`, `likely`, `COLLATE`, unary plus, a cast to text, `min` and
890/// `max` (the aggregates and the scalars), an aggregate with a FILTER and a scalar subquery, and
891/// was dropped by a subquery's or view's column, a WITH query's, `lag`, a scalar subquery that
892/// sorts its rows and a window call in a statement with a second window.
893#[derive(Debug, Clone, Copy, PartialEq, Eq)]
894enum Carry {
895    /// Never: the value is read as the type it has.
896    No,
897    /// Always, where it is not NULL.
898    Yes,
899    /// On some SQLite builds or for some values: the engine says nothing of how it reads.
900    Maybe,
901}
902
903/// Several values', one of which is the value: no subtype only where none has it.
904fn 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
914/// A value as a JSON function reads it ([`Analyzer::json_fact`]).
915struct JsonFact {
916    ty: Ty,
917    non_null: bool,
918    carry: Carry,
919}
920
921/// Whether a built-in returns JSON: every JSON function that returns a document or a value of
922/// one (`json_extract`, `->`, `json_quote`), and every `jsonb_*` one, whose blob a JSON function
923/// reads as JSON. `->>`, `json_type`, `json_valid` and `json_array_length` return plain values,
924/// and `json_pretty` is the engine's to leave unsaid.
925fn 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
933/// The built-ins that hand back one of their arguments as it is, subtype or not.
934const PASSING: &[&str] = &["min", "max", "lag", "lead", "first_value", "last_value", "nth_value"];
935
936/// The built-ins whose value is a new one of their own, which carries no subtype.
937const 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
947/// A value without the subtype, as SQLite writes it into JSON: an INTEGER (a 64-bit column's too)
948/// as a number, a REAL as a number (an infinity as `9.0e+999`, which JSON.parse reads as one), a
949/// TEXT as a string, and a NUMERIC as either. A BLOB is read as JSONB (`x'01'` is `true`,
950/// `x'00'` null) or is an error, and a value of no known storage class may be one: any JSON.
951fn 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
958/// Whether a value may be JSON's null inside the JSON a function builds: one that may be NULL,
959/// which SQLite writes there as null, and any value of plain JSON, which may be the document `null`
960/// itself however NOT NULL it is (`json(doc)` where `doc` holds `'null'`), as on Postgres and
961/// MySQL. A value of no known type is left as it is: `unknown` already admits null.
962fn 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
970/// The JSON Schema of a value inside a document SQLite built, as src/schema.ts spells SQLite's
971/// values there, for a tuple's items and an object's values of any key.
972fn 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
993/// An object of any keys whose values are each one of `values`.
994fn 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
1005/// The FROM lists in scope, innermost last: a column reference names a cursor of one of them.
1006type ScopeStack<'a> = Vec<&'a [From]>;
1007
1008struct Analyzer<'a> {
1009    tree: &'a Tree,
1010    extras: &'a Extras,
1011    /// Per table (lowercase), the events (`TRIGGER_ROW_INSERT`, `_UPDATE`, `_DELETE`) a BEFORE or
1012    /// INSTEAD OF trigger fires on: its `SELECT RAISE(IGNORE)` skips the row.
1013    skipping: &'a HashMap<String, i32>,
1014    /// The parameters (`?n`) the caller may pass NULL for because they are cast to `nullable(…)`;
1015    /// with the bare ones written whole to a column that may hold NULL ([`Analyzer::params`]),
1016    /// every other one is a non-null value, as on Postgres and MySQL.
1017    nullable_params: HashSet<String>,
1018    /// The parameters (`?n`) whose value may be NULL: those of `nullable_params`, and each one
1019    /// that is, bare, the whole value written to a column that may hold NULL, which the caller may
1020    /// pass NULL for ([`Analyzer::bare_nullable`]).
1021    nullable_values: HashSet<String>,
1022    /// The target's columns (lowercase) the statement writes a non-null value to in every row its
1023    /// RETURNING reads ([`Analyzer::written_non_null`]).
1024    written: std::cell::RefCell<HashSet<String>>,
1025    /// What the WHERE and the grouping of the SELECT arm whose columns are being typed prove.
1026    level: std::cell::RefCell<Level>,
1027    /// The JSON each constructor builds, by its node ([`Analyzer::shape`]).
1028    shapes: std::cell::RefCell<HashMap<usize, Option<Ty>>>,
1029    /// The recursive WITH queries being settled, innermost last: each one's name and what its reads
1030    /// of itself are taken to be ([`Analyzer::recursive_column`]).
1031    recursion: std::cell::RefCell<Vec<(String, Vec<Fact>)>>,
1032    /// Each recursive WITH query's settled columns, by its node.
1033    settled: std::cell::RefCell<HashMap<usize, Vec<Fact>>>,
1034}
1035
1036/// What one SELECT arm's WHERE and grouping prove of the expressions in its select list.
1037#[derive(Debug, Clone, Default)]
1038struct Level {
1039    /// Columns (cursor, name) a strict WHERE test rejects NULL in: not NULL in a returned row.
1040    narrowed: HashSet<(i64, String)>,
1041    /// Cursors of outer-joined items a strict WHERE test reads: a returned row has their row.
1042    reduced: HashSet<i64>,
1043    /// A plain GROUP BY: no group is empty.
1044    grouped: bool,
1045    /// The cursors of the arm's own FROM items where it aggregates with no GROUP BY: over no rows
1046    /// it still returns one row, in which a column outside an aggregate's arguments is NULL,
1047    /// whatever its table declares and its WHERE tests.
1048    lone: HashSet<i64>,
1049    /// How many aggregate calls the expression being typed stands inside: their arguments are
1050    /// read from the rows aggregated, each a row that is there.
1051    aggregating: u32,
1052    /// The cursors of the arm's own FROM items.
1053    own: HashSet<i64>,
1054    /// The same cursors of the arms around this one, each read here outside its arm's
1055    /// aggregates: a subquery's read of such an arm's column (`(select e.name)`) is NULL in the
1056    /// row that arm returns over no rows.
1057    around: HashSet<i64>,
1058    /// How many of the aggregate calls the expression stands inside read none of this arm's own
1059    /// items for certain. SQLite gives an aggregate to the innermost query whose items it reads,
1060    /// so such a call is an arm's around this one (`(select json_group_array(name) from posts)`
1061    /// over `users` aggregates the users), and reads that arm's rows, each one there.
1062    foreign: u32,
1063    /// The arm has a window call. SQLite then computes the arm's aggregates in a subquery and
1064    /// reads each back as that subquery's column, which drops the JSON subtype:
1065    /// `json_object('a', json_group_array(x))` beside `count(*) over ()` is `{"a":"[1]"}` on
1066    /// 3.45.1 to 3.54.1.
1067    windowed: bool,
1068}
1069
1070/// The parameter a value is under the conversion a `::type` cast compiles to: `CAST(?n AS type)`,
1071/// or the `json(?n)` of a `::json` where no function the host registers takes the name.
1072fn 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
1081/// What a SELECT arm's WHERE proves of its own FROM items, by the strict tests at its top level
1082/// (not the ON terms of outer joins SQLite moved there), and whether it groups plainly.
1083fn 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    // A RIGHT or FULL JOIN null-extends the items before it after their inner joins' ON terms
1087    // removed rows: those terms narrow none of their columns.
1088    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
1098/// Whether an expression reads a column of one of `cursors`, or may: a subquery in it may read
1099/// one in any of its clauses.
1100fn 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
1109/// The columns a WHERE test at the top level rejects NULL in: under OR the ones every arm does; a
1110/// comparison, `IN`, `BETWEEN`, `IS NOT NULL`, `LIKE` or `GLOB`, in the columns its operands
1111/// answer NULL for. `IS` and `IS NOT` compare NULL like a value, and reject nothing. A function the
1112/// host registers over a built-in's name is the one a call resolves to, and proves nothing.
1113fn 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            // `x NOT IN (SELECT …)` is true of a NULL `x` where the subquery returns no row; a
1127            // list is never empty.
1128            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
1139/// The columns an expression answers NULL for: the column itself, and through arithmetic,
1140/// concatenation, a cast, a COLLATE or a built-in that is NULL for a NULL argument (not one the
1141/// host registers over it), every column an operand answers NULL for.
1142fn 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
1153/// The RENAME COLUMN that stands in for libSQL's `ALTER TABLE t ALTER [COLUMN] c TO <definition>`
1154/// ([`run`]): the statement up to its second ALTER, `rename`, the statement on to its TO, and a
1155/// name no table has; with the byte offset in it where the statement's own text resumes, one past
1156/// where it does in the statement. `None` for any other statement.
1157fn 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    // The table's name, with its schema when it has one.
1164    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    // `words` counts characters; the text is sliced by bytes.
1173    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
1179/// The words of a statement as SQLite's tokenizer splits them: a name or a keyword, and each
1180/// other character alone; comments are none. A quoted name (`"a b"`, `` `a` ``, `[a]`, `'a'`) is
1181/// one word without its quotes, and is marked, since it is never a keyword. Each word comes with
1182/// the index of the character it starts at.
1183fn 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            // A doubled quote inside the name is the quote itself; `[` ends at the first `]`.
1201            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
1230/// A `CREATE TRIGGER` statement's timing (`before`, `after`, `instead`), event (`insert`,
1231/// `update`, `delete`) and table, the table in ASCII lowercase, as SQLite compares names; `None`
1232/// for any other statement.
1233fn trigger_header(sql: &str) -> Option<(String, String, String)> {
1234    // Most of a schema is tables and indexes, which need no reading here.
1235    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    // Steps over the next word when it is one of the keywords `want`.
1241    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    // The trigger's name, with its schema when it has one.
1261    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        // "If no timing is specified, BEFORE is the default."
1274        "before"
1275    };
1276    let event = keyword(i)?;
1277    // `UPDATE OF a, b ON t`: the first ON that is no quoted column name.
1278    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
1286/// An INSTEAD OF trigger with an empty body: its header up to its WHEN or its BEGIN, either of
1287/// which may call a function only the application registers. Replayed, it lets a write to its
1288/// view through as SQLite does, which refuses a write to a view with no INSTEAD OF trigger for it
1289/// (`UPDATE OF a` only for the columns it names); a WHEN only decides at run time whether the body
1290/// runs. `None` for any other statement.
1291fn 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    // Past the view's name, with its schema when it has one.
1300    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    // On a line of its own: the header may end in a `--` comment.
1304    Some(format!("{}\nBEGIN SELECT 1; END", header.trim_end()))
1305}
1306
1307/// The events of a row trigger, as bits: Postgres's `pg_trigger.tgtype` values, which the two
1308/// proofs have always shared.
1309const TRIGGER_ROW_INSERT: i32 = 4;
1310const TRIGGER_ROW_DELETE: i32 = 8;
1311const TRIGGER_ROW_UPDATE: i32 = 16;
1312
1313/// The events per table that some BEFORE or INSTEAD OF trigger fires on.
1314fn 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/// When a function's result can be NULL.
1333#[derive(Clone, Copy)]
1334enum Nulls {
1335    /// Never, whatever the arguments.
1336    Never,
1337    /// Only when an argument can be.
1338    IfArgs,
1339    /// Always possibly (an aggregate over no rows, a lookup that can miss).
1340    Always,
1341}
1342
1343impl Analyzer<'_> {
1344    // ---- result columns ---------------------------------------------------------------------
1345
1346    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    /// Per result column, the constants it holds, where the statement writes nothing else into it:
1370    /// a RETURNING list's, and a select's, whose every arm a UNION joins adds its values, where an
1371    /// INTERSECT's or an EXCEPT's arm only removes rows ([`literals_of`]).
1372    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    /// Per result column, whether it is a truth value ([`SqliteAnalysis::booleans`]).
1402    fn booleans(&self) -> Vec<bool> {
1403        self.result_truths(false)
1404    }
1405
1406    /// Per result column, whether its values are booleans to a host that decodes them: a truth
1407    /// value, or a column of a table that declares it `BOOLEAN` or `BOOL`, as Prisma's and other
1408    /// schemas do, read through any subquery or view, or what passes one of those through. SQLite
1409    /// holds such a column to nothing (`BOOLEAN` is a NUMERIC affinity), so a host reads 0 and 1
1410    /// and refuses any other value it finds there.
1411    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    /// Per result column, whether it holds its declared type alone, as a column of a STRICT table
1428    /// and a rowid do: read as it is, through subqueries and views, in every arm of a compound.
1429    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        // A generated column of a STRICT table is left out: SQLite checks what it computes only
1467        // from 3.51, and an app's driver may carry an older SQLite, which stores anything there.
1468        (n.strict && !n.generated) || n.rowid
1469    }
1470
1471    /// Whether column `i` of a select is a truth value in every arm of a compound.
1472    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    /// Whether an expression is a truth value: what a comparison, a test or a logical operator
1486    /// answers, and what passes one through unchanged. A NULL arm is no counterexample (`CASE`
1487    /// without `ELSE`), and nullability is [`Analyzer::type_of`]'s business. `declared`: a table's
1488    /// column declared `BOOLEAN` or `BOOL` counts as one too ([`Analyzer::flags`]).
1489    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                "likely" | "unlikely" | "likelihood" => n.args.first().is_some_and(|a| self.truth(a, scope, declared)),
1509                "coalesce" | "ifnull" => every(&mut n.args.iter()),
1510                "iif" | "if" => every(&mut iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i))),
1511                _ => false,
1512            },
1513            // `list` alternates WHEN and THEN; an odd tail is the ELSE.
1514            "case" => {
1515                let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
1516                let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
1517                every(&mut results.chain(otherwise))
1518            }
1519            "select" => n.select.as_deref().is_some_and(|sub| self.select_truth(sub, 0, scope, declared)),
1520            "column" => {
1521                for froms in scope.iter().rev() {
1522                    if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
1523                        if let Some(sub) = f.subquery.as_deref() {
1524                            return self.select_truth(sub, n.index.max(0) as usize, scope, declared);
1525                        }
1526                        break;
1527                    }
1528                }
1529                declared && !n.rowid && n.declared.as_deref().is_some_and(is_boolean_declared)
1530            }
1531            _ => false,
1532        }
1533    }
1534
1535    /// Column `i` of a select: for a compound, the type every arm's value shares ([`values_type`]),
1536    /// and any arm's nullability. Every row of a multi-row VALUES is an arm.
1537    fn select_column(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> Fact {
1538        let mut arms: Vec<&Sel> = Vec::new();
1539        let mut s = Some(sel);
1540        while let Some(arm) = s {
1541            arms.push(arm);
1542            s = arm.prior.as_deref();
1543        }
1544        arms.reverse();
1545        // Each arm's value, and the expression it is.
1546        let facts: Vec<(Option<&Node>, Fact)> = arms
1547            .iter()
1548            .flat_map(|arm| {
1549                let mut inner = scope.clone();
1550                inner.push(&arm.from);
1551                let outer = self.level.replace(self.level_within(arm));
1552                let rows = std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i)));
1553                let facts: Vec<(Option<&Node>, Fact)> = rows.map(|e| (e, e.map(|e| self.type_of(e, &inner)).unwrap_or_else(Fact::unknown))).collect();
1554                self.level.replace(outer);
1555                facts
1556            })
1557            .collect();
1558        let Some((_, first)) = facts.first() else { return Fact::unknown() };
1559        let values: Option<Vec<(&Node, &Fact)>> = facts.iter().map(|(e, f)| Some(((*e)?, f))).collect();
1560        let ty = match values {
1561            _ if facts.iter().all(|(_, f)| f.ty == first.ty) => first.ty.clone(),
1562            Some(values) => values_type(&values),
1563            None => Ty::Unknown,
1564        };
1565        Fact { ty, non_null: facts.iter().all(|(_, f)| f.non_null) }
1566    }
1567
1568    /// Column `i` of a recursive WITH query, which reads itself, so that its columns are a fixed
1569    /// point, and the greatest one is sound. Each column is first taken to be non-null and of the
1570    /// type its first arm gives it, for the query's reads of itself; the query is typed under that
1571    /// assumption; a column that comes out nullable, or of another type, is taken so, and the query
1572    /// is typed again, until nothing changes. What survives holds by induction over the recursion:
1573    /// the first arm's rows are so on their own account, each later row given the rows it was
1574    /// computed from, and a UNION's column is non-null only where every arm's is. A query that does
1575    /// not settle within a few rounds proves nothing.
1576    fn recursive_column(&self, name: &str, sub: &Sel, i: usize, scope: &ScopeStack) -> Fact {
1577        let key = sub as *const Sel as usize;
1578        if let Some(facts) = self.settled.borrow().get(&key) {
1579            return facts.get(i).cloned().unwrap_or_else(Fact::unknown);
1580        }
1581        let mut first = sub;
1582        while let Some(prior) = first.prior.as_deref() {
1583            first = prior;
1584        }
1585        let width = first.columns.len();
1586        let mut inner = scope.clone();
1587        inner.push(&first.from);
1588        let outer = self.level.replace(self.level_within(first));
1589        let mut assumed: Vec<Fact> = first.columns.iter().map(|c| Fact { ty: self.type_of(&c.expr, &inner).ty, non_null: true }).collect();
1590        self.level.replace(outer);
1591        // What a round works out under its assumption, a JSON constructor's shape or a recursive
1592        // WITH query's columns within this one, holds under that assumption alone: each round
1593        // starts from what was known before the first, and only the round that settles keeps its own.
1594        let shapes = self.shapes.borrow().clone();
1595        let nested = self.settled.borrow().clone();
1596        let mut settled = None;
1597        for _ in 0..=width + 1 {
1598            *self.shapes.borrow_mut() = shapes.clone();
1599            *self.settled.borrow_mut() = nested.clone();
1600            self.recursion.borrow_mut().push((name.to_string(), assumed.clone()));
1601            let got: Vec<Fact> = (0..width).map(|k| self.select_column(sub, k, scope)).collect();
1602            self.recursion.borrow_mut().pop();
1603            if got.iter().zip(&assumed).all(|(g, a)| g.ty == a.ty && g.non_null == a.non_null) {
1604                settled = Some(got);
1605                break;
1606            }
1607            assumed = got.iter().zip(&assumed).map(|(g, a)| Fact { ty: g.ty.clone(), non_null: g.non_null && a.non_null }).collect();
1608        }
1609        if settled.is_none() {
1610            *self.shapes.borrow_mut() = shapes;
1611            *self.settled.borrow_mut() = nested;
1612        }
1613        let facts = settled.unwrap_or_else(|| vec![Fact::unknown(); width]);
1614        let fact = facts.get(i).cloned().unwrap_or_else(Fact::unknown);
1615        self.settled.borrow_mut().insert(key, facts);
1616        fact
1617    }
1618
1619    /// A column reference: through the cursor to a subquery's column, or the table column itself.
1620    fn column_ref(&self, n: &Node, scope: &ScopeStack) -> Fact {
1621        // RETURNING's read of a column the statement wrote a non-null value to in every row it
1622        // returns, where no BEFORE trigger fires on the write ([`Analyzer::written_non_null`]): no
1623        // trigger can assign NEW, and RETURNING reports the row before any AFTER trigger runs. A
1624        // view's INSTEAD OF trigger is no table.
1625        if n.register && !n.view && !n.generated && n.column.as_ref().is_some_and(|c| self.written.borrow().contains(&c.to_ascii_lowercase())) {
1626            let aff = n.affinity.as_deref().unwrap_or(&n.aff);
1627            let ty = match &n.declared {
1628                Some(declared) if !n.rowid => column_type(declared, aff, n.strict),
1629                _ => affinity_type(aff),
1630            };
1631            return Fact { ty, non_null: true };
1632        }
1633        // A strict WHERE test on the column, or on any column of its outer-joined item, keeps
1634        // its NULL (or the item's null extension) out of every returned row.
1635        let (narrowed, reduced, lone) = {
1636            let level = self.level.borrow();
1637            (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)))
1638        };
1639        for froms in scope.iter().rev() {
1640            if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
1641                let index = n.index.max(0) as usize;
1642                let inner = match (&f.subquery, f.table.as_deref()) {
1643                    (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),
1644                    (Some(sub), Some(name)) if f.cte && reads_itself(sub) => Some(self.recursive_column(name, sub, index, scope)),
1645                    (Some(sub), _) => Some(self.select_column(sub, index, scope)),
1646                    // A recursive WITH query's read of itself, inside the query: what it is taken to be.
1647                    (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)),
1648                    _ => None,
1649                };
1650                if let Some(inner) = inner {
1651                    return Fact { ty: inner.ty, non_null: !lone && (narrowed || (inner.non_null && ((!f.outer && !n.outer) || reduced))) };
1652                }
1653                break;
1654            }
1655        }
1656        // An INSERT through a view's INSTEAD OF trigger returns each value as the statement wrote
1657        // it, with none of the view column's affinity: `values (42)` returns 42 for a TEXT one.
1658        if n.view && self.tree.dml.as_ref().is_some_and(|d| d.kind == "insert") {
1659            return Fact::unknown();
1660        }
1661        let aff = n.affinity.as_deref().unwrap_or(&n.aff);
1662        let ty = match &n.declared {
1663            Some(declared) if !n.rowid => column_type(declared, aff, n.strict),
1664            _ => affinity_type(aff),
1665        };
1666        Fact { ty, non_null: !lone && (narrowed || ((n.not_null || n.rowid) && (!n.outer || reduced))) }
1667    }
1668
1669    /// What libSQL's `vector_top_k` returns as `id`: the key of the row of the table its index
1670    /// holds, as libSQL 0.10.0's search reads it, which is never NULL. A rowid table's rowid, an
1671    /// integer, whatever its primary key; a WITHOUT ROWID table's first primary key column, as it
1672    /// is stored, which is of any storage class: libSQL refuses a vector column in a STRICT table,
1673    /// so a table with a vector index never is one, and the key comes back with no declared type to
1674    /// name it by. `None` where the index is not written as a string or names no index.
1675    fn vector_key(&self, f: &From) -> Option<Fact> {
1676        let table = self.tree.tables.get(f.vector_table.as_deref()?)?;
1677        Some(if table.without_rowid { Fact { ty: Ty::Unknown, non_null: true } } else { Fact::new("integer", true) })
1678    }
1679
1680    // ---- expressions -------------------------------------------------------------------------
1681
1682    /// A function call's type: the JSON a constructor builds, or what the function returns for
1683    /// its arguments' types.
1684    fn call(&self, n: &Node, scope: &ScopeStack) -> Fact {
1685        // The JSON a `json_*` constructor builds, which SQLite returns as its text.
1686        if let Some(ty) = self.built_text(n, scope) {
1687            return Fact { ty, non_null: self.built_non_null(n, scope) };
1688        }
1689        let args: Vec<Fact> = n.args.iter().map(|a| self.type_of(a, scope)).collect();
1690        self.function(n, &args)
1691    }
1692
1693    /// Whether JSON a constructor builds ([`Analyzer::shape`]) is never NULL. Every constructor
1694    /// reads a NULL as a null (`[null]`, `{}`) but `json()` and `jsonb()`, which are NULL where
1695    /// their argument is: a scalar subquery that finds no row, at any depth of them.
1696    fn built_non_null(&self, n: &Node, scope: &ScopeStack) -> bool {
1697        match (self.builtin_name(n), n.args.as_slice()) {
1698            (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) },
1699            _ => true,
1700        }
1701    }
1702
1703    fn type_of(&self, n: &Node, scope: &ScopeStack) -> Fact {
1704        let arg = |x: &Option<Box<Node>>| x.as_deref().map(|x| self.type_of(x, scope)).unwrap_or_else(Fact::unknown);
1705        match n.op.as_str() {
1706            "column" => self.column_ref(n, scope),
1707            "integer" => Fact::new(if integer_literal_fits(n) { "integer" } else { "real" }, true),
1708            "truefalse" => Fact::new("integer", true),
1709            "float" => Fact::new("real", true),
1710            "string" => Fact::new("text", true),
1711            "blob" => Fact::new("blob", true),
1712            "null" => Fact::unknown(),
1713            // A parameter is a non-null value unless the statement means to take NULL for it.
1714            "variable" => Fact { ty: Ty::Unknown, non_null: n.name.as_ref().is_some_and(|name| !self.nullable_values.contains(name)) },
1715            "function" => {
1716                self.aggregated(n, || self.call(n, scope))
1717            }
1718            "+" | "-" | "*" => {
1719                let (l, r) = (arg(&n.left), arg(&n.right));
1720                Fact { ty: arithmetic(&l.ty, &r.ty), non_null: l.non_null && r.non_null }
1721            }
1722            "/" | "%" => {
1723                // A zero divisor gives NULL; a literal divisor is one the statement rules out. `%`
1724                // divides by its divisor cast to INTEGER, which truncates toward zero and
1725                // saturates as `as i64` does, so `x % 0.5` is NULL on every row.
1726                let (l, r) = (arg(&n.left), arg(&n.right));
1727                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());
1728                let literal_divisor = divisor.is_some_and(|v| if n.op == "%" { v as i64 != 0 } else { v != 0.0 });
1729                Fact { ty: arithmetic(&l.ty, &r.ty), non_null: l.non_null && r.non_null && literal_divisor }
1730            }
1731            "||" => {
1732                let (l, r) = (arg(&n.left), arg(&n.right));
1733                Fact::new("text", l.non_null && r.non_null)
1734            }
1735            "=" | "!=" | "<" | "<=" | ">" | ">=" | "and" | "or" | "in" | "between" | "&" | "|" | "<<" | ">>" => {
1736                let (l, r) = (arg(&n.left), arg(&n.right));
1737                let list_non_null = n.list.iter().all(|x| self.type_of(x, scope).non_null);
1738                let right_non_null = if n.right.is_some() { r.non_null } else { list_non_null && n.select.is_none() };
1739                Fact::new("integer", l.non_null && right_non_null)
1740            }
1741            "is" | "is not" | "isnull" | "notnull" | "exists" => Fact::new("integer", true),
1742            "not" | "~" => {
1743                let l = arg(&n.left);
1744                Fact::new("integer", l.non_null)
1745            }
1746            // SQLite reads the literal 2^63 under a minus as its smallest INTEGER, -2^63, though
1747            // alone it is a REAL.
1748            "neg" if n.left.as_deref().is_some_and(is_two_to_the_63) => Fact::new("integer", true),
1749            "neg" => {
1750                let l = arg(&n.left);
1751                Fact { ty: if is_numeric(&l.ty) { computed(l.ty) } else { Ty::Scalar { name: "real".into() } }, non_null: l.non_null }
1752            }
1753            // Unary plus does nothing to any storage class: `+name` is the text 'bob'. SQLite's
1754            // parser also writes a one-element `x IN (e)` as `x = +e`.
1755            "pos" => arg(&n.left),
1756            "cast" => {
1757                let l = arg(&n.left);
1758                Fact::new(n.affinity.as_deref().unwrap_or("none"), l.non_null)
1759            }
1760            "collate" => arg(&n.left),
1761            "case" => {
1762                // `list` alternates WHEN and THEN; an odd tail is the ELSE.
1763                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();
1764                let otherwise = if n.list.len() % 2 == 1 { n.list.last().map(|e| (e, self.type_of(e, scope))) } else { None };
1765                let mut all: Vec<&(&Node, Fact)> = results.iter().collect();
1766                if let Some(o) = &otherwise {
1767                    all.push(o);
1768                }
1769                let values: Vec<(&Node, &Fact)> = all.iter().map(|(e, f)| (*e, f)).collect();
1770                Fact { ty: values_type(&values), non_null: otherwise.is_some() && all.iter().all(|(_, f)| f.non_null) }
1771            }
1772            "select" => {
1773                // A scalar subquery: its first column, NULL when it finds no row, unless it always
1774                // finds exactly one (an ungrouped aggregate: `(SELECT count(*) FROM t)`). Its
1775                // column is then its own answer, so `(SELECT max(x) FROM t)` stays nullable.
1776                let Some(sub) = n.select.as_deref() else { return Fact::unknown() };
1777                let inner = self.select_column(sub, 0, scope);
1778                Fact { ty: inner.ty, non_null: inner.non_null && self.exactly_one(sub).is_ok() }
1779            }
1780            _ => Fact::unknown(),
1781        }
1782    }
1783
1784    /// The built-in functions: their result type, and when it is NULL.
1785    fn function(&self, n: &Node, args: &[Fact]) -> Fact {
1786        let name = n.name.as_deref().unwrap_or("");
1787        let all_non_null = args.iter().all(|a| a.non_null);
1788        let first = args.first().cloned().unwrap_or_else(Fact::unknown);
1789        let done = |aff: &str, nulls: Nulls| {
1790            let non_null = match nulls {
1791                Nulls::Never => true,
1792                Nulls::IfArgs => all_non_null,
1793                Nulls::Always => false,
1794            };
1795            Fact::new(aff, non_null)
1796        };
1797        let typed = |ty: Ty, nulls: Nulls| Fact { ty, non_null: matches!(nulls, Nulls::Never) || (matches!(nulls, Nulls::IfArgs) && all_non_null) };
1798        if !n.agg && !n.window {
1799            if let Some(f) = self.extras.function(name, args.len()) {
1800                return done(f.returns.name(), Nulls::IfArgs);
1801            }
1802        }
1803        if n.window {
1804            // A frame that always holds the current row has that row, so there `min` and `max`
1805            // follow their argument, as under a plain GROUP BY; `sum` and `avg` stay nullable as
1806            // they do there. So does a window's `group_concat` or `string_agg`: before 3.47.0
1807            // (libSQL and Turso run 3.45.1) it is NULL over a frame of nothing but `''`.
1808            let has_a_row = holds_current_row(n);
1809            return match name {
1810                "row_number" | "rank" | "dense_rank" | "ntile" => done("integer", Nulls::Never),
1811                "percent_rank" | "cume_dist" => done("real", Nulls::Never),
1812                "count" => done("integer", Nulls::Never),
1813                "total" => done("real", total_nulls(&first)),
1814                "sum" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::Always),
1815                "avg" => done("real", Nulls::Always),
1816                // `lag` and `lead` hand back their default where the row they read is missing.
1817                "lag" | "lead" if args.len() >= 3 => typed(values_type(&[(&n.args[0], &args[0]), (&n.args[2], &args[2])]), Nulls::Always),
1818                "min" | "max" => typed(first.ty.clone(), if has_a_row { Nulls::IfArgs } else { Nulls::Always }),
1819                "lag" | "lead" | "first_value" | "last_value" | "nth_value" => typed(first.ty.clone(), Nulls::Always),
1820                "group_concat" | "string_agg" => done("text", Nulls::Always),
1821                _ => Fact::unknown(),
1822            };
1823        }
1824        if n.agg {
1825            // Under a plain GROUP BY every group has a row, so an aggregate that is NULL only
1826            // over no rows or only NULLs follows its argument. (A FILTER makes the call a window
1827            // call in SQLite's tree, and is read above.) `sum` stays nullable: a sum of `1e999`
1828            // and `-1e999` is NaN, which SQLite stores as NULL, and so is a `total` of them.
1829            let grouped = self.level.borrow().grouped;
1830            return match name {
1831                "count" => done("integer", Nulls::Never),
1832                "total" => done("real", total_nulls(&first)),
1833                "sum" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::Always),
1834                "avg" => done("real", Nulls::Always),
1835                "min" | "max" => typed(first.ty.clone(), if grouped { Nulls::IfArgs } else { Nulls::Always }),
1836                "group_concat" | "string_agg" => done("text", if grouped { Nulls::IfArgs } else { Nulls::Always }),
1837                "json_group_array" | "json_group_object" => done("text", Nulls::Never),
1838                "jsonb_group_array" | "jsonb_group_object" => done("blob", Nulls::Never),
1839                _ => Fact::unknown(),
1840            };
1841        }
1842        // A number for SQLite's math functions: a value of INTEGER or REAL type. Any other gives
1843        // NULL, text that reads as no number included (`sqrt('abc')`, `sign('')`).
1844        let numbers = all_non_null && args.iter().all(|a| matches!(scalar_name(&a.ty), Some("integer" | "int8" | "real")));
1845        match name {
1846            // An argument after one that is never NULL is never reached: `coalesce((select
1847            // json_group_array(…) …), '[]')` is the array.
1848            "coalesce" | "ifnull" => Fact { ty: values_type(&n.args.iter().zip(reached(args)).collect::<Vec<_>>()), non_null: args.iter().any(|a| a.non_null) },
1849            "nullif" => Fact { ty: first.ty.clone(), non_null: false },
1850            // `iif(c1, v1, c2, v2, …, else)`: NULL where no condition holds and there is no ELSE,
1851            // an even count of arguments.
1852            "iif" | "if" => {
1853                let values = iif_values(args.len());
1854                let arms: Vec<(&Node, &Fact)> = values.iter().filter_map(|i| Some((n.args.get(*i)?, args.get(*i)?))).collect();
1855                Fact { ty: values_type(&arms), non_null: args.len() >= 3 && args.len() % 2 == 1 && arms.iter().all(|(_, a)| a.non_null) }
1856            }
1857            "min" | "max" => Fact { ty: values_type(&n.args.iter().zip(args).collect::<Vec<_>>()), non_null: all_non_null },
1858            // `abs` of the least integer is an error, not NULL; of text, 0.0.
1859            "abs" => typed(if is_numeric(&first.ty) { computed(first.ty.clone()) } else { Ty::Scalar { name: "real".into() } }, Nulls::IfArgs),
1860            "round" => done("real", Nulls::IfArgs),
1861            "length" | "instr" | "json_valid" | "octet_length" => done("integer", Nulls::IfArgs),
1862            // A path that finds nothing is NULL: `json_array_length('{}', '$.a')`, `json_type('{}', '$.a')`.
1863            "json_array_length" => done("integer", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
1864            "json_type" => done("text", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
1865            // `json_remove(j, '$')` is NULL, and so is a NULL path; with no path it is `json(j)`.
1866            "json_remove" => done("text", if args.len() == 1 { Nulls::IfArgs } else { Nulls::Always }),
1867            // `unicode('')` is NULL: an empty string has no first character.
1868            "unicode" => done("integer", Nulls::Always),
1869            "like" | "glob" | "regexp" | "match" | "likely" | "unlikely" | "likelihood" => {
1870                if matches!(name, "likely" | "unlikely" | "likelihood") { first.clone() } else { done("integer", Nulls::IfArgs) }
1871            }
1872            // `concat` skips NULL arguments (all NULL is ''), and `concat_ws` too, NULL only for a
1873            // NULL separator.
1874            "concat" => done("text", Nulls::Never),
1875            "concat_ws" => Fact::new("text", first.non_null),
1876            // A blob's slice is a blob, and the slice of an empty blob is NULL (`substr(x'', 1)`):
1877            // non-null only over text. A parameter there is typed text ([`Analyzer::argument`]).
1878            "substr" | "substring" => {
1879                let blob = matches!(scalar_name(&first.ty), Some("blob"));
1880                let any = matches!(first.ty, Ty::Unknown) && n.args.first().is_some_and(|a| a.op != "variable");
1881                let ty = if blob { first.ty.clone() } else if any { Ty::Unknown } else { Ty::Scalar { name: "text".into() } };
1882                Fact { ty, non_null: all_non_null && !blob && !any }
1883            }
1884            // NULL where it writes nothing, as for an empty format or one that stops at a
1885            // conversion SQLite does not know (`printf('%T')`).
1886            "printf" | "format" => Fact::new("text", n.args.first().and_then(literal_text).is_some_and(printf_writes)),
1887            "upper" | "lower" | "trim" | "ltrim" | "rtrim" | "replace" | "json" | "json_patch" | "json_pretty" => done("text", Nulls::IfArgs),
1888            // A NULL argument is a JSON null or the code point 0; a NULL path changes nothing.
1889            "char" | "json_array" | "json_object" | "json_quote" => done("text", Nulls::Never),
1890            "json_insert" | "json_replace" | "json_set" => Fact::new("text", first.non_null),
1891            "jsonb" => done("blob", Nulls::IfArgs),
1892            // The date and time functions are NULL for a time value they cannot read and for a
1893            // modifier that fails, so they are non-null only for the current time with modifiers
1894            // that cannot fail on it (`date()`, `datetime('now', 'localtime')`).
1895            "date" | "time" | "datetime" => Fact::new("text", current_time(&n.args)),
1896            "julianday" => Fact::new("real", current_time(&n.args)),
1897            // `unixepoch(…, 'subsec')` is a real.
1898            "unixepoch" => {
1899                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")));
1900                Fact::new(if whole { "integer" } else { "real" }, current_time(&n.args))
1901            }
1902            // A conversion it does not know makes `strftime` NULL (`strftime('%Q')`).
1903            "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())),
1904            "timediff" => Fact::new("text", n.args.len() == 2 && current_time(&n.args[..1]) && current_time(&n.args[1..])),
1905            // `soundex(NULL)` is '?000'.
1906            "hex" | "quote" | "typeof" | "soundex" => done("text", Nulls::Never),
1907            "sqlite_version" | "sqlite_source_id" | "current_date" | "current_time" | "current_timestamp" => done("text", Nulls::Never),
1908            "random" | "last_insert_rowid" | "changes" | "total_changes" => done("integer", Nulls::Never),
1909            "randomblob" | "zeroblob" => done("blob", Nulls::IfArgs),
1910            "json_extract" | "jsonb_extract" | "->" | "->>" => Fact::unknown(),
1911            // Defined on every number, infinities included: NULL only for an argument that is no
1912            // number.
1913            "atan" | "atan2" | "asinh" | "sinh" | "cosh" | "tanh" | "exp" | "degrees" | "radians" | "ceil" | "ceiling" | "floor" | "trunc" => Fact::new("real", numbers),
1914            "sign" => Fact::new("integer", numbers),
1915            // NULL outside their domain (`sqrt(-1)`, `ln(0)`, `acos(2)`, `mod(1, 0)`,
1916            // `pow(-1, 0.5)`) and for an infinite argument (`sin(1e999)`).
1917            "acos" | "acosh" | "asin" | "atanh" | "cos" | "sin" | "tan" | "ln" | "log" | "log10" | "log2" | "mod" | "pow" | "power" | "sqrt" => done("real", Nulls::Always),
1918            "pi" => done("real", Nulls::Never),
1919            // The full-text functions, which an FTS table answers for the rows of its own MATCH.
1920            // FTS5's `bm25` is a real on every row, 0 where no MATCH ranks it; with weights it is
1921            // NULL where an infinite or overflowing weight makes the score NaN
1922            // (`bm25(t, 1e308, 1.0)` on a row that matches twice). `highlight` is NULL
1923            // where its column is, and so is FTS5's `snippet` where its column is (every column,
1924            // for -1); FTS4's `snippet` has the same name. FTS3's and FTS4's `offsets` and
1925            // `matchinfo` answer every row.
1926            "bm25" => done("real", if n.args.len() == 1 { Nulls::Never } else { Nulls::Always }),
1927            "highlight" | "snippet" => done("text", Nulls::Always),
1928            "offsets" => done("text", Nulls::Never),
1929            "matchinfo" => done("blob", Nulls::Never),
1930            // libSQL's vectors (`csrc/reylo_sqlite.c`, `openLibsql`), as libSQL 0.10.0 answers: each
1931            // of these is an error on a NULL argument, never NULL. A vector is a blob, and its text
1932            // is the JSON-like array `vector_extract` writes (`[1,2,3]`, `[inf]`).
1933            "vector" | "vector32" | "vector64" | "vector1bit" | "vector8" | "vector16" | "vectorb16" => done("blob", Nulls::Never),
1934            "vector_extract" => done("text", Nulls::Never),
1935            // NULL where the distance is NaN, which SQLite stores as NULL: a zero vector's cosine,
1936            // two empty vectors, infinite components.
1937            "vector_distance_cos" | "vector_distance_l2" => done("real", Nulls::Always),
1938            // The marker a vector index is made with returns its argument, whatever a vector column
1939            // holds: a vector index takes a vector's text as well as its blob.
1940            "libsql_vector_idx" => Fact { ty: Ty::Unknown, non_null: first.non_null },
1941            _ => Fact::unknown(),
1942        }
1943    }
1944
1945    // ---- built JSON ----------------------------------------------------------------------------
1946    //
1947    // SQLite's JSON functions answer with text (the `jsonb_*` ones with a blob), so a column a
1948    // constructor builds was `text`. Its shape is in the statement, as on Postgres and MySQL, and
1949    // the run time parses the text: what follows types it as the JSON it is. Inside a document a
1950    // value is what SQLite writes there, measured on SQLite 3.53.4 (wiki/dialects.md): an INTEGER,
1951    // a REAL and a TEXT as a JSON number or string, NULL as null, a truth value as 1 or 0. A value
1952    // that carries SQLite's JSON subtype, which every JSON function sets on what it returns, nests
1953    // as JSON rather than as a string, and the subtype passes through some expressions and not
1954    // others ([`Carry`]).
1955
1956    /// The JSON a call that SQLite answers with text builds: a `json_object`, `json_array`,
1957    /// `json_group_array` or `json_group_object` call, or `json()` of one of those or of a
1958    /// `jsonb_*` constructor. A `jsonb_*` call is a blob, which stays one.
1959    fn built_text(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
1960        match self.builtin_name(n)? {
1961            "json_object" | "json_array" | "json_group_array" | "json_group_object" => self.shape(n, scope),
1962            "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)),
1963            _ => None,
1964        }
1965    }
1966
1967    /// The JSON a scalar subquery's one column builds, which `json()` of the subquery marks as
1968    /// JSON again whether or not the subquery's value kept SQLite's subtype ([`Analyzer::carry`]).
1969    /// None for a compound or a `VALUES` list, whose rows the first arm's column does not type.
1970    fn subquery_shape(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
1971        if n.op != "select" {
1972            return None;
1973        }
1974        let sub = n.select.as_deref()?;
1975        if sub.columns.len() != 1 || sub.prior.is_some() || !sub.rows.is_empty() || sub.values {
1976            return None;
1977        }
1978        let col = sub.columns.first()?;
1979        self.within(sub, scope, |inner| self.built_text(&col.expr, inner))
1980    }
1981
1982    /// The built-in a call resolves to: none where the host registers a scalar function of that
1983    /// name and argument count, which SQLite prefers.
1984    fn builtin_name<'n>(&self, n: &'n Node) -> Option<&'n str> {
1985        let name = n.name.as_deref().filter(|_| n.op == "function")?;
1986        (n.agg || n.window || self.extras.function(name, n.args.len()).is_none()).then_some(name)
1987    }
1988
1989    /// The JSON a constructor builds, `json_*` or `jsonb_*`, each value as SQLite writes it
1990    /// there ([`Analyzer::json_fact`]); `json()` and `jsonb()` of one build the same. Each node's
1991    /// shape is worked out once: a constructor's nullability and its parent's shape both read it.
1992    fn shape(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
1993        let key = n as *const Node as usize;
1994        if let Some(found) = self.shapes.borrow().get(&key) {
1995            return found.clone();
1996        }
1997        let shape = self.aggregated(n, || self.shape_here(n, scope));
1998        self.shapes.borrow_mut().insert(key, shape.clone());
1999        shape
2000    }
2001
2002    fn shape_here(&self, n: &Node, scope: &ScopeStack) -> Option<Ty> {
2003        let name = self.builtin_name(n)?;
2004        let aggregate = n.agg || n.window;
2005        // What a JSON function reads an argument as, and whether it may be a null there.
2006        let value = |x: &Node| {
2007            let f = self.json_fact(x, scope);
2008            let nullable = nullable_in_json(&f);
2009            (f.ty, nullable)
2010        };
2011        match name {
2012            "json_object" | "jsonb_object" if !aggregate => {
2013                // An odd count of arguments is an error, and so is a key that is no text.
2014                if n.args.len() % 2 != 0 {
2015                    return Some(Ty::Json { schema: None });
2016                }
2017                let mut fields: Vec<TyField> = Vec::new();
2018                let mut dynamic = false;
2019                for pair in n.args.chunks(2) {
2020                    let (ty, nullable) = value(&pair[1]);
2021                    match literal_text(&pair[0]) {
2022                        // A key written twice is in the text twice, and JSON.parse keeps the last.
2023                        Some(key) => match fields.iter_mut().find(|f| f.name == key) {
2024                            Some(f) => {
2025                                f.ty = ty;
2026                                f.nullable = nullable;
2027                            }
2028                            None => fields.push(TyField { name: key.to_string(), ty, nullable }),
2029                        },
2030                        None => {
2031                            dynamic = true;
2032                            fields.push(TyField { name: String::new(), ty, nullable });
2033                        }
2034                    }
2035                }
2036                // A key the statement computes: an object of any keys, each value one of these.
2037                if dynamic {
2038                    return Some(record(fields.iter().map(|f| value_schema(&f.ty, f.nullable)).collect()));
2039                }
2040                Some(Ty::Object { fields })
2041            }
2042            // A JSON array of exactly these values, in this order: a tuple.
2043            "json_array" | "jsonb_array" if !aggregate => {
2044                let items: Vec<serde_json::Value> = n.args.iter().map(|x| {
2045                    let (ty, nullable) = value(x);
2046                    value_schema(&ty, nullable)
2047                }).collect();
2048                let mut schema = serde_json::json!({"type": "array", "items": false});
2049                if !items.is_empty() {
2050                    schema["minItems"] = serde_json::json!(items.len());
2051                    schema["prefixItems"] = serde_json::Value::Array(items);
2052                }
2053                Some(Ty::Json { schema: Some(schema) })
2054            }
2055            // `[]` over no rows, never NULL; a FILTER and a window frame alike.
2056            "json_group_array" | "jsonb_group_array" if aggregate && n.args.len() == 1 => {
2057                let (ty, nullable) = value(&n.args[0]);
2058                Some(Ty::List { of: Box::new(ty), nullable_items: nullable })
2059            }
2060            // `{}` over no rows; a key aggregated twice is in the text twice.
2061            "json_group_object" | "jsonb_group_object" if aggregate && n.args.len() == 2 => {
2062                let (ty, nullable) = value(&n.args[1]);
2063                Some(record(vec![value_schema(&ty, nullable)]))
2064            }
2065            "json" | "jsonb" if !aggregate && n.args.len() == 1 => self.shape(&n.args[0], scope).or_else(|| self.subquery_shape(&n.args[0], scope)),
2066            _ => None,
2067        }
2068    }
2069
2070    /// A value as a JSON function reads it: its type inside the document, whether it is never
2071    /// NULL, and whether it carries the JSON subtype. A value that does not carries the type it
2072    /// has anywhere ([`in_json`]); one that does nests as the JSON it is, where every way it can
2073    /// take builds the same; a value the engine cannot follow is any JSON.
2074    fn json_fact(&self, n: &Node, scope: &ScopeStack) -> JsonFact {
2075        let plain = || {
2076            let f = self.type_of(n, scope);
2077            JsonFact { ty: in_json(&f.ty), non_null: f.non_null, carry: Carry::No }
2078        };
2079        let any = JsonFact { ty: Ty::Unknown, non_null: false, carry: Carry::Maybe };
2080        match n.op.as_str() {
2081            "function" => {
2082                // A function the host registers may set the subtype on what it returns.
2083                let Some(name) = self.builtin_name(n) else { return any };
2084                // A window call's value dropped the subtype on 3.53.4 where the statement has a
2085                // second window (`json_object('w', json_group_array(x) over ())`).
2086                if n.over && is_json_result(name) {
2087                    return any;
2088                }
2089                // So did an aggregate's value beside a window call ([`Level::windowed`]).
2090                if self.windowed_aggregate(n) && self.carry(n, scope) != Carry::No {
2091                    return any;
2092                }
2093                if let Some(ty) = self.shape(n, scope) {
2094                    let non_null = self.built_non_null(n, scope);
2095                    return JsonFact { ty, non_null, carry: Carry::Yes };
2096                }
2097                let first = n.args.first().into_iter();
2098                let non_null = || self.type_of(n, scope).non_null;
2099                match name {
2100                    "coalesce" | "ifnull" => self.json_arms(n.args.iter(), true, scope).map(|f| JsonFact { non_null: f.non_null, ..f }).unwrap_or_else(plain),
2101                    "nullif" => self.json_arms(first, false, scope).map(|f| JsonFact { non_null: false, ..f }).unwrap_or_else(plain),
2102                    "likely" | "unlikely" | "likelihood" => self.json_arms(first, false, scope).unwrap_or_else(plain),
2103                    "iif" | "if" => {
2104                        let arms = iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i));
2105                        self.json_arms(arms, false, scope).map(|f| JsonFact { non_null: non_null(), ..f }).unwrap_or_else(plain)
2106                    }
2107                    // The aggregate hands back one of its values.
2108                    "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),
2109                    _ if is_json_result(name) => JsonFact { ty: Ty::Json { schema: None }, non_null: non_null(), carry: Carry::Yes },
2110                    // `max(a, b)` and `lag(x)` hand back one of their arguments: `max` kept the
2111                    // subtype on 3.53.4 and `lag` dropped it.
2112                    _ if PASSING.contains(&name) => {
2113                        if n.args.iter().all(|a| self.carry(a, scope) == Carry::No) { plain() } else { any }
2114                    }
2115                    _ if PLAIN.contains(&name) => plain(),
2116                    _ => any,
2117                }
2118            }
2119            // A scalar subquery's JSON may have lost the subtype ([`Analyzer::carry`]): wrapped in
2120            // `json()`, it nests as the JSON it is on every SQLite.
2121            "select" => if self.carry(n, scope) == Carry::No { plain() } else { any },
2122            "collate" | "pos" => n.left.as_deref().map_or(any, |l| self.json_fact(l, scope)),
2123            "case" => {
2124                let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
2125                let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
2126                match self.json_arms(results.chain(otherwise), false, scope) {
2127                    Some(f) => JsonFact { non_null: self.type_of(n, scope).non_null, ..f },
2128                    None => plain(),
2129                }
2130            }
2131            // `cast(json_array(1) as text)` kept the subtype on 3.53.4, `as integer` gave 0.
2132            "cast" | "column" => if self.carry(n, scope) == Carry::No { plain() } else { any },
2133            _ => plain(),
2134        }
2135    }
2136
2137    /// A value that is one of `arms`, NULL arms aside: `None` where none carries the subtype, so
2138    /// the value is the plain one its type says. `coalesce`: an arm after one that is never NULL
2139    /// is never reached.
2140    fn json_arms<'n>(&self, arms: impl Iterator<Item = &'n Node>, coalesce: bool, scope: &ScopeStack) -> Option<JsonFact> {
2141        let mut facts: Vec<JsonFact> = Vec::new();
2142        for arm in arms.filter(|a| a.op != "null") {
2143            let f = self.json_fact(arm, scope);
2144            let last = coalesce && f.non_null;
2145            facts.push(f);
2146            if last {
2147                break;
2148            }
2149        }
2150        if facts.iter().all(|f| f.carry == Carry::No) {
2151            return None;
2152        }
2153        let non_null = facts.iter().any(|f| f.non_null);
2154        if !facts.iter().all(|f| f.carry == Carry::Yes) {
2155            return Some(JsonFact { ty: Ty::Unknown, non_null, carry: Carry::Maybe });
2156        }
2157        let types: Vec<&Ty> = facts.iter().map(|f| &f.ty).collect();
2158        let ty = if types.iter().all(|t| *t == types[0]) { types[0].clone() } else { same_json(&types).unwrap_or(Ty::Unknown) };
2159        Some(JsonFact { ty, non_null, carry: Carry::Yes })
2160    }
2161
2162    /// Whether a value carries SQLite's JSON subtype ([`Carry`]).
2163    fn carry(&self, n: &Node, scope: &ScopeStack) -> Carry {
2164        match n.op.as_str() {
2165            "function" => {
2166                let Some(name) = self.builtin_name(n) else { return Carry::Maybe };
2167                let carry = match name {
2168                    "coalesce" | "ifnull" => self.carries(n.args.iter(), scope),
2169                    "nullif" | "likely" | "unlikely" | "likelihood" => self.carries(n.args.first().into_iter(), scope),
2170                    "iif" | "if" => self.carries(iif_values(n.args.len()).into_iter().filter_map(|i| n.args.get(i)), scope),
2171                    "min" | "max" if n.args.len() == 1 && !n.window => self.carries(n.args.iter(), scope),
2172                    _ if is_json_result(name) => if n.over { Carry::Maybe } else { Carry::Yes },
2173                    _ if PASSING.contains(&name) => {
2174                        if self.carries(n.args.iter(), scope) == Carry::No { Carry::No } else { Carry::Maybe }
2175                    }
2176                    _ if PLAIN.contains(&name) => Carry::No,
2177                    _ => Carry::Maybe,
2178                };
2179                if carry != Carry::No && self.windowed_aggregate(n) { Carry::Maybe } else { carry }
2180            }
2181            // A scalar subquery kept the subtype on 3.53.4 and drops it on 3.54.1 (the SQLite of
2182            // Node 26.11's `node:sqlite`): `json_object('n', (select json_object('a', 1)))` is
2183            // `{"n":{"a":1}}` on one and `{"n":"{\"a\":1}"}` on the other, so a JSON value from one may
2184            // be either.
2185            "select" => {
2186                let Some(sub) = n.select.as_deref() else { return Carry::No };
2187                match self.select_carry(sub, 0, scope) {
2188                    Carry::No => Carry::No,
2189                    _ => Carry::Maybe,
2190                }
2191            }
2192            "collate" | "pos" => n.left.as_deref().map_or(Carry::No, |l| self.carry(l, scope)),
2193            "cast" => match n.left.as_deref().map_or(Carry::No, |l| self.carry(l, scope)) {
2194                Carry::No => Carry::No,
2195                _ => Carry::Maybe,
2196            },
2197            "case" => {
2198                let results = n.list.chunks(2).filter_map(|pair| if pair.len() == 2 { Some(&pair[1]) } else { None });
2199                let otherwise = if n.list.len() % 2 == 1 { n.list.last() } else { None };
2200                self.carries(results.chain(otherwise), scope)
2201            }
2202            // A column of a subquery, a view or a WITH query dropped the subtype on 3.53.4
2203            // (`json_object('a', x) from (select json_array(1) as x)` is `{"a":"[1]"}`), which
2204            // a SQLite that flattens the subquery may keep.
2205            "column" => {
2206                for froms in scope.iter().rev() {
2207                    if let Some(f) = froms.iter().find(|f| f.cursor == n.cursor) {
2208                        if let Some(sub) = f.subquery.as_deref() {
2209                            return if self.select_carry(sub, n.index.max(0) as usize, scope) == Carry::No { Carry::No } else { Carry::Maybe };
2210                        }
2211                        break;
2212                    }
2213                }
2214                // A VIRTUAL generated column is computed where it is read, its expression's
2215                // subtype and all; a STORED one is read back from the row, as any column is.
2216                if n.subtype { Carry::Maybe } else { Carry::No }
2217            }
2218            _ => Carry::No,
2219        }
2220    }
2221
2222    /// Whether column `i` of a select carries the subtype, in every arm and row of a compound.
2223    fn select_carry(&self, sel: &Sel, i: usize, scope: &ScopeStack) -> Carry {
2224        let mut carries = Vec::new();
2225        let mut s = Some(sel);
2226        while let Some(arm) = s {
2227            self.within(arm, scope, |inner| {
2228                for e in std::iter::once(arm.columns.get(i).map(|c| &c.expr)).chain(arm.rows.iter().map(|row| row.get(i))).flatten() {
2229                    carries.push(self.carry(e, inner));
2230                }
2231            });
2232            s = arm.prior.as_deref();
2233        }
2234        combine(&carries)
2235    }
2236
2237    /// Whether one of `arms` is the value, NULL arms aside, carries the subtype.
2238    fn carries<'n>(&self, arms: impl Iterator<Item = &'n Node>, scope: &ScopeStack) -> Carry {
2239        let carries: Vec<Carry> = arms.filter(|a| a.op != "null").map(|a| self.carry(a, scope)).collect();
2240        combine(&carries)
2241    }
2242
2243    /// `f` inside the arguments of `n` where it is an aggregate call: they are read from the rows
2244    /// it aggregates ([`Level`]), where a window call's are read from the statement's own rows.
2245    fn aggregated<T>(&self, n: &Node, f: impl FnOnce() -> T) -> T {
2246        if !(n.op == "function" && n.agg && !n.over) {
2247            return f();
2248        }
2249        // A FILTER, which the tree does not carry (`window`, on a call with no OVER), may read
2250        // the arm's own items too: only a call seen to read none of them is an arm's around it.
2251        let foreign = {
2252            let level = self.level.borrow();
2253            !n.window && !reads_cursor(n, &level.own)
2254        };
2255        {
2256            let mut level = self.level.borrow_mut();
2257            level.aggregating += 1;
2258            level.foreign += u32::from(foreign);
2259        }
2260        let out = f();
2261        let mut level = self.level.borrow_mut();
2262        level.aggregating -= 1;
2263        level.foreign -= u32::from(foreign);
2264        out
2265    }
2266
2267    /// Whether `n` is an aggregate call, a FILTER's included, in a query with a window call
2268    /// ([`Level::windowed`]): its value reaches the expression around it through a subquery's
2269    /// column. (SQLite refuses an aggregate of a query with a window call inside a subquery.)
2270    fn windowed_aggregate(&self, n: &Node) -> bool {
2271        n.op == "function" && n.agg && !n.over && self.level.borrow().windowed
2272    }
2273
2274    /// A select arm's level, read from where the analysis stands: what the arm proves of its own
2275    /// FROM items, and the cursors of the arms around it that are NULL where it reads them.
2276    fn level_within(&self, sel: &Sel) -> Level {
2277        let mut level = level_of(sel, self.extras);
2278        let outer = self.level.borrow();
2279        level.around = outer.around.clone();
2280        if outer.aggregating == 0 {
2281            level.around.extend(outer.lone.iter().copied());
2282        }
2283        level
2284    }
2285
2286    /// `f` over a select arm's own scope and level, as [`Analyzer::select_column`] reads its columns.
2287    fn within<T>(&self, sel: &Sel, scope: &ScopeStack, f: impl FnOnce(&ScopeStack) -> T) -> T {
2288        let mut inner = scope.clone();
2289        inner.push(&sel.from);
2290        let outer = self.level.replace(self.level_within(sel));
2291        let out = f(&inner);
2292        self.level.replace(outer);
2293        out
2294    }
2295
2296    // ---- written values ----------------------------------------------------------------------
2297
2298    /// The target's columns (lowercase) an INSERT, an upsert or an UPDATE with a RETURNING writes
2299    /// a non-null value to in every row it returns: each value of every row an INSERT writes to
2300    /// the column, its VALUES or its SELECT's column, and each value every DO UPDATE of an upsert
2301    /// assigns it (a DO NOTHING returns no row), or each value an UPDATE's SET assigns it, all of
2302    /// them non-null. A column a write leaves out takes its default, or keeps what the row held,
2303    /// and `excluded.<column>` proves nothing here. Nothing at all where a BEFORE or INSTEAD OF
2304    /// trigger on the table fires on the write: SQLite leaves undefined what a BEFORE UPDATE
2305    /// trigger's change to the row being updated does to the update.
2306    fn written_non_null(&self) -> HashSet<String> {
2307        let t = self.tree;
2308        let (Some(dml), Some(_)) = (&t.dml, &t.returning) else { return HashSet::new() };
2309        let events = match dml.kind.as_str() {
2310            "update" => TRIGGER_ROW_UPDATE,
2311            _ if dml.upserts.iter().any(|u| u.do_update) => TRIGGER_ROW_INSERT | TRIGGER_ROW_UPDATE,
2312            _ => TRIGGER_ROW_INSERT,
2313        };
2314        if self.skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & events != 0) {
2315            return HashSet::new();
2316        }
2317        let scope: ScopeStack = Vec::new();
2318        let non_null = |known: HashMap<String, bool>| -> HashSet<String> { known.into_iter().filter(|(_, n)| *n).map(|(c, _)| c).collect() };
2319        let assigned = |items: &[tree::SetItem]| -> HashSet<String> {
2320            let mut known: HashMap<String, bool> = HashMap::new();
2321            for item in items {
2322                let Some(column) = &item.column else { continue };
2323                *known.entry(column.to_ascii_lowercase()).or_insert(true) &= self.type_of(&item.expr, &scope).non_null;
2324            }
2325            non_null(known)
2326        };
2327        match dml.kind.as_str() {
2328            "update" => assigned(&dml.set),
2329            "insert" | "upsert" => {
2330                let mut known: HashMap<String, bool> = HashMap::new();
2331                for (i, column) in dml.columns.iter().enumerate() {
2332                    let Some(column) = column else { continue };
2333                    let fact = match (&dml.values, &t.statement) {
2334                        (Some(values), _) => values.get(i).map(|v| self.type_of(v, &scope)),
2335                        (None, Some(sel)) => Some(self.select_column(sel, i, &scope)),
2336                        (None, None) => None,
2337                    };
2338                    *known.entry(column.to_ascii_lowercase()).or_insert(true) &= fact.is_some_and(|f| f.non_null);
2339                }
2340                let mut written = non_null(known);
2341                for upsert in dml.upserts.iter().filter(|u| u.do_update) {
2342                    let updated = assigned(&upsert.set);
2343                    written.retain(|c| updated.contains(c));
2344                }
2345                written
2346            }
2347            _ => HashSet::new(),
2348        }
2349    }
2350
2351    /// The parameters that are, bare, with no cast, the whole value written to a column that may
2352    /// hold NULL, and to no column that refuses it: the caller may pass NULL for each
2353    /// ([`Analyzer::params`]), so the value written may be NULL.
2354    fn bare_nullable(&self) -> HashSet<String> {
2355        let t = self.tree;
2356        let Some(dml) = &t.dml else { return HashSet::new() };
2357        let mut fills: HashMap<String, bool> = HashMap::new();
2358        let mut fill = |v: &Node, column: Option<&str>| {
2359            let (Some(name), Some(column)) = (v.name.as_ref().filter(|_| v.op == "variable"), column) else { return };
2360            let Some(target) = self.table_column(&dml.table, column) else { return };
2361            let refuses = target.non_null || self.checked_not_null(&dml.table, column);
2362            *fills.entry(name.clone()).or_insert(true) &= !refuses;
2363        };
2364        if let (Some(sel), "insert" | "upsert") = (&t.statement, dml.kind.as_str()) {
2365            if sel.prior.is_none() {
2366                for (i, v) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
2367                    fill(v, dml.columns.get(i).and_then(|c| c.as_deref()));
2368                }
2369            }
2370        }
2371        for (i, v) in dml.values.iter().flatten().enumerate() {
2372            fill(v, dml.columns.get(i).and_then(|c| c.as_deref()));
2373        }
2374        for item in dml.set.iter().chain(dml.upserts.iter().flat_map(|u| u.set.iter())) {
2375            fill(&item.expr, item.column.as_deref());
2376        }
2377        fills.into_iter().filter(|(_, nullable)| *nullable).map(|(name, _)| name).collect()
2378    }
2379
2380    // ---- parameters --------------------------------------------------------------------------
2381
2382    /// Every parameter, typed by the context SQLite placed it in; the first typed context wins.
2383    /// Beside them, each parameter cast to `nullable(…)` that is written whole to a column refusing
2384    /// NULL, as `(?n, table, column)`.
2385    fn params(&self, lexed: &Lexed) -> (Vec<Param>, Vec<(String, String, String)>) {
2386        let mut found: Vec<(String, Fact)> = Vec::new();
2387        let t = self.tree;
2388        let checked = |c: Option<&str>| t.dml.as_ref().zip(c).is_some_and(|(dml, c)| self.checked_not_null(&dml.table, c));
2389        // A parameter that is, bare, with no cast, the whole value written to a column may be null
2390        // where that column may hold NULL, and no column that refuses NULL it also fills forbids
2391        // it. A cast one, `CAST(? AS type)` or the `json(?)` a `::json` compiles to, is its cast's
2392        // type, never the column's.
2393        let mut fills: HashMap<String, bool> = HashMap::new();
2394        let mut refused: Vec<(String, String, String)> = Vec::new();
2395        let mut fill = |v: &Node, target: &Option<Fact>, column: Option<&str>| {
2396            let Some(target) = target else { return };
2397            let refuses = target.non_null || checked(column);
2398            let bare = v.op == "variable";
2399            let Some(name) = (if bare { v.name.as_ref() } else { cast_variable(v, self.extras) }) else { return };
2400            if bare {
2401                *fills.entry(name.clone()).or_insert(true) &= !refuses;
2402            }
2403            if let (true, true, Some(column), Some(dml)) = (refuses, self.nullable_params.contains(name), column, t.dml.as_ref()) {
2404                refused.push((name.clone(), dml.table.clone(), column.to_string()));
2405            }
2406        };
2407        if let Some(sel) = &t.statement {
2408            let targets: Vec<Option<Fact>> = match &t.dml {
2409                // The SELECT or the VALUES rows that feed an INSERT: their columns type from the
2410                // target columns.
2411                Some(dml) if dml.kind == "insert" => dml.columns.iter().map(|c| c.as_deref().and_then(|c| self.table_column(&dml.table, c))).collect(),
2412                _ => Vec::new(),
2413            };
2414            // Every row of a VALUES list writes its values whole, as the one-row form below does,
2415            // and so does the one SELECT that feeds an INSERT; a compound's columns are any arm's.
2416            if sel.prior.is_none() {
2417                for (i, v) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
2418                    if let Some(target) = targets.get(i) {
2419                        fill(v, target, t.dml.as_ref().and_then(|d| d.columns.get(i)).and_then(|c| c.as_deref()));
2420                    }
2421                }
2422            }
2423            self.walk_select(sel, &Vec::new(), &targets, &mut found);
2424        }
2425        if let Some(dml) = &t.dml {
2426            let scope: ScopeStack = Vec::new();
2427            if let Some(values) = &dml.values {
2428                for (i, v) in values.iter().enumerate() {
2429                    let target = dml.columns.get(i).and_then(|c| c.as_deref()).and_then(|c| self.table_column(&dml.table, c));
2430                    fill(v, &target, dml.columns.get(i).and_then(|c| c.as_deref()));
2431                    self.walk(v, Ctx::Typed(target), &scope, &mut found);
2432                }
2433            }
2434            for item in dml.set.iter().chain(dml.upserts.iter().flat_map(|u| u.set.iter())) {
2435                let target = item.column.as_deref().and_then(|c| self.table_column(&dml.table, c));
2436                fill(&item.expr, &target, item.column.as_deref());
2437                self.walk(&item.expr, Ctx::Typed(target), &scope, &mut found);
2438            }
2439            if let Some(w) = &dml.where_ {
2440                self.walk(w, Ctx::Bool, &scope, &mut found);
2441            }
2442            for w in dml.upserts.iter().filter_map(|u| u.where_.as_ref()) {
2443                self.walk(w, Ctx::Bool, &scope, &mut found);
2444            }
2445        }
2446        if let Some(returning) = &t.returning {
2447            for c in returning {
2448                self.walk(&c.expr, Ctx::None, &Vec::new(), &mut found);
2449            }
2450        }
2451        // The tree was prepared over the `?n` rewrite (see `analyze`): SQLite's `?k` is the lexer's
2452        // k-th parameter, whatever the author wrote.
2453        let mut typed: HashMap<&str, &Fact> = HashMap::new();
2454        for (name, fact) in found.iter().filter(|(_, f)| !matches!(f.ty, Ty::Unknown)) {
2455            typed.entry(name.as_str()).or_insert(fact);
2456        }
2457        let params = lexed
2458            .params
2459            .iter()
2460            .enumerate()
2461            .map(|(k, name)| {
2462                let numbered = format!("?{}", k + 1);
2463                let fact = typed.get(numbered.as_str()).map(|f| (*f).clone()).unwrap_or_else(Fact::unknown);
2464                // A parameter compared with built JSON is bound as the text it is compared with.
2465                let fact = Fact { ty: textual(&fact.ty), ..fact };
2466                let nullable = fills.get(&numbered).copied().unwrap_or(false) || self.nullable_params.contains(&numbered);
2467                Param { nullable, ..Param::new(name.clone(), descriptor(&fact.ty, None, false, false)) }
2468            })
2469            .collect();
2470        (params, refused)
2471    }
2472
2473    /// Whether a CHECK of the table refuses NULL in the column (`check (col is not null)`). A view
2474    /// is no table here (its INSTEAD OF trigger says what a write takes), so a parameter written
2475    /// to one has no target column and takes no NULL.
2476    fn checked_not_null(&self, table: &str, column: &str) -> bool {
2477        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)
2478    }
2479
2480    fn table_column(&self, table: &str, column: &str) -> Option<Fact> {
2481        let info = self.tree.tables.get(table)?;
2482        let col = info.columns.iter().find(|c| c.name.eq_ignore_ascii_case(column))?;
2483        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)) })
2484    }
2485
2486    fn walk_select(&self, sel: &Sel, scope: &ScopeStack, targets: &[Option<Fact>], found: &mut Vec<(String, Fact)>) {
2487        // In a compound every arm's column i is one result column: a parameter in one arm takes
2488        // the type the other arms give it (`SELECT name FROM users UNION ALL SELECT :x`).
2489        let compound: Vec<Option<Fact>>;
2490        let targets = if targets.is_empty() && (sel.prior.is_some() || !sel.rows.is_empty()) {
2491            compound = (0..sel.columns.len())
2492                .map(|i| {
2493                    let ty = self.select_column(sel, i, scope).ty;
2494                    (!matches!(ty, Ty::Unknown)).then_some(Fact { ty, non_null: true })
2495                })
2496                .collect();
2497            compound.as_slice()
2498        } else {
2499            targets
2500        };
2501        let mut inner = scope.clone();
2502        inner.push(&sel.from);
2503        for (i, e) in sel.columns.iter().map(|c| &c.expr).enumerate().chain(sel.rows.iter().flat_map(|row| row.iter().enumerate())) {
2504            self.walk(e, Ctx::Typed(targets.get(i).cloned().flatten()), &inner, found);
2505        }
2506        for f in &sel.from {
2507            if let Some(sub) = &f.subquery {
2508                self.walk_select(sub, &inner, &[], found);
2509            }
2510            if let Some(on) = &f.on {
2511                self.walk(on, Ctx::Bool, &inner, found);
2512            }
2513            // `json_each` and `json_tree` read JSON text and a path (`IN (SELECT value FROM json_each(:ids))`);
2514            // libSQL's `vector_top_k` an index's name, a vector, as its text, and a count, which it
2515            // refuses as a real or as text.
2516            let json = f.tab_func && matches!(f.table.as_deref(), Some("json_each" | "json_tree"));
2517            let top_k = f.tab_func && f.table.as_deref() == Some("vector_top_k");
2518            for (i, a) in f.args.iter().enumerate() {
2519                let ctx = match i {
2520                    0 | 1 if json || top_k => Ctx::Typed(Some(Fact::new("text", true))),
2521                    2 if top_k => Ctx::Typed(Some(Fact::new("integer", true))),
2522                    _ => Ctx::None,
2523                };
2524                self.walk(a, ctx, &inner, found);
2525            }
2526        }
2527        if let Some(w) = &sel.where_ {
2528            self.walk(w, Ctx::Bool, &inner, found);
2529        }
2530        for g in &sel.group_by {
2531            self.walk(g, Ctx::None, &inner, found);
2532        }
2533        if let Some(h) = &sel.having {
2534            self.walk(h, Ctx::Bool, &inner, found);
2535        }
2536        for o in &sel.order_by {
2537            self.walk(o, Ctx::None, &inner, found);
2538        }
2539        for l in sel.limit.iter().chain(sel.offset.iter()) {
2540            self.walk(l, Ctx::Typed(Some(Fact::new("integer", true))), &inner, found);
2541        }
2542        if let Some(prior) = &sel.prior {
2543            self.walk_select(prior, scope, targets, found);
2544        }
2545    }
2546
2547    /// Visits every node; a variable takes the type its context gives it.
2548    fn walk(&self, n: &Node, ctx: Ctx, scope: &ScopeStack, found: &mut Vec<(String, Fact)>) {
2549        if n.op == "variable" {
2550            let fact = match ctx {
2551                Ctx::Typed(Some(f)) => f,
2552                Ctx::Typed(None) | Ctx::Row(_) | Ctx::None => Fact::unknown(),
2553                Ctx::Bool => Fact::new("integer", false),
2554            };
2555            found.push((n.name.clone().unwrap_or_default(), fact));
2556            return;
2557        }
2558        let sibling = |other: &Option<Box<Node>>| other.as_deref().map(|o| self.type_of(o, scope));
2559        let case_results: std::cell::OnceCell<Ty> = std::cell::OnceCell::new();
2560        let child_ctx = |slot: Position| -> Ctx {
2561            match n.op.as_str() {
2562                "=" | "!=" | "<" | "<=" | ">" | ">=" | "is" | "is not" => {
2563                    let (this, other) = match slot {
2564                        Position::Left => (&n.left, &n.right),
2565                        Position::Right => (&n.right, &n.left),
2566                        _ => return Ctx::None,
2567                    };
2568                    // Row values compare element by element, so each element takes the type of
2569                    // the one it is compared with: `(created_at, id) < (:created_at, :id)`, and a
2570                    // subquery's columns: `(created_at, id) = (SELECT :at, :id)`.
2571                    match (this.as_deref(), other.as_deref().and_then(|o| self.row(o, scope))) {
2572                        (Some(t), Some(row)) if matches!(t.op.as_str(), "vector" | "select") => Ctx::Row(row),
2573                        _ => Ctx::Typed(sibling(other)),
2574                    }
2575                }
2576                "in" => match slot {
2577                    // `(created_at, id) IN (SELECT …)`: SQLite writes a list of row values as
2578                    // a VALUES subquery, which the left side types (see the select walk below).
2579                    Position::Left if is_vector(&n.left) => n.select.as_deref().map_or(Ctx::None, |s| Ctx::Row(self.select_columns(s, scope))),
2580                    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)))),
2581                    Position::List(_) => Ctx::Typed(sibling(&n.left)),
2582                    _ => Ctx::None,
2583                },
2584                "between" => match slot {
2585                    Position::Left if is_vector(&n.left) => Ctx::Row(self.rows(&n.list.iter().collect::<Vec<_>>(), scope)),
2586                    Position::Left => Ctx::Typed(n.list.first().map(|x| self.type_of(x, scope))),
2587                    Position::List(_) => match n.left.as_deref().and_then(|l| self.row(l, scope)) {
2588                        Some(row) if is_vector(&n.left) => Ctx::Row(row),
2589                        _ => Ctx::Typed(sibling(&n.left)),
2590                    },
2591                    _ => Ctx::None,
2592                },
2593                // An element of a row value takes its place's type.
2594                "vector" => match (slot, &ctx) {
2595                    (Position::List(i), Ctx::Row(row)) => Ctx::Typed(row.get(i).cloned().flatten()),
2596                    _ => Ctx::None,
2597                },
2598                // One column of a row subquery, as `UPDATE … SET (a, b) = (SELECT …)` writes it.
2599                "select_column" => match (slot, &ctx) {
2600                    (Position::Left, Ctx::Typed(Some(f))) => {
2601                        let mut row = vec![None; n.index.max(0) as usize + 1];
2602                        row[n.index.max(0) as usize] = Some(f.clone());
2603                        Ctx::Row(row)
2604                    }
2605                    _ => Ctx::None,
2606                },
2607                "cast" => Ctx::Typed(Some(Fact::new(n.affinity.as_deref().unwrap_or("none"), true))),
2608                "+" | "-" | "*" | "/" | "%" => {
2609                    let other = match slot {
2610                        Position::Left => sibling(&n.right),
2611                        _ => sibling(&n.left),
2612                    };
2613                    Ctx::Typed(Some(match other {
2614                        Some(f) if is_numeric(&f.ty) => f,
2615                        _ => Fact::new("real", true),
2616                    }))
2617                }
2618                "||" => Ctx::Typed(Some(Fact::new("text", true))),
2619                "neg" | "~" | "&" | "|" | "<<" | ">>" => Ctx::Typed(Some(Fact::new("real", true))),
2620                // Unary plus hands its operand the context it stands in: `x IN (?)` is `x = +?`.
2621                // So does a COLLATE, which names how the value compares and leaves it as it is.
2622                "pos" | "collate" => ctx.clone(),
2623                "and" | "or" | "not" => Ctx::Bool,
2624                "case" => match slot {
2625                    // A WHEN compares with the base when there is one, else it is a condition; a
2626                    // THEN or ELSE shares the other results' type, or failing that the type the
2627                    // CASE stands in (`name = CASE WHEN … THEN :a ELSE :b END`).
2628                    Position::List(i) if i % 2 == 0 && i + 1 < n.list.len() => match &n.left {
2629                        Some(base) if base.op == "vector" => self.row(base, scope).map_or(Ctx::None, Ctx::Row),
2630                        Some(base) => Ctx::Typed(Some(self.type_of(base, scope))),
2631                        None => Ctx::Bool,
2632                    },
2633                    // Typed once for the CASE, not once per arm: a CASE of thousands of arms.
2634                    Position::List(_) => match case_results.get_or_init(|| {
2635                        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();
2636                        shared(&others.iter().collect::<Vec<_>>())
2637                    }) {
2638                        Ty::Unknown => outer_type(&ctx),
2639                        ty => Ctx::Typed(Some(Fact { ty: ty.clone(), non_null: true })),
2640                    },
2641                    // A base compares with each WHEN value (`CASE :kind WHEN 'a' THEN …`), a row
2642                    // value element by element.
2643                    Position::Left if is_vector(&n.left) => {
2644                        let values: Vec<&Node> = n.list.iter().enumerate().filter(|(j, _)| j % 2 == 0 && j + 1 < n.list.len()).map(|(_, x)| x).collect();
2645                        Ctx::Row(self.rows(&values, scope))
2646                    }
2647                    // A base compares with each WHEN value (`CASE :kind WHEN 'a' THEN …`).
2648                    Position::Left => {
2649                        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();
2650                        let refs: Vec<&Fact> = values.iter().collect();
2651                        match shared(&refs) {
2652                            Ty::Unknown => Ctx::None,
2653                            ty => Ctx::Typed(Some(Fact { ty, non_null: true })),
2654                        }
2655                    }
2656                    _ => Ctx::None,
2657                },
2658                // A function whose result is one of its arguments gives an argument its siblings'
2659                // type, or failing that the type the call stands in (`name = coalesce(:a, :b)`).
2660                "function" => match (slot, self.argument(n, i_of(slot), scope)) {
2661                    (Position::Arg(_), Ctx::Typed(None) | Ctx::None) if matches!(n.name.as_deref(), Some("coalesce" | "ifnull" | "nullif" | "min" | "max")) && !n.agg => outer_type(&ctx),
2662                    (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),
2663                    (Position::Arg(_), c) => c,
2664                    _ => Ctx::None,
2665                },
2666                _ => Ctx::None,
2667            }
2668        };
2669        if let Some(l) = &n.left {
2670            self.walk(l, child_ctx(Position::Left), scope, found);
2671        }
2672        if let Some(r) = &n.right {
2673            self.walk(r, child_ctx(Position::Right), scope, found);
2674        }
2675        for (i, x) in n.list.iter().enumerate() {
2676            self.walk(x, child_ctx(Position::List(i)), scope, found);
2677        }
2678        for (i, x) in n.args.iter().enumerate() {
2679            self.walk(x, child_ctx(Position::Arg(i)), scope, found);
2680        }
2681        if let Some(s) = &n.select {
2682            // A subquery's columns take the types they are compared with or stand in: `id IN
2683            // (SELECT :p)`, `id = (SELECT :p)`, `(created_at, id) IN (VALUES (:at, :id))`.
2684            let targets: Vec<Option<Fact>> = match (n.op.as_str(), &ctx) {
2685                ("select", Ctx::Row(row)) => row.clone(),
2686                ("select", Ctx::Typed(Some(f))) => vec![Some(f.clone())],
2687                ("in", _) => match n.left.as_deref() {
2688                    Some(l) if l.op == "vector" => self.row(l, scope).unwrap_or_default(),
2689                    Some(l) => vec![Some(self.type_of(l, scope))],
2690                    None => Vec::new(),
2691                },
2692                _ => Vec::new(),
2693            };
2694            self.walk_select(s, scope, &targets, found);
2695        }
2696    }
2697
2698    /// A row value's elements, one fact per place: a vector's elements, or a subquery's columns.
2699    fn row(&self, n: &Node, scope: &ScopeStack) -> Option<Vec<Option<Fact>>> {
2700        match n.op.as_str() {
2701            "vector" => Some(n.list.iter().map(|x| Some(self.type_of(x, scope))).collect()),
2702            "select" => n.select.as_deref().map(|s| self.select_columns(s, scope)),
2703            _ => None,
2704        }
2705    }
2706
2707    fn select_columns(&self, sel: &Sel, scope: &ScopeStack) -> Vec<Option<Fact>> {
2708        (0..sel.columns.len()).map(|i| Some(self.select_column(sel, i, scope))).collect()
2709    }
2710
2711    /// The type at each place of several row values (BETWEEN's bounds, a CASE's WHEN values):
2712    /// the first that has one there.
2713    fn rows(&self, values: &[&Node], scope: &ScopeStack) -> Vec<Option<Fact>> {
2714        let mut out: Vec<Option<Fact>> = Vec::new();
2715        for row in values.iter().filter_map(|v| self.row(v, scope)) {
2716            for (i, f) in row.into_iter().enumerate() {
2717                if i >= out.len() {
2718                    out.push(None);
2719                }
2720                if out[i].as_ref().is_none_or(|known| matches!(known.ty, Ty::Unknown)) {
2721                    out[i] = f;
2722                }
2723            }
2724        }
2725        out
2726    }
2727
2728    /// The type a built-in function gives its argument `i`, for a parameter written there.
2729    fn argument(&self, n: &Node, i: usize, scope: &ScopeStack) -> Ctx {
2730        let name = n.name.as_deref().unwrap_or("");
2731        if !n.agg && !n.window && self.extras.function(name, n.args.len()).is_some() {
2732            return Ctx::None;
2733        }
2734        let text = || Ctx::Typed(Some(Fact::new("text", true)));
2735        let integer = || Ctx::Typed(Some(Fact::new("integer", true)));
2736        let real = || Ctx::Typed(Some(Fact::new("real", true)));
2737        let others = || {
2738            let facts: Vec<Fact> = n.args.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, a)| self.type_of(a, scope)).collect();
2739            let refs: Vec<&Fact> = facts.iter().collect();
2740            let ty = shared(&refs);
2741            Ctx::Typed(if matches!(ty, Ty::Unknown) { None } else { Some(Fact { ty, non_null: true }) })
2742        };
2743        match name {
2744            "like" | "glob" | "regexp" | "match" | "upper" | "lower" | "trim" | "ltrim" | "rtrim" | "length" | "hex" | "unicode" | "quote" | "instr" | "replace" | "soundex"
2745            | "printf" | "format" | "concat" | "concat_ws" | "date" | "time" | "datetime" | "strftime" | "julianday" | "unixepoch" | "timediff" | "json"
2746            | "json_extract" | "json_type" | "json_valid" | "json_array_length" | "json_quote" | "json_pretty" | "json_insert" | "json_replace" | "json_set"
2747            | "json_remove" | "json_patch" | "->" | "->>" => text(),
2748            "substr" | "substring" => {
2749                if i == 0 { text() } else { integer() }
2750            }
2751            "zeroblob" | "randomblob" | "char" => integer(),
2752            "abs" | "round" | "acos" | "acosh" | "asin" | "asinh" | "atan" | "atan2" | "atanh" | "ceil" | "ceiling" | "cos" | "cosh" | "degrees" | "exp"
2753            | "floor" | "ln" | "log" | "log10" | "log2" | "mod" | "pow" | "power" | "radians" | "sin" | "sinh" | "sqrt" | "tan" | "tanh" | "trunc" => real(),
2754            "coalesce" | "ifnull" | "nullif" | "min" | "max" => others(),
2755            // `lag` and `lead` hand back their default where the row they read is missing, so the
2756            // value and the default each take the other's type.
2757            "lag" | "lead" if n.args.len() >= 3 && (i == 0 || i == 2) => {
2758                let other = self.type_of(&n.args[2 - i], scope);
2759                Ctx::Typed(if matches!(other.ty, Ty::Unknown) { None } else { Some(Fact { ty: other.ty, non_null: true }) })
2760            }
2761            // A condition is a truth value; a value shares the other values' type.
2762            "iif" | "if" => {
2763                let values = iif_values(n.args.len());
2764                if !values.contains(&i) {
2765                    Ctx::Bool
2766                } else {
2767                    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();
2768                    let ty = shared(&facts.iter().collect::<Vec<_>>());
2769                    Ctx::Typed(if matches!(ty, Ty::Unknown) { None } else { Some(Fact { ty, non_null: true }) })
2770                }
2771            }
2772            "sum" | "avg" | "total" => real(),
2773            // After the FTS table: `highlight(t, column, open, close)` and `bm25(t, weight, …)`.
2774            // `snippet` takes its arguments in another order on FTS4 than on FTS5.
2775            "highlight" if i == 1 => integer(),
2776            "highlight" if i > 1 => text(),
2777            "bm25" if i > 0 => real(),
2778            // libSQL takes a vector as its text (`'[1,2,3]'`) or its blob: a parameter is the text.
2779            "vector" | "vector32" | "vector64" | "vector1bit" | "vector8" | "vector16" | "vectorb16" | "vector_extract" | "vector_distance_cos" | "vector_distance_l2" => text(),
2780            _ => Ctx::None,
2781        }
2782    }
2783
2784    // ---- the row count -----------------------------------------------------------------------
2785
2786    fn cardinality(&self) -> (Cardinality, Option<String>) {
2787        let t = self.tree;
2788        if let Some(dml) = &t.dml {
2789            if t.returning.is_none() {
2790                return (Cardinality::None, None);
2791            }
2792            return match dml.kind.as_str() {
2793                "insert" => {
2794                    if dml.rows == 1 {
2795                        let triggered = |events: i32| self.skipping.get(&dml.table.to_ascii_lowercase()).is_some_and(|mask| mask & events != 0);
2796                        // With no OR clause of its own, a constraint's own conflict clause applies.
2797                        let declared_ignore = dml.on_error == "default" && self.tree.tables.get(&dml.table).is_some_and(|t| t.ignores);
2798                        let can_skip = dml.on_error == "ignore"
2799                            || declared_ignore
2800                            || dml.upserts.iter().any(|u| !u.do_update || u.where_.is_some() || triggered(TRIGGER_ROW_UPDATE))
2801                            || triggered(TRIGGER_ROW_INSERT);
2802                        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) }
2803                    } else if dml.rows > 1 {
2804                        (Cardinality::Many, Some(format!("a VALUES list of {} rows returns {} rows", dml.rows, dml.rows)))
2805                    } else {
2806                        (Cardinality::Many, Some("an INSERT ... SELECT returns a row per row it reads".into()))
2807                    }
2808                }
2809                _ => {
2810                    // UPDATE or DELETE: the WHERE pins a unique key of the target, or any number.
2811                    match self.pinned_by_name(&dml.table, dml.where_.as_ref()) {
2812                        Ok(()) => (Cardinality::AtMostOne, None),
2813                        Err(why) => (Cardinality::Many, Some(why)),
2814                    }
2815                }
2816            };
2817        }
2818        let Some(sel) = &t.statement else { return (Cardinality::None, None) };
2819        match self.exactly_one(sel) {
2820            Ok(()) => (Cardinality::One, None),
2821            Err(one_why) => match self.at_most_one(sel) {
2822                Ok(()) => (Cardinality::AtMostOne, Some(one_why)),
2823                Err(why) => (Cardinality::Many, Some(why)),
2824            },
2825        }
2826    }
2827
2828    fn exactly_one(&self, sel: &Sel) -> Result<(), String> {
2829        // A constant LIMIT of a row or more keeps the one row, and so does an OFFSET of 0; a
2830        // parameter may be 0.
2831        let keeps = |n: &Node, least: i64| integer(n).is_some_and(|n| n >= least);
2832        if sel.limit.as_ref().is_some_and(|l| !keeps(l, 1)) || sel.offset.as_ref().is_some_and(|o| integer(o) != Some(0)) {
2833            return Err("a LIMIT or an OFFSET can remove the row (LIMIT 0, OFFSET 1)".into());
2834        }
2835        self.one_before_limit(sel)
2836    }
2837
2838    /// Exactly one row before the statement's LIMIT and OFFSET apply.
2839    fn one_before_limit(&self, sel: &Sel) -> Result<(), String> {
2840        if sel.prior.is_some() {
2841            return Err("a set operation (UNION, INTERSECT, EXCEPT) returns any number of rows".into());
2842        }
2843        if sel.values && !sel.rows.is_empty() {
2844            return Err("a VALUES list returns a row per row it lists".into());
2845        }
2846        if sel.values {
2847            return Ok(());
2848        }
2849        if !sel.group_by.is_empty() {
2850            return Err("GROUP BY returns one row per group, and none when nothing matches".into());
2851        }
2852        if sel.having.is_some() {
2853            return Err("HAVING can remove the row".into());
2854        }
2855        // SQLite marks the SELECT an aggregate belongs to: one whose arguments read only columns
2856        // of a query around this one (`count(a.id)` in a subquery over `b`) is that query's, and
2857        // leaves this one a row per row of its FROM.
2858        if sel.aggregate && sel.columns.iter().any(|c| has_aggregate(&c.expr)) {
2859            return Ok(());
2860        }
2861        if sel.from.is_empty() && sel.where_.is_none() {
2862            return Ok(());
2863        }
2864        // A FROM of exactly one row, as `cardinality` proves it: never empty, and one row at most.
2865        if !sel.from.is_empty() && self.never_empty(sel) && self.arm_at_most_one(sel).is_ok() {
2866            return Ok(());
2867        }
2868        Err("a FROM returns a row per row it matches, and only an aggregate with no GROUP BY collapses them to one".into())
2869    }
2870
2871    /// Whether the FROM returns a row whatever the tables hold: every item is a subquery or a WITH
2872    /// query of exactly one row, or sits on the nullable side of a LEFT JOIN, which keeps the row
2873    /// of its other side; and no WHERE term can fail but one from an outer join's ON, which
2874    /// removes no row. An inner join's ON is a WHERE term here, so `ON 1 = 1` is one that holds.
2875    /// A VALUES in a FROM is any number of rows: SQLite reads a list of several rows as one such
2876    /// item, which does not say how many it lists.
2877    fn never_empty(&self, sel: &Sel) -> bool {
2878        let holds = |t: &Node| match (t.op.as_str(), t.left.as_deref().and_then(integer), t.right.as_deref().and_then(integer)) {
2879            ("=", Some(l), Some(r)) => l == r,
2880            _ => integer(t).is_some_and(|n| n != 0),
2881        };
2882        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())))
2883            && conjuncts(sel.where_.as_ref()).iter().all(|t| t.outer_on || holds(t))
2884    }
2885
2886    fn at_most_one(&self, sel: &Sel) -> Result<(), String> {
2887        if sel.limit.as_ref().and_then(integer).is_some_and(|n| (0..=1).contains(&n)) {
2888            return Ok(());
2889        }
2890        // Any other LIMIT, and an OFFSET, only remove rows: the bound is the one the statement has
2891        // without them.
2892        if !sel.values && self.one_before_limit(sel).is_ok() {
2893            return Ok(());
2894        }
2895        // An INTERSECT returns only rows both sides return, and an EXCEPT only rows of its left
2896        // side (`prior`, the arms before this one): at most one row when a side it draws every
2897        // row from is.
2898        if let Some(prior) = &sel.prior {
2899            let drawn = match sel.op.as_deref() {
2900                Some("intersect") => self.at_most_one(prior).is_ok() || self.arm_at_most_one(sel).is_ok(),
2901                Some("except") => self.at_most_one(prior).is_ok(),
2902                _ => false,
2903            };
2904            return if drawn { Ok(()) } else { Err("a set operation (UNION, INTERSECT, EXCEPT) returns any number of rows".into()) };
2905        }
2906        self.arm_at_most_one(sel)
2907    }
2908
2909    /// The proof for one SELECT arm, its set operation aside: the closure of [`Self::determined`],
2910    /// as `cardinality` proves it over libpg_query's tree. Every FROM item determined is one row
2911    /// at most; one group at most when every GROUP BY expression is pinned; one row at most from
2912    /// a DISTINCT over pinned values.
2913    fn arm_at_most_one(&self, sel: &Sel) -> Result<(), String> {
2914        if sel.values {
2915            return Err("a VALUES list returns a row per row it lists".into());
2916        }
2917        if !sel.group_by.is_empty() {
2918            if sel.from.iter().all(|f| !f.right) && self.determined(sel, false).iter().all(|d| *d) {
2919                return Ok(());
2920            }
2921            let constant = self.determined(sel, true);
2922            if sel.group_by.iter().all(|g| self.pinned(sel, g, &constant)) {
2923                return Ok(());
2924            }
2925            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());
2926        }
2927        if sel.having.is_some() {
2928            return Err("HAVING leaves a row per group".into());
2929        }
2930        if sel.from.is_empty() {
2931            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());
2932        }
2933        // A RIGHT or FULL JOIN keeps the rows of each side that match nothing: two rows where
2934        // each side has one.
2935        if sel.from.iter().any(|f| f.right) {
2936            return Err("a RIGHT or FULL JOIN returns a row for each side that matches nothing".into());
2937        }
2938        let determined = self.determined(sel, false);
2939        if determined.iter().all(|d| *d) {
2940            return Ok(());
2941        }
2942        if sel.distinct {
2943            let constant = self.determined(sel, true);
2944            if !sel.columns.is_empty() && sel.columns.iter().all(|c| self.pinned(sel, &c.expr, &constant)) {
2945                return Ok(());
2946            }
2947        }
2948        let i = determined.iter().position(|d| !d).unwrap_or(0);
2949        let f = &sel.from[i];
2950        let Some(table) = f.table.as_deref().filter(|_| f.subquery.is_none() && !f.tab_func) else {
2951            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("?")));
2952        };
2953        let keys = self.tree.tables.get(table).map(|t| t.unique_keys.clone()).unwrap_or_default();
2954        if keys.is_empty() {
2955            return Err(format!("`{table}` has no unique index the engine can read, so nothing bounds the rows a WHERE matches"));
2956        }
2957        let shown: Vec<String> = keys.iter().map(|k| format!("({})", k.join(", "))).collect();
2958        if sel.from.len() == 1 {
2959            Err(format!("the WHERE does not equate every column of a unique key of `{table}` — it has {}", shown.join(", ")))
2960        } else {
2961            let name = f.alias.as_deref().unwrap_or(table);
2962            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(", ")))
2963        }
2964    }
2965
2966    /// Which FROM items are determined: every row carries the same row of each, or its null
2967    /// extension (see `cardinality`'s `From`). A table is, when a unique key's every column is
2968    /// equated to a value or to a column of a determined item; a subquery or a WITH query, when the
2969    /// proof bounds it. SQLite moves every ON term into the WHERE: a term from an outer join's ON
2970    /// pins only that join's right side, and with `constant`, which asks that every row carry the
2971    /// same row of an item, never: some rows may meet the null extension instead.
2972    fn determined(&self, sel: &Sel, constant: bool) -> Vec<bool> {
2973        let derived = self.derived_keys(sel);
2974        self.determined_from(sel, vec![false; sel.from.len()], &derived, constant)
2975    }
2976
2977    /// The keys of each subquery, WITH query and view in the FROM ([`Self::output_keys`]): they
2978    /// pin it to one row as a unique index pins a table. None for a table.
2979    fn derived_keys(&self, sel: &Sel) -> Vec<Vec<Vec<i64>>> {
2980        sel.from.iter().map(|f| f.subquery.as_ref().map(|sub| self.output_keys(sub)).unwrap_or_default()).collect()
2981    }
2982
2983    /// [`Self::determined`], with the items `done` names taken as determined from the start: with
2984    /// one item alone, whether every row of it meets one row at most of each other item.
2985    fn determined_from(&self, sel: &Sel, mut done: Vec<bool>, derived: &[Vec<Vec<i64>>], constant: bool) -> Vec<bool> {
2986        let n = sel.from.len();
2987        let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
2988        let terms = conjuncts(sel.where_.as_ref());
2989        loop {
2990            let mut changed = false;
2991            for i in 0..n {
2992                if done[i] {
2993                    continue;
2994                }
2995                let f = &sel.from[i];
2996                let pinned = if let Some(sub) = &f.subquery {
2997                    let usable: Vec<&Node> = terms.iter().copied().filter(|t| !t.outer_on || (!constant && t.join == f.cursor)).collect();
2998                    !(constant && f.outer) && (self.at_most_one(sub).is_ok() || self.derived_pinned(&derived[i], f.cursor, &usable, &done, &index))
2999                } else if let (Some(table), false, false) = (f.table.as_deref(), f.tab_func, f.virtual_) {
3000                    // A WHERE term's `=` rejects the null extension, so it pins even an outer
3001                    // join's right side for every row.
3002                    let usable: Vec<&Node> = terms.iter().copied().filter(|t| !t.outer_on || (!constant && t.join == f.cursor)).collect();
3003                    self.key_pinned(table, f.cursor, &usable, &done, &index)
3004                } else {
3005                    false
3006                };
3007                if pinned {
3008                    done[i] = true;
3009                    changed = true;
3010                }
3011            }
3012            if !changed {
3013                return done;
3014            }
3015        }
3016    }
3017
3018    /// Whether some unique key of `table` (read through `cursor`) has every column equated by
3019    /// one of `terms` to a value: one that reads no column of this FROM's undetermined items (a
3020    /// column of a determined item is one value, and so is an enclosing query's), calls nothing
3021    /// that changes from row to row, and carries no COLLATE.
3022    fn key_pinned(&self, table: &str, cursor: i64, terms: &[&Node], done: &[bool], index: &HashMap<i64, usize>) -> bool {
3023        let Some(info) = self.tree.tables.get(table) else { return false };
3024        let pins: Vec<&str> = terms.iter().filter_map(|t| self.pins(t, cursor, done, index)).collect();
3025        info.unique_keys.iter().any(|key| !key.is_empty() && key.iter().all(|c| pins.iter().any(|p| p.eq_ignore_ascii_case(c))))
3026    }
3027
3028    /// Whether `terms` equate every column of one of `keys` (output positions of the subquery read
3029    /// through `cursor`) to a value, as [`Self::key_pinned`] equates a table's.
3030    fn derived_pinned(&self, keys: &[Vec<i64>], cursor: i64, terms: &[&Node], done: &[bool], index: &HashMap<i64, usize>) -> bool {
3031        let pinned: Vec<i64> = terms.iter().filter_map(|t| self.pinned_column(t, cursor, done, index)).map(|c| c.index).collect();
3032        keys.iter().any(|key| !key.is_empty() && key.iter().all(|p| pinned.contains(p)))
3033    }
3034
3035    /// The unique keys of a SELECT's rows, each a set of its output columns by position, no two of
3036    /// its rows sharing a value of every one of them (NULL aside, which no `=` matches):
3037    ///
3038    /// - a unique key of one of its FROM items, every column of it in the select list unchanged,
3039    ///   when every other item is determined against that item ([`Self::determined_from`]): each
3040    ///   of its rows then meets one row at most of the rest. A WHERE, a HAVING, a LIMIT and an
3041    ///   OFFSET only remove rows, and a window function adds none;
3042    /// - the GROUP BY's expressions, each a column of the select list;
3043    /// - under DISTINCT, the whole select list, every entry a column.
3044    ///
3045    /// None for a set operation or a VALUES list, which may repeat a row.
3046    fn output_keys(&self, sel: &Sel) -> Vec<Vec<i64>> {
3047        if let Some(prior) = &sel.prior {
3048            return self.compound_keys(sel, prior);
3049        }
3050        if sel.values {
3051            return Vec::new();
3052        }
3053        let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
3054        // The output position of a column of this FROM, kept unchanged.
3055        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);
3056        let mut keys = Vec::new();
3057        if !sel.group_by.is_empty() {
3058            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();
3059            keys.extend(key);
3060            return keys;
3061        }
3062        if sel.distinct && !sel.columns.is_empty() && sel.columns.iter().all(|c| c.expr.op == "column" && index.contains_key(&c.expr.cursor)) {
3063            keys.push((0..sel.columns.len() as i64).collect());
3064        }
3065        // A RIGHT or FULL JOIN keeps rows of a side that match nothing, which the closure does not
3066        // read.
3067        if sel.from.iter().any(|f| f.right) {
3068            return keys;
3069        }
3070        let derived = self.derived_keys(sel);
3071        let n = sel.from.len();
3072        for (r, f) in sel.from.iter().enumerate() {
3073            if f.tab_func || f.virtual_ {
3074                continue;
3075            }
3076            let mut seed = vec![false; n];
3077            seed[r] = true;
3078            if !self.determined_from(sel, seed, &derived, false).iter().all(|d| *d) {
3079                continue;
3080            }
3081            if f.subquery.is_some() {
3082                for key in &derived[r] {
3083                    keys.extend(key.iter().map(|p| position(&|e: &Node| e.cursor == f.cursor && e.index == *p)).collect::<Option<Vec<i64>>>());
3084                }
3085            } else if let Some(info) = f.table.as_deref().and_then(|t| self.tree.tables.get(t)) {
3086                // A key column the select list leaves out still counts where the WHERE pins it to
3087                // one value.
3088                let fixed = |c: &str| {
3089                    let none = vec![false; n];
3090                    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)))
3091                };
3092                for key in info.unique_keys.iter().filter(|k| !k.is_empty()) {
3093                    keys.extend(
3094                        key.iter()
3095                            .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))) {
3096                                Some(p) => Some(Some(p)),
3097                                None if fixed(c) => None,
3098                                None => Some(None),
3099                            })
3100                            .collect::<Option<Vec<i64>>>(),
3101                    );
3102                }
3103            }
3104        }
3105        keys
3106    }
3107
3108    /// The keys of a compound SELECT's rows, `sel` its last arm and `prior` the arms before it.
3109    /// INTERSECT and EXCEPT return only rows of their left side, so they keep its keys. Any operator
3110    /// but UNION ALL returns distinct rows, so the whole row is a key, where each column is a
3111    /// column on every arm, of one affinity and one collation, which the comparison that told the
3112    /// rows apart and the one that reads them agree on.
3113    fn compound_keys(&self, sel: &Sel, prior: &Sel) -> Vec<Vec<i64>> {
3114        let op = sel.op.as_deref().unwrap_or("");
3115        let mut keys = Vec::new();
3116        if op == "intersect" || op == "except" {
3117            keys.extend(self.output_keys(prior));
3118        }
3119        if op != "union all" {
3120            let mut arms = vec![sel];
3121            let mut at = Some(prior);
3122            while let Some(arm) = at {
3123                arms.push(arm);
3124                at = arm.prior.as_deref();
3125            }
3126            let width = sel.columns.len();
3127            let alike = width > 0
3128                && arms.iter().all(|arm| !arm.values && arm.columns.len() == width)
3129                && (0..width).all(|i| {
3130                    let first = &sel.columns[i].expr;
3131                    first.op == "column" && arms.iter().all(|arm| {
3132                        let e = &arm.columns[i].expr;
3133                        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"))
3134                    })
3135                });
3136            if alike {
3137                keys.push((0..width as i64).collect());
3138            }
3139        }
3140        keys
3141    }
3142
3143    /// The column of `cursor` a term equates to a value, if it does, under a comparison that
3144    /// leaves the column as it is ([`keeps_column`]) and a collation its unique index holds to:
3145    /// the left operand's column's, else the right's (`sqlite3BinaryCompareCollSeq`), which must
3146    /// be BINARY or the key's own.
3147    fn pins<'n>(&self, t: &'n Node, cursor: i64, done: &[bool], index: &HashMap<i64, usize>) -> Option<&'n str> {
3148        self.pinned_column(t, cursor, done, index).and_then(|col| col.column.as_deref())
3149    }
3150
3151    /// [`Self::pins`]'s column itself.
3152    fn pinned_column<'n>(&self, t: &'n Node, cursor: i64, done: &[bool], index: &HashMap<i64, usize>) -> Option<&'n Node> {
3153        if t.op != "=" {
3154            return None;
3155        }
3156        let (l, r) = (t.left.as_deref()?, t.right.as_deref()?);
3157        let collation = column_of(l).or_else(|| column_of(r)).and_then(|c| c.coll.as_deref()).unwrap_or("BINARY");
3158        [(l, r), (r, l)].into_iter().find_map(|(col, other)| {
3159            let value = col.op == "column"
3160                && col.cursor == cursor
3161                && !has_op(other, "collate")
3162                && keeps_column(col, other)
3163                && (collation.eq_ignore_ascii_case("BINARY") || col.coll.as_deref().is_some_and(|c| c.eq_ignore_ascii_case(collation)))
3164                && !self.calls_volatile(other)
3165                && other.select.is_none()
3166                && cursors(other).is_some_and(|read| read.iter().all(|c| *c != cursor && index.get(c).is_none_or(|i| done[*i])));
3167            value.then_some(col)
3168        })
3169    }
3170
3171    /// Whether every row carries the same value of `e`: a column of a constant item, a column the
3172    /// WHERE (not an outer join's ON) equates to a value, or a value itself.
3173    fn pinned(&self, sel: &Sel, e: &Node, constant: &[bool]) -> bool {
3174        let index: HashMap<i64, usize> = sel.from.iter().enumerate().map(|(i, f)| (f.cursor, i)).collect();
3175        if e.op == "column" {
3176            if index.get(&e.cursor).is_some_and(|i| constant[*i]) {
3177                return true;
3178            }
3179            let terms = conjuncts(sel.where_.as_ref());
3180            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)));
3181        }
3182        e.select.is_none() && !self.calls_volatile(e) && cursors(e).is_some_and(|read| read.iter().all(|c| !index.contains_key(c)))
3183    }
3184
3185    /// The DML form: the target table's columns have no stable cursor, so they match by name.
3186    fn pinned_by_name(&self, table: &str, where_: Option<&Node>) -> Result<(), String> {
3187        let equated = self.equated(where_);
3188        let Some(info) = self.tree.tables.get(table) else { return Err(format!("`{table}` is not a table the engine can read")) };
3189        let names: HashSet<String> = equated.iter().map(|(_, n)| n.to_ascii_lowercase()).collect();
3190        if info.unique_keys.iter().any(|key| !key.is_empty() && key.iter().all(|c| names.contains(&c.to_ascii_lowercase()))) {
3191            return Ok(());
3192        }
3193        if info.unique_keys.is_empty() {
3194            return Err(format!("`{table}` has no unique index the engine can read, so nothing bounds the rows a WHERE matches"));
3195        }
3196        let shown: Vec<String> = info.unique_keys.iter().map(|k| format!("({})", k.join(", "))).collect();
3197        Err(format!("the WHERE does not equate every column of a unique key of `{table}` — it has {}", shown.join(", ")))
3198    }
3199
3200    /// The columns the WHERE equates to a value: `col = <no column anywhere>` under ANDs, where
3201    /// the value calls nothing that changes from row to row.
3202    fn equated(&self, where_: Option<&Node>) -> HashSet<(i64, String)> {
3203        let mut out = HashSet::new();
3204        for n in conjuncts(where_) {
3205            if n.op != "=" || n.outer_on {
3206                continue;
3207            }
3208            if let (Some(l), Some(r)) = (n.left.as_deref(), n.right.as_deref()) {
3209                for (col, other) in [(l, r), (r, l)] {
3210                    // An explicit COLLATE (NOCASE) may compare more loosely than the
3211                    // unique index distinguishes.
3212                    if col.op == "column" && !reads_column(other) && !has_op(other, "collate") && keeps_column(col, other) && !self.calls_volatile(other) {
3213                        if let Some(name) = &col.column {
3214                            out.insert((col.cursor, name.clone()));
3215                        }
3216                    }
3217                }
3218            }
3219        }
3220        out
3221    }
3222
3223    /// Whether `n` calls a function that may give each row another value: `random()`,
3224    /// `changes()`, a date or time function (`'now'` moves), one the host registers or the
3225    /// engine does not know, whose determinism it cannot tell, or a window call or aggregate,
3226    /// whose value is its frame's or its group's (`min(1) over (… rows 1 preceding …)` is NULL on
3227    /// the first row and 1 on the next).
3228    fn calls_volatile(&self, n: &Node) -> bool {
3229        const VOLATILE: &[&str] = &["random", "randomblob", "changes", "total_changes", "last_insert_rowid", "date", "time", "datetime", "julianday", "unixepoch", "strftime", "timediff"];
3230        if n.op == "function" {
3231            if n.agg || n.window || n.over {
3232                return true;
3233            }
3234            let name = n.name.as_deref().unwrap_or("").to_ascii_lowercase();
3235            if VOLATILE.contains(&name.as_str()) || self.extras.function(&name, n.args.len()).is_some() || !KNOWN_FUNCTIONS.contains(&name.as_str()) {
3236                return true;
3237            }
3238        }
3239        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))
3240    }
3241}
3242
3243/// Whether comparing key column `col` with `other` leaves the column's values as they are. SQLite
3244/// applies NUMERIC affinity to both sides where either side's affinity is INTEGER, REAL or NUMERIC,
3245/// and one side's affinity to both where the other has none, so a TEXT key compared with a number
3246/// reads '01' and '1' as 1, and a key of no affinity compared with a TEXT side reads 7 as '7'. A
3247/// numeric key converts nothing it holds: what stays text there is no number.
3248fn keeps_column(col: &Node, other: &Node) -> bool {
3249    let numeric = |a: &str| matches!(a, "integer" | "real" | "numeric");
3250    let none = |a: &str| matches!(a, "blob" | "none");
3251    numeric(&col.aff) || none(&other.aff) || (col.aff == "text" && other.aff == "text")
3252}
3253
3254/// The column an operand reads through casts and unary plus, as SQLite looks for the collation.
3255fn column_of(n: &Node) -> Option<&Node> {
3256    match n.op.as_str() {
3257        "column" => Some(n),
3258        "cast" | "pos" => n.left.as_deref().and_then(column_of),
3259        _ => None,
3260    }
3261}
3262
3263/// A string literal's text.
3264fn literal_text(n: &Node) -> Option<&str> {
3265    if n.op == "string" { n.value.as_deref() } else { None }
3266}
3267
3268/// The arguments of `iif(c1, v1, c2, v2, …, else)` that are its values: each one after a
3269/// condition, and the last of an odd count, the ELSE.
3270fn iif_values(count: usize) -> Vec<usize> {
3271    let mut out: Vec<usize> = (1..count).step_by(2).collect();
3272    if count >= 3 && count % 2 == 1 {
3273        out.push(count - 1);
3274    }
3275    out
3276}
3277
3278/// Whether a call is a window call whose frame always holds the current row, as SQLite resolved
3279/// it (a named window's frame copied in), with no FILTER. No frame clause is `RANGE BETWEEN
3280/// UNBOUNDED PRECEDING AND CURRENT ROW`: every row through the current row's last peer, the whole
3281/// partition without ORDER BY. A frame that starts UNBOUNDED PRECEDING, `n PRECEDING` or at
3282/// CURRENT ROW and ends at CURRENT ROW, `n FOLLOWING` or UNBOUNDED FOLLOWING holds it in every
3283/// mode: SQLite refuses a negative offset and, in RANGE mode, finds the current row within any
3284/// offset of itself, a NULL, an infinity, a text and a blob included (measured on 3.51 and
3285/// checked by the oracle on the embedded SQLite). A start `n FOLLOWING` or an end `n PRECEDING`
3286/// can leave the row out, and `EXCLUDE CURRENT ROW` and `EXCLUDE GROUP` do; `EXCLUDE TIES` keeps it.
3287fn holds_current_row(n: &Node) -> bool {
3288    let start = matches!(n.frame_start.as_deref(), Some("unbounded" | "preceding" | "current"));
3289    let end = matches!(n.frame_end.as_deref(), Some("unbounded" | "following" | "current"));
3290    let exclude = matches!(n.exclude.as_deref(), Some("no" | "ties"));
3291    n.over && !n.filter && start && end && exclude
3292}
3293
3294/// When `total` is NULL: never over integers, but over reals a `1e999` and a `-1e999` add up to
3295/// NaN, which SQLite gives as NULL.
3296fn total_nulls(arg: &Fact) -> Nulls {
3297    if is_integral(&arg.ty) { Nulls::Never } else { Nulls::Always }
3298}
3299
3300/// Whether a date and time function always reads its time value and modifiers. SQLite gives NULL
3301/// for a time value it cannot read (`date('not a date')`), one outside the julian days 0 to
3302/// 5373484 it reads (`date(-1)`, `datetime(1e18, 'unixepoch')`), and a modifier that fails
3303/// (`'weekday 7'`, `'unixepoch'` after a text value) or moves the time out of that range. So this
3304/// holds only for no time value (the current time), the current time (`'now'` in any case, or
3305/// `current_timestamp`, `current_date` or `current_time`) moved less than a thousand years, or a
3306/// number literal (a julian day, or a unix time read by a first `'unixepoch'`) whose modifiers
3307/// keep it in range; and only for literal modifiers that cannot fail on it.
3308fn current_time(args: &[Node]) -> bool {
3309    let Some((value, modifiers)) = args.split_first() else { return true };
3310    let now = literal_text(value).is_some_and(|v| v.eq_ignore_ascii_case("now"))
3311        || (value.op == "function" && value.args.is_empty() && matches!(value.name.as_deref(), Some("current_timestamp" | "current_date" | "current_time")));
3312    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 };
3313    let mut modifiers = modifiers.iter().map(literal_text).peekable();
3314    let julian_day = match number {
3315        Some(v) if modifiers.peek().is_some_and(|m| m.is_some_and(|m| m.eq_ignore_ascii_case("unixepoch"))) => {
3316            modifiers.next();
3317            v / 86_400.0 + 2_440_587.5
3318        }
3319        Some(v) => v,
3320        None if now => 0.0,
3321        None => return false,
3322    };
3323    // The days the modifiers may move the time by, each at most.
3324    let mut days = 0.0;
3325    for m in modifiers {
3326        let Some(m) = m else { return false };
3327        let m = m.to_ascii_lowercase();
3328        days += match m.as_str() {
3329            "subsec" | "subsecond" => 0.0,
3330            // `ceiling` and `floor` are new in 3.46.0, and NULL before it (libSQL's 3.45.1).
3331            "localtime" | "utc" => 1.0,
3332            "start of day" | "start of month" | "start of year" => 366.0,
3333            _ if m.len() == 9 && m.starts_with("weekday ") && matches!(m.as_bytes()[8], b'0'..=b'6') => 7.0,
3334            _ => match shift_days(&m) {
3335                Some(d) => d,
3336                None => return false,
3337            },
3338        };
3339    }
3340    if now {
3341        days < 365_000.0
3342    } else {
3343        // With a margin for the rounding of months and years.
3344        let margin = if days > 0.0 { days + 400.0 } else { 0.0 };
3345        julian_day - margin >= 0.0 && julian_day + margin < 5_373_484.0
3346    }
3347}
3348
3349/// How far a modifier `±N unit` (`'+7 days'`, `'-1.5 hours'`) moves a time, in days at most, as
3350/// SQLite spells one: a number, spaces, and a unit, with or without its plural `s`.
3351fn shift_days(m: &str) -> Option<f64> {
3352    let (number, unit) = m.split_once(' ')?;
3353    let unit = unit.trim_start_matches(' ');
3354    let unit = unit.strip_suffix('s').unwrap_or(unit);
3355    let days = match unit {
3356        "second" => 1.0 / 86_400.0,
3357        "minute" => 1.0 / 1_440.0,
3358        "hour" => 1.0 / 24.0,
3359        "day" => 1.0,
3360        "month" => 31.0,
3361        "year" => 366.0,
3362        _ => return None,
3363    };
3364    let digits = number.strip_prefix(['+', '-']).unwrap_or(number);
3365    let (whole, fraction) = digits.split_once('.').unwrap_or((digits, "0"));
3366    let all_digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
3367    if !all_digits(whole) || !all_digits(fraction) {
3368        return None;
3369    }
3370    Some(digits.parse::<f64>().ok()? * days)
3371}
3372
3373/// Whether `printf` with this format writes a character whatever its arguments are. SQLite gives
3374/// NULL where it wrote none, as for an empty format, and stops at a conversion it does not know
3375/// (`printf('%T')` is NULL, `printf('a%T')` is 'a'), so a character of the format itself or a `%%`
3376/// must come before any such conversion. The directive is read as SQLite's `sqlite3_str_vappendf`
3377/// reads it: flags, a width, a precision and a length, in that loop's order.
3378fn printf_writes(format: &str) -> bool {
3379    let b = format.as_bytes();
3380    let at = |i: usize| b.get(i).copied().unwrap_or(0);
3381    let mut i = 0;
3382    loop {
3383        match at(i) {
3384            0 => return false,
3385            b'%' => {}
3386            _ => return true,
3387        }
3388        i += 1;
3389        // A `%` that ends the format is written as it is.
3390        if at(i) == 0 {
3391            return true;
3392        }
3393        let mut c = at(i);
3394        loop {
3395            match c {
3396                b'-' | b'+' | b' ' | b'#' | b'!' | b'0' | b',' => {}
3397                b'l' => {
3398                    i += 1;
3399                    if at(i) == b'l' {
3400                        i += 1;
3401                    }
3402                    c = at(i);
3403                    break;
3404                }
3405                b'1'..=b'9' => {
3406                    while at(i + 1).is_ascii_digit() {
3407                        i += 1;
3408                    }
3409                    if !matches!(at(i + 1), b'.' | b'l') {
3410                        i += 1;
3411                        c = at(i);
3412                        break;
3413                    }
3414                }
3415                b'*' => {
3416                    if !matches!(at(i + 1), b'.' | b'l') {
3417                        i += 1;
3418                        c = at(i);
3419                        break;
3420                    }
3421                }
3422                b'.' => {
3423                    i += 1;
3424                    if at(i) == b'*' {
3425                        i += 1;
3426                    } else {
3427                        while at(i).is_ascii_digit() {
3428                            i += 1;
3429                        }
3430                    }
3431                    if at(i) != b'l' {
3432                        c = at(i);
3433                        break;
3434                    }
3435                    i -= 1;
3436                }
3437                _ => break,
3438            }
3439            i += 1;
3440            c = at(i);
3441            if c == 0 {
3442                break;
3443            }
3444        }
3445        match c {
3446            b'%' => return true,
3447            // `T` and `S` are SQLite's own, which a SQL call cannot use: it stops there.
3448            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,
3449            _ => return false,
3450        }
3451    }
3452}
3453
3454/// Whether every conversion of a `strftime` format is one SQLite knows; any other makes it NULL,
3455/// as does a `%` that ends the format. `%G`, `%g`, `%U` and `%V` are left out: they are new in
3456/// 3.46.0, and before it (libSQL and Turso run 3.45.1) they make the call NULL.
3457fn strftime_format(format: &str) -> bool {
3458    let mut bytes = format.bytes();
3459    while let Some(b) = bytes.next() {
3460        if b == b'%' && !bytes.next().is_some_and(|c| b"deFfHkIljJmMpPRsSTuwWY%".contains(&c)) {
3461            return false;
3462        }
3463    }
3464    true
3465}
3466
3467/// SQLite's built-in scalar functions the engine's table reads, by name.
3468const KNOWN_FUNCTIONS: &[&str] = &[
3469    "coalesce", "ifnull", "nullif", "iif", "if", "min", "max", "abs", "round", "length", "instr", "unicode", "json_array_length", "json_valid", "octet_length", "sign",
3470    "like", "glob", "regexp", "match", "likely", "unlikely", "likelihood", "upper", "lower", "trim", "ltrim", "rtrim", "substr", "substring", "replace", "char",
3471    "printf", "format", "concat", "concat_ws", "json", "jsonb", "json_array", "json_object", "json_insert", "json_replace", "json_set", "json_remove", "json_patch",
3472    "json_quote", "json_pretty", "json_type", "hex", "quote", "typeof", "soundex", "zeroblob", "json_extract", "jsonb_extract", "->", "->>", "acos", "acosh", "asin", "asinh",
3473    "atan", "atan2", "atanh", "ceil", "ceiling", "cos", "cosh", "degrees", "exp", "floor", "ln", "log", "log10", "log2", "mod", "pow", "power", "radians", "sin",
3474    "sinh", "sqrt", "tan", "tanh", "trunc", "pi",
3475];
3476
3477/// An integer literal's value.
3478fn integer(n: &Node) -> Option<i64> {
3479    if n.op == "integer" { n.value.as_deref().and_then(|v| v.parse().ok()) } else { None }
3480}
3481
3482/// Whether SQLite reads an integer literal as an INTEGER: a decimal one that fits in 64 bits, or
3483/// any hexadecimal one, since one past 64 bits is an error. A decimal one past 2^63 - 1 is a REAL.
3484/// Its digit separators are gone from its text, and leading zeros do not count.
3485fn integer_literal_fits(n: &Node) -> bool {
3486    n.value.as_deref().is_none_or(|v| v.starts_with("0x") || v.starts_with("0X") || v.parse::<i64>().is_ok())
3487}
3488
3489/// Whether a node is the decimal integer literal 2^63.
3490fn is_two_to_the_63(n: &Node) -> bool {
3491    n.op == "integer" && n.value.as_deref().and_then(|v| v.parse::<u64>().ok()) == Some(1 << 63)
3492}
3493
3494/// The terms of a condition's top-level `AND`.
3495fn conjuncts(n: Option<&Node>) -> Vec<&Node> {
3496    let mut out = Vec::new();
3497    let mut stack: Vec<&Node> = n.into_iter().collect();
3498    while let Some(n) = stack.pop() {
3499        if n.op == "and" {
3500            stack.extend(n.left.as_deref());
3501            stack.extend(n.right.as_deref());
3502        } else {
3503            out.push(n);
3504        }
3505    }
3506    out
3507}
3508
3509/// The cursors an expression reads, or `None` when it holds a subquery, whose reads the walk
3510/// does not place.
3511fn cursors(n: &Node) -> Option<Vec<i64>> {
3512    if n.select.is_some() {
3513        return None;
3514    }
3515    let mut out = Vec::new();
3516    if n.op == "column" {
3517        out.push(n.cursor);
3518    }
3519    for child in n.left.iter().chain(n.right.iter()).map(|b| b.as_ref()).chain(n.list.iter()).chain(n.args.iter()) {
3520        out.extend(cursors(child)?);
3521    }
3522    Some(out)
3523}
3524
3525/// The type of `a op b` for `+`, `-`, `*`, `/`, `%`: integer stays integer, anything else is real.
3526fn arithmetic(l: &Ty, r: &Ty) -> Ty {
3527    match (scalar_name(l), scalar_name(r)) {
3528        (Some("integer" | "int8"), Some("integer" | "int8")) => Ty::Scalar { name: "integer".into() },
3529        _ => Ty::Scalar { name: "real".into() },
3530    }
3531}
3532
3533/// Whether a node of this operator sits anywhere in `n`.
3534fn has_op(n: &Node, op: &str) -> bool {
3535    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))
3536}
3537
3538fn has_aggregate(n: &Node) -> bool {
3539    if n.op == "function" && n.agg && !n.window {
3540        return true;
3541    }
3542    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)
3543}
3544
3545/// Whether an expression reads any column, at any depth (a subquery's columns included).
3546fn reads_column(n: &Node) -> bool {
3547    if n.op == "column" {
3548        return true;
3549    }
3550    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()
3551}
3552
3553/// The type the context an expression stands in gives its operand, when it gives one.
3554fn is_vector(n: &Option<Box<Node>>) -> bool {
3555    n.as_deref().is_some_and(|n| n.op == "vector")
3556}
3557
3558fn outer_type(ctx: &Ctx) -> Ctx {
3559    match ctx {
3560        Ctx::Typed(Some(f)) => Ctx::Typed(Some(f.clone())),
3561        _ => Ctx::None,
3562    }
3563}
3564
3565/// The argument position of a slot (0 for any other slot).
3566fn i_of(slot: Position) -> usize {
3567    match slot {
3568        Position::Arg(i) => i,
3569        _ => 0,
3570    }
3571}
3572
3573/// Whether a column's declared type is `BOOLEAN` or `BOOL`, in any case.
3574fn is_boolean_declared(declared: &str) -> bool {
3575    let d = declared.trim();
3576    d.eq_ignore_ascii_case("boolean") || d.eq_ignore_ascii_case("bool")
3577}
3578
3579/// SQLite's five affinity rules over a declared type.
3580pub fn affinity(declared: &str) -> &'static str {
3581    let d = declared.to_ascii_uppercase();
3582    if d.contains("INT") {
3583        "integer"
3584    } else if d.contains("CHAR") || d.contains("CLOB") || d.contains("TEXT") {
3585        "text"
3586    } else if d.contains("BLOB") || d.is_empty() {
3587        "blob"
3588    } else if d.contains("REAL") || d.contains("FLOA") || d.contains("DOUB") {
3589        "real"
3590    } else {
3591        "numeric"
3592    }
3593}
3594
3595/// A parameter's context while walking.
3596#[derive(Clone)]
3597enum Ctx {
3598    Typed(Option<Fact>),
3599    /// A row value's place: element i takes fact i (`(created_at, id) < (:created_at, :id)`).
3600    Row(Vec<Option<Fact>>),
3601    Bool,
3602    None,
3603}
3604
3605#[derive(Clone, Copy)]
3606enum Position {
3607    Left,
3608    Right,
3609    List(usize),
3610    Arg(usize),
3611}
3612
3613#[cfg(test)]
3614mod tests {
3615    use super::*;
3616
3617    #[test]
3618    fn a_row_assigned_fewer_values_than_columns_is_the_database_s_error() {
3619        let ddl = vec!["create table t1 (a integer primary key, b, c, d)".to_string(), "create table t2 (w, x, y)".to_string()];
3620        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)"] {
3621            let a = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
3622            assert!(!a.diagnostics.is_empty(), "{sql}: {a:?}");
3623        }
3624    }
3625
3626    fn ddl() -> Vec<String> {
3627        vec![
3628            "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(),
3629            "create table posts (id integer primary key, user_id integer not null references users(id), title text not null, body text)".to_string(),
3630        ]
3631    }
3632
3633    fn analysis(sql: &str) -> Analysis {
3634        analyze_ddl(sql, &ddl(), &Extras::default()).analysis
3635    }
3636
3637    /// The analysis of `sql`, a statement as the structured pass hands it on, with `names` cast to
3638    /// `nullable(…)`.
3639    fn marked(sql: &str, ddl: &[String], names: &[&str]) -> Analysis {
3640        let names: Vec<String> = names.iter().map(|n| n.to_string()).collect();
3641        run(sql, &lex::lex(sql, Dialect::Sqlite).unwrap(), ddl, &Extras::default(), &names).analysis
3642    }
3643
3644    #[test]
3645    fn the_facts_are_read_for_every_table_the_statement_names_and_no_with_query() {
3646        let mut schema = ddl();
3647        schema.push("create table tags (id integer primary key, post_id integer)".into());
3648        schema.push("create view titles as select title from posts".into());
3649        let tables = |sql: &str| {
3650            let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
3651            assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
3652            let mut t = a.tables.expect("the tree names its tables");
3653            t.read.sort();
3654            t.read.dedup();
3655            (t.read, t.write)
3656        };
3657        let names = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
3658        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![]));
3659        // A WITH query is no table, and a view is named, not what it reads.
3660        assert_eq!(tables("with recent as (select user_id from posts) select title from titles join recent on true"), (names(&["posts", "titles"]), vec![]));
3661        assert_eq!(tables("select value from json_each('[1]')"), (vec![], vec![]));
3662        assert_eq!(tables("select s.n from (select count(*) as n from posts) s join titles on true"), (names(&["posts", "titles"]), vec![]));
3663        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"])));
3664        // What an INSERT, an UPDATE and a DELETE write, and the tables they read.
3665        assert_eq!(tables("insert into tags (post_id) select id from posts"), (names(&["posts"]), names(&["tags"])));
3666        assert_eq!(tables("update users set name = (select max(title) from posts) where id = 1"), (names(&["posts"]), names(&["users"])));
3667        assert_eq!(tables("delete from users where id in (select user_id from posts)"), (names(&["posts"]), names(&["users"])));
3668    }
3669
3670    #[test]
3671    fn a_key_declared_on_conflict_replace_is_read_from_sqlite_s_parse_however_the_ddl_spells_it() {
3672        let replaces = |clause: &str| {
3673            let ddl = vec![format!("create table p (id integer primary key, email text {clause})")];
3674            let t = tree::analyze(&ddl, "insert into p (email) values (?1)", "insert into p (email) values (?)", &[], None).expect("the tree parses");
3675            assert!(t.error.is_none(), "{clause}: {:?}", t.error);
3676            t.tables["p"].replaces
3677        };
3678        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"] {
3679            assert!(replaces(clause), "{clause}");
3680        }
3681        // A NOT NULL's REPLACE writes the column's default, and deletes no row.
3682        for clause in ["unique", "not null on conflict replace default '' unique", "unique on conflict ignore"] {
3683            assert!(!replaces(clause), "{clause}");
3684        }
3685    }
3686
3687    #[test]
3688    fn the_schema_replay_reaches_no_file_and_sets_no_pragma() {
3689        // A row of sqlite_schema may hold more than one statement: SQLite loads the first, and the
3690        // replay runs the text whole.
3691        let dir = std::env::temp_dir().join(format!("reylo-sqlite-replay-test-{}", std::process::id()));
3692        std::fs::create_dir_all(&dir).unwrap();
3693        let (attached, vacuumed) = (dir.join("attached.db"), dir.join("vacuumed.db"));
3694        let ddl = vec![
3695            format!("create table t (a integer not null); attach '{}' as x; create table x.y (z)", attached.display()),
3696            format!("create table u (b); vacuum into '{}'", vacuumed.display()),
3697            "create table v (c); pragma hard_heap_limit = 1; create table w (d)".to_string(),
3698        ];
3699        // What each row made before the refused statement is there.
3700        let a = analyze_ddl("select a, b, c from t, u, v", &ddl, &Extras::default()).analysis;
3701        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
3702        assert!(!attached.exists() && !vacuumed.exists());
3703        // A refused statement ends its row's replay, which every statement that fails on what it
3704        // would have made says, the replay kept from the statement before included.
3705        for _ in 0..2 {
3706            let refused = analyze_ddl("select d from w", &ddl, &Extras::default()).analysis;
3707            let messages: Vec<&str> = refused.diagnostics.iter().map(|d| d.message.as_str()).collect();
3708            assert_eq!(messages.first(), Some(&"no such table: w"), "{messages:?}");
3709            assert!(messages.contains(&"The schema replay skipped statement 1: not authorized"), "{messages:?}");
3710            assert!(messages.contains(&"The schema replay skipped statement 3: not authorized"), "{messages:?}");
3711        }
3712        std::fs::remove_dir_all(&dir).unwrap();
3713    }
3714
3715    #[test]
3716    fn the_tree_describes_the_schema_tables_alone_and_no_with_query() {
3717        // A WITH query's table belongs to the statement, which frees it as the prepare ends,
3718        // before the serializer lists the tables: read then, a recursive one nested in another,
3719        // whose memory SQLite had reused, ended the analysis in a crash.
3720        let described = |sql: &str| {
3721            let t = tree::analyze(&ddl(), sql, sql, &[], None).expect("the tree parses");
3722            assert!(t.error.is_none(), "{sql}: {:?}", t.error);
3723            let mut names = t.tables.into_keys().collect::<Vec<_>>();
3724            names.sort();
3725            names
3726        };
3727        assert_eq!(described("with recent as (select user_id from posts) select user_id from recent"), ["posts"]);
3728        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());
3729        assert_eq!(described("with users as (select id from main.users) select id from users"), ["users"]);
3730        let nested = "with recursive t (n, x, j) as (select 1, 'a', json_array('a') union all select n + 1, null, \
3731                      (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) \
3732                      from t where n < 3) select n, x, j from t";
3733        assert_eq!(described(nested), Vec::<String>::new());
3734        assert!(analysis(nested).diagnostics.is_empty());
3735    }
3736
3737    #[test]
3738    fn a_statement_as_deep_as_the_engine_reads_is_typed_and_one_level_past_it_is_an_error_at_the_bound() {
3739        // From a thread with a small stack, as a host may call from: the embedded SQLite's
3740        // recursion, the reading of its tree and the walks over it run on the engine's stack.
3741        let ddl = vec!["create table users (id integer primary key, name text not null, nick text)".to_string()];
3742        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());
3743        // SQLite's own bound is 1,000; the engine's SQLite takes 350 (`csrc/reylo_sqlite.c`).
3744        for (shape, n) in [("sum", 350), ("and_or", 348), ("case", 348), ("coalesce", 349), ("subquery", 23)] {
3745            let at = small(crate::stack::nested(shape, n));
3746            assert!(at.diagnostics.is_empty() && at.kind == Some(StatementKind::Select), "{shape} at {n}: {:?}", at.diagnostics);
3747            let past = small(crate::stack::nested(shape, n + 1));
3748            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);
3749        }
3750        // A list does not nest: SQLite's OR is a tree, which its bound counts; an IN list is not.
3751        let list = (0..5_000).map(|i| i.to_string()).collect::<Vec<_>>().join(", ");
3752        assert!(small(format!("select id from users where id in ({list})")).diagnostics.is_empty());
3753    }
3754
3755    fn col(a: &Analysis, name: &str) -> (String, bool) {
3756        let c = a.columns.iter().find(|c| c.name == name).unwrap_or_else(|| panic!("no column {name}"));
3757        (affinity_of(&c.ty).unwrap_or("unknown").to_string(), c.nullable)
3758    }
3759
3760    #[test]
3761    fn returning_reads_a_value_the_statement_wrote_to_the_row() {
3762        let nullable = |sql: &str| analysis(sql).columns.iter().map(|c| c.nullable).collect::<Vec<_>>();
3763        // A literal, an expression of written values and a parameter the caller cannot pass NULL
3764        // for are values; a column the INSERT leaves out takes its default.
3765        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]);
3766        // A bare parameter written to a column that may hold NULL may be NULL.
3767        assert_eq!(nullable("insert into users (name, email) values ('a', :e) returning email"), [true]);
3768        assert_eq!(nullable("update users set email = :e returning email"), [true]);
3769        // Every row of a VALUES list, and the SELECT that feeds an INSERT, must write a value.
3770        assert_eq!(nullable("insert into users (name, email) values ('a', 'x'), ('b', null) returning email"), [true]);
3771        assert_eq!(nullable("insert into users (name, email) values ('a', 'x'), ('b', 'y') returning email"), [false]);
3772        assert_eq!(nullable("insert into users (name, email) select name, email from users returning email"), [true]);
3773        assert_eq!(nullable("insert into users (name, email) select name, name from users returning email"), [false]);
3774        // An UPDATE writes what its SET does, from the row it changes; a column it leaves out keeps
3775        // what the row held.
3776        assert_eq!(nullable("update users set email = 'x', score = coalesce(score, 0) where id = 1 returning email, score, avatar"), [false, false, true]);
3777        assert_eq!(nullable("update users set email = name returning email"), [false]);
3778        assert_eq!(nullable("update users set email = score returning email"), [true]);
3779        // An upsert's DO UPDATE must write one too, where a DO NOTHING returns no row.
3780        assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do update set email = 'y' returning email"), [false]);
3781        assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do update set name = 'b' returning email"), [true]);
3782        assert_eq!(nullable("insert into users (id, name, email) values (1, 'a', 'x') on conflict (id) do nothing returning email"), [false]);
3783        // A BEFORE trigger that fires on the write may change the row, and an AFTER one runs after
3784        // RETURNING reads it.
3785        let triggered = |sql: &str, trigger: &str| {
3786            let mut schema = ddl();
3787            schema.push(trigger.to_string());
3788            analyze_ddl(sql, &schema, &Extras::default()).analysis.columns.iter().map(|c| c.nullable).collect::<Vec<_>>()
3789        };
3790        assert_eq!(triggered("update users set email = 'x' returning email", "create trigger b before update on users begin select 1; end"), [true]);
3791        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]);
3792        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]);
3793        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]);
3794        // A DELETE returns the row as it was, and a column read elsewhere than the row is the table's.
3795        assert_eq!(nullable("delete from users where id = 1 returning email"), [true]);
3796        assert_eq!(nullable("update users set email = 'x' returning (select email from users where id = 2) as other"), [true]);
3797    }
3798
3799    fn param(a: &Analysis, name: &str) -> String {
3800        let p = a.params.iter().find(|p| p.name == name).unwrap_or_else(|| panic!("no param {name}"));
3801        affinity_of(&p.ty).unwrap_or("unknown").to_string()
3802    }
3803
3804    #[test]
3805    fn the_full_text_functions_are_typed() {
3806        // Measured on SQLite 3.53.4 over rows with a NULL in each column: `bm25` is a real on
3807        // every row (0 with no MATCH) and NULL with an infinite weight, `highlight` and FTS5's `snippet` are NULL where their
3808        // column is, and FTS4's `offsets` and `matchinfo` answer every row.
3809        let mut schema = ddl();
3810        schema.push("CREATE VIRTUAL TABLE docs USING fts5(title, body)".into());
3811        schema.push("CREATE VIRTUAL TABLE notes USING fts4(body)".into());
3812        let a = |sql: &str| {
3813            let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
3814            assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
3815            a
3816        };
3817        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, \
3818                      snippet(docs, -1, '<b>', '</b>', '…', 8) as excerpt from docs where docs match :q order by rank");
3819        assert_eq!(col(&fts5, "rank"), ("real".into(), false));
3820        assert_eq!(col(&fts5, "weighted"), ("real".into(), true));
3821        assert_eq!(col(&fts5, "hit"), ("text".into(), true));
3822        assert_eq!(col(&fts5, "excerpt"), ("text".into(), true));
3823        assert_eq!((param(&fts5, "w"), param(&fts5, "col"), param(&fts5, "open"), param(&fts5, "q")), ("real".into(), "integer".into(), "text".into(), "text".into()));
3824        let fts4 = a("select offsets(notes) as o, matchinfo(notes) as m, snippet(notes) as s from notes where notes match :q");
3825        assert_eq!(col(&fts4, "o"), ("text".into(), false));
3826        assert_eq!(col(&fts4, "m"), ("blob".into(), false));
3827        assert_eq!(col(&fts4, "s"), ("text".into(), true));
3828        // Inside built JSON, each nests as the value it is.
3829        let built = a("select json_object('hit', highlight(docs, 0, '<b>', '</b>'), 'rank', bm25(docs)) as j from docs where docs match :q");
3830        assert_eq!(shown(&built), "j: { hit: string | null; rank: number }");
3831    }
3832
3833    #[test]
3834    fn a_built_in_is_non_null_only_where_sqlite_never_answers_null_for_non_null_arguments() {
3835        // Every argument below is non-null; each NULL noted is what SQLite 3.53 answers.
3836        let ddl = vec![
3837            "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(),
3838            "create table loose (id integer primary key, num numeric not null)".to_string(),
3839        ];
3840        let typed = |expr: &str| {
3841            let a = analyze_ddl(&format!("select {expr} as v from o, loose"), &ddl, &Extras::default()).analysis;
3842            assert!(a.diagnostics.is_empty(), "{expr}: {:?}", a.diagnostics);
3843            col(&a, "v")
3844        };
3845        let nullable = |expr: &str| typed(expr).1;
3846        // A time value SQLite cannot read, a number outside its range, a modifier that fails.
3847        for expr in [
3848            "date(placed_at)", "time(placed_at)", "datetime(placed_at)", "julianday(placed_at)", "unixepoch(placed_at)", "strftime('%Y', placed_at)",
3849            "date(placed_at, '+1 day')", "timediff(placed_at, 'now')", "date(n)", "date(x, 'unixepoch')", "date('2024-01-01')", "date(:d)",
3850            "date('now', 'weekday 7')", "date('now', 'unixepoch')", "date('now', 'julianday')", "date('now', '+8000 years')", "date('now', '+1 day ')",
3851            "date('now', '+600 years', '+600 years')", "date('now', fmt)", "date('now ')", "strftime('%Q', 'now')", "strftime('%Y%')", "strftime(fmt)",
3852            "date(5373485)", "datetime(1e18, 'unixepoch')", "date(0, '-1 day')", "date(1700000000, 'unixepoch', 'unixepoch')", "date(1, 'auto')", "date(-1)",
3853        ] {
3854            assert!(nullable(expr), "{expr}");
3855        }
3856        // The current time with modifiers that cannot fail on it.
3857        for expr in [
3858            "date()", "time()", "datetime()", "julianday()", "unixepoch()", "date('now')", "date('NOW')", "datetime('now', 'localtime')", "datetime('now', 'utc')",
3859            "date('now', 'start of month', '+1 month', '-1 day')", "date('now', 'weekday 0')", "datetime('now', '-7 days', '+1.5 hours', '+30 MINUTES')",
3860            "date('now', 'subsec')", "strftime('%Y-%m-%d %H:%M:%f %% %j', 'now')", "strftime('%s')", "strftime('')", "timediff('now', 'now')",
3861            "strftime('%Y', current_timestamp)", "date(current_date, '+1 month')", "datetime(0, 'unixepoch')", "date(2460000.5)", "date(1700000000, 'unixepoch', 'start of day', '+1 day')",
3862        ] {
3863            assert!(!nullable(expr), "{expr}");
3864        }
3865        assert_eq!(typed("unixepoch()"), ("integer".into(), false));
3866        assert_eq!(typed("unixepoch('now', 'subsec')"), ("real".into(), false));
3867        assert_eq!(typed("unixepoch('now', fmt)"), ("real".into(), true));
3868        // Outside a function's domain (`sqrt(-1)`, `ln(0)`, `acos(2)`, `mod(1, 0)`, `pow(-1, 0.5)`)
3869        // or at an infinity (`sin(1e999)`).
3870        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)"] {
3871            assert_eq!(typed(f), ("real".into(), true), "{f}");
3872        }
3873        // Defined on every number; NULL for an argument that is no number (`sign('')`).
3874        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()"] {
3875            assert_eq!(typed(f), ("real".into(), false), "{f}");
3876        }
3877        assert_eq!(typed("sign(x)"), ("integer".into(), false));
3878        for f in ["sign(placed_at)", "sign(v)", "sign(num)", "ceil(placed_at)", "floor(b)", "exp(v)", "atan2(x, placed_at)", "sinh(num)"] {
3879            assert!(nullable(f), "{f}");
3880        }
3881        // An empty format, or one that stops at a conversion SQLite does not know (`printf('%T')`).
3882        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('%-')"] {
3883            assert!(nullable(f), "{f}");
3884        }
3885        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')"] {
3886            assert!(!nullable(f), "{f}");
3887        }
3888        // The slice of an empty blob is NULL, and of any blob a blob.
3889        assert_eq!(typed("substr(placed_at, 2)"), ("text".into(), false));
3890        assert_eq!(typed("substr(n, 2, 1)"), ("text".into(), false));
3891        assert_eq!(typed("substr(:s, 2)"), ("text".into(), false));
3892        assert_eq!(typed("substr(b, 2)"), ("blob".into(), true));
3893        assert_eq!(typed("substring(v, 1, 2)"), ("unknown".into(), true));
3894        // A path that finds nothing, and `json_remove(j, '$')`.
3895        for f in ["json_type(doc, '$.a')", "json_array_length(doc, '$.a')", "json_remove(doc, '$')", "json_remove(doc, '$.a')"] {
3896            assert!(nullable(f), "{f}");
3897        }
3898        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)"] {
3899            assert!(!nullable(f), "{f}");
3900        }
3901        assert_eq!(typed("jsonb(doc)"), ("blob".into(), false));
3902        assert_eq!(typed("(select jsonb_group_array(id) from o)"), ("blob".into(), false));
3903        // `iif` with an even count of arguments has no ELSE: NULL where no condition holds.
3904        assert_eq!(typed("iif(n > 0, placed_at)"), ("text".into(), true));
3905        assert_eq!(typed("iif(n > 0, placed_at, n > 1, doc)"), ("text".into(), true));
3906        assert_eq!(typed("iif(n > 0, placed_at, n > 1, doc, fmt)"), ("text".into(), false));
3907        assert_eq!(typed("if(n > 0, x, n > 1, x, 1.5)"), ("real".into(), false));
3908        // A condition takes a truth value, which SQLite reads as an integer; a value the other values' type.
3909        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");
3910        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");
3911        // `total` of a `1e999` and a `-1e999` is NaN, which SQLite gives as NULL; of integers never.
3912        assert_eq!(typed("(select total(x) from o)"), ("real".into(), true));
3913        assert_eq!(typed("(select total(n) from o)"), ("real".into(), false));
3914        assert_eq!(typed("total(x) over ()"), ("real".into(), true));
3915        // What never gives NULL for non-null arguments.
3916        for f in [
3917            "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')",
3918            "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)",
3919        ] {
3920            assert!(!nullable(f), "{f}");
3921        }
3922        assert!(nullable("unicode(placed_at)"));
3923    }
3924
3925    #[test]
3926    fn the_postgres_nullability_rules_hold_on_sqlite() {
3927        let nullable_param = |sql: &str, name: &str| analysis(sql).params.iter().find(|p| p.name == name).is_some_and(|p| p.nullable);
3928        // A parameter cast to `nullable(…)` takes NULL, through the WITH query that selects it
3929        // once too; any other is a value, one the statement coalesces or tests for NULL included.
3930        let marked_param = |sql: &str, name: &str| marked(sql, &ddl(), &[name]).params.iter().find(|p| p.name == name).is_some_and(|p| p.nullable);
3931        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"));
3932        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"));
3933        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"));
3934        assert!(!nullable_param("select id from users, (select :p as p) s where coalesce(s.p, score) = score", "p"));
3935        assert!(!nullable_param("with input as (select :p as p) select id from users, input where score = coalesce(input.p, score)", "p"));
3936        assert!(!nullable_param("with input as (select :p as p) select id from users, input where score > input.p", "p"));
3937        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"));
3938        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"));
3939        assert!(!nullable_param("select id from users where cast(:p as integer) is null", "p"));
3940        assert!(!nullable_param("select id from users where :p is not null", "p"));
3941        assert!(!nullable_param("select id from users where email is :p", "p"));
3942        assert!(!nullable_param("select id from users where :p is not email", "p"));
3943        assert!(!nullable_param("select id from users where :p isnull", "p"));
3944        assert!(!nullable_param("select id from users where score = coalesce(score, :p)", "p"));
3945        let sql = "select id from users where (:p is null or score > :p)";
3946        let repeated = analysis(sql);
3947        assert_eq!(repeated.diagnostics.iter().map(|d| (d.code, d.start, d.length)).collect::<Vec<_>>(), [(3, sql.rfind(":p").unwrap(), 2)]);
3948        assert!(!nullable_param("select coalesce(:s, 0) as x", "s"));
3949        assert!(!nullable_param("select id from users where score > :p", "p"));
3950        assert_eq!(col(&analysis("select upper(:s) as u"), "u"), ("text".into(), false));
3951        // A strict WHERE narrows the column it tests, and reduces the outer join of its item.
3952        assert_eq!(col(&analysis("select email from users where email is not null"), "email"), ("text".into(), false));
3953        assert_eq!(col(&analysis("select email from users where lower(email) = :e or email like 'a%'"), "email").1, false);
3954        assert_eq!(col(&analysis("select email from users where email like 'a%' or id = 1"), "email").1, true);
3955        assert_eq!(col(&analysis("select email from users where lower(email) = :e and email like 'a%'"), "email").1, false);
3956        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");
3957        assert_eq!(col(&reduced, "name"), ("text".into(), false));
3958        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));
3959        // An ON term is not a WHERE test: the posts that meet no user still have NULL there.
3960        // Nor is an inner join's, for the rows a RIGHT JOIN after it null-extends.
3961        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");
3962        assert_eq!((col(&right, "title").1, col(&right, "name").1), (true, true));
3963        assert_eq!(col(&analysis("select u.email from posts p join users u on u.email is not null"), "email").1, false);
3964        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));
3965        // Under a plain GROUP BY no group is empty.
3966        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");
3967        assert_eq!((col(&grouped, "t").1, col(&grouped, "m").1, col(&grouped, "g").1), (false, false, false));
3968        assert!(col(&analysis("select max(title) as t from posts"), "t").1);
3969        // `concat` skips NULLs; `concat_ws` is NULL only for a NULL separator.
3970        let concat = analysis("select concat(email, 'x') as c, concat_ws(',', email) as w, concat_ws(email, 'a') as n from users");
3971        assert_eq!((col(&concat, "c").1, col(&concat, "w").1, col(&concat, "n").1), (false, false, true));
3972    }
3973
3974    #[test]
3975    fn a_cast_parameter_is_its_casts_type_and_a_bare_one_its_columns() {
3976        // A `:name::type` cast compiles to `CAST(? AS type)`, and `::json` to `json(?)`: the
3977        // parameter is the cast's type and takes no NULL, written whole or not. A bare one written whole (an INSERT's values, every row of a
3978        // VALUES list, an UPDATE's or an upsert's SET, a row value's elements) is as nullable as
3979        // its column; a column a CHECK refuses NULL in, by a conjunct `col is not null`, is not.
3980        // Neither takes NULL coalesced or tested for NULL; either takes it cast to `nullable(…)`.
3981        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()];
3982        let types = |sql: &str| {
3983            let a = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
3984            assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
3985            a.params.iter().map(|p| format!("{}{}", p.name, if p.nullable { "?" } else { "" })).collect::<Vec<_>>().join(" ")
3986        };
3987        for (sql, want) in [
3988            ("insert into users (name, email) values (:name, :email) on conflict (email) do update set name = excluded.name returning id", "name email?"),
3989            ("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"),
3990            ("insert into users (name, email, score, n, doc, meta) values (:name, :email, :score, :n, :doc, :meta)", "name email? score? n? doc? meta"),
3991            ("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"),
3992            ("insert into users (name, email) values (:a, :b), (:c, CAST(:d AS TEXT))", "a b? c d"),
3993            ("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"),
3994            ("update users set (name, email) = (:name, :email) where id = :id", "name email? id"),
3995            ("update users set (name, email) = (CAST(:name AS TEXT), CAST(:email AS TEXT)) where id = CAST(:id AS INTEGER)", "name email id"),
3996            ("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"),
3997            ("update users set email = CAST(CAST(:e AS INTEGER) AS TEXT), meta = json(:m) where id = 1", "e m"),
3998            ("insert into users (name, nick, code, tag) values (:name, :nick, :code, :tag)", "name nick code tag?"),
3999            ("update users set nick = :nick, code = :code, tag = :tag where id = :id", "nick code tag? id"),
4000            ("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"),
4001            ("select id from users where (json(:doc) is null or doc = json(:d)) and :x is not null", "doc d x"),
4002            ("insert into users (name, email) select CAST(:name AS TEXT), CAST(:email AS TEXT)", "name email"),
4003            ("insert into users (name, email) select :name, :email", "name email?"),
4004        ] {
4005            assert_eq!(types(sql), want, "{sql}");
4006        }
4007        // Cast to `nullable(…)`, a parameter takes NULL, written whole or not, bare (a typed JSON
4008        // one is) or under its cast; written whole to a column that refuses NULL, by its NOT NULL
4009        // or a CHECK, it is an error at the parameter.
4010        let ddl: Vec<String> = ddl.iter().map(|s| s.to_string()).collect();
4011        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))";
4012        let a = marked(sql, &ddl, &["name", "email", "nick", "doc", "meta"]);
4013        assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true; 5]);
4014        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.");
4015        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"))]);
4016        // Written whole by the one SELECT that feeds the INSERT, as a VALUES item is.
4017        let sql = "insert into users (name, email) select CAST(:name AS TEXT), CAST(:email AS TEXT)";
4018        let a = marked(sql, &ddl, &["name", "email"]);
4019        assert_eq!(a.diagnostics.iter().map(|d| (&sql[d.start..d.start + d.length], d.message.clone())).collect::<Vec<_>>(), [(":name", said(":name", "name"))]);
4020        let a = marked("update users set email = CAST(:e AS TEXT), n = coalesce(CAST(:n AS INTEGER), n) where id = 1", &ddl, &["e", "n"]);
4021        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4022        assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true, true]);
4023    }
4024
4025    #[test]
4026    fn a_parameter_takes_the_type_its_call_case_or_compound_stands_in() {
4027        assert_eq!(param(&analysis("select id from users where name = coalesce(:a, :b)"), "a"), "text");
4028        assert_eq!(param(&analysis("select id from users where name = coalesce(:a, :b)"), "b"), "text");
4029        assert_eq!(param(&analysis("select id from users where name = case when id > 1 then :a else :b end"), "a"), "text");
4030        assert_eq!(param(&analysis("select id from users where name = iif(id > 1, :a, 'x')"), "a"), "text");
4031        assert_eq!(param(&analysis("select case :kind when 'a' then 1 else 2 end as k from users"), "kind"), "text");
4032        assert_eq!(param(&analysis("select name from users union all select :x"), "x"), "text");
4033        assert_eq!(param(&analysis("select :x union all select name from users"), "x"), "text");
4034        // A call whose result is not an argument's gives none of its own context.
4035        assert_eq!(param(&analysis("select id from users where name = printf(:f, 1)"), "f"), "text");
4036        assert_eq!(param(&analysis("select :x as v"), "x"), "unknown");
4037    }
4038
4039    #[test]
4040    fn an_outer_joins_on_term_pins_its_right_side_but_groups_nothing() {
4041        // SQLite moves the ON terms into the WHERE: `u.id = :id` restricts which user a post
4042        // meets, and the posts that meet none have NULL there, a second group.
4043        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");
4044        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");
4045        // The ON term still pins the right side against a pinned left one.
4046        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");
4047    }
4048
4049    #[test]
4050    fn an_insert_returns_no_row_where_something_can_skip_it() {
4051        let count = |sql: &str, extra: &[&str]| {
4052            let mut schema = ddl();
4053            schema.extend(extra.iter().map(|s| s.to_string()));
4054            analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
4055        };
4056        let insert = "insert into users (name) values (:n) returning id";
4057        assert_eq!(count(insert, &[]), "one");
4058        // A BEFORE trigger's RAISE(IGNORE) skips the row; an AFTER trigger cannot.
4059        assert_eq!(count(insert, &["create trigger skip before insert on users begin select raise(ignore) where new.name = 'x'; end"]), "at_most_one");
4060        assert_eq!(count(insert, &["create trigger untimed insert on users begin select 1; end"]), "at_most_one", "BEFORE is the default");
4061        assert_eq!(count(insert, &["create trigger later after insert on users begin select 1; end"]), "one");
4062        // `DO UPDATE … WHERE` leaves a conflicting row alone and returns nothing for it.
4063        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");
4064        assert_eq!(count("insert into users (id, name) values (:id, :n) on conflict (id) do update set name = excluded.name returning id", &[]), "one");
4065        // A later ON CONFLICT clause is tried as the first is.
4066        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");
4067        // A constraint declared ON CONFLICT IGNORE skips the row, unless the statement's own OR
4068        // clause says otherwise.
4069        let declared = |sql: &str, table: &str| {
4070            let schema = vec![table.to_string()];
4071            analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
4072        };
4073        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");
4074        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");
4075        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");
4076        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");
4077        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");
4078        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");
4079    }
4080
4081    #[test]
4082    fn a_write_to_a_view_goes_through_its_instead_of_trigger() {
4083        let schema = vec![
4084            "create table w (id integer primary key, k text not null, v integer)".to_string(),
4085            "create view wv as select id, k, v from w".to_string(),
4086            "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(),
4087            "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(),
4088        ];
4089        let analysis = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
4090        let insert = analysis("insert into wv (k, v) values (42, 9) returning k");
4091        assert!(insert.diagnostics.is_empty(), "{:?}", insert.diagnostics);
4092        // Returned as written, with no affinity: the INTEGER 42 for a column of TEXT affinity.
4093        assert_eq!(col(&insert, "k"), ("unknown".into(), true));
4094        assert!(analysis("update wv set v = :v where id = :id").diagnostics.is_empty());
4095        // The trigger fires on an update of `v` alone: SQLite refuses an update of `k`, and so does
4096        // its type check. A view with no trigger for the write stays read-only.
4097        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"));
4098        assert_eq!(analysis("delete from wv").diagnostics.first().map(|d| d.message.as_str()), Some("cannot modify wv because it is a view"));
4099        assert_eq!(instead_of_stub("create trigger t before insert on w begin select 1; end"), None);
4100        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"));
4101        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"));
4102    }
4103
4104    #[test]
4105    fn a_unique_key_bounds_only_a_comparison_under_its_own_collation() {
4106        let count = |sql: &str| {
4107            let mut schema = ddl();
4108            schema.push("create table c (id integer primary key, e text collate nocase, b text unique)".into());
4109            schema.push("create unique index c_e on c (e collate binary)".into());
4110            analyze_ddl(sql, &schema, &Extras::default()).analysis.cardinality
4111        };
4112        // `e` compares under NOCASE, and its unique index tells 'A' from 'a'.
4113        assert_eq!(count("select id from c where e = :e"), "many");
4114        assert_eq!(count("select id from c where b = :b"), "at_most_one");
4115        assert_eq!(count("select id from c where b = :b collate nocase"), "many");
4116        assert_eq!(count("select e from c where id = :id"), "at_most_one");
4117    }
4118
4119    #[test]
4120    fn a_function_the_host_registers_over_a_built_in_proves_nothing_strict() {
4121        let lower = Extras { total: vec![TotalFunction { name: "lower".into(), arity: 1, returns: Affinity::Text }], host: None };
4122        let nullable = |extras: &Extras| col(&analyze_ddl("select email from users where lower(email) = :e", &ddl(), extras).analysis, "email").1;
4123        assert!(!nullable(&Extras::default()));
4124        assert!(nullable(&lower));
4125    }
4126
4127    #[test]
4128    fn a_strict_column_and_a_rowid_hold_their_declared_type_alone() {
4129        let ddl = [
4130            "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",
4131            "create table loose (id integer primary key, n integer not null, t text)",
4132            "create table desc_key (a integer primary key desc)",
4133        ]
4134        .map(String::from);
4135        let kinds = |sql: &str| {
4136            let analysis = analyze_ddl(sql, &ddl, &Extras::default()).analysis;
4137            analysis.columns.iter().map(|c| serde_json::to_value(&c.ty).unwrap()["kind"].as_str().unwrap().to_string()).collect::<Vec<_>>().join(" ")
4138        };
4139        assert_eq!(kinds("select id, n, x, t, b, a from s"), "integer integer float text bytes unknown");
4140        assert_eq!(kinds("select id, n, t from loose"), "integer union union");
4141        assert_eq!(kinds("select a from desc_key"), "union");
4142        // A generated column keeps its affinity's union: SQLite before 3.51 never checks it.
4143        assert_eq!(kinds("select g from s"), "union");
4144        // Through subqueries, views and every arm of a compound, and no further.
4145        assert_eq!(kinds("select n, t from (select n, t from s)"), "integer text");
4146        assert_eq!(kinds("select n from s union all select id from loose"), "integer");
4147        assert_eq!(kinds("select n from s union all select n from loose"), "union");
4148        assert_eq!(kinds("select n from s union all values (1)"), "union");
4149    }
4150
4151    /// A schema as libSQL 0.10.0 writes it into `sqlite_schema` for a vector column and its
4152    /// index: its own shadow tables, then the index on the marker function.
4153    fn libsql_schema() -> Vec<String> {
4154        [
4155            "CREATE TABLE docs (id integer primary key, title text not null, emb F32_BLOB(3))",
4156            "CREATE TABLE libsql_vector_meta_shadow ( name TEXT PRIMARY KEY, metadata BLOB ) WITHOUT ROWID",
4157            "CREATE TABLE docs_emb_shadow (index_key  INTEGER , data BLOB, PRIMARY KEY (index_key))",
4158            "CREATE INDEX docs_emb_shadow_idx ON docs_emb_shadow (index_key)",
4159            "CREATE INDEX docs_emb on docs (libsql_vector_idx(emb))",
4160            "CREATE TABLE words (k text primary key, e F32_BLOB(2)) WITHOUT ROWID",
4161            "CREATE INDEX words_e on words (libsql_vector_idx(e, 'metric=l2'))",
4162        ]
4163        .map(String::from)
4164        .to_vec()
4165    }
4166
4167    /// The SQLite that reads the file lists none of libSQL's functions, as the engine's program's does.
4168    fn sqlite_host() -> Extras {
4169        Extras { total: vec![], host: Some(["lower", "upper", "length", "count"].map(|name| HostFunction { name: name.into(), arity: -1, kind: 's' }).to_vec()) }
4170    }
4171
4172    #[test]
4173    fn libsql_s_vector_functions_are_typed_whatever_the_host_lists() {
4174        for extras in [Extras::default(), sqlite_host()] {
4175            let a = |sql: &str| {
4176                let a = analyze_ddl(sql, &libsql_schema(), &extras).analysis;
4177                assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4178                a
4179            };
4180            // The schema replays, its vector index and libSQL's tables with it.
4181            let plain = a("select id, title from docs where id = :id");
4182            assert_eq!((col(&plain, "id"), col(&plain, "title")), (("integer".into(), false), ("text".into(), false)));
4183            // A vector column outside a STRICT table, which libSQL refuses them in, holds what its BLOB affinity stores.
4184            assert_eq!(a("select emb from docs").columns[0].nullable, true);
4185            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");
4186            assert_eq!((col(&distance, "d"), col(&distance, "l")), (("real".into(), true), ("real".into(), true)));
4187            assert_eq!((param(&distance, "q"), param(&distance, "r")), ("text".into(), "text".into()));
4188            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");
4189            for name in ["v", "a", "b", "c", "d", "e", "f"] {
4190                assert_eq!(col(&made, name), ("blob".into(), false), "{name}");
4191            }
4192            assert_eq!(col(&made, "text"), ("text".into(), false));
4193            let insert = a("insert into docs (title, emb) values (:title, vector(:v)) returning id");
4194            assert_eq!((param(&insert, "title"), param(&insert, "v")), ("text".into(), "text".into()));
4195        }
4196    }
4197
4198    #[test]
4199    fn vector_top_k_returns_the_key_of_its_index_s_table() {
4200        for extras in [Extras::default(), sqlite_host()] {
4201            let a = |sql: &str| {
4202                let a = analyze_ddl(sql, &libsql_schema(), &extras).analysis;
4203                assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4204                a
4205            };
4206            // A rowid table's rowid.
4207            let top = a("select id from vector_top_k('docs_emb', vector(:q), :k)");
4208            assert_eq!(col(&top, "id"), ("integer".into(), false));
4209            assert_eq!((param(&top, "q"), param(&top, "k")), ("text".into(), "integer".into()));
4210            assert_eq!(a("select * from vector_top_k('docs_emb', :q, 5)").columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id"]);
4211            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");
4212            assert_eq!(col(&joined, "title"), ("text".into(), false));
4213            // A WITHOUT ROWID table's primary key, of any storage class outside a STRICT table.
4214            assert_eq!(col(&a("select id from vector_top_k('words_e', :q, 3)"), "id"), ("unknown".into(), false));
4215            // On the nullable side of an outer join, and from an index named some other way.
4216            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));
4217            assert_eq!(a("select id from vector_top_k(:index, :q, 5)").columns[0].nullable, true);
4218        }
4219    }
4220
4221    #[test]
4222    fn libsql_s_alter_column_prepares_on_a_table_and_column_that_exist() {
4223        let a = |sql: &str| analyze_ddl(sql, &libsql_schema(), &Extras::default()).analysis;
4224        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"] {
4225            let altered = a(sql);
4226            assert!(altered.diagnostics.is_empty(), "{sql}: {:?}", altered.diagnostics);
4227            assert!(altered.columns.is_empty());
4228            assert_eq!(altered.cardinality, Cardinality::None);
4229        }
4230        let missing = a("alter table docs alter column nope to nope integer");
4231        assert!(missing.diagnostics.len() == 1 && missing.diagnostics[0].message.starts_with("no such column: \"nope\", so if it is a migration"), "{:?}", missing.diagnostics);
4232        assert!(!a("alter table nope alter column title to title text").diagnostics.is_empty());
4233        assert!(!a("alter table docs alter column title").diagnostics.is_empty());
4234    }
4235
4236    #[test]
4237    fn a_table_whose_check_calls_a_function_the_host_lacks_still_replays() {
4238        // sqlite-jsonschema's function, which the application's connection loads and the type
4239        // check's does not: CREATE TABLE resolves the CHECK, and the table was left out.
4240        let ddl = vec!["create table docs (id integer primary key, doc text check (doc is null or jsonschema_matches('{\"type\":\"object\"}', doc)))".to_string()];
4241        let without = Extras { total: vec![], host: Some(vec![HostFunction { name: "lower".into(), arity: 1, kind: 's' }]) };
4242        for extras in [Extras::default(), without.clone()] {
4243            let read = analyze_ddl("select id, doc from docs", &ddl, &extras).analysis;
4244            assert!(read.diagnostics.is_empty(), "{:?}", read.diagnostics);
4245            assert_eq!(read.columns.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), ["id", "doc"]);
4246            let write = analyze_ddl("insert into docs (doc) values (:doc) returning id", &ddl, &extras).analysis;
4247            assert!(write.diagnostics.is_empty(), "{:?}", write.diagnostics);
4248            assert_eq!(param(&write, "doc"), "text");
4249        }
4250        // A statement that calls the function itself is still refused where the host lacks it.
4251        let call = analyze_ddl("select jsonschema_matches('{}', doc) as m from docs", &ddl, &without).analysis;
4252        assert!(!call.diagnostics.is_empty());
4253    }
4254
4255    #[test]
4256    fn columns_from_provenance_and_rules() {
4257        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");
4258        assert_eq!(col(&a, "id"), ("integer".into(), false));
4259        assert_eq!(col(&a, "name"), ("text".into(), false));
4260        assert_eq!(col(&a, "email"), ("text".into(), true));
4261        assert_eq!(col(&a, "score"), ("real".into(), true));
4262        assert_eq!(col(&a, "l"), ("integer".into(), true));
4263        assert_eq!(col(&a, "e"), ("text".into(), false));
4264        assert_eq!(col(&a, "d"), ("integer".into(), false));
4265        assert_eq!(col(&a, "h"), ("integer".into(), false));
4266        assert_eq!(a.cardinality, "many");
4267    }
4268
4269    #[test]
4270    fn a_column_beside_an_aggregate_with_no_group_by_is_null_over_no_rows() {
4271        // The one row an aggregate with no GROUP BY returns over no rows holds NULL in every
4272        // column outside an aggregate's arguments, whatever the table declares or the WHERE tests.
4273        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'");
4274        assert_eq!(col(&a, "id"), ("integer".into(), true));
4275        assert_eq!(col(&a, "name"), ("text".into(), true));
4276        assert_eq!(col(&a, "e"), ("text".into(), false));
4277        assert_eq!(col(&a, "d"), ("integer".into(), true));
4278        assert_eq!(col(&a, "n"), ("integer".into(), false));
4279        assert_eq!(col(&a, "c"), ("integer".into(), false));
4280        assert_eq!(a.cardinality, "one");
4281        // A group has a row, and an aggregate reads rows that are there.
4282        let a = analysis("select name, count(*) as n from users group by name");
4283        assert_eq!(col(&a, "name"), ("text".into(), false));
4284    }
4285
4286    #[test]
4287    fn outer_join_and_subquery_provenance() {
4288        let a = analysis("select u.id, p.title from users u left join posts p on p.user_id = u.id");
4289        assert_eq!(col(&a, "title"), ("text".into(), true));
4290        let a = analysis("select t.id, t.name from (select id, name from users) t where t.id = :id");
4291        assert_eq!(col(&a, "id"), ("integer".into(), false));
4292        assert_eq!(col(&a, "name"), ("text".into(), false));
4293        assert_eq!(param(&a, "id"), "integer");
4294    }
4295
4296    #[test]
4297    fn parameters_from_context() {
4298        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");
4299        assert_eq!(param(&a, "email"), "text");
4300        assert_eq!(param(&a, "min"), "real");
4301        assert_eq!(param(&a, "a"), "integer");
4302        assert_eq!(param(&a, "from"), "text");
4303        assert_eq!(param(&a, "q"), "text");
4304        assert_eq!(param(&a, "n"), "text");
4305        assert_eq!(param(&a, "lim"), "integer");
4306        assert_eq!(param(&a, "off"), "integer");
4307        let a = analysis("insert into users (email, name, score) values (:e, upper(:n), :s * 2) returning id");
4308        assert_eq!(param(&a, "e"), "text");
4309        assert_eq!(param(&a, "n"), "text");
4310        assert_eq!(param(&a, "s"), "integer");
4311        assert_eq!(a.cardinality, "one");
4312        let a = analysis("update users set name = :name, score = :score where id = :id returning id");
4313        assert_eq!(param(&a, "name"), "text");
4314        assert_eq!(param(&a, "score"), "real");
4315        assert_eq!(param(&a, "id"), "integer");
4316        assert_eq!(a.cardinality, "at_most_one");
4317    }
4318
4319    #[test]
4320    fn json_each_reads_text() {
4321        // A list of values in one parameter: the JSON text and the path are text, as written or cast.
4322        let a = analysis("select id from users where id in (select value from json_each(:ids))");
4323        assert_eq!(param(&a, "ids"), "text");
4324        assert!(!a.params.iter().find(|p| p.name == "ids").unwrap().nullable);
4325        let a = analysis("select key, value from json_tree(:doc, :path)");
4326        assert_eq!(param(&a, "doc"), "text");
4327        assert_eq!(param(&a, "path"), "text");
4328        assert_eq!(param(&analysis("select value from json_each(cast(:ids as text))"), "ids"), "text");
4329        let a = marked("select value from json_each(coalesce(CAST(:ids AS TEXT), '[]'))", &ddl(), &["ids"]);
4330        assert_eq!(param(&a, "ids"), "text");
4331        assert!(a.params.iter().find(|p| p.name == "ids").unwrap().nullable);
4332        // A parameter beside the call keeps its own context.
4333        let a = analysis("select users.id from users, json_each(:ids) j where users.id = j.value and users.name = :n");
4334        assert_eq!(param(&a, "ids"), "text");
4335        assert_eq!(param(&a, "n"), "text");
4336    }
4337
4338    #[test]
4339    fn cardinality_by_keys() {
4340        assert_eq!(analysis("select id from users where email = :email").cardinality, "at_most_one");
4341        assert_eq!(analysis("select id from users where name = :name").cardinality, "many");
4342        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");
4343        assert_eq!(analysis("select id from users limit 1").cardinality, "at_most_one");
4344        assert_eq!(analysis("insert or ignore into users (email, name) values (:e, :n) returning id").cardinality, "at_most_one");
4345        assert_eq!(analysis("insert into users (email, name) values (:e, :n)").cardinality, "none");
4346        assert_eq!(analysis("delete from users where id = :id returning id").cardinality, "at_most_one");
4347        assert_eq!(analysis("select id from users union all select user_id from posts").cardinality, "many");
4348    }
4349
4350    /// The whole path, schema query included, as the host drives it.
4351    fn analyzed(sql: &str) -> Analysis {
4352        let ddl = [
4353            "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)",
4354        ];
4355        let rows = ddl.iter().map(|d| vec![serde_json::Value::String(d.to_string())]).collect();
4356        let answers = HashMap::from([(format!("query:{DDL_QUERY}|[]"), crate::api::Answer::Rows { rows }), (format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]))]);
4357        let host = Host::new(&answers);
4358        analyze(sql, &lex::lex(sql, Dialect::Sqlite).unwrap(), &host, &[]).expect("the schema and the functions were answered")
4359    }
4360
4361    /// What a SQLite with none of the optional families lists, as [`FUNCTIONS_QUERY`]'s rows: the
4362    /// functions the tests call, and `extra` on top.
4363    fn listed(extra: &[(&str, i32, char)]) -> Vec<Vec<serde_json::Value>> {
4364        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')];
4365        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')];
4366        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()
4367    }
4368
4369    fn functions_answer(extra: &[(&str, i32, char)]) -> crate::api::Answer {
4370        crate::api::Answer::Rows { rows: listed(extra) }
4371    }
4372
4373    /// The direct entry on a host whose SQLite lists [`listed`]'s functions.
4374    fn on_host(sql: &str, schema: &[String], extra: &[(&str, i32, char)], total: Vec<TotalFunction>) -> Analysis {
4375        analyze_ddl(sql, schema, &Extras { total, host: host_functions(&listed(extra)) }).analysis
4376    }
4377
4378    #[test]
4379    fn names_fold_ascii_case_as_sqlite_folds_them() {
4380        let schema: Vec<String> = [
4381            "create table Books (id integer primary key, Title text not null, ISBN text unique, note text)",
4382            "create table \"\u{c9}t\u{e9}\" (id integer primary key, v text)",
4383            "create table wr (K text primary key, v text) without rowid",
4384            "create table rt (RowId integer, v text)",
4385            "create table \"my table\" (id integer primary key, v text)",
4386            "create trigger \"skip one\" before insert on \"BOOKS\" begin select raise(ignore) where new.title = 'x'; end",
4387            "create trigger skip_two before insert on \"my table\" begin select raise(ignore) where new.v = 'x'; end",
4388            "create trigger [later] after update of \"on\", v on main . [my table] begin select 1; end",
4389        ]
4390        .iter()
4391        .map(|s| s.to_string())
4392        .collect();
4393        let a = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
4394        // The table as the statement spells it, bare, quoted or qualified, is the table the DDL
4395        // declares, and its keys are that table's.
4396        for sql in [
4397            "select * from books where id = :id",
4398            "select * from BOOKS where ID = :id",
4399            "select * from \"books\" where \"ID\" = :id",
4400            "select * from [BOOKS] b where B.Id = :id",
4401            "select b.* from main.bOOKS b join Books c on c.ID = b.id where C.id = :id",
4402            "select title from books where isbn = :i",
4403            "update BOOKS set TITLE = :t where ID = :id returning Title",
4404            "delete from books where Isbn = :i returning id",
4405            "select v from WR where k = :k",
4406            "select v from Rt where _ROWID_ = :r",
4407        ] {
4408            let got = a(sql);
4409            assert!(got.diagnostics.is_empty(), "{sql}: {:?}", got.diagnostics);
4410            assert_eq!(got.cardinality, "at_most_one", "{sql}: {:?}", got.cardinality_reason);
4411        }
4412        // A declared column named rowid in any case hides the rowid, and a table without a rowid
4413        // has none to name.
4414        assert_eq!(a("select v from RT where ROWID = :r").cardinality, "many");
4415        assert_eq!(a("select v from wr where rowid = 1").diagnostics[0].message, "no such column: rowid");
4416        // A target column in another case is the declared column: its type, and its NOT NULL.
4417        let insert = a("insert into BOOKS (TITLE, NOTE) values (:t, :n)");
4418        assert_eq!((param(&insert, "t"), param(&insert, "n")), ("text".into(), "text".into()));
4419        assert_eq!(insert.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [false, true]);
4420        assert_eq!(col(&a("select TITLE, Note from books"), "Title"), ("text".into(), false));
4421        // The rowid by any of its names, in any case, is the INTEGER PRIMARY KEY column.
4422        assert_eq!(param(&a("insert into books (ROWID, title) values (:r, :t)"), "r"), "integer");
4423        assert_eq!(param(&a("insert into rt (_rowid_, v) values (:r, :v)"), "r"), "unknown");
4424        // SQLite folds ASCII alone: `été` is another name than `Été`, and no table.
4425        assert_eq!(a("select v from \"\u{c9}t\u{e9}\" where id = :id").cardinality, "at_most_one");
4426        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}");
4427        // A table-valued function in any case is the function.
4428        assert_eq!(param(&a("select value from JSON_EACH(:ids)"), "ids"), "text");
4429        // A trigger's table is read as SQLite reads it, quoted and in another case, and so is a
4430        // trigger whose name or column list holds a keyword.
4431        assert_eq!(a("insert into books (title) values (:t) returning id").cardinality, "at_most_one");
4432        assert_eq!(a("insert into \"My Table\" (v) values (:v) returning id").cardinality, "at_most_one");
4433        assert_eq!(trigger_header(&schema[5]), Some(("before".into(), "insert".into(), "books".into())));
4434        assert_eq!(trigger_header(&schema[7]), Some(("after".into(), "update".into(), "my table".into())));
4435        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())));
4436        assert_eq!(trigger_header("create table trigger_log (\"on\" text)"), None);
4437    }
4438
4439    #[test]
4440    fn every_row_of_a_values_list_types_its_parameters() {
4441        let a = analysis("insert into users (id, name, email) values (:a, :b, :e), (:c, :d, :e2), (:f, upper(:g), 'x') returning id");
4442        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4443        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();
4444        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)];
4445        assert_eq!(got, want.map(|(n, t, null)| (n.to_string(), t.to_string(), null)));
4446        assert_eq!((a.cardinality.as_str(), a.cardinality_reason.as_deref()), ("many", Some("a VALUES list of 3 rows returns 3 rows")));
4447        // A parameter a row does not write whole cannot be null. Each parameter appears once, so
4448        // one cannot be written to a nullable column in one row and a NOT NULL one in another.
4449        let a = analysis("insert into users (name, email) values ('a', :x), (:w, 'b'), ('c', lower(:y))");
4450        assert_eq!(a.params.iter().map(|p| p.nullable).collect::<Vec<_>>(), [true, false, false]);
4451        assert_eq!(a.cardinality, "none");
4452        let a = analysis("insert into users (name, email) values ('a', :x), (:x, 'b')");
4453        assert_eq!(a.diagnostics.iter().map(|d| d.code).collect::<Vec<_>>(), [3]);
4454        // Without a column list the rows fill the columns in order; under a WITH too.
4455        let a = analysis("with w as (select 1) insert into posts values (:id, :u, :t, :b), (:id2, :u2, :t2, :b2)");
4456        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));
4457        // A list of any length: SQLite keeps a row per arm, and the tree nests none of them.
4458        let rows: Vec<String> = (0..3000).map(|i| format!("(:n{i}, :e{i}, {i})")).collect();
4459        let a = analysis(&format!("insert into users (name, email, score) values {}", rows.join(", ")));
4460        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4461        assert_eq!((a.params.len(), param(&a, "n2999"), param(&a, "e2999")), (6000, "text".into(), "text".into()));
4462        // A VALUES list on its own: a row per row, a column of the type its rows share, NULL where
4463        // a row has one, and a parameter typed by the rows beside it.
4464        let a = analysis("values (1, 'a', :p), (2, null, 3), (:q, 'c', 4.5)");
4465        assert_eq!((col(&a, "column1"), col(&a, "column2")), (("integer".into(), false), ("text".into(), true)));
4466        assert_eq!((param(&a, "p"), param(&a, "q"), a.cardinality.as_str()), ("real".into(), "integer".into(), "many"));
4467        assert_eq!(analysis("values (1, 'a')").cardinality, "one");
4468        assert_eq!(col(&analysis("values (1), ('a')"), "column1").0, "unknown");
4469        assert_eq!(analysis("select v.column1 from (values (1), (2)) v").cardinality, "many");
4470        assert_eq!(analysis("select 1 union all values (2), (3)").cardinality, "many");
4471        assert_eq!(col(&analysis("select (values (1), (2)) as x"), "x"), ("integer".into(), true));
4472    }
4473
4474    #[test]
4475    fn the_select_that_feeds_an_insert_types_its_parameters() {
4476        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()];
4477        let a = |sql: &str| {
4478            let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
4479            assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
4480            a
4481        };
4482        let params = |a: &Analysis| a.params.iter().map(|p| (affinity_of(&p.ty).unwrap_or("unknown").to_string(), p.nullable)).collect::<Vec<_>>();
4483        let typed = |types: &[&str]| types.iter().map(|t| (t.to_string(), false)).collect::<Vec<_>>();
4484        // A select-list parameter takes its target column's type; one the WHERE compares, the
4485        // column's: `bool` is a declared type of NUMERIC affinity, a number or a text.
4486        // A bare one written to a column that may hold NULL takes NULL, as in a VALUES row.
4487        let got = a("insert into foo (name, meta) select name, ? from bar where ready = ?");
4488        assert_eq!((got.kind.map_or("", StatementKind::as_str), got.cardinality.as_str()), ("insert", "none"));
4489        assert_eq!(params(&got), [("text".to_string(), true), ("numeric".to_string(), false)]);
4490        assert_eq!(params(&a("select name from bar where ready = ?")), typed(&["numeric"]));
4491        // Without a column list, through an expression, in every arm of a compound, and under a
4492        // LIMIT; only a bare column of the one SELECT is a value written whole.
4493        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)]);
4494        assert_eq!(params(&a("insert into foo (k, name) select n + :d, upper(:u) from bar limit :l")), typed(&["integer", "text", "integer"]));
4495        assert_eq!(params(&a("insert into foo (name, k) select name, :a from bar union all select :b, n from bar")), typed(&["integer", "text"]));
4496        let returning = a("insert into foo (name, meta) select name, :m from bar where n > :n returning name, meta");
4497        assert_eq!((params(&returning), returning.cardinality.as_str()), (vec![("text".to_string(), true), ("integer".to_string(), false)], "many"));
4498        // A subquery elsewhere in the statement is not the INSERT's source: one in RETURNING
4499        // stands in no typed place, and one in a VALUES row is the value written to its own
4500        // column (k, not the first target column name), as any scalar subquery takes the type of
4501        // the place it stands in.
4502        assert_eq!(params(&a("insert into foo (name, meta) select name, 'x' from bar returning (select :p) as p")), typed(&["unknown"]));
4503        assert_eq!(params(&a("insert into foo (name, k) values ('a', (select :p))")), typed(&["integer"]));
4504        // A whole-table copy, which SQLite runs without a SELECT, is still an INSERT.
4505        let copy = a("insert into foo2 select * from foo");
4506        assert_eq!((copy.kind.map_or("", StatementKind::as_str), copy.cardinality.as_str()), ("insert", "none"));
4507    }
4508
4509    #[test]
4510    fn the_hosts_sqlite_decides_which_functions_exist() {
4511        // The embedded SQLite has the math functions and `soundex`; a host may have neither.
4512        let sql = "select id, ACOS(score) as a from users where name = :n";
4513        let a = on_host(sql, &ddl(), &[], Vec::new());
4514        assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
4515        assert_eq!(a.diagnostics[0].message, "no such function: ACOS on this database's SQLite");
4516        assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length, a.diagnostics[0].code), (sql.find("ACOS").unwrap(), 4, 6));
4517        assert!(a.columns.is_empty());
4518        let a = on_host(sql, &ddl(), &[("acos", 1, 's')], Vec::new());
4519        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4520        assert_eq!(col(&a, "a"), ("real".into(), true));
4521        let a = on_host("select soundex(name) as s from users where soundex(:x) = 'A000'", &ddl(), &[("SOUNDEX", 1, 's')], Vec::new());
4522        assert_eq!((col(&a, "s"), param(&a, "x")), (("text".into(), false), "text".into()));
4523        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");
4524        // A host that cannot list its functions keeps every function the embedded SQLite has.
4525        assert_eq!(col(&analysis("select acos(score) as a, soundex(name) as s from users"), "a"), ("real".into(), true));
4526        // What every SQLite has stays: operators that are functions underneath, keywords, `*`.
4527        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());
4528        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4529        // A call inside a window definition, a subquery, a WITH query and an ORDER BY is a call.
4530        for sql in [
4531            "select row_number() over (order by sqrt(score)) as r from users",
4532            "select id from users where id in (select id from users where sqrt(score) > 1)",
4533            "with w as (select sqrt(score) as s from users) select s from w",
4534            "select id from users order by sqrt(score)",
4535            "update users set score = sqrt(score) where id = :id",
4536            "insert into users (name, score) values (:n, sqrt(:s))",
4537            "delete from users where id = :id returning sqrt(score) as s",
4538        ] {
4539            let a = on_host(sql, &ddl(), &[], Vec::new());
4540            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}");
4541        }
4542        // A view that calls one fails every statement that reads it, with no place in the
4543        // statement to point at; the replay itself keeps the view.
4544        let mut schema = ddl();
4545        schema.push("create view roots as select id, sqrt(score) as root from users".into());
4546        let sql = "select root from roots";
4547        let a = on_host(sql, &schema, &[], Vec::new());
4548        assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
4549        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()));
4550        assert_eq!(col(&on_host(sql, &schema, &[("sqrt", 1, 's')], Vec::new()), "root"), ("real".into(), true));
4551        assert!(on_host("select id from users", &schema, &[], Vec::new()).diagnostics.is_empty());
4552        // A function the host has and the embedded SQLite lacks prepares, with no type; an
4553        // aggregate is one row, and a window function takes an OVER.
4554        let extra = [("host_only", 2, 's'), ("host_only", 3, 's'), ("host_agg", 1, 'a'), ("host_win", -1, 'w')];
4555        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());
4556        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4557        assert_eq!((col(&a, "two"), col(&a, "three"), a.cardinality.as_str()), (("unknown".into(), true), ("unknown".into(), true), "at_most_one"));
4558        // It may change from row to row, so it pins no key.
4559        assert_eq!(on_host("select name from users where id = host_only(1, 2)", &ddl(), &extra, Vec::new()).cardinality, "many");
4560        let a = on_host("select host_agg(score) as total from users", &ddl(), &extra, Vec::new());
4561        assert_eq!((col(&a, "total"), a.cardinality.as_str()), (("unknown".into(), true), "one"));
4562        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());
4563        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4564        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()");
4565        // A function the host registers on its connection is one it has, listed or not.
4566        let html = vec![TotalFunction { name: "reylo_html".into(), arity: 1, returns: Affinity::Text }];
4567        assert_eq!(col(&on_host("select reylo_html(name) as h from users", &ddl(), &[], html), "h"), ("text".into(), false));
4568        // No list at all is no list: every SQLite has functions.
4569        assert_eq!(host_functions(&[]), None);
4570        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' }]));
4571    }
4572
4573    #[test]
4574    fn the_replay_asks_the_host_for_its_functions_with_the_schema() {
4575        let sql = "select acos(score) as a from users";
4576        let lexed = lex::lex(sql, Dialect::Sqlite).unwrap();
4577        let schema = crate::api::Answer::Rows { rows: ddl().iter().map(|d| vec![serde_json::Value::String(d.clone())]).collect() };
4578        let ask = |answers: &HashMap<String, crate::api::Answer>| {
4579            let host = Host::new(answers);
4580            let analysis = analyze(sql, &lexed, &host, &[]);
4581            let needs: Vec<String> = host
4582                .needs()
4583                .iter()
4584                .map(|n| match n {
4585                    crate::api::Need::Query { sql, scope, .. } => format!("{sql} {scope:?}"),
4586                    crate::api::Need::Describe { sql, .. } => format!("describe {sql}"),
4587                })
4588                .collect();
4589            (analysis, needs)
4590        };
4591        // One round asks both, for the session.
4592        let mut answers = HashMap::new();
4593        let (analysis, needs) = ask(&answers);
4594        assert!(analysis.is_none());
4595        assert_eq!(needs, [format!("{DDL_QUERY} Session"), format!("{FUNCTIONS_QUERY} Session")]);
4596        answers.insert(format!("query:{DDL_QUERY}|[]"), schema);
4597        assert_eq!(ask(&answers).1, [format!("{FUNCTIONS_QUERY} Session")]);
4598        // The host's list decides.
4599        answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]));
4600        let (analysis, needs) = ask(&answers);
4601        assert!(needs.is_empty());
4602        assert_eq!(analysis.unwrap().diagnostics[0].message, "no such function: acos on this database's SQLite");
4603        answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[("acos", 1, 's')]));
4604        assert!(ask(&answers).0.unwrap().diagnostics.is_empty());
4605        // A host whose SQLite refuses the question, or answers nothing, keeps the embedded one's.
4606        answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), crate::api::Answer::Error { error: crate::api::DbError { message: "not authorized".into(), code: None, position: None } });
4607        assert_eq!(col(&ask(&answers).0.unwrap(), "a"), ("real".into(), true));
4608        answers.insert(format!("query:{FUNCTIONS_QUERY}|[]"), crate::api::Answer::Rows { rows: Vec::new() });
4609        assert_eq!(col(&ask(&answers).0.unwrap(), "a"), ("real".into(), true));
4610    }
4611
4612    #[test]
4613    fn a_table_in_an_attached_database_is_named_as_one() {
4614        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");
4615        for (sql, reference) in [
4616            ("select id, name from baz.users where id = :id", "baz.users"),
4617            ("select u.id from \"baz\".[users] u", "\"baz\".[users]"),
4618            ("select 1 from users join /* x */ baz . users b on b.id = users.id", "baz . users"),
4619            ("insert into baz.users (id) values (:id)", "baz.users"),
4620            ("update baz.users set name = :n where id = :id", "baz.users"),
4621            ("delete from baz.users where id = :id", "baz.users"),
4622        ] {
4623            let a = analysis(sql);
4624            assert_eq!(a.diagnostics.len(), 1, "{sql}: {:?}", a.diagnostics);
4625            assert_eq!(a.diagnostics[0].message, message("baz"), "{sql}");
4626            assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length), (sql.find(reference).unwrap(), reference.len()), "{sql}");
4627        }
4628        // The position survives the placeholder rewrite.
4629        let sql = "select :auth.user_id as u, id from baz.users";
4630        assert_eq!(analysis(sql).diagnostics[0].start, sql.find("baz").unwrap());
4631        // A schema the database has, and a name that only holds a dot, are SQLite's own message.
4632        assert_eq!(analysis("select id from main.nope").diagnostics[0].message, "no such table: main.nope");
4633        assert_eq!(analysis("select id from temp.nope").diagnostics[0].message, "no such table: temp.nope");
4634        assert_eq!(analysis("select id from \"baz.users\"").diagnostics[0].message, "no such table: baz.users");
4635        assert_eq!(analysis("select id from nope").diagnostics[0].message, "no such table: nope");
4636        assert!(analysis("select main.users.id from main.users").diagnostics.is_empty());
4637    }
4638
4639    #[test]
4640    fn sqlites_own_tables_replay_without_a_note() {
4641        // `sqlite_schema` lists SQLite's own tables beside the application's: the sequence table
4642        // an AUTOINCREMENT makes, the statistics ANALYZE writes, a virtual table's shadow tables.
4643        let schema: Vec<String> = [
4644            "CREATE TABLE t (id integer primary key autoincrement, v text)",
4645            "CREATE TABLE sqlite_sequence(name,seq)",
4646            "CREATE TABLE sqlite_stat1(tbl,idx,stat)",
4647            "CREATE VIRTUAL TABLE ft USING fts5(body)",
4648            "CREATE TABLE 'ft_data'(id INTEGER PRIMARY KEY, block BLOB)",
4649            "CREATE TABLE 'ft_idx'(segid, term, pgno, PRIMARY KEY(segid, term)) WITHOUT ROWID",
4650            "CREATE TABLE 'ft_content'(id INTEGER PRIMARY KEY, c0)",
4651            "CREATE TABLE 'ft_docsize'(id INTEGER PRIMARY KEY, sz BLOB)",
4652            "CREATE TABLE 'ft_config'(k PRIMARY KEY, v) WITHOUT ROWID",
4653            "CREATE VIRTUAL TABLE rt USING rtree(id, minx, maxx)",
4654            "CREATE TABLE \"rt_rowid\"(rowid INTEGER PRIMARY KEY,nodeno)",
4655            "CREATE TABLE \"rt_node\"(nodeno INTEGER PRIMARY KEY,data)",
4656            "CREATE TABLE \"rt_parent\"(nodeno INTEGER PRIMARY KEY,parentnode)",
4657            "CREATE VIRTUAL TABLE f4 USING fts4(body)",
4658            "CREATE TABLE 'f4_content'(docid INTEGER PRIMARY KEY, 'c0body')",
4659            "CREATE TABLE 'f4_segments'(blockid INTEGER PRIMARY KEY, block BLOB)",
4660            "CREATE TABLE 'f4_segdir'(level INTEGER,idx INTEGER,start_block INTEGER,leaves_end_block INTEGER,end_block INTEGER,root BLOB,PRIMARY KEY(level, idx))",
4661            "CREATE TABLE 'f4_docsize'(docid INTEGER PRIMARY KEY, size BLOB)",
4662            "CREATE TABLE 'f4_stat'(id INTEGER PRIMARY KEY, value BLOB)",
4663        ]
4664        .iter()
4665        .map(|s| s.to_string())
4666        .collect();
4667        let a = |sql: &str, schema: &[String]| analyze_ddl(sql, schema, &Extras::default()).analysis;
4668        // An error in the statement is the only thing reported.
4669        let failed = a("select nope from t", &schema);
4670        assert_eq!(failed.diagnostics.iter().map(|d| d.message.as_str()).collect::<Vec<_>>(), ["no such column: nope"]);
4671        for sql in [
4672            "select name, seq from sqlite_sequence where name = :n",
4673            "update sqlite_sequence set seq = :s where name = :n",
4674            "select tbl, idx, stat from sqlite_stat1",
4675            "select name, sql from sqlite_schema where type = 'table'",
4676            "select name from sqlite_master",
4677            "select rowid, body from ft where ft match :q",
4678            "select id from rt where minx > :x",
4679            "select docid from f4 where f4 match :q",
4680            "select block from ft_data where id = :id",
4681            "insert into t (v) values (:v) returning id",
4682        ] {
4683            let got = a(sql, &schema);
4684            assert!(got.diagnostics.is_empty(), "{sql}: {:?}", got.diagnostics);
4685        }
4686        assert_eq!(a("insert into t (v) values (:v) returning id", &schema).cardinality, "one");
4687        // The schema table itself stays read-only, as on the host.
4688        assert_eq!(a("delete from sqlite_schema", &schema).diagnostics[0].message, "table sqlite_master may not be modified");
4689        // A sequence table that outlived its AUTOINCREMENT table, before one made later.
4690        let later = vec!["CREATE TABLE sqlite_sequence(name,seq)".to_string(), "CREATE TABLE u (id integer primary key autoincrement, v text)".to_string()];
4691        assert!(a("select seq from sqlite_sequence", &later).diagnostics.is_empty());
4692        assert_eq!(a("insert into u (v) values (:v) returning id", &later).cardinality, "one");
4693        assert_eq!(a("select nope from u", &later).diagnostics.len(), 1);
4694        // A step that really fails is still named beside the statement's error.
4695        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()];
4696        let notes: Vec<String> = a("select nope from t", &broken).diagnostics.iter().map(|d| d.message.clone()).collect();
4697        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"]);
4698    }
4699
4700    #[test]
4701    fn a_double_quoted_word_that_names_no_column_is_refused_as_the_drivers_refuse_it() {
4702        // A schema that holds one replays, as SQLite reads it from a file.
4703        let schema = vec!["create table t (id integer primary key, v text default \"none\" check (v <> \"bad\"))".to_string()];
4704        let a = |sql: &str| analyze_ddl(sql, &schema, &Extras::default()).analysis;
4705        for sql in ["select \"hello\"", "select \"hello\" from t", "select id from t where v = \"x\""] {
4706            let messages: Vec<String> = a(sql).diagnostics.iter().map(|d| d.message.clone()).collect();
4707            assert_eq!(messages, [format!("no such column: \"{}\" - should this be a string literal in single-quotes?", if sql.contains("hello") { "hello" } else { "x" })], "{sql}");
4708        }
4709        for sql in ["select \"id\", \"v\" from t", "select 'hello'", "insert into t (id) values (1) returning v"] {
4710            assert!(a(sql).diagnostics.is_empty(), "{sql}: {:?}", a(sql).diagnostics);
4711        }
4712    }
4713
4714    #[test]
4715    fn the_version_reported_is_the_embedded_sqlites() {
4716        // The release the docs name (site/content/docs/sqlite.mdx): a newer amalgamation changes both.
4717        assert!(tree::version().starts_with("3.53."), "{}", tree::version());
4718    }
4719
4720    #[test]
4721    fn a_parameter_sqlite_reads_and_the_lexer_does_not_is_an_error_at_its_place() {
4722        let unbound = |sql: &str| analysis(sql).diagnostics.iter().filter(|d| d.code == 1).map(|d| (d.start, d.length, d.message.clone())).collect::<Vec<_>>();
4723        // SQLite's parameter is `:`, `@` or `$` and any run of name characters, digits and bytes
4724        // past ASCII among them; the lexer's name is ASCII and starts with no digit.
4725        for written in [":été", ":1st", "@2x"] {
4726            let sql = format!("select id from users where name = :n and email = {written}");
4727            let found = unbound(&sql);
4728            assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(sql.find(written).unwrap(), written.len())], "{sql}");
4729            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"));
4730        }
4731        // The place is the parameter's, not the same text in a string before it.
4732        let sql = "select ':été' from users where name = :été";
4733        assert_eq!(unbound(sql).iter().map(|(s, _, _)| *s).collect::<Vec<_>>(), [sql.rfind(":été").unwrap()]);
4734        // Every parameter the lexer read is one SQLite numbers, in each form, and a bracketed
4735        // name hides nothing after it.
4736        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)"] {
4737            assert!(unbound(sql).is_empty(), "{sql}");
4738        }
4739        assert_eq!(analysis("select id as [it's], :n as n from users").params.len(), 1);
4740    }
4741
4742    #[test]
4743    fn a_parameter_as_a_whole_sort_or_group_key_is_an_error_at_its_place() {
4744        // Through the protocol's whole path, which compiles a `::type` cast to SQLite's own.
4745        let full = |sql: &str| {
4746            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)"];
4747            let rows = ddl.iter().map(|d| vec![serde_json::Value::String(d.to_string())]).collect();
4748            let answers = HashMap::from([(format!("query:{DDL_QUERY}|[]"), crate::api::Answer::Rows { rows }), (format!("query:{FUNCTIONS_QUERY}|[]"), functions_answer(&[]))]);
4749            let host = Host::new(&answers);
4750            <crate::api::Sqlite as reylo_engine_core::database::Database>::analyze(sql, &host).expect("answered")
4751        };
4752        let keys = |sql: &str| full(sql).diagnostics.iter().filter(|d| d.code == 17).map(|d| (d.start, d.length, d.message.clone())).collect::<Vec<_>>();
4753        let at = |sql: &str, written: &str| sql.find(written).unwrap();
4754        // A `::type` cast is part of the parameter's place, as on every diagnostic at a cast one.
4755        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)] {
4756            let found = keys(sql);
4757            assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(at(sql, ":sort"), length)], "{sql}");
4758            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");
4759        }
4760        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")] {
4761            let found = keys(sql);
4762            assert_eq!(found.iter().map(|(s, l, _)| (*s, *l)).collect::<Vec<_>>(), [(at(sql, written), written.len())], "{sql}");
4763            assert!(found[0].2.starts_with(&format!("order by {written} sorts every row")), "{sql}");
4764        }
4765        assert_eq!(keys("select id from users order by ?2, ?1").iter().map(|(s, ..)| *s).collect::<Vec<_>>(), [30, 34]);
4766        assert_eq!(keys("select id from users order by name, ?").len(), 1);
4767        // GROUP BY, alone and beside another key.
4768        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");
4769        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"));
4770        // A window's keys, a named window's, and an aggregate's ORDER BY.
4771        let sql = "select row_number() over (partition by :p order by :o) as n from users";
4772        let found = keys(sql);
4773        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())]);
4774        assert_eq!(keys("select row_number() over w as n from users window w as (order by :o)").len(), 1);
4775        assert_eq!(keys("select group_concat(name, ',' order by :o) as names from users").len(), 1);
4776        // In a subquery, a WITH query (read twice, reported once), an expression's subquery and a
4777        // set operation's ORDER BY.
4778        assert_eq!(keys("select id from (select id from users order by :s limit 3) t").len(), 1);
4779        assert_eq!(keys("with t as (select name from users group by :g, name) select a.name from t a, t b").len(), 1);
4780        assert_eq!(keys("select id from users where id in (select id from users order by :s limit 3)").len(), 1);
4781        // SQLite itself refuses a compound's ORDER BY term that names no column of its result.
4782        let refused = full("select id from users union select id from users order by :s");
4783        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")]);
4784        assert_eq!(keys("insert into users (name) select name from users order by :s").len(), 1);
4785        // A key that holds a parameter chooses a column with it; a position and a LIMIT are none,
4786        // and so is a position or an alias of a result column that is a parameter, which SQLite
4787        // resolves to a copy of the parameter.
4788        for sql in [
4789            "select id, :tag as tag from users order by 2",
4790            "select id, :tag as tag from users order by tag",
4791            "select :tenant as tenant, name, count(*) as n from users group by 1, 2",
4792            "select id, name from users order by case :sort when 'name' then name end",
4793            "select id from users order by case when :desc then id end desc, id",
4794            "select id from users order by 1 limit :n",
4795            "select id from users order by lower(:x) || name",
4796        ] {
4797            assert_eq!(keys(sql), [], "{sql}");
4798        }
4799        // The rest of the statement is typed all the same.
4800        let a = full("select id from users order by :sort::text");
4801        assert_eq!(a.columns.len(), 1);
4802        assert_eq!(affinity_of(&a.params[0].ty), Some("text"));
4803    }
4804
4805    #[test]
4806    fn names_a_column_as_the_statement_is_sent() {
4807        // The tree is read over `?1`; the statement runs with `?`, and a driver's row holds the name that text gives.
4808        let names = |sql: &str| analysis(sql).columns.iter().map(|c| c.name.clone()).collect::<Vec<_>>();
4809        assert_eq!(names("select id + cast(:a as integer), name from users"), ["id + cast(? as integer)", "name"]);
4810        assert_eq!(names("select * from (select id + cast(:a as integer) from users)"), ["id + cast(? as integer)"]);
4811        assert_eq!(names("update users set name = name returning id + cast(:a as integer)"), ["id + cast(? as integer)"]);
4812        assert_eq!(names("select cast(:a as integer) as a"), ["a"]);
4813    }
4814
4815    #[test]
4816    fn prepares_the_numbered_rewrite() {
4817        // SQLite's own `:auth` would end at the dot; the rewrite keeps the whole name one parameter.
4818        let a = analyzed("select name from users where email = :auth.email and id = :auth.id and score > :auth.email");
4819        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4820        assert_eq!(param(&a, "auth.email"), "text");
4821        assert_eq!(param(&a, "auth.id"), "integer");
4822        assert_eq!(a.rewritten.sql, "select name from users where email = ? and id = ? and score > ?");
4823        assert_eq!(a.rewritten.order, ["auth.email", "auth.id", "auth.email"]);
4824        // Positional forms: SQLite's `?3` is the parameter `3`, and a bare `?` the next number.
4825        assert_eq!(param(&analyzed("select name from users where id = ?3"), "3"), "integer");
4826        assert_eq!(param(&analyzed("select name from users where email = ?"), "1"), "text");
4827        // An error SQLite reports in the rewrite lands on the author's text.
4828        let sql = "select :auth.user_id, nope from users";
4829        let a = analyzed(sql);
4830        assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
4831        assert_eq!((a.diagnostics[0].start, a.diagnostics[0].length), (sql.find("nope").unwrap(), 4));
4832    }
4833
4834    #[test]
4835    fn a_column_declared_without_a_type_holds_any_value() {
4836        let ddl = vec!["CREATE TABLE t (a, b TEXT, c ANY)".to_string(), "CREATE TABLE s (x ANY, y INTEGER) STRICT".to_string()];
4837        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());
4838        let a = &r.analysis;
4839        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4840        // `t.a = :a` and `s.x = :x` keep NULL out of the rows they return.
4841        assert_eq!(col(a, "a"), ("unknown".into(), false));
4842        assert_eq!(col(a, "b"), ("text".into(), true));
4843        assert_eq!(col(a, "x"), ("unknown".into(), false));
4844        assert_eq!(col(a, "y"), ("integer".into(), true));
4845        assert_eq!((param(a, "a"), param(a, "x")), ("unknown".into(), "unknown".into()));
4846        // In a table that is not STRICT, `ANY` is a declared type with NUMERIC affinity, not a wildcard.
4847        let r = analyze_ddl("SELECT c FROM t", &ddl, &Extras::default());
4848        assert_eq!(col(&r.analysis, "c"), ("numeric".into(), true));
4849    }
4850
4851    #[test]
4852    fn the_direct_entry_reads_a_schema_it_is_handed() {
4853        let ddl = vec![
4854            "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(),
4855            "CREATE INDEX todos_org ON todos (org_id)".to_string(),
4856        ];
4857        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";
4858        let r = analyze_ddl(sql, &ddl, &Extras::default());
4859        let a = &r.analysis;
4860        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4861        assert_eq!(a.kind, Some(StatementKind::Select));
4862        assert!(r.readonly);
4863        assert_eq!(col(a, "id"), ("numeric".into(), false));
4864        assert_eq!(col(a, "title"), ("text".into(), false));
4865        assert_eq!(col(a, "org_id"), ("numeric".into(), true));
4866        assert_eq!(col(a, "n"), ("integer".into(), false));
4867        assert_eq!(r.declared, [Some("uuid".to_string()), Some("varchar(200)".into()), Some("uuid".into()), Some("boolean".into()), None]);
4868        assert_eq!(param(a, "auth.user_id"), "text");
4869        assert_eq!(param(a, "title"), "text");
4870        assert_eq!(a.cardinality, "at_most_one");
4871        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 = ?");
4872        // A write: not read-only, and its RETURNING typed from the target.
4873        let r = analyze_ddl("INSERT INTO todos (id, owner_id, title) VALUES (:id, :owner, :title) RETURNING id, done", &ddl, &Extras::default());
4874        assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
4875        assert!(!r.readonly);
4876        assert_eq!((r.analysis.kind.map_or("", StatementKind::as_str), r.analysis.cardinality.as_str()), ("insert", "one"));
4877        // A column declared BOOLEAN is a boolean to the loader's run time, which refuses a value
4878        // other than 0 or 1 in it.
4879        assert_eq!(col(&r.analysis, "done"), ("bool".into(), false));
4880        // The unique keys of the table it read: the primary key's index and the UNIQUE constraint's.
4881        assert_eq!(r.unique_keys.len(), 1, "{:?}", r.unique_keys);
4882        let mut keys = r.unique_keys["todos"].clone();
4883        keys.sort();
4884        assert_eq!(keys, [vec!["id".to_string()], vec!["owner_id".into(), "title".into()], vec!["rowid".into()]]);
4885        // A lex error comes back as the replayed path reports it.
4886        let r = analyze_ddl("SELECT id FROM todos WHERE id = :a AND title = ?", &ddl, &Extras::default());
4887        assert_eq!(r.analysis.diagnostics.len(), 1, "{:?}", r.analysis.diagnostics);
4888        assert!(r.declared.is_empty() && !r.readonly);
4889    }
4890
4891    #[test]
4892    fn the_unique_keys_of_every_table_read() {
4893        let mut schema = ddl();
4894        schema.push("create unique index users_lower_name on users (lower(name))".into());
4895        schema.push("create unique index posts_title on posts (title) where body is not null".into());
4896        schema.push("create table tags (label text not null, post_id integer not null, primary key (post_id, label)) without rowid".into());
4897        schema.push("create view titled as select p.id, p.title from posts p".into());
4898        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());
4899        assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
4900        let mut tables: Vec<&String> = r.unique_keys.keys().collect();
4901        tables.sort();
4902        // The view reads through to `posts`; a view has no keys of its own.
4903        assert_eq!(tables, ["posts", "tags", "users"]);
4904        // The INTEGER PRIMARY KEY and the UNIQUE column; an expression index is no key.
4905        assert_eq!(r.unique_keys["users"], [vec!["id".to_string()], vec!["email".into()]]);
4906        // A partial index is no key either.
4907        assert_eq!(r.unique_keys["posts"], [vec!["id".to_string()]]);
4908        // WITHOUT ROWID: no rowid, only the primary key.
4909        assert_eq!(r.unique_keys["tags"], [vec!["post_id".to_string(), "label".into()]]);
4910        // A statement that does not prepare has none.
4911        assert!(analyze_ddl("select nope from users", &schema, &Extras::default()).unique_keys.is_empty());
4912    }
4913
4914    fn html() -> Extras {
4915        Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: 1, returns: Affinity::Text }], host: None }
4916    }
4917
4918    #[test]
4919    fn a_host_function_prepares_and_is_typed_from_its_argument() {
4920        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());
4921        let a = &r.analysis;
4922        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4923        assert_eq!(col(a, "h"), ("text".into(), false));
4924        assert_eq!(col(a, "e"), ("text".into(), true));
4925        // The parameter is a non-null value, so the call over it is too.
4926        assert_eq!(col(a, "q"), ("text".into(), false));
4927        assert_eq!(r.declared, [None, None, None]);
4928        // The same call without the registration, and with the wrong argument count: SQLite's own
4929        // message, at the call.
4930        let sql = "select id, reylo_html(name) as h from users";
4931        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()")] {
4932            let a = analyze_ddl(sql, &ddl(), &extras).analysis;
4933            assert_eq!(a.diagnostics.len(), 1, "{:?}", a.diagnostics);
4934            assert_eq!(a.diagnostics[0].message, message);
4935            assert_eq!((a.diagnostics[0].start, a.diagnostics[0].code), (sql.find("reylo_html").unwrap(), 6));
4936            assert!(a.columns.is_empty());
4937        }
4938        // Any argument count, and a schema that calls the function replays.
4939        let any = Extras { total: vec![TotalFunction { name: "reylo_html".into(), arity: -1, returns: Affinity::Text }], host: None };
4940        let mut schema = ddl();
4941        schema.push("create view safe_users as select id, reylo_html(name) as name from users".into());
4942        let a = analyze_ddl("select name, reylo_html(name, name) as twice from safe_users", &schema, &any).analysis;
4943        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
4944        assert_eq!(col(&a, "name"), ("text".into(), false));
4945        assert_eq!(col(&a, "twice"), ("text".into(), false));
4946    }
4947
4948    #[test]
4949    fn a_scalar_subquery_is_non_null_only_when_it_always_finds_one_row() {
4950        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");
4951        assert_eq!(col(&a, "n"), ("integer".into(), false));
4952        assert_eq!(col(&a, "top"), ("text".into(), true));
4953        assert_eq!(col(&a, "one"), ("text".into(), true));
4954        assert_eq!(col(&a, "g"), ("integer".into(), true));
4955        assert_eq!(col(&a, "k"), ("integer".into(), false));
4956    }
4957
4958    #[test]
4959    fn truth_values_are_marked_and_typed_boolean() {
4960        let r = analyze_ddl(
4961            "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",
4962            &ddl(),
4963            &Extras::default(),
4964        );
4965        assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
4966        assert_eq!(r.booleans, [true, true, true, true, true, true, true, false, false, true, false]);
4967        // The storage class is an integer, 0 or 1, which the type says is a boolean.
4968        assert_eq!(col(&r.analysis, "a"), ("bool".into(), false));
4969        assert_eq!(col(&r.analysis, "b"), ("bool".into(), false));
4970        assert_eq!(col(&r.analysis, "h"), ("integer".into(), false));
4971        // Through a subquery's column, and across every arm of a compound.
4972        let r = analyze_ddl("select t.x, t.y from (select id > 1 as x, id as y from users) t", &ddl(), &Extras::default());
4973        assert_eq!(r.booleans, [true, false]);
4974        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());
4975        assert_eq!(r.booleans, [false]);
4976        let r = analyze_ddl("select id > 1 as x from users union all select email is null from users", &ddl(), &Extras::default());
4977        assert_eq!(r.booleans, [true]);
4978        // RETURNING, and a statement that does not prepare.
4979        let r = analyze_ddl("insert into users (name) values ('a') returning id, id > 0 as positive", &ddl(), &Extras::default());
4980        assert_eq!(r.booleans, [false, true]);
4981        assert!(analyze_ddl("select nope from users", &ddl(), &Extras::default()).booleans.is_empty());
4982    }
4983
4984    #[test]
4985    fn a_column_declared_boolean_is_typed_boolean_and_no_truth_value() {
4986        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()];
4987        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());
4988        assert!(r.analysis.diagnostics.is_empty(), "{:?}", r.analysis.diagnostics);
4989        let types: Vec<String> = r.analysis.columns.iter().map(|c| affinity_of(&c.ty).unwrap_or("?").to_string()).collect();
4990        // `coalesce(b, 0)` is NUMERIC's number or text: a BOOLEAN column may hold 'yes'.
4991        assert_eq!(types, ["bool", "bool", "integer", "integer", "real", "bool", "numeric", "bool", "bool", "bool"]);
4992        // The truth values are the ones SQLite computes alone.
4993        assert_eq!(r.booleans, [false; 10]);
4994        // Through a view, and across a compound only where every arm is one.
4995        let r = analyze_ddl("select done from v", &ddl, &Extras::default());
4996        assert_eq!(col(&r.analysis, "done"), ("bool".into(), false));
4997        let r = analyze_ddl("select done from flags union all select 5", &ddl, &Extras::default());
4998        assert_ne!(affinity_of(&r.analysis.columns[0].ty), Some("bool"));
4999        let r = analyze_ddl("select done from flags union all select id > 1 from flags", &ddl, &Extras::default());
5000        assert_eq!(affinity_of(&r.analysis.columns[0].ty), Some("bool"));
5001    }
5002
5003    /// A type as src/render.ts writes a SQLite one, compactly: the value `.run()` returns at the
5004    /// top, and what JSON writes inside a document.
5005    fn ts(t: &Type, in_json: bool) -> String {
5006        let null = |s: String, nullable: bool| if nullable { format!("{s} | null") } else { s };
5007        let list = |s: String| if s.contains('|') { format!("({s})[]") } else { format!("{s}[]") };
5008        match &t.kind {
5009            Kind::Json(crate::types::JsonType { content: Some(c), .. }) => ts(&c.ty, true),
5010            Kind::Struct(r) => {
5011                let fields: Vec<String> = r.fields.iter().map(|f| format!("{}: {}", f.name, null(ts(&f.ty, true), f.nullable))).collect();
5012                if fields.is_empty() { "Record<never, never>".into() } else { format!("{{ {} }}", fields.join("; ")) }
5013            }
5014            Kind::Array(a) => list(null(ts(&a.element.ty, true), a.element.nullable)),
5015            Kind::Json(crate::types::JsonType { schema: Some(_), .. }) => schema_ts(&t.schema().unwrap_or(serde_json::Value::Bool(true))),
5016            _ => match (affinity_of(t).unwrap_or("?"), in_json) {
5017                ("integer" | "real", _) | ("int8", true) => "number".into(),
5018                ("int8", false) => "bigint".into(),
5019                ("text", _) => "string".into(),
5020                ("numeric", _) => "number | string".into(),
5021                ("blob", false) => "Uint8Array".into(),
5022                ("bool", _) => "boolean".into(),
5023                _ => "unknown".into(),
5024            },
5025        }
5026    }
5027
5028    /// The analysis's affinity name for a value of the format's type, as [`descriptor`] wrote it.
5029    fn affinity_of(t: &Type) -> Option<&'static str> {
5030        let name = t.label.as_deref().unwrap_or("");
5031        match &t.kind {
5032            // The constants a column holds, of their type's affinity.
5033            Kind::Enum(e) => affinity_of(&e.ty),
5034            Kind::Boolean(_) => Some("bool"),
5035            Kind::Integer(_) if name == "BIGINT" => Some("int8"),
5036            Kind::Integer(_) => Some("integer"),
5037            Kind::Float(_) => Some("real"),
5038            Kind::Text(_) => Some("text"),
5039            Kind::Bytes(_) => Some("blob"),
5040            Kind::Union(_) if is_boolean_declared(name) => Some("bool"),
5041            Kind::Union(u) if u.members.len() == 2 => Some("text"),
5042            Kind::Union(u) if u.members.len() == 3 => Some("real"),
5043            Kind::Union(_) if affinity(name) == "integer" && is_int8_declared(name) => Some("int8"),
5044            Kind::Union(_) => Some(affinity(name)),
5045            _ => None,
5046        }
5047    }
5048
5049    fn schema_ts(s: &serde_json::Value) -> String {
5050        if let Some(any) = s["anyOf"].as_array() {
5051            return any.iter().map(schema_ts).collect::<Vec<_>>().join(" | ");
5052        }
5053        let kinds: Vec<&str> = match &s["type"] {
5054            serde_json::Value::String(k) => vec![k.as_str()],
5055            serde_json::Value::Array(ks) => ks.iter().filter_map(|k| k.as_str()).collect(),
5056            _ => return "unknown".into(),
5057        };
5058        let one = |kind: &str| match kind {
5059            "integer" | "number" => "number".to_string(),
5060            "string" => "string".into(),
5061            "null" => "null".into(),
5062            "array" => match s["prefixItems"].as_array() {
5063                Some(items) => format!("[{}]", items.iter().map(schema_ts).collect::<Vec<_>>().join(", ")),
5064                None if s["items"] == false => "[]".into(),
5065                None => {
5066                    let item = schema_ts(&s["items"]);
5067                    if item.contains('|') { format!("({item})[]") } else { format!("{item}[]") }
5068                }
5069            },
5070            "object" => match s["properties"].as_object() {
5071                _ if s["additionalProperties"] == false && s["properties"].as_object().is_none_or(|p| p.is_empty()) => "Record<never, never>".into(),
5072                Some(p) if !p.is_empty() => format!("{{ {} }}", p.iter().map(|(k, v)| format!("{k}: {}", schema_ts(v))).collect::<Vec<_>>().join("; ")),
5073                _ => format!("{{ [key: string]: {} }}", schema_ts(&s["additionalProperties"])),
5074            },
5075            _ => "unknown".into(),
5076        };
5077        kinds.into_iter().map(one).collect::<Vec<_>>().join(" | ")
5078    }
5079
5080    /// Each result column as `name: type`, `| null` where it may be NULL.
5081    fn shown(a: &Analysis) -> String {
5082        assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5083        a.columns.iter().map(|c| format!("{}: {}{}", c.name, ts(&c.ty, false), if c.nullable { " | null" } else { "" })).collect::<Vec<_>>().join("; ")
5084    }
5085
5086    fn json_ddl() -> Vec<String> {
5087        vec![
5088            "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(),
5089            "create table posts (id integer primary key, user_id integer not null references users(id), title text not null, body text) strict".to_string(),
5090            "create view titled as select id, json_object('id', id, 'title', title) as post from posts".to_string(),
5091        ]
5092    }
5093
5094    fn json_typed(sql: &str) -> String {
5095        shown(&analyze_ddl(sql, &json_ddl(), &Extras::default()).analysis)
5096    }
5097
5098    #[test]
5099    fn json_whose_subtype_is_out_of_sight_is_any_json() {
5100        // Beside a window call, SQLite reads each aggregate back from a subquery of its own, which
5101        // drops the subtype: `{"ids":"[1]"}`. An aggregate that builds no JSON keeps its type.
5102        assert_eq!(
5103            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"),
5104            "doc: { ids: unknown }; top: [unknown]; counted: { n: number }; total: number"
5105        );
5106        assert_eq!(json_typed("select json_object('ids', json_group_array(id)) as doc from posts group by user_id"), "doc: { ids: number[] }");
5107        // A subquery's own aggregate is read where it is computed.
5108        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");
5109        // `json()` is NULL where its argument is, however deep the scalar subquery.
5110        assert_eq!(json_typed("select json(json((select json_object('a', 1) where 0))) as v"), "v: { a: number } | null");
5111        assert_eq!(json_typed("select json_object('k', json(jsonb((select json_object('a', 1) where 0)))) as w"), "w: { k: { a: number } | null }");
5112        // A VIRTUAL generated column is computed where it is read: a JSON function's subtype is
5113        // still on it, and so it may be on one read from another generated column. A STORED one
5114        // is read back as the text it is, and so is a VIRTUAL one no function computes.
5115        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()];
5116        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]");
5117        assert_eq!(shown(&analyze_ddl("select json_object('j', j) as v from (select j from d)", &schema, &Extras::default()).analysis), "v: { j: unknown }");
5118    }
5119
5120    #[test]
5121    fn a_number_beside_a_numeric_value_is_a_number_or_text() {
5122        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()];
5123        let typed = |sql: &str| col(&analyze_ddl(sql, &schema, &Extras::default()).analysis, "v");
5124        // A DATE column holds the text '2024-01-01', which no number beside it converts.
5125        assert_eq!(typed("select ifnull(dt, 0) as v from dts"), ("numeric".into(), false));
5126        assert_eq!(typed("select case when ok then d else 0 end as v from dts"), ("numeric".into(), false));
5127        assert_eq!(typed("select coalesce(dt, 1.5) as v from dts"), ("numeric".into(), false));
5128        assert_eq!(typed("select coalesce(n, 1.5) as v from dts"), ("integer".into(), false));
5129        assert_eq!(typed("select iif(ok, n, x) as v from dts"), ("real".into(), false));
5130    }
5131
5132    #[test]
5133    fn a_window_call_is_no_value_every_row_shares() {
5134        let count = |sql: &str| analyze_ddl(sql, &ddl(), &Extras::default()).analysis.cardinality;
5135        assert_eq!(count("select distinct min(1) over (order by id rows between 1 preceding and 1 preceding) as m from users"), "many");
5136        assert_eq!(count("select distinct max(1) filter (where id > 2) over (order by id) as m from users"), "many");
5137        assert_eq!(count("select distinct 1 as m from users"), "at_most_one");
5138    }
5139
5140    #[test]
5141    fn a_date_conversion_newer_than_libsql_s_sqlite_is_nullable() {
5142        let typed = |sql: &str| col(&analyze_ddl(sql, &ddl(), &Extras::default()).analysis, "v");
5143        // `%G`, `%g`, `%U`, `%V` and the `floor` and `ceiling` modifiers are new in 3.46.0, and NULL
5144        // on libSQL's 3.45.1.
5145        assert_eq!(typed("select strftime('%Y-%m-%d', 'now') as v"), ("text".into(), false));
5146        assert_eq!(typed("select strftime('%G-W%V', 'now') as v"), ("text".into(), true));
5147        assert_eq!(typed("select date('now', 'start of month', '+1 month', 'floor') as v"), ("text".into(), true));
5148    }
5149
5150    #[test]
5151    fn a_json_constructor_is_typed_as_the_json_it_builds() {
5152        // The docs' profile: SQLite answers with the text, which the run time parses. A scalar
5153        // subquery's JSON nests as JSON in `json()`, on every SQLite.
5154        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";
5155        assert_eq!(json_typed(profile), "profile: { user: { id: number; name: string }; posts: { id: number; title: string }[] }");
5156        // Without `json()`, SQLite 3.54.1 nests it as its text, and 3.53.4 as JSON.
5157        let bare = profile.replace("json((select", "((select");
5158        assert_eq!(json_typed(&bare), "profile: { user: { id: number; name: string }; posts: unknown }");
5159        // At the top, a scalar subquery's JSON is text either way, which the run time parses.
5160        assert_eq!(json_typed("select (select json_group_array(id) from posts) as ids"), "ids: number[]");
5161        assert_eq!(json_typed("select json((select json_object('n', name) from users where id = 1)) as u"), "u: { n: string } | null");
5162        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 }");
5163        let a = analyze_ddl(profile, &json_ddl(), &Extras::default()).analysis;
5164        assert_eq!((a.columns[0].ty.kind.name(), a.cardinality.as_str()), ("json", "at_most_one"));
5165        // Each value as SQLite writes it there: an INTEGER, a BIGINT column's too, as a number
5166        // (which JSON.parse rounds past 2^53), a REAL, a TEXT, a NUMERIC as either, NULL as null,
5167        // a truth value as 1 or 0 and a BOOLEAN column as what it holds. A BLOB is read as JSONB
5168        // (`x'01'` is `true`) or is an error, and a column of no type may hold one.
5169        assert_eq!(
5170            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"),
5171            "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 }"
5172        );
5173        // A JSON array of these values is a tuple; an object with a key the statement computes
5174        // is one of any keys.
5175        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>]");
5176        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 }");
5177        // A key written twice is in the text twice, and JSON.parse keeps the last.
5178        assert_eq!(json_typed("select json_object('k', id, 'k', name) as o from users"), "o: { k: string }");
5179        // The aggregates are `[]` and `{}` over no rows, never NULL, with a FILTER or as a window.
5180        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 }");
5181        // Beside an aggregate, a window call runs over the aggregate's one row, where a bare
5182        // column is NULL over no rows: `[null]`.
5183        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)[]");
5184        assert_eq!(
5185            // The window call makes SQLite read the FILTER aggregate back as text: `{"f":"[2,3]"}`.
5186            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"),
5187            "f: { f: unknown }; w: { w: unknown }"
5188        );
5189        assert_eq!(
5190            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"),
5191            "id: number; titles: string[]; grouped: string[] | null"
5192        );
5193        // `json()` of a constructor builds the same; `jsonb_*` is a blob, read as JSON inside a
5194        // document and by `json()`.
5195        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] }");
5196        assert_eq!(json_typed("select jsonb(json_array(1)) as b, (select jsonb_group_array(id) from users) as g"), "b: Uint8Array; g: Uint8Array");
5197        // A column that passes built JSON through is the text, parsed all the same.
5198        assert_eq!(json_typed("select post from titled"), "post: { id: number; title: string }");
5199        assert_eq!(json_typed("with t as (select json_array(id) as x from users) select x from t"), "x: [number]");
5200        assert_eq!(json_typed("select max(json_array(id)) as m from users"), "m: [number] | null");
5201        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 }");
5202    }
5203
5204    #[test]
5205    fn a_value_nests_as_json_only_where_it_keeps_sqlites_json_subtype() {
5206        // Through what kept the subtype on SQLite 3.53.4 a JSON value nests as the JSON it is.
5207        for (expr, ty) in [
5208            ("coalesce(json_array(id), 'x')", "[number]"),
5209            ("ifnull(json_array(id), 'x')", "[number]"),
5210            ("nullif(json_array(id), 'x')", "[number] | null"),
5211            ("iif(id > 1, json_array(id), json_array(0))", "[number]"),
5212            ("case when id > 1 then json_object('x', id) end", "{ x: number } | null"),
5213            ("json_array(id) collate nocase", "[number]"),
5214            ("+json_array(id)", "[number]"),
5215            ("likely(json_array(id))", "[number]"),
5216            // `json()` marks a scalar subquery's JSON again, NULL where it finds no row.
5217            ("json((select json_object('n', name) from users u2 where u2.id = users.id))", "{ n: string } | null"),
5218            ("json((select json_group_array(p.id) from posts p where p.user_id = users.id order by p.id))", "number[]"),
5219            ("json((select json_array(1)))", "[number]"),
5220            // Another constructor reads the subquery's NULL as a null, and is never NULL.
5221            ("json_array((select name from users u2 where u2.id = users.id))", "[string | null]"),
5222            ("json_group_array((select name from users u2 where u2.id = users.id))", "(string | null)[]"),
5223            // `coalesce` never reaches an argument after one that is never NULL.
5224            ("coalesce(json((select json_group_array(p.id) from posts p where p.user_id = users.id)), '[]')", "number[]"),
5225            ("coalesce(json_object('e', email), json_array())", "{ e: string | null }"),
5226            ("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[]"),
5227            // A plain value: a TEXT is a string, even one that holds JSON.
5228            ("doc", "string | null"),
5229            ("json_array(id) || ''", "string"),
5230            ("upper(json_array(id))", "string"),
5231            ("length(json_array(id))", "number"),
5232            ("json_type(json_array(id))", "string"),
5233            ("json_array_length(json_array(id))", "number"),
5234        ] {
5235            assert_eq!(json_typed(&format!("select json_object('a', {expr}) as o from users")), format!("o: {{ a: {ty} }}"), "{expr}");
5236        }
5237        // What dropped it on 3.53.4, or keeps it on one SQLite and not another, and what returns
5238        // any JSON: any JSON.
5239        for expr in [
5240            "x",
5241            "post",
5242            // A scalar subquery's JSON kept the subtype on 3.53.4 and lost it on 3.54.1.
5243            "(select json_object('n', name) from users u2 where u2.id = users.id)",
5244            "(select json_array(1))",
5245            "(select json_object('id', id) from users order by name limit 1)",
5246            "(select distinct json_array(id) from users)",
5247            "(select json_array(1) union all select json_array(2))",
5248            "lag(json_array(id)) over (order by id)",
5249            "max(json_array(id), json_array(0))",
5250            "cast(json_array(id) as text)",
5251            "doc ->> '$.a'",
5252            "json_pretty(json_array(1))",
5253            "case when id > 1 then json_array(id) else 'x' end",
5254            "case when id > 1 then json_array(id) else json_object('a', 1) end",
5255        ] {
5256            let sql = format!("select json_object('a', {expr}) as o from (select *, json_array(id) as x from users) users, (select post from titled)");
5257            assert_eq!(json_typed(&sql), "o: { a: unknown }", "{expr}");
5258        }
5259        // Any JSON a function returns, which may be the document `null` itself, however NOT NULL
5260        // the value it reads (`json(doc)` where `doc` holds `'null'`): a null there too.
5261        for expr in ["json(doc)", "json_extract(doc, '$.a')", "doc -> '$.a'", "json_set(doc, '$.a', 1)", "json_quote(name)"] {
5262            assert_eq!(json_typed(&format!("select json_object('a', {expr}) as o from users")), "o: { a: unknown | null }", "{expr}");
5263        }
5264        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()];
5265        for (expr, ty) in [
5266            ("json_object('k', json(doc))", "{ k: unknown | null }"),
5267            ("json_object('k', doc -> '$')", "{ k: unknown | null }"),
5268            ("json_object('k', json_extract(doc, '$'))", "{ k: unknown | null }"),
5269            ("json_object('k', json(b))", "{ k: unknown | null }"),
5270            ("json_group_array(json(doc))", "(unknown | null)[]"),
5271        ] {
5272            assert_eq!(shown(&analyze_ddl(&format!("select {expr} as o from js"), &not_null, &Extras::default()).analysis), format!("o: {ty}"), "{expr}");
5273        }
5274        // A function the host registers over a built-in is its own, and may set the subtype.
5275        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 };
5276        let a = analyze_ddl("select json_array(1) as a, json_object('b', html(name)) as b from users", &json_ddl(), &host).analysis;
5277        assert_eq!(shown(&a), "a: string; b: { b: unknown }");
5278    }
5279
5280    #[test]
5281    fn a_deep_constructor_is_read_once_per_node() {
5282        // Each node's shape is worked out once, so a statement as deep as the engine reads takes
5283        // no longer than its size.
5284        let ddl = vec!["create table users (id integer primary key, name text not null)".to_string()];
5285        let deep = |open: &str, close: &str, n: usize| format!("select {}id{} as o from users", open.repeat(n), close.repeat(n));
5286        let started = std::time::Instant::now();
5287        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)] {
5288            let a = crate::stack::run(|| analyze_ddl(&sql, &ddl, &Extras::default()).analysis);
5289            assert!(a.diagnostics.is_empty(), "{:?}", a.diagnostics);
5290        }
5291        assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
5292    }
5293
5294    #[test]
5295    fn built_json_beside_other_text_is_the_text_it_is() {
5296        // SQLite returns built JSON as text: where a value may be other text, it is a string.
5297        assert_eq!(
5298            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"),
5299            "a: [number]; b: string; c: string; d: [number] | null"
5300        );
5301        assert_eq!(json_typed("select json_array(id) as a from users union all select 'x'"), "a: string");
5302        assert_eq!(json_typed("select json_array(id) as a from users union all select null"), "a: [number] | null");
5303        // A parameter that may be any text the caller passes: `coalesce(:doc::nullable(text),
5304        // json_array())` is that text, and the parameter is a string.
5305        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"]);
5306        assert_eq!(shown(&a), "d: string; o: { a: unknown }");
5307        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"]);
5308    }
5309
5310    #[test]
5311    fn a_json_object_of_an_odd_count_of_arguments_is_built_in_alone() {
5312        let sql = "select json_object('id', id, 'name') as j from users";
5313        let odd = |extras: &Extras| analyze_ddl(sql, &ddl(), extras).analysis.diagnostics.iter().filter(|d| d.code == 15).count();
5314        assert_eq!(odd(&Extras::default()), 1);
5315        let listed = |arities: &[i32]| Extras { total: vec![], host: Some(arities.iter().map(|&arity| HostFunction { name: "json_object".into(), arity, kind: 's' }).collect()) };
5316        assert_eq!(odd(&listed(&[-1])), 1);
5317        // A function of the name the host registers is called in the built-in's place.
5318        assert_eq!(odd(&listed(&[-1, 3])), 0);
5319        assert_eq!(odd(&Extras { total: vec![TotalFunction { name: "JSON_OBJECT".into(), arity: 3, returns: Affinity::Text }], host: None }), 0);
5320    }
5321
5322    #[test]
5323    fn a_modulo_by_a_fractional_literal_under_one_is_nullable() {
5324        // SQLite casts both `%` operands to INTEGER, so 0.5 truncates to 0 and the remainder is
5325        // NULL on every row. `/ 0.5` stays non-null: division keeps the float.
5326        let schema = vec!["create table items (id integer primary key, qty integer not null)".to_string()];
5327        let typed = |sql: &str| {
5328            let a = analyze_ddl(sql, &schema, &Extras::default()).analysis;
5329            assert!(a.diagnostics.is_empty(), "{sql}: {:?}", a.diagnostics);
5330            col(&a, "r")
5331        };
5332        assert_eq!(typed("select qty % 0.5 as r from items"), ("real".into(), true));
5333        assert_eq!(typed("select qty % 0.99 as r from items"), ("real".into(), true));
5334        assert_eq!(typed("select qty % 1e-3 as r from items"), ("real".into(), true));
5335        assert_eq!(typed("select qty % 2.5 as r from items"), ("real".into(), false));
5336        assert_eq!(typed("select qty % 2 as r from items"), ("integer".into(), false));
5337        // The cast saturates: an infinite divisor is the largest INTEGER.
5338        assert_eq!(typed("select qty % 1e999 as r from items"), ("real".into(), false));
5339        assert_eq!(typed("select qty / 0.5 as r from items"), ("real".into(), false));
5340        assert_eq!(typed("select qty / 0 as r from items"), ("integer".into(), true));
5341    }
5342
5343    #[test]
5344    fn sqlite_only_syntax_parses() {
5345        let a = analysis("select id from users limit :n, :m");
5346        assert_eq!(param(&a, "n"), "integer");
5347        assert_eq!(analysis("insert or replace into users (id, name) values (:id, :name) returning id").cardinality, "one");
5348    }
5349}
5350