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 pk_cols: Vec<(i64, usize)> = Vec::new();
76        {
77            let mut stmt = conn.prepare(&format!("PRAGMA table_info({})", quote_ident(&name)))?;
78            let mut rows = stmt.query([])?;
79            while let Some(r) = rows.next()? {
80                let col: String = r.get(1)?;
81                let pk: i64 = r.get(5)?;
82                if pk > 0 {
83                    pk_cols.push((pk, columns.len()));
84                }
85                columns.push(col);
86            }
87        }
88        pk_cols.sort();
89        // A single-column primary key names the rows. A view has no
90        // primary key ever; when it projects exactly one column —
91        // the `SELECT DISTINCT` dimension idiom — that column is
92        // the row's identity, so it names the rows (and keys `-->`
93        // resolution into the view).
94        let pk = (pk_cols.len() == 1)
95            .then(|| pk_cols[0].1)
96            .or_else(|| (is_view && columns.len() == 1).then_some(0));
97
98        // Declared foreign keys (an omitted target column means the
99        // target's primary key).
100        let mut fks = Vec::new();
101        {
102            let mut stmt =
103                conn.prepare(&format!("PRAGMA foreign_key_list({})", quote_ident(&name)))?;
104            let mut rows = stmt.query([])?;
105            while let Some(r) = rows.next()? {
106                let target: String = r.get(2)?;
107                let from: String = r.get(3)?;
108                let to: Option<String> = r.get(4)?;
109                if let Some(idx) = columns.iter().position(|c| *c == from) {
110                    fks.push((idx, target, to.unwrap_or_default()));
111                }
112            }
113        }
114        // Declared client-side references: synthesize an edge to the
115        // target container's key for every matching column the
116        // schema does not already cover.
117        for (field, container) in refs {
118            let col = match field.split_once('.') {
119                Some((table, col)) if table == name => col,
120                Some(_) => continue,
121                None => field.as_str(),
122            };
123            if let Some(idx) = columns.iter().position(|c| c == col)
124                && !fks.iter().any(|(i, _, _)| *i == idx)
125                // A container's key column pointing at the container
126                // itself is the identity, not an edge.
127                && !(*container == name && pk == Some(idx))
128            {
129                fks.push((idx, container.clone(), String::new()));
130            }
131        }
132        out.push(TableSpec {
133            name,
134            columns,
135            pk,
136            fks,
137        });
138    }
139    Ok(out)
140}
141
142/// Stream one table's rows, optionally filtered (partial
143/// pushdown: the engine re-applies the pushed predicates).
144fn fetch_rows_where(
145    conn: &Connection,
146    spec: &TableSpec,
147    where_sql: Option<&str>,
148) -> Result<Vec<RowSpec>, SqliteError> {
149    let cols = spec
150        .columns
151        .iter()
152        .map(|c| quote_ident(c))
153        .collect::<Vec<_>>()
154        .join(", ");
155    let table = quote_ident(&spec.name);
156    let filter = match where_sql {
157        Some(w) => format!(" WHERE {w}"),
158        None => String::new(),
159    };
160    // Prefer SQLite's rowid: stable row identity, and the row's edge
161    // name for tables without a single-column primary key. WITHOUT
162    // ROWID tables have no rowid column, so `SELECT rowid` fails to
163    // prepare; fall back to a positional ordinal (below), ordered by
164    // the key for determinism.
165    let with_rowid = format!("SELECT rowid, {cols} FROM {table}{filter} ORDER BY rowid");
166    if let Ok(mut stmt) = conn.prepare(&with_rowid) {
167        let mut rows = stmt.query([])?;
168        let mut out = Vec::new();
169        while let Some(r) = rows.next()? {
170            let rowid: i64 = r.get(0)?;
171            let values: Vec<Value> = (0..spec.columns.len())
172                .map(|i| to_value(r.get_ref(i + 1).expect("column in range")))
173                .collect();
174            out.push(RowSpec {
175                rowid: Some(rowid),
176                values,
177            });
178        }
179        return Ok(out);
180    }
181    // WITHOUT ROWID: no rowid column to select or order by. Order by
182    // the single-column primary key (which names the rows) when
183    // present, else by every column so the ordinal keys are stable.
184    let order = match spec.pk {
185        Some(i) => quote_ident(&spec.columns[i]),
186        None => cols.clone(),
187    };
188    let mut stmt = conn.prepare(&format!(
189        "SELECT {cols} FROM {table}{filter} ORDER BY {order}"
190    ))?;
191    let mut rows = stmt.query([])?;
192    let mut out = Vec::new();
193    let mut rowid = 0i64;
194    while let Some(r) = rows.next()? {
195        rowid += 1;
196        let values: Vec<Value> = (0..spec.columns.len())
197            .map(|i| to_value(r.get_ref(i).expect("column in range")))
198            .collect();
199        out.push(RowSpec {
200            rowid: Some(rowid),
201            values,
202        });
203    }
204    Ok(out)
205}
206
207/// The rows of a table whose column — `col`, or the row key (the
208/// primary key, else `rowid`) — holds one of `values`, in rowid
209/// order: what a hop reads instead of the table. Each value is
210/// bound in its own storage class and, where it reads as a number
211/// or is one, in the other too, so the comparison finds what the
212/// engine's text equality would under any column affinity; the
213/// statement can only return more, never less, and the model
214/// matches by text afterwards. A WITHOUT ROWID table is declined
215/// (its rows carry positional ids, which a keyed read cannot
216/// assign).
217fn fetch_rows_keyed(
218    conn: &Connection,
219    spec: &TableSpec,
220    filter: Option<&str>,
221    col: Option<usize>,
222    values: &[Value],
223) -> Result<Vec<RowSpec>, String> {
224    use rusqlite::types::Value as Sql;
225    let column = match col.or(spec.pk) {
226        Some(i) => quote_ident(&spec.columns[i]),
227        None => "rowid".to_string(),
228    };
229    let mut binds: Vec<Sql> = Vec::new();
230    for v in values {
231        match v {
232            Value::Int(i) => {
233                binds.push(Sql::Integer(*i));
234                binds.push(Sql::Text(i.to_string()));
235            }
236            Value::Float(f) => {
237                binds.push(Sql::Real(*f));
238                binds.push(Sql::Text(v.to_string()));
239            }
240            Value::Bool(b) => binds.push(Sql::Integer(*b as i64)),
241            Value::Null => {}
242            other => {
243                let text = other.to_string();
244                if let Ok(i) = text.parse::<i64>() {
245                    binds.push(Sql::Integer(i));
246                } else if let Ok(f) = text.parse::<f64>() {
247                    binds.push(Sql::Real(f));
248                }
249                binds.push(Sql::Text(text));
250            }
251        }
252    }
253    if binds.is_empty() {
254        return Ok(Vec::new());
255    }
256    let cols = spec
257        .columns
258        .iter()
259        .map(|c| quote_ident(c))
260        .collect::<Vec<_>>()
261        .join(", ");
262    let marks = vec!["?"; binds.len()].join(", ");
263    let filter = match filter {
264        Some(w) => format!("({w}) AND "),
265        None => String::new(),
266    };
267    let sql = format!(
268        "SELECT rowid, {cols} FROM {} WHERE {filter}{column} IN ({marks}) ORDER BY rowid",
269        quote_ident(&spec.name)
270    );
271    let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
272    let mut rows = stmt
273        .query(rusqlite::params_from_iter(binds.iter()))
274        .map_err(|e| e.to_string())?;
275    let mut out = Vec::new();
276    while let Some(r) = rows.next().map_err(|e| e.to_string())? {
277        let rowid: i64 = r.get(0).map_err(|e| e.to_string())?;
278        let values: Vec<Value> = (0..spec.columns.len())
279            .map(|i| to_value(r.get_ref(i + 1).expect("column in range")))
280            .collect();
281        out.push(RowSpec {
282            rowid: Some(rowid),
283            values,
284        });
285    }
286    Ok(out)
287}
288
289impl SqliteAdapter {
290    /// Open a database file (read-only): the catalog now, each
291    /// table's rows on first touch (the connection stays owned by
292    /// the adapter).
293    pub fn open(path: &std::path::Path) -> Result<Self, SqliteError> {
294        Self::open_impl(path, None, &[])
295    }
296
297    /// [`open`], with a declared-references document: each `(field,
298    /// container)` pair supplies the edge the schema does not
299    /// declare (see [`quarb_relational::parse_refs`]).
300    pub fn open_with_refs(
301        path: &std::path::Path,
302        refs: &[(String, String)],
303    ) -> Result<Self, SqliteError> {
304        Self::open_impl(path, None, refs)
305    }
306
307    /// [`open`], with one table's fetch filtered by a WHERE clause
308    /// (partial pushdown; the engine re-applies the predicates).
309    pub fn open_filtered(
310        path: &std::path::Path,
311        table: &str,
312        where_sql: &str,
313    ) -> Result<Self, SqliteError> {
314        Self::open_impl(path, Some((table.to_string(), where_sql.to_string())), &[])
315    }
316
317    /// [`open_filtered`], with a declared-references document.
318    pub fn open_filtered_with_refs(
319        path: &std::path::Path,
320        table: &str,
321        where_sql: &str,
322        refs: &[(String, String)],
323    ) -> Result<Self, SqliteError> {
324        Self::open_impl(path, Some((table.to_string(), where_sql.to_string())), refs)
325    }
326
327    fn open_impl(
328        path: &std::path::Path,
329        filter: Option<(String, String)>,
330        refs: &[(String, String)],
331    ) -> Result<Self, SqliteError> {
332        let conn = std::rc::Rc::new(Connection::open_with_flags(
333            path,
334            rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
335        )?);
336        let specs = specs(&conn, refs)?;
337        let (whole, keyed, listed) = (conn.clone(), conn.clone(), conn);
338        let mut model = RelationalModel::lazy(
339            specs,
340            Box::new(move |_, spec| {
341                fetch_rows_where(&whole, spec, None).map_err(|e| e.to_string())
342            }),
343        )
344        // A hop reads the rows it lands on, by key.
345        .with_key_fetcher(Box::new(move |_, spec, col, values| {
346            fetch_rows_keyed(&keyed, spec, None, col, values)
347        }));
348        // The pushed-down WHERE filters the table's listing only:
349        // hops into it go by key, unfiltered, so they stay exact.
350        if let Some((table, where_sql)) = filter {
351            model = model.with_filtered_listing(
352                &table,
353                Box::new(move |_, spec| {
354                    fetch_rows_where(&listed, spec, Some(&where_sql)).map_err(|e| e.to_string())
355                }),
356            );
357        }
358        Ok(SqliteAdapter { model })
359    }
360
361    /// Open a database held entirely in memory — the bytes of a
362    /// `.db` file that never touched a filesystem (the browser's
363    /// uploaded files). Deserializes read-only, then materializes
364    /// eagerly, as [`SqliteAdapter::load`] does.
365    pub fn from_bytes(bytes: &[u8]) -> Result<Self, SqliteError> {
366        let mut conn = Connection::open_in_memory()?;
367        conn.deserialize_read_exact(rusqlite::MAIN_DB, bytes, bytes.len(), true)?;
368        Self::load(&conn)
369    }
370
371    /// Materialize every user table of an open connection, eagerly
372    /// (in-memory databases, tests).
373    pub fn load(conn: &Connection) -> Result<Self, SqliteError> {
374        Self::load_with_refs(conn, &[])
375    }
376
377    /// [`load`], with a declared-references document.
378    pub fn load_with_refs(
379        conn: &Connection,
380        refs: &[(String, String)],
381    ) -> Result<Self, SqliteError> {
382        let mut input = Vec::new();
383        for spec in specs(conn, refs)? {
384            let rows = fetch_rows_where(conn, &spec, None)?;
385            input.push((spec, rows));
386        }
387        Ok(SqliteAdapter {
388            model: RelationalModel::build(input),
389        })
390    }
391
392    /// A human-readable locator: `/table/key` for rows.
393    /// Surface a filtered fetch's error now (see
394    /// `RelationalModel::prefetch`): the partial-pushdown caller
395    /// falls back to the scan instead of answering empty.
396    pub fn prefetch(&self, table: &str) -> Result<(), String> {
397        self.model.prefetch(table)
398    }
399
400    pub fn locator(&self, node: NodeId) -> String {
401        self.model.locator(node)
402    }
403}
404
405/// Execute pushed-down SQL directly (read-only): the column names
406/// and rows, ordered by `order_table`'s key when one is given (the
407/// pushdown contract: row order must match the adapter's document
408/// order, which is that key).
409/// Whether `cols` covers the primary key or a non-partial UNIQUE
410/// index of `table` — the soundness condition for executing a
411/// witness-JOIN pushdown (see `raw_query`).
412fn unique_key(conn: &Connection, table: &str, cols: &[String]) -> Result<bool, SqliteError> {
413    use std::collections::HashSet;
414    let want: HashSet<&str> = cols.iter().map(|s| s.as_str()).collect();
415    if want.is_empty() {
416        return Ok(false);
417    }
418    // Primary key (pk ordinal > 0 in table_info).
419    let mut stmt = conn.prepare(&format!("PRAGMA table_info({})", quote_ident(table)))?;
420    let mut pk: HashSet<String> = HashSet::new();
421    let mut rows = stmt.query([])?;
422    while let Some(r) = rows.next()? {
423        let name: String = r.get(1)?;
424        let ord: i64 = r.get(5)?;
425        if ord > 0 {
426            pk.insert(name);
427        }
428    }
429    if !pk.is_empty() && pk.iter().all(|c| want.contains(c.as_str())) {
430        return Ok(true);
431    }
432    // Non-partial UNIQUE indexes.
433    let mut stmt = conn.prepare(&format!("PRAGMA index_list({})", quote_ident(table)))?;
434    let mut uniques: Vec<String> = Vec::new();
435    let mut rows = stmt.query([])?;
436    while let Some(r) = rows.next()? {
437        let name: String = r.get(1)?;
438        let is_unique: i64 = r.get(2)?;
439        let partial: i64 = r.get(4).unwrap_or(0);
440        if is_unique == 1 && partial == 0 {
441            uniques.push(name);
442        }
443    }
444    for idx in uniques {
445        let mut stmt = conn.prepare(&format!("PRAGMA index_info({})", quote_ident(&idx)))?;
446        let mut cols_of: Vec<String> = Vec::new();
447        let mut rows = stmt.query([])?;
448        while let Some(r) = rows.next()? {
449            cols_of.push(r.get(2)?);
450        }
451        if !cols_of.is_empty() && cols_of.iter().all(|c| want.contains(c.as_str())) {
452            return Ok(true);
453        }
454    }
455    Ok(false)
456}
457
458/// The catalog for a pushed plan's column-type assumptions
459/// (`quarb_sql::ColumnTypes::hold`): every column of `tables`, with
460/// whether SQLite gives it a numeric affinity. A column of INTEGER,
461/// REAL or NUMERIC affinity holds numbers and compares with a
462/// numeric literal as Quarb's scan does; a TEXT or untyped column
463/// compares by storage class (`'150'` is not `150`, and any text
464/// is greater than any number), which the scan's comparison by
465/// value is not.
466pub fn column_catalog(
467    path: &std::path::Path,
468    tables: &[&str],
469) -> Result<Vec<(String, bool)>, SqliteError> {
470    let conn = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
471    let mut catalog = Vec::new();
472    for table in tables {
473        let mut stmt = conn.prepare(&format!("PRAGMA table_info({})", quote_ident(table)))?;
474        let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(1)?, r.get::<_, String>(2)?)))?;
475        for row in rows {
476            let (name, declared) = row?;
477            catalog.push((name, numeric_affinity(&declared)));
478        }
479    }
480    Ok(catalog)
481}
482
483/// SQLite's affinity rules (its "Datatypes" document, section 3.1),
484/// reduced to the question asked: INTEGER, REAL or NUMERIC.
485fn numeric_affinity(declared: &str) -> bool {
486    let d = declared.to_ascii_uppercase();
487    if d.contains("INT") {
488        true
489    } else if d.contains("CHAR") || d.contains("CLOB") || d.contains("TEXT") {
490        false
491    } else {
492        !(d.contains("BLOB") || d.trim().is_empty())
493    }
494}
495
496pub fn raw_query(
497    path: &std::path::Path,
498    sql: &str,
499    order_table: Option<&str>,
500    join_left: Option<(&str, &[String])>,
501) -> Result<(Vec<String>, Vec<Vec<Value>>), SqliteError> {
502    let conn = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
503    // A witness-JOIN plan is only sound when the ON binds the left
504    // table by a unique key (else SQL multiplies rows where
505    // Quarb's existential binding does not). Verify against the
506    // catalog; refusing sends the caller back to the scan.
507    if let Some((table, cols)) = join_left
508        && !unique_key(&conn, table, cols)?
509    {
510        return Err(SqliteError::Plan(format!(
511            "join ON does not bind {table} by a unique key; \
512             the SQL JOIN would multiply rows"
513        )));
514    }
515    let sql = match order_table {
516        Some(t) => {
517            let key = specs(&conn, &[])?
518                .into_iter()
519                .find(|s| s.name == t)
520                .and_then(|s| s.pk.map(|i| s.columns[i].clone()))
521                .unwrap_or_else(|| "rowid".to_string());
522            format!("{sql} ORDER BY {t}.{key}")
523        }
524        None => sql.to_string(),
525    };
526    // --explain prints what ran: the ORDER BY key is a
527    // catalog lookup made here, so the final statement
528    // exists nowhere earlier.
529    quarb_relational::record_executed(&sql);
530    let mut stmt = conn.prepare(&sql)?;
531    let cols: Vec<String> = stmt.column_names().iter().map(|c| c.to_string()).collect();
532    let n = cols.len();
533    let mut rows = stmt.query([])?;
534    let mut out = Vec::new();
535    while let Some(r) = rows.next()? {
536        out.push(
537            (0..n)
538                .map(|i| to_value(r.get_ref(i).expect("column in range")))
539                .collect(),
540        );
541    }
542    Ok((cols, out))
543}
544
545impl AstAdapter for SqliteAdapter {
546    fn root(&self) -> NodeId {
547        self.model.root()
548    }
549    fn children(&self, node: NodeId) -> Vec<NodeId> {
550        self.model.children(node)
551    }
552    fn children_named(&self, node: NodeId, name: &str) -> Vec<NodeId> {
553        self.model.children_named(node, name)
554    }
555    fn name(&self, node: NodeId) -> Option<String> {
556        self.model.name(node)
557    }
558    fn parent(&self, node: NodeId) -> Option<NodeId> {
559        self.model.parent(node)
560    }
561    fn property(&self, node: NodeId, name: &str) -> Option<Value> {
562        self.model.property(node, name)
563    }
564    fn default_value(&self, node: NodeId) -> Option<Value> {
565        self.model.default_value(node)
566    }
567    fn metadata(&self, node: NodeId, key: &str) -> Option<Value> {
568        self.model.metadata(node, key)
569    }
570    fn resolve(&self, node: NodeId, property: &str, hint: Option<&str>) -> Option<NodeId> {
571        self.model.resolve(node, property, hint)
572    }
573    fn links(&self, node: NodeId) -> Vec<(String, NodeId)> {
574        self.model.links(node)
575    }
576    fn backlinks(&self, node: NodeId) -> Vec<(String, NodeId)> {
577        self.model.backlinks(node)
578    }
579    fn reverse_resolve(
580        &self,
581        node: NodeId,
582        property: Option<&str>,
583        hint: Option<&str>,
584    ) -> Option<Vec<NodeId>> {
585        self.model.reverse_resolve(node, property, hint)
586    }
587    fn can_refer_to(&self, source: NodeId, target: NodeId) -> Option<bool> {
588        self.model.can_refer_to(source, target)
589    }
590    fn prefetch_links(&self, nodes: &[NodeId], dir: quarb::LinkDir) {
591        self.model.prefetch_links(nodes, dir)
592    }
593    fn index_referrers(
594        &self,
595        scope: &str,
596        property: &str,
597        label: Option<&str>,
598        target: NodeId,
599    ) -> Option<Vec<NodeId>> {
600        self.model.index_referrers(scope, property, label, target)
601    }
602    fn reference_properties(&self, source: NodeId, target: NodeId) -> Vec<String> {
603        self.model.reference_properties(source, target)
604    }
605    fn resolve_needs_label(&self, node: NodeId, property: &str) -> bool {
606        self.model.resolve_needs_label(node, property)
607    }
608    fn reverse_label(&self, target: NodeId) -> Option<String> {
609        self.model.reverse_label(target)
610    }
611}