Skip to main content

reylo_engine_sqlite/
sqlite_tree.rs

1//! SQLite's resolved parse tree, as `csrc/reylo_sqlite.c` serializes it: what SQLite itself
2//! resolved while preparing the statement against an in-memory replay of the schema DDL.
3//!
4//! Every member the walker always writes is required, so that one it stops writing, or spells
5//! otherwise, fails the analysis with an error naming it, where a default would read it as
6//! `false`, `0` or nothing: for a fact such as "on the null-extended side of a join", the unsound
7//! answer. A member the walker writes for some objects only has `#[serde(default)]` and says when
8//! it is absent; where that turns on the object's kind (a node's `op`, a write's `kind`), the
9//! members of each kind are required once the object is read ([`Members`]). A member no struct
10//! declares is refused, so the walker writes nothing the analysis does not read.
11use serde::de::{self, value::MapAccessDeserializer, DeserializeSeed, Deserializer, IntoDeserializer, MapAccess, Visitor};
12use serde::Deserialize;
13use std::collections::HashMap;
14use std::ffi::{CStr, CString};
15use std::marker::PhantomData;
16use std::os::raw::{c_char, c_int};
17use std::sync::Mutex;
18
19/// The serializer keeps one schema replay and one capture in globals, so calls are serialized.
20static LOCK: Mutex<()> = Mutex::new(());
21
22/// The version of the tree's format, which the walker writes as the tree's first member
23/// (`REYLO_TREE_VERSION` in `csrc/reylo_sqlite.c`): a tree of another is refused, by both numbers,
24/// before anything in it is read. A change to what either side reads or writes moves both.
25pub const TREE_VERSION: u32 = 2;
26
27#[derive(Debug, Deserialize)]
28#[serde(remote = "Self", rename_all = "camelCase", deny_unknown_fields)]
29pub struct Tree {
30    #[serde(deserialize_with = "tree_version")]
31    pub version: u32,
32    // Absent, with `columns`, `params`, `readonly` and `tables`, when `error` is set.
33    /// The top-level SELECT, or the SELECT that feeds an INSERT.
34    #[serde(default)]
35    pub statement: Option<Sel>,
36    #[serde(default)]
37    pub dml: Option<Dml>,
38    #[serde(default)]
39    pub returning: Option<Vec<Col>>,
40    /// The public column metadata: the names tsc sees and the declared type.
41    #[serde(default)]
42    pub columns: Vec<PublicColumn>,
43    #[serde(default)]
44    pub params: Vec<PublicParam>,
45    #[serde(default)]
46    pub readonly: bool,
47    #[serde(default)]
48    pub tables: HashMap<String, TableInfo>,
49    /// Absent when the statement prepared.
50    #[serde(default)]
51    pub error: Option<TreeError>,
52    pub schema_errors: Vec<SchemaError>,
53}
54
55#[derive(Debug, Deserialize)]
56#[serde(rename_all = "camelCase", deny_unknown_fields)]
57pub struct TreeError {
58    pub message: String,
59    pub offset: i64,
60    /// The length of what `offset` points at, where the serializer knows it; absent otherwise.
61    #[serde(default)]
62    pub length: Option<usize>,
63    /// The function, as the statement spells it, that the embedded SQLite has and the host's
64    /// SQLite does not list; `view` names the view that calls it, when one does. Each is absent
65    /// where it names nothing.
66    #[serde(default)]
67    pub missing_function: Option<String>,
68    #[serde(default)]
69    pub view: Option<String>,
70    /// The schema of a `schema.table` the statement reads, where the database has no such
71    /// schema; absent otherwise.
72    #[serde(default)]
73    pub missing_schema: Option<String>,
74}
75
76#[derive(Debug, Deserialize)]
77#[serde(remote = "Self", rename_all = "camelCase", deny_unknown_fields)]
78pub struct SchemaError {
79    /// The DDL step that failed; absent where `function` is set.
80    #[serde(default)]
81    pub index: usize,
82    /// Set when the failed step registered a host function rather than replaying DDL; absent
83    /// otherwise.
84    #[serde(default)]
85    pub function: Option<String>,
86    pub message: String,
87}
88
89#[derive(Debug, Deserialize)]
90#[serde(rename_all = "camelCase", deny_unknown_fields)]
91pub struct PublicColumn {
92    pub name: String,
93    #[serde(deserialize_with = "present")]
94    pub declared: Option<String>,
95}
96
97#[derive(Debug, Deserialize)]
98#[serde(rename_all = "camelCase", deny_unknown_fields)]
99pub struct PublicParam {
100    #[serde(deserialize_with = "present")]
101    pub name: Option<String>,
102}
103
104#[derive(Debug, Deserialize)]
105#[serde(rename_all = "camelCase", deny_unknown_fields)]
106pub struct TableInfo {
107    pub strict: bool,
108    /// The table is WITHOUT ROWID: its primary key is its rows' key (libSQL's `vector_top_k` returns it).
109    pub without_rowid: bool,
110    #[serde(deserialize_with = "present")]
111    pub rowid_alias: Option<String>,
112    /// A NOT NULL, UNIQUE or PRIMARY KEY of the table is declared ON CONFLICT IGNORE: a write
113    /// that breaks it, with no OR clause of its own, skips the row.
114    pub ignores: bool,
115    /// The PRIMARY KEY or a UNIQUE of the table is declared ON CONFLICT REPLACE: a write that
116    /// breaks it, with no OR clause of its own, deletes the row it conflicts with.
117    pub replaces: bool,
118    pub columns: Vec<ColumnInfo>,
119    pub unique_keys: Vec<Vec<String>>,
120}
121
122#[derive(Debug, Deserialize)]
123#[serde(rename_all = "camelCase", deny_unknown_fields)]
124pub struct ColumnInfo {
125    pub name: String,
126    pub declared: String,
127    pub affinity: String,
128    pub not_null: bool,
129    /// A CHECK of the table tests the column IS NOT NULL among its conjuncts: a write of NULL fails.
130    pub checked_not_null: bool,
131}
132
133#[derive(Debug, Deserialize)]
134#[serde(rename_all = "camelCase", deny_unknown_fields)]
135pub struct Sel {
136    pub columns: Vec<Col>,
137    /// The rows after the first of a multi-row VALUES, whose first row is `columns`; absent for
138    /// any other SELECT.
139    #[serde(default)]
140    pub rows: Vec<Vec<Node>>,
141    pub from: Vec<From>,
142    #[serde(rename = "where", deserialize_with = "present")]
143    pub where_: Option<Node>,
144    pub group_by: Vec<Node>,
145    #[serde(deserialize_with = "present")]
146    pub having: Option<Node>,
147    pub order_by: Vec<Node>,
148    #[serde(deserialize_with = "present")]
149    pub limit: Option<Node>,
150    #[serde(deserialize_with = "present")]
151    pub offset: Option<Node>,
152    pub distinct: bool,
153    pub aggregate: bool,
154    pub values: bool,
155    pub window: bool,
156    /// The set operator between this arm and `prior`; both are absent from an arm with none
157    /// before it.
158    #[serde(default)]
159    pub op: Option<String>,
160    #[serde(default)]
161    pub prior: Option<Box<Sel>>,
162}
163
164#[derive(Debug, Deserialize)]
165#[serde(rename_all = "camelCase", deny_unknown_fields)]
166pub struct Col {
167    #[serde(deserialize_with = "present")]
168    pub name: Option<String>,
169    pub named: bool,
170    pub expr: Node,
171}
172
173#[derive(Debug, Deserialize)]
174#[serde(rename_all = "camelCase", deny_unknown_fields)]
175pub struct From {
176    pub cursor: i64,
177    /// A table by the name its DDL spells, whatever case the statement writes it in, and a
178    /// table-valued function by its module's name; a view, a WITH query or a subquery as written.
179    #[serde(deserialize_with = "present")]
180    pub table: Option<String>,
181    #[serde(deserialize_with = "present")]
182    pub alias: Option<String>,
183    /// On the nullable side of an outer join.
184    pub outer: bool,
185    /// Joined by a RIGHT or FULL JOIN, which keeps the rows of the side before it that match nothing.
186    pub right: bool,
187    /// Before a RIGHT or FULL JOIN, which null-extends it.
188    pub left_of_right: bool,
189    pub tab_func: bool,
190    /// A table-valued function's arguments (`json_each(:ids)`); empty for anything else.
191    pub args: Vec<Node>,
192    /// For libSQL's `vector_top_k('docs_emb', …)`, the table whose rows the index it names holds,
193    /// which `tables` describes; `None` where the index is not written as a string or names no index.
194    #[serde(deserialize_with = "present")]
195    pub vector_table: Option<String>,
196    pub cte: bool,
197    /// A recursive WITH query's read of itself, inside the query, which has no subquery of its own.
198    pub recursive: bool,
199    pub view: bool,
200    #[serde(rename = "virtual")]
201    pub virtual_: bool,
202    #[serde(deserialize_with = "present")]
203    pub subquery: Option<Box<Sel>>,
204    #[serde(deserialize_with = "present")]
205    pub on: Option<Node>,
206}
207
208/// An INSERT, an UPDATE (`kind` `update`, or `upsert` for an upsert's DO UPDATE) or a DELETE: each
209/// kind's members are required by [`Members`], and absent from the other kinds.
210#[derive(Debug, Deserialize)]
211#[serde(remote = "Self", rename_all = "camelCase", deny_unknown_fields)]
212pub struct Dml {
213    pub kind: String,
214    pub table: String,
215    // An INSERT's and an UPDATE's.
216    #[serde(default)]
217    pub on_error: String,
218    // An INSERT's.
219    /// Each ON CONFLICT clause, in the order SQLite tries them.
220    #[serde(default)]
221    pub upserts: Vec<Upsert>,
222    /// The target column per value position; `None` where SQLite could not name one.
223    #[serde(default)]
224    pub columns: Vec<Option<String>>,
225    #[serde(default)]
226    pub values: Option<Vec<Node>>,
227    /// 1 for one VALUES row, the row count for a multi-row VALUES (whose rows are `statement`'s),
228    /// -1 for a SELECT source.
229    #[serde(default)]
230    pub rows: i64,
231    // An UPDATE's.
232    #[serde(default)]
233    pub set: Vec<SetItem>,
234    // An UPDATE's and a DELETE's.
235    #[serde(rename = "where", default)]
236    pub where_: Option<Node>,
237}
238
239#[derive(Debug, Deserialize)]
240#[serde(rename_all = "camelCase", deny_unknown_fields)]
241pub struct Upsert {
242    pub do_update: bool,
243    pub set: Vec<SetItem>,
244    #[serde(rename = "where", deserialize_with = "present")]
245    pub where_: Option<Node>,
246}
247
248#[derive(Debug, Deserialize)]
249#[serde(rename_all = "camelCase", deny_unknown_fields)]
250pub struct SetItem {
251    #[serde(deserialize_with = "present")]
252    pub column: Option<String>,
253    pub expr: Node,
254}
255
256/// One expression node. `op` names the kind; `op`, `aff`, `outerOn` and `innerOn` are every node's,
257/// and the members after them belong to some kinds only, absent from the others: [`Members`]
258/// requires the ones a node's kind always has.
259#[derive(Debug, Deserialize)]
260#[serde(remote = "Self", rename_all = "camelCase", deny_unknown_fields)]
261pub struct Node {
262    pub op: String,
263    /// `sqlite3ExprAffinity`: integer, real, text, blob, numeric or none.
264    pub aff: String,
265    /// A WHERE term that came from an outer join's ON clause, which SQLite moves into the WHERE:
266    /// it restricts the join's right side (the cursor `join`, present with it) and removes no row.
267    pub outer_on: bool,
268    #[serde(default)]
269    pub join: i64,
270    /// A WHERE term that came from an inner join's ON clause.
271    pub inner_on: bool,
272    // A column's (`column`), and `index` a variable's and a select_column's too. A column SQLite
273    // resolved to no table has `table` null and nothing after `register`; a rowid read by no
274    // declared column has no `declared` and no `coll`.
275    #[serde(default)]
276    pub cursor: i64,
277    #[serde(default)]
278    pub index: i64,
279    #[serde(default)]
280    pub table: Option<String>,
281    #[serde(default)]
282    pub column: Option<String>,
283    #[serde(default)]
284    pub declared: Option<String>,
285    /// A column's, and a cast's: the affinity it converts to.
286    #[serde(default)]
287    pub affinity: Option<String>,
288    #[serde(default)]
289    pub not_null: bool,
290    #[serde(default)]
291    pub rowid: bool,
292    #[serde(default)]
293    pub outer: bool,
294    /// The column's table is STRICT.
295    #[serde(default)]
296    pub strict: bool,
297    /// The column is generated.
298    #[serde(default)]
299    pub generated: bool,
300    /// The column is VIRTUAL and computed by a function or from another generated column: its
301    /// value, computed where it is read, may carry the JSON subtype.
302    #[serde(default)]
303    pub subtype: bool,
304    /// The column is a view's, as a write through the view's INSTEAD OF trigger reads it.
305    #[serde(default)]
306    pub view: bool,
307    /// The column of the row the statement wrote, as its RETURNING reads it: from the registers
308    /// that hold the row, with no cursor (`cursor` is a register's number).
309    #[serde(default)]
310    pub register: bool,
311    /// The column's collation, which a comparison with it uses where the column decides.
312    #[serde(default)]
313    pub coll: Option<String>,
314    // A variable's and a function's.
315    #[serde(default)]
316    pub name: Option<String>,
317    // A literal's.
318    #[serde(default)]
319    pub value: Option<String>,
320    // A function's.
321    #[serde(default)]
322    pub agg: bool,
323    /// A window call, or an aggregate with a FILTER, which SQLite holds as a window as well.
324    #[serde(default)]
325    pub window: bool,
326    /// A window call: one with an OVER clause, which has every member from `partition_by` to
327    /// `filter`.
328    #[serde(default)]
329    pub over: bool,
330    #[serde(default)]
331    pub distinct: bool,
332    #[serde(default)]
333    pub args: Vec<Node>,
334    /// An aggregate's own ORDER BY, absent where it has none, or a window call's.
335    #[serde(default)]
336    pub order_by: Vec<Node>,
337    /// A window call's PARTITION BY.
338    #[serde(default)]
339    pub partition_by: Vec<Node>,
340    /// A window call's frame: where it starts (`unbounded`, which is UNBOUNDED PRECEDING,
341    /// `preceding`, `current` or `following`) and ends (`unbounded` is UNBOUNDED FOLLOWING), and
342    /// what it excludes (`no`, `current`, `group` or `ties`), a named window's included.
343    #[serde(default)]
344    pub frame_start: Option<String>,
345    #[serde(default)]
346    pub frame_end: Option<String>,
347    #[serde(default)]
348    pub exclude: Option<String>,
349    /// A window call with a FILTER.
350    #[serde(default)]
351    pub filter: bool,
352    // The operands: `left` a cast's, an IN's, a BETWEEN's, a CASE's, a row value's and a
353    // select_column's, null where it has none; `list` an IN's (or `select`), a BETWEEN's, a CASE's
354    // and a row value's; `select` a subquery's. Any other operator writes the operands it has.
355    #[serde(default)]
356    pub left: Option<Box<Node>>,
357    #[serde(default)]
358    pub right: Option<Box<Node>>,
359    #[serde(default)]
360    pub list: Vec<Node>,
361    #[serde(default)]
362    pub select: Option<Box<Sel>>,
363}
364
365/// An object whose members turn on its kind, which its struct, holding every kind's members, cannot
366/// require: once it is read, each member [`Members::required`] names must have been in it.
367trait Members: Sized {
368    /// The struct's own reader, which `#[serde(remote = "Self")]` derives.
369    fn read<'de, D: Deserializer<'de>>(d: D) -> Result<Self, D::Error>;
370    /// What it is, for a message: `a column node`.
371    fn kind(&self) -> String;
372    /// The members an object of its kind always has.
373    fn required(&self) -> Vec<&'static str>;
374}
375
376impl Members for Tree {
377    fn read<'de, D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
378        Tree::deserialize(d)
379    }
380    fn kind(&self) -> String {
381        "the tree of a statement that prepared".into()
382    }
383    fn required(&self) -> Vec<&'static str> {
384        if self.error.is_some() { Vec::new() } else { vec!["statement", "dml", "returning", "columns", "params", "readonly", "tables"] }
385    }
386}
387
388impl Members for SchemaError {
389    fn read<'de, D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
390        SchemaError::deserialize(d)
391    }
392    fn kind(&self) -> String {
393        "a failed DDL step".into()
394    }
395    fn required(&self) -> Vec<&'static str> {
396        if self.function.is_some() { Vec::new() } else { vec!["index"] }
397    }
398}
399
400impl Members for Dml {
401    fn read<'de, D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
402        Dml::deserialize(d)
403    }
404    fn kind(&self) -> String {
405        format!("a write of kind `{}`", self.kind)
406    }
407    fn required(&self) -> Vec<&'static str> {
408        match self.kind.as_str() {
409            "insert" => vec!["onError", "upserts", "columns", "values", "rows"],
410            "update" | "upsert" => vec!["onError", "set", "where"],
411            "delete" => vec!["where"],
412            _ => Vec::new(),
413        }
414    }
415}
416
417impl Members for Node {
418    fn read<'de, D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
419        Node::deserialize(d)
420    }
421    fn kind(&self) -> String {
422        format!("a `{}` node", self.op)
423    }
424    fn required(&self) -> Vec<&'static str> {
425        let mut members = Vec::new();
426        if self.outer_on {
427            members.push("join");
428        }
429        match self.op.as_str() {
430            "column" => {
431                members.extend(["cursor", "index", "table", "register"]);
432                if self.table.is_some() {
433                    members.extend(["column", "affinity", "notNull", "rowid", "outer", "strict", "view", "generated", "subtype"]);
434                }
435            }
436            "variable" => members.extend(["name", "index"]),
437            "integer" | "float" | "string" | "blob" | "truefalse" | "id" => members.push("value"),
438            "function" => {
439                members.extend(["name", "agg", "window", "over", "distinct", "args"]);
440                if self.over {
441                    members.extend(["partitionBy", "orderBy", "frameStart", "frameEnd", "exclude", "filter"]);
442                }
443            }
444            "cast" => members.extend(["affinity", "left"]),
445            "in" => members.push("left"),
446            "between" | "case" | "vector" => members.extend(["left", "list"]),
447            "select" | "exists" => members.push("select"),
448            "select_column" => members.extend(["index", "left"]),
449            _ => {}
450        }
451        members
452    }
453}
454
455macro_rules! read_with_members {
456    ($($t:ty),*) => {$(
457        impl<'de> Deserialize<'de> for $t {
458            fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
459                d.deserialize_map(Checked(PhantomData))
460            }
461        }
462    )*};
463}
464read_with_members!(Tree, SchemaError, Dml, Node);
465
466/// Reads an object through [`Members::read`], noting each member's name, then refuses it if a
467/// member [`Members::required`] names was not among them.
468struct Checked<T>(PhantomData<T>);
469
470impl<'de, T: Members> Visitor<'de> for Checked<T> {
471    type Value = T;
472
473    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
474        f.write_str("an object")
475    }
476
477    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<T, A::Error> {
478        let mut seen = Vec::new();
479        let value = T::read(MapAccessDeserializer::new(Noting { map, seen: &mut seen }))?;
480        match value.required().into_iter().find(|member| !seen.iter().any(|s| s == member)) {
481            Some(member) => Err(de::Error::custom(format!("missing field `{member}` of {}", value.kind()))),
482            None => Ok(value),
483        }
484    }
485}
486
487/// A map's entries, as they are, with each key's name noted.
488struct Noting<'a, A> {
489    map: A,
490    seen: &'a mut Vec<String>,
491}
492
493impl<'de, A: MapAccess<'de>> MapAccess<'de> for Noting<'_, A> {
494    type Error = A::Error;
495
496    fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>, A::Error> {
497        let Some(key) = self.map.next_key::<String>()? else { return Ok(None) };
498        let read = seed.deserialize(<&str as IntoDeserializer<'de, A::Error>>::into_deserializer(key.as_str()))?;
499        self.seen.push(key);
500        Ok(Some(read))
501    }
502
503    fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, A::Error> {
504        self.map.next_value_seed(seed)
505    }
506}
507
508/// The tree's version, refused unless it is [`TREE_VERSION`].
509fn tree_version<'de, D: Deserializer<'de>>(d: D) -> Result<u32, D::Error> {
510    let version = u32::deserialize(d)?;
511    if version != TREE_VERSION {
512        return Err(de::Error::custom(format!("the tree is of version {version}, and this engine reads version {TREE_VERSION}")));
513    }
514    Ok(version)
515}
516
517/// A member the walker always writes, null or not. Serde reads a missing `Option` as `None`, unless
518/// a function of the member's own reads it, as this one does, changing nothing else.
519fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<T>, D::Error> {
520    Option::<T>::deserialize(d)
521}
522
523extern "C" {
524    fn reylo_sqlite_analyze(ddl: *const *const c_char, n: c_int, sql: *const c_char, sent: *const c_char, functions: *const *const c_char, arities: *const c_int, n_functions: c_int, host: *const *const c_char, host_arities: *const c_int, host_kinds: *const c_char, n_host: c_int) -> *mut c_char;
525    fn reylo_sqlite_free(p: *mut c_char);
526    fn reylo_sqlite_version() -> *const c_char;
527}
528
529/// The version of the embedded SQLite, as `3.53.4`: the one that prepares every statement the
530/// engine types, whichever SQLite reads the database file or runs the statement.
531pub fn version() -> &'static str {
532    // A string constant of the library.
533    unsafe { CStr::from_ptr(reylo_sqlite_version()) }.to_str().unwrap_or_default()
534}
535
536/// A function the host's SQLite lists (`pragma_function_list`): its name, its argument count as
537/// SQLite keeps it (-1 for any number) and its kind, `s` for a scalar, `a` for an aggregate, `w`
538/// for a window function.
539pub type Listed<'a> = (&'a str, i32, char);
540
541/// Prepares `sql` against the schema `ddl` inside the embedded SQLite and returns what it resolved.
542/// `functions` are the host's own scalar functions, by name and argument count (-1 for any): the
543/// replay registers a stub for each, so a statement that calls one prepares. `host` is every
544/// function the host's SQLite has, when the host could list them: the replay registers a stub for
545/// one the embedded build has no function of that name for, and the prepare refuses a call to one
546/// the embedded build has and the host does not. `sent` is the statement as the application runs it,
547/// whose text names the columns.
548pub fn analyze(ddl: &[String], sql: &str, sent: &str, functions: &[(&str, i32)], host: Option<&[Listed]>) -> Result<Tree, String> {
549    let owned: Vec<CString> = ddl.iter().map(|d| CString::new(d.replace('\0', " ")).unwrap()).collect();
550    let pointers: Vec<*const c_char> = owned.iter().map(|c| c.as_ptr()).collect();
551    let names: Vec<CString> = functions.iter().map(|(n, _)| CString::new(n.replace('\0', " ")).unwrap()).collect();
552    let name_pointers: Vec<*const c_char> = names.iter().map(|c| c.as_ptr()).collect();
553    let arities: Vec<c_int> = functions.iter().map(|(_, a)| *a as c_int).collect();
554    let listed = host.unwrap_or_default();
555    let host_names: Vec<CString> = listed.iter().map(|(n, _, _)| CString::new(n.replace('\0', " ")).unwrap()).collect();
556    let host_pointers: Vec<*const c_char> = host_names.iter().map(|c| c.as_ptr()).collect();
557    let host_arities: Vec<c_int> = listed.iter().map(|(_, a, _)| *a as c_int).collect();
558    let host_kinds: Vec<c_char> = listed.iter().map(|(_, _, k)| if k.is_ascii() { *k as u8 as c_char } else { b's' as c_char }).collect();
559    let n_host = if host.is_some() { listed.len() as c_int } else { -1 };
560    let sql = CString::new(sql.replace('\0', " ")).map_err(|e| e.to_string())?;
561    let sent = CString::new(sent.replace('\0', " ")).map_err(|e| e.to_string())?;
562    let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
563    let json = unsafe {
564        let p = reylo_sqlite_analyze(pointers.as_ptr(), pointers.len() as c_int, sql.as_ptr(), sent.as_ptr(), name_pointers.as_ptr(), arities.as_ptr(), name_pointers.len() as c_int, host_pointers.as_ptr(), host_arities.as_ptr(), host_kinds.as_ptr(), n_host);
565        if p.is_null() {
566            return Err("the embedded SQLite returned nothing".into());
567        }
568        let text = CStr::from_ptr(p).to_string_lossy().into_owned();
569        reylo_sqlite_free(p);
570        text
571    };
572    parse(&json)
573}
574
575/// The walker's answer as a [`Tree`], or why it is not one: a member missing or not declared names it.
576fn parse(json: &str) -> Result<Tree, String> {
577    // The tree nests as deeply as the statement, which SQLite bounds at 1,000 levels of an
578    // expression (SQLITE_MAX_EXPR_DEPTH), past serde_json's default limit of 128; the engine's
579    // stack has the room for SQLite's own bound (`crate::stack`).
580    let mut reader = serde_json::Deserializer::from_str(json);
581    reader.disable_recursion_limit();
582    <Tree as Deserialize>::deserialize(&mut reader).map_err(|e| format!("the embedded SQLite's answer did not parse: {e}"))
583}
584
585#[cfg(test)]
586mod tests {
587    use super::*;
588    use serde_json::{json, Value};
589
590    /// A prepared statement's tree, `select a from t`, as the walker writes it.
591    fn tree() -> Value {
592        let column = json!({ "op": "column", "aff": "none", "outerOn": false, "innerOn": false, "cursor": 0, "index": 0, "register": false, "table": "t", "column": "a", "declared": "", "affinity": "blob", "coll": "BINARY", "notNull": false, "rowid": false, "generated": false, "subtype": false, "outer": false, "strict": false, "view": false });
593        let from = json!({ "cursor": 0, "table": "t", "alias": null, "outer": false, "right": false, "leftOfRight": false, "tabFunc": false, "args": [], "vectorTable": null, "cte": false, "recursive": false, "view": false, "virtual": false, "subquery": null, "on": null });
594        let statement = json!({ "columns": [{ "name": "a", "named": false, "expr": column }], "from": [from], "where": null, "groupBy": [], "having": null, "orderBy": [], "limit": null, "offset": null, "distinct": false, "aggregate": false, "values": false, "window": false });
595        json!({ "version": TREE_VERSION, "statement": statement, "dml": null, "returning": null, "columns": [{ "name": "a", "declared": null }], "params": [], "readonly": true, "tables": {}, "schemaErrors": [] })
596    }
597
598    fn read(tree: &Value) -> Result<Tree, String> {
599        parse(&tree.to_string())
600    }
601
602    #[test]
603    fn a_member_the_walker_always_writes_is_required_and_one_it_does_not_is_refused() {
604        assert!(read(&tree()).is_ok());
605        // A column reference's outer-join mark, which a default would read as `false`.
606        let mut t = tree();
607        t["statement"]["columns"][0]["expr"].as_object_mut().unwrap().remove("outer");
608        assert!(read(&t).unwrap_err().contains("missing field `outer` of a `column` node"), "{:?}", read(&t));
609        // Every node's own, and a FROM item's.
610        for (at, member) in [("/statement/columns/0/expr", "outerOn"), ("/statement/from/0", "outer"), ("/statement", "where"), ("", "readonly"), ("", "schemaErrors")] {
611            let mut t = tree();
612            t.pointer_mut(at).unwrap().as_object_mut().unwrap().remove(member);
613            assert!(read(&t).unwrap_err().contains(&format!("`{member}`")), "{member}: {:?}", read(&t));
614        }
615        // A member no struct declares.
616        let mut t = tree();
617        t["statement"]["columns"][0]["expr"]["canBeNull"] = json!(true);
618        assert!(read(&t).unwrap_err().contains("unknown field `canBeNull`"), "{:?}", read(&t));
619        // A column SQLite resolved to no table has no member after `register`.
620        let mut t = tree();
621        t["statement"]["columns"][0]["expr"] = json!({ "op": "column", "aff": "none", "outerOn": false, "innerOn": false, "cursor": 0, "index": 0, "table": null, "register": false });
622        assert!(read(&t).is_ok());
623        // A failed statement's tree has no statement.
624        assert!(read(&json!({ "version": TREE_VERSION, "error": { "message": "no such table: x", "offset": 14 }, "schemaErrors": [] })).is_ok());
625    }
626
627    #[test]
628    fn a_tree_of_another_version_is_refused_by_both_numbers() {
629        let mut t = tree();
630        t["version"] = json!(TREE_VERSION + 1);
631        let refused = read(&t).unwrap_err();
632        assert!(refused.contains(&format!("the tree is of version {}, and this engine reads version {TREE_VERSION}", TREE_VERSION + 1)), "{refused}");
633        t.as_object_mut().unwrap().remove("version");
634        assert!(read(&t).unwrap_err().contains("missing field `version`"));
635    }
636}