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