Skip to main content

quarb_sqlite/
lib.rs

1//! SQLite adapter for the Quarb query engine.
2//!
3//! A thin catalog driver over the shared relational model
4//! (`quarb-relational`): it introspects the schema via PRAGMAs
5//! (`table_info`, `foreign_key_list`), streams every user table,
6//! maps SQLite's storage classes to values (`NULL` → null,
7//! `INTEGER`/`REAL` → numbers, text as itself, blobs as a size
8//! placeholder), and hands the result to [`RelationalModel`].
9//!
10//! The arbor mapping, the foreign-key reference machinery (`-->`
11//! chains, `->`/`<-` crosslinks, `<--` reverse resolution, the
12//! table-naming hint), and the metadata surface are documented on
13//! the shared model.
14
15use quarb::{AstAdapter, NodeId, Value};
16use quarb_relational::{RelationalModel, RowSpec, TableSpec};
17use rusqlite::Connection;
18use rusqlite::types::ValueRef;
19
20/// An error loading a database.
21#[derive(Debug, thiserror::Error)]
22pub enum SqliteError {
23    #[error("sqlite: {0}")]
24    Sqlite(#[from] rusqlite::Error),
25    #[error("pushdown plan: {0}")]
26    Plan(String),
27}
28
29/// A SQLite database, materialized as an arbor.
30pub struct SqliteAdapter {
31    model: RelationalModel,
32}
33
34fn to_value(v: ValueRef<'_>) -> Value {
35    match v {
36        ValueRef::Null => Value::Null,
37        ValueRef::Integer(n) => Value::Int(n),
38        ValueRef::Real(f) => Value::Float(f),
39        ValueRef::Text(t) => Value::Str(String::from_utf8_lossy(t).into_owned()),
40        ValueRef::Blob(b) => Value::Str(format!("<blob {} bytes>", b.len())),
41    }
42}
43
44/// Quote an identifier (table or column name) for interpolation into
45/// SQL: wrap in double quotes, doubling any embedded quote, so
46/// reserved words and special characters survive.
47fn quote_ident(name: &str) -> String {
48    quarb_relational::quote_double(name)
49}
50
51/// Introspect the schema: every user table's and view's spec, via
52/// PRAGMAs. Views are containers like tables — a single-column view
53/// (the `SELECT DISTINCT` dimension idiom) is named by that column,
54/// the way a single-column primary key names a table's rows.
55/// `refs` is the declared-references document: each `(field,
56/// container)` pair synthesizes a foreign-key edge from every
57/// matching column (bare `column`, or `table.column` to scope) to
58/// the target container's key, unless the schema already declares
59/// one there.
60fn specs(conn: &Connection, refs: &[(String, String)]) -> Result<Vec<TableSpec>, SqliteError> {
61    let named: Vec<(String, bool)> = conn
62        .prepare(
63            "SELECT name, type = 'view' FROM sqlite_master \
64             WHERE type IN ('table', 'view') \
65             AND name NOT LIKE 'sqlite_%' ORDER BY name",
66        )?
67        .query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
68        .collect::<Result<_, _>>()?;
69
70    let mut out = Vec::new();
71    for (name, is_view) in named {
72        // Columns and the primary key (a single-column pk names the
73        // rows; a composite or absent pk falls back to rowid).
74        let mut columns = Vec::new();
75        let mut json_columns = Vec::new();
76        let mut pk_cols: Vec<(i64, usize)> = Vec::new();
77        let mut column_types: Vec<String> = Vec::new();
78        {
79            let mut stmt = conn.prepare(&format!("PRAGMA table_info({})", quote_ident(&name)))?;
80            let mut rows = stmt.query([])?;
81            while let Some(r) = rows.next()? {
82                let col: String = r.get(1)?;
83                let declared: String = r.get(2)?;
84                let pk: i64 = r.get(5)?;
85                if pk > 0 {
86                    pk_cols.push((pk, columns.len()));
87                }
88                // a column declared JSON or JSONB declares its
89                // cells' notation (spec: Grafting)
90                if declared.trim().eq_ignore_ascii_case("json")
91                    || declared.trim().eq_ignore_ascii_case("jsonb")
92                {
93                    json_columns.push(columns.len());
94                }
95                columns.push(col);
96                column_types.push(declared);
97            }
98        }
99        pk_cols.sort();
100        // A single-column primary key names the rows. A view has no
101        // primary key ever; when it projects exactly one column —
102        // the `SELECT DISTINCT` dimension idiom — that column is
103        // the row's identity, so it names the rows (and keys `-->`
104        // resolution into the view).
105        let pk = (pk_cols.len() == 1)
106            .then(|| pk_cols[0].1)
107            .or_else(|| (is_view && columns.len() == 1).then_some(0));
108
109        // Declared foreign keys (an omitted target column means the
110        // target's primary key).
111        let mut fks = Vec::new();
112        {
113            let mut stmt =
114                conn.prepare(&format!("PRAGMA foreign_key_list({})", quote_ident(&name)))?;
115            let mut rows = stmt.query([])?;
116            while let Some(r) = rows.next()? {
117                let target: String = r.get(2)?;
118                let from: String = r.get(3)?;
119                let to: Option<String> = r.get(4)?;
120                if let Some(idx) = columns.iter().position(|c| *c == from) {
121                    fks.push((idx, target, to.unwrap_or_default()));
122                }
123            }
124        }
125        // Declared client-side references: synthesize an edge to the
126        // target container's key for every matching column the
127        // schema does not already cover.
128        for (field, container) in refs {
129            let col = match field.split_once('.') {
130                Some((table, col)) if table == name => col,
131                Some(_) => continue,
132                None => field.as_str(),
133            };
134            if let Some(idx) = columns.iter().position(|c| c == col)
135                && !fks.iter().any(|(i, _, _)| *i == idx)
136                // A container's key column pointing at the container
137                // itself is the identity, not an edge.
138                && !(*container == name && pk == Some(idx))
139            {
140                fks.push((idx, container.clone(), String::new()));
141            }
142        }
143        out.push(TableSpec {
144            name,
145            columns,
146            pk,
147            fks,
148            json_columns,
149            column_types,
150        });
151    }
152    Ok(out)
153}
154
155/// Stream one table's rows, optionally filtered (partial
156/// pushdown: the engine re-applies the pushed predicates).
157fn fetch_rows_where(
158    conn: &Connection,
159    spec: &TableSpec,
160    where_sql: Option<&str>,
161) -> Result<Vec<RowSpec>, SqliteError> {
162    let cols = spec
163        .columns
164        .iter()
165        .map(|c| quote_ident(c))
166        .collect::<Vec<_>>()
167        .join(", ");
168    let table = quote_ident(&spec.name);
169    let filter = match where_sql {
170        Some(w) => format!(" WHERE {w}"),
171        None => String::new(),
172    };
173    // Prefer SQLite's rowid: stable row identity, and the row's edge
174    // name for tables without a single-column primary key. WITHOUT
175    // ROWID tables have no rowid column, so `SELECT rowid` fails to
176    // prepare; fall back to a positional ordinal (below), ordered by
177    // the key for determinism.
178    let with_rowid = format!("SELECT rowid, {cols} FROM {table}{filter} ORDER BY rowid");
179    if let Ok(mut stmt) = conn.prepare(&with_rowid) {
180        let mut rows = stmt.query([])?;
181        let mut out = Vec::new();
182        while let Some(r) = rows.next()? {
183            let rowid: i64 = r.get(0)?;
184            let values: Vec<Value> = (0..spec.columns.len())
185                .map(|i| to_value(r.get_ref(i + 1).expect("column in range")))
186                .collect();
187            out.push(RowSpec {
188                rowid: Some(rowid),
189                values,
190            });
191        }
192        return Ok(out);
193    }
194    // WITHOUT ROWID: no rowid column to select or order by. Order by
195    // the single-column primary key (which names the rows) when
196    // present, else by every column so the ordinal keys are stable.
197    let order = match spec.pk {
198        Some(i) => quote_ident(&spec.columns[i]),
199        None => cols.clone(),
200    };
201    let mut stmt = conn.prepare(&format!(
202        "SELECT {cols} FROM {table}{filter} ORDER BY {order}"
203    ))?;
204    let mut rows = stmt.query([])?;
205    let mut out = Vec::new();
206    let mut rowid = 0i64;
207    while let Some(r) = rows.next()? {
208        rowid += 1;
209        let values: Vec<Value> = (0..spec.columns.len())
210            .map(|i| to_value(r.get_ref(i).expect("column in range")))
211            .collect();
212        out.push(RowSpec {
213            rowid: Some(rowid),
214            values,
215        });
216    }
217    Ok(out)
218}
219
220/// The rows of a table whose column — `col`, or the row key (the
221/// primary key, else `rowid`) — holds one of `values`, in rowid
222/// order: what a hop reads instead of the table. Each value is
223/// bound in its own storage class and, where it reads as a number
224/// or is one, in the other too, so the comparison finds what the
225/// engine's text equality would under any column affinity; the
226/// statement can only return more, never less, and the model
227/// matches by text afterwards. A WITHOUT ROWID table is declined
228/// (its rows carry positional ids, which a keyed read cannot
229/// assign).
230fn fetch_rows_keyed(
231    conn: &Connection,
232    spec: &TableSpec,
233    filter: Option<&str>,
234    col: Option<usize>,
235    values: &[Value],
236) -> Result<Vec<RowSpec>, String> {
237    use rusqlite::types::Value as Sql;
238    let column = match col.or(spec.pk) {
239        Some(i) => quote_ident(&spec.columns[i]),
240        None => "rowid".to_string(),
241    };
242    let mut binds: Vec<Sql> = Vec::new();
243    for v in values {
244        match v {
245            Value::Int(i) => {
246                binds.push(Sql::Integer(*i));
247                binds.push(Sql::Text(i.to_string()));
248            }
249            Value::Float(f) => {
250                binds.push(Sql::Real(*f));
251                binds.push(Sql::Text(v.to_string()));
252            }
253            Value::Bool(b) => binds.push(Sql::Integer(*b as i64)),
254            Value::Null => {}
255            other => {
256                let text = other.to_string();
257                if let Ok(i) = text.parse::<i64>() {
258                    binds.push(Sql::Integer(i));
259                } else if let Ok(f) = text.parse::<f64>() {
260                    binds.push(Sql::Real(f));
261                }
262                binds.push(Sql::Text(text));
263            }
264        }
265    }
266    if binds.is_empty() {
267        return Ok(Vec::new());
268    }
269    let cols = spec
270        .columns
271        .iter()
272        .map(|c| quote_ident(c))
273        .collect::<Vec<_>>()
274        .join(", ");
275    let marks = vec!["?"; binds.len()].join(", ");
276    let filter = match filter {
277        Some(w) => format!("({w}) AND "),
278        None => String::new(),
279    };
280    let sql = format!(
281        "SELECT rowid, {cols} FROM {} WHERE {filter}{column} IN ({marks}) ORDER BY rowid",
282        quote_ident(&spec.name)
283    );
284    let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
285    let mut rows = stmt
286        .query(rusqlite::params_from_iter(binds.iter()))
287        .map_err(|e| e.to_string())?;
288    let mut out = Vec::new();
289    while let Some(r) = rows.next().map_err(|e| e.to_string())? {
290        let rowid: i64 = r.get(0).map_err(|e| e.to_string())?;
291        let values: Vec<Value> = (0..spec.columns.len())
292            .map(|i| to_value(r.get_ref(i + 1).expect("column in range")))
293            .collect();
294        out.push(RowSpec {
295            rowid: Some(rowid),
296            values,
297        });
298    }
299    Ok(out)
300}
301
302/// `ANALYZE`'s figure for one value of `column`: the average rows
303/// per distinct key of an index that opens with the column
304/// (`sqlite_stat1.stat`'s second number). An error when no index
305/// opens with it or the statistics are missing.
306fn index_rows_per_key(conn: &Connection, table: &str, column: &str) -> Result<u64, String> {
307    let mut list = conn
308        .prepare(&format!("PRAGMA index_list({})", quote_ident(table)))
309        .map_err(|e| e.to_string())?;
310    let names: Vec<String> = list
311        .query_map([], |r| r.get::<_, String>(1))
312        .map_err(|e| e.to_string())?
313        .filter_map(Result::ok)
314        .collect();
315    for idx in names {
316        let first: Option<String> = conn
317            .query_row(
318                &format!("PRAGMA index_info({})", quote_ident(&idx)),
319                [],
320                |r| r.get(2),
321            )
322            .ok();
323        if first.as_deref() != Some(column) {
324            continue;
325        }
326        let stat: String = conn
327            .query_row(
328                "SELECT stat FROM sqlite_stat1 WHERE tbl = ?1 AND idx = ?2",
329                [table, idx.as_str()],
330                |r| r.get(0),
331            )
332            .map_err(|e| e.to_string())?;
333        return stat
334            .split_whitespace()
335            .nth(1)
336            .and_then(|t| t.parse().ok())
337            .ok_or_else(|| "no per-key figure in sqlite_stat1".to_string());
338    }
339    Err(format!("no index opens with {column}"))
340}
341
342impl SqliteAdapter {
343    /// Open a database file (read-only): the catalog now, each
344    /// table's rows on first touch (the connection stays owned by
345    /// the adapter).
346    pub fn open(path: &std::path::Path) -> Result<Self, SqliteError> {
347        Self::open_impl(path, None, &[])
348    }
349
350    /// [`open`], with a declared-references document: each `(field,
351    /// container)` pair supplies the edge the schema does not
352    /// declare (see [`quarb_relational::parse_refs`]).
353    pub fn open_with_refs(
354        path: &std::path::Path,
355        refs: &[(String, String)],
356    ) -> Result<Self, SqliteError> {
357        Self::open_impl(path, None, refs)
358    }
359
360    /// [`open`], with one table's fetch filtered by a WHERE clause
361    /// (partial pushdown; the engine re-applies the predicates).
362    pub fn open_filtered(
363        path: &std::path::Path,
364        table: &str,
365        where_sql: &str,
366    ) -> Result<Self, SqliteError> {
367        Self::open_impl(path, Some((table.to_string(), where_sql.to_string())), &[])
368    }
369
370    /// [`open_filtered`], with a declared-references document.
371    pub fn open_filtered_with_refs(
372        path: &std::path::Path,
373        table: &str,
374        where_sql: &str,
375        refs: &[(String, String)],
376    ) -> Result<Self, SqliteError> {
377        Self::open_impl(path, Some((table.to_string(), where_sql.to_string())), refs)
378    }
379
380    fn open_impl(
381        path: &std::path::Path,
382        filter: Option<(String, String)>,
383        refs: &[(String, String)],
384    ) -> Result<Self, SqliteError> {
385        let conn = std::rc::Rc::new(Connection::open_with_flags(
386            path,
387            rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
388        )?);
389        let specs = specs(&conn, refs)?;
390        let (whole, keyed, stats, listed) = (conn.clone(), conn.clone(), conn.clone(), conn);
391        let mut model = RelationalModel::lazy(
392            specs,
393            Box::new(move |_, spec| {
394                fetch_rows_where(&whole, spec, None).map_err(|e| e.to_string())
395            }),
396        )
397        // A hop reads the rows it lands on, by key.
398        .with_key_fetcher(Box::new(move |_, spec, col, values| {
399            fetch_rows_keyed(&keyed, spec, None, col, values)
400        }))
401        // `ANALYZE`'s statistics, when the file carries them: the
402        // table's row count as the planner knows it. A table with
403        // no index has one row with a null `idx`; an indexed table
404        // has one row per index, each opening with the table's row
405        // count. Without statistics the estimate is unknown — a
406        // count would be the scan.
407        .with_estimator(std::rc::Rc::new(move |_, spec, equals| {
408            let stat: String = stats
409                .query_row(
410                    "SELECT stat FROM sqlite_stat1 WHERE tbl = ?1 \
411                     ORDER BY idx IS NULL DESC LIMIT 1",
412                    [spec.name.as_str()],
413                    |r| r.get(0),
414                )
415                .map_err(|e| e.to_string())?;
416            let n: u64 = stat
417                .split_whitespace()
418                .next()
419                .and_then(|t| t.parse().ok())
420                .ok_or("no row count in sqlite_stat1")?;
421            // An equality on a column some index opens with: the
422            // index's statistics say how many rows one value of it
423            // selects on average, the planner's own figure. The
424            // smallest over the equalities bounds the read.
425            let mut per_key: Option<u64> = None;
426            for (col, _) in equals {
427                let column = &spec.columns[*col];
428                if let Ok(k) = index_rows_per_key(&stats, &spec.name, column) {
429                    per_key = Some(per_key.map_or(k, |p| p.min(k)));
430                }
431            }
432            Ok(quarb::Estimate {
433                nodes: match (equals.is_empty(), per_key) {
434                    (true, _) => (n, n),
435                    (false, Some(k)) => (0, k.min(n)),
436                    (false, None) => (0, n),
437                },
438                bytes: None,
439                requests: Some(0),
440                latency: quarb::Latency::Local,
441                confidence: quarb::Confidence::Guess,
442            })
443        }));
444        // The pushed-down WHERE filters the table's listing only:
445        // hops into it go by key, unfiltered, so they stay exact.
446        if let Some((table, where_sql)) = filter {
447            model = model.with_filtered_listing(
448                &table,
449                Box::new(move |_, spec| {
450                    fetch_rows_where(&listed, spec, Some(&where_sql)).map_err(|e| e.to_string())
451                }),
452            );
453        }
454        Ok(SqliteAdapter { model })
455    }
456
457    /// Open a database held entirely in memory — the bytes of a
458    /// `.db` file that never touched a filesystem (the browser's
459    /// uploaded files). Deserializes read-only, then materializes
460    /// eagerly, as [`SqliteAdapter::load`] does.
461    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SqliteError> {
462        let mut conn = Connection::open_in_memory()?;
463        conn.deserialize_read_exact(rusqlite::MAIN_DB, bytes, bytes.len(), true)?;
464        Self::load(&conn)
465    }
466
467    /// Materialize every user table of an open connection, eagerly
468    /// (in-memory databases, tests).
469    pub fn load(conn: &Connection) -> Result<Self, SqliteError> {
470        Self::load_with_refs(conn, &[])
471    }
472
473    /// [`load`], with a declared-references document.
474    pub fn load_with_refs(
475        conn: &Connection,
476        refs: &[(String, String)],
477    ) -> Result<Self, SqliteError> {
478        let mut input = Vec::new();
479        for spec in specs(conn, refs)? {
480            let rows = fetch_rows_where(conn, &spec, None)?;
481            input.push((spec, rows));
482        }
483        Ok(SqliteAdapter {
484            model: RelationalModel::build(input),
485        })
486    }
487
488    /// A human-readable locator: `/table/key` for rows.
489    /// Surface a filtered fetch's error now (see
490    /// `RelationalModel::prefetch`): the partial-pushdown caller
491    /// falls back to the scan instead of answering empty.
492    pub fn prefetch(&self, table: &str) -> Result<(), String> {
493        self.model.prefetch(table)
494    }
495
496    pub fn locator(&self, node: NodeId) -> String {
497        self.model.locator(node)
498    }
499}
500
501/// Execute pushed-down SQL directly (read-only): the column names
502/// and rows, ordered by `order_table`'s key when one is given (the
503/// pushdown contract: row order must match the adapter's document
504/// order, which is that key).
505/// Whether `cols` covers the primary key or a non-partial UNIQUE
506/// index of `table` — the soundness condition for executing a
507/// witness-JOIN pushdown (see `raw_query`).
508fn unique_key(conn: &Connection, table: &str, cols: &[String]) -> Result<bool, SqliteError> {
509    use std::collections::HashSet;
510    let want: HashSet<&str> = cols.iter().map(|s| s.as_str()).collect();
511    if want.is_empty() {
512        return Ok(false);
513    }
514    // Primary key (pk ordinal > 0 in table_info).
515    let mut stmt = conn.prepare(&format!("PRAGMA table_info({})", quote_ident(table)))?;
516    let mut pk: HashSet<String> = HashSet::new();
517    let mut rows = stmt.query([])?;
518    while let Some(r) = rows.next()? {
519        let name: String = r.get(1)?;
520        let ord: i64 = r.get(5)?;
521        if ord > 0 {
522            pk.insert(name);
523        }
524    }
525    if !pk.is_empty() && pk.iter().all(|c| want.contains(c.as_str())) {
526        return Ok(true);
527    }
528    // Non-partial UNIQUE indexes.
529    let mut stmt = conn.prepare(&format!("PRAGMA index_list({})", quote_ident(table)))?;
530    let mut uniques: Vec<String> = Vec::new();
531    let mut rows = stmt.query([])?;
532    while let Some(r) = rows.next()? {
533        let name: String = r.get(1)?;
534        let is_unique: i64 = r.get(2)?;
535        let partial: i64 = r.get(4).unwrap_or(0);
536        if is_unique == 1 && partial == 0 {
537            uniques.push(name);
538        }
539    }
540    for idx in uniques {
541        let mut stmt = conn.prepare(&format!("PRAGMA index_info({})", quote_ident(&idx)))?;
542        let mut cols_of: Vec<String> = Vec::new();
543        let mut rows = stmt.query([])?;
544        while let Some(r) = rows.next()? {
545            cols_of.push(r.get(2)?);
546        }
547        if !cols_of.is_empty() && cols_of.iter().all(|c| want.contains(c.as_str())) {
548            return Ok(true);
549        }
550    }
551    Ok(false)
552}
553
554/// The catalog for a pushed plan's column-type assumptions
555/// (`quarb_sql::ColumnTypes::hold`): every column of `tables`, with
556/// whether SQLite gives it a numeric affinity. A column of INTEGER,
557/// REAL or NUMERIC affinity holds numbers and compares with a
558/// numeric literal as Quarb's scan does; a TEXT or untyped column
559/// compares by storage class (`'150'` is not `150`, and any text
560/// is greater than any number), which the scan's comparison by
561/// value is not.
562pub fn column_catalog(
563    path: &std::path::Path,
564    tables: &[&str],
565) -> Result<Vec<(String, bool, bool)>, SqliteError> {
566    let conn = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
567    let mut catalog = Vec::new();
568    for table in tables {
569        let mut stmt = conn.prepare(&format!("PRAGMA table_info({})", quote_ident(table)))?;
570        let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(1)?, r.get::<_, String>(2)?)))?;
571        for row in rows {
572            let (name, declared) = row?;
573            // numeric affinity, and whether the column is declared
574            // json (the graft's declaration, kept by SQLite as the
575            // type name)
576            let json = matches!(
577                declared.trim().to_ascii_lowercase().as_str(),
578                "json" | "jsonb"
579            );
580            catalog.push((name, numeric_affinity(&declared), json));
581        }
582    }
583    Ok(catalog)
584}
585
586/// SQLite's affinity rules (its "Datatypes" document, section 3.1),
587/// reduced to the question asked: INTEGER, REAL or NUMERIC.
588fn numeric_affinity(declared: &str) -> bool {
589    let d = declared.to_ascii_uppercase();
590    if d.contains("INT") {
591        true
592    } else if d.contains("CHAR") || d.contains("CLOB") || d.contains("TEXT") {
593        false
594    } else {
595        !(d.contains("BLOB") || d.trim().is_empty())
596    }
597}
598
599pub fn raw_query(
600    path: &std::path::Path,
601    sql: &str,
602    order_table: Option<&str>,
603    join_left: Option<(&str, &[String])>,
604) -> Result<(Vec<String>, Vec<Vec<Value>>), SqliteError> {
605    let conn = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
606    // A witness-JOIN plan is only sound when the ON binds the left
607    // table by a unique key (else SQL multiplies rows where
608    // Quarb's existential binding does not). Verify against the
609    // catalog; refusing sends the caller back to the scan.
610    if let Some((table, cols)) = join_left
611        && !unique_key(&conn, table, cols)?
612    {
613        return Err(SqliteError::Plan(format!(
614            "join ON does not bind {table} by a unique key; \
615             the SQL JOIN would multiply rows"
616        )));
617    }
618    let sql = match order_table {
619        Some(t) => {
620            let key = specs(&conn, &[])?
621                .into_iter()
622                .find(|s| s.name == t)
623                .and_then(|s| s.pk.map(|i| s.columns[i].clone()))
624                .unwrap_or_else(|| "rowid".to_string());
625            format!("{sql} ORDER BY {t}.{key}")
626        }
627        None => sql.to_string(),
628    };
629    // --explain prints what ran: the ORDER BY key is a
630    // catalog lookup made here, so the final statement
631    // exists nowhere earlier.
632    quarb_relational::record_executed(&sql);
633    let mut stmt = conn.prepare(&sql)?;
634    let cols: Vec<String> = stmt.column_names().iter().map(|c| c.to_string()).collect();
635    let n = cols.len();
636    let mut rows = stmt.query([])?;
637    let mut out = Vec::new();
638    while let Some(r) = rows.next()? {
639        out.push(
640            (0..n)
641                .map(|i| to_value(r.get_ref(i).expect("column in range")))
642                .collect(),
643        );
644    }
645    Ok((cols, out))
646}
647
648impl AstAdapter for SqliteAdapter {
649    // Every trait method, through the relational model: the search
650    // fast paths, the plan and its estimate included.
651    quarb::forward_ast_adapter!(model);
652}