Skip to main content

reylo_engine_sqlite/
errors.rs

1//! The errors a SQLite statement may raise, where it runs no trigger
2//! ([`reylo_engine_core::errors`]): a function the application registers fails the type check, so
3//! a trigger is the only code of a user's a statement may set off. Its constraint errors then name
4//! only the tables and columns of the unique keys, the NOT NULL columns, the columns of a STRICT
5//! table and the indexes of expressions of the tables it writes. A CHECK's name is not in the
6//! catalog, so a CHECK's error is not narrowed.
7
8use reylo_engine_core::types::StatementKind;
9use crate::host::Host;
10use reylo_engine_core::api::{Analysis, Scope};
11use reylo_engine_core::dialect::Dialect;
12use reylo_engine_core::errors::{has_word, Errors};
13use reylo_engine_core::host::Lazy;
14use serde_json::Value;
15
16/// `{written}` is a SELECT of the tables the statement writes; `{cascades}` whether a row it writes
17/// may change a key another table's foreign key refers to. One row `('open', why)` for each trigger
18/// that may fire, and one `('name', code, field, name)` for each name an error may carry: a unique
19/// key's columns as SQLite's message lists them, `a, b`. What a write reaches: the written tables,
20/// and, where `{cascades}`, the tables a foreign key's action writes in turn. A name is matched as
21/// SQLite matches it, whatever its case: a trigger and a foreign key spell a table as they please.
22const ERRORS_QUERY: &str = "with recursive w(t) as ( \
23      select name from sqlite_schema where type in ('table', 'view') and name collate nocase in ({written}) \
24      union select s.name from sqlite_schema s join pragma_foreign_key_list(s.name) f join w on f.\"table\" = w.t collate nocase \
25        where s.type = 'table' and {cascades} and (f.on_delete in ('CASCADE', 'SET NULL', 'SET DEFAULT') or f.on_update in ('CASCADE', 'SET NULL', 'SET DEFAULT'))), \
26    keys(t, code, name, columns, expression) as ( \
27      select w.t, case i.origin when 'pk' then 'SQLITE_CONSTRAINT_PRIMARYKEY' else 'SQLITE_CONSTRAINT_UNIQUE' end, i.name, \
28        (select group_concat(name, ', ') from (select name from pragma_index_info(i.name) order by seqno)), \
29        exists (select 1 from pragma_index_xinfo(i.name) x where x.key and x.cid = -2) \
30      from w join pragma_index_list(w.t) i where i.\"unique\" \
31      union all select w.t, 'SQLITE_CONSTRAINT_PRIMARYKEY', null, (select group_concat(name, ', ') from (select name from pragma_table_info(w.t) where pk > 0 order by pk)), 0 \
32      from w where exists (select 1 from pragma_table_info(w.t) where pk > 0)) \
33    select 'open' as kind, 'trigger' as code, g.name as field, null as name from sqlite_schema g join w on g.tbl_name = w.t collate nocase where g.type = 'trigger' \
34    union all select 'name', code, 'constraint', name from keys where expression \
35    union all select 'name', code, 'columns', columns from keys where not expression and columns is not null \
36    union all select 'name', code, 'table', t from keys \
37    union all select 'name', 'SQLITE_CONSTRAINT_ROWID', 'columns', 'rowid' from w join pragma_table_list(w.t) l where l.type = 'table' and not l.wr \
38    union all select 'name', 'SQLITE_CONSTRAINT_ROWID', 'table', w.t from w join pragma_table_list(w.t) l where l.type = 'table' and not l.wr \
39    union all select 'name', 'SQLITE_CONSTRAINT_NOTNULL', 'columns', c.name from w join pragma_table_xinfo(w.t) c where c.\"notnull\" or c.pk > 0 \
40    union all select 'name', 'SQLITE_CONSTRAINT_NOTNULL', 'table', w.t from w \
41    union all select 'name', 'SQLITE_CONSTRAINT_DATATYPE', 'columns', c.name from w join pragma_table_list(w.t) l join pragma_table_xinfo(w.t) c where l.strict \
42    union all select 'name', 'SQLITE_CONSTRAINT_DATATYPE', 'table', w.t from w join pragma_table_list(w.t) l where l.strict";
43
44/// A string literal: a quote doubled.
45fn literal(s: &str) -> String {
46    format!("'{}'", s.replace('\'', "''"))
47}
48
49/// The names each error the statement may raise can carry: `Some(None)` where it may fire a
50/// trigger, or the parse named no table, or no table it writes.
51pub fn errors(analysis: &Analysis, host: &Host) -> Lazy<Option<Errors>> {
52    let Some(tables) = &analysis.tables else { return Some(None) };
53    // SQLite's tree names a table as its DDL does, with no schema: `my.table` is one name.
54    let written: Vec<String> = tables.write.iter().map(|t| literal(t)).collect();
55    if analysis.kind != Some(StatementKind::Select) && written.is_empty() {
56        return Some(None);
57    }
58    // An INSERT changes no key but as a REPLACE, which deletes, or through an upsert that updates.
59    // A REPLACE is the statement's own, or a key's the written table declares ON CONFLICT REPLACE,
60    // as SQLite parsed it.
61    let cascades = if written.is_empty() {
62        "0"
63    } else if analysis.kind != Some(StatementKind::Insert) || has_word(&analysis.rewritten.sql, Dialect::Sqlite, &["update", "replace"]) || crate::sqlite::declares_replace(analysis, host)? {
64        "1"
65    } else {
66        "0"
67    };
68    let query = ERRORS_QUERY.replace("{cascades}", cascades).replace("{written}", &if written.is_empty() { "null".to_string() } else { written.join(", ") });
69    let rows = host.query(&query, Vec::new(), Scope::Statement)?;
70    let Ok(rows) = rows else { return Some(None) };
71    Some(narrowed(&rows))
72}
73
74/// What [`ERRORS_QUERY`]'s rows say: nothing where one opens the statement. A name an extended
75/// code's error may carry is one the primary code's may too, which is the code sqlite3 and the
76/// sqlite package give, but for the constraint: given the primary code alone, the run time reads a
77/// failed CHECK's name or expression into it too, which the catalog does not hold. SQLite's message
78/// names a column `table.column`, which the run time splits at the first dot, so a table whose name
79/// holds one (`my.table`) is named otherwise there: nothing is narrowed then.
80fn narrowed(rows: &[Vec<Value>]) -> Option<Errors> {
81    let text = |row: &[Value], k: usize| row.get(k).and_then(Value::as_str).map(str::to_string);
82    let mut errors = Errors::default();
83    for row in rows {
84        match text(row, 0).as_deref() {
85            Some("name") => {
86                if let (Some(code), Some(field), Some(name)) = (text(row, 1), text(row, 2), text(row, 3)) {
87                    if field == "table" && name.contains('.') {
88                        return None;
89                    }
90                    errors.add(&code, &field, &name);
91                    if field != "constraint" {
92                        errors.add("SQLITE_CONSTRAINT", &field, &name);
93                    }
94                }
95            }
96            _ => return None,
97        }
98    }
99    Some(errors)
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use serde_json::json;
106
107    #[test]
108    fn a_name_is_the_primary_code_s_too_and_a_trigger_opens_the_statement() {
109        let rows = vec![vec![json!("name"), json!("SQLITE_CONSTRAINT_UNIQUE"), json!("columns"), json!("email")], vec![json!("name"), json!("SQLITE_CONSTRAINT_UNIQUE"), json!("table"), json!("users")]];
110        assert_eq!(
111            serde_json::to_value(narrowed(&rows)).unwrap(),
112            json!({ "SQLITE_CONSTRAINT": { "columns": ["email"], "table": ["users"] }, "SQLITE_CONSTRAINT_UNIQUE": { "columns": ["email"], "table": ["users"] } })
113        );
114        let mut open = rows.clone();
115        open.push(vec![json!("open"), json!("trigger"), json!("audit"), Value::Null]);
116        assert_eq!(narrowed(&open), None);
117        // An index's name is the extended code's alone: the primary code's may be a CHECK's.
118        let index = vec![vec![json!("name"), json!("SQLITE_CONSTRAINT_UNIQUE"), json!("constraint"), json!("users_lower_email")]];
119        assert_eq!(serde_json::to_value(narrowed(&index)).unwrap(), json!({ "SQLITE_CONSTRAINT_UNIQUE": { "constraint": ["users_lower_email"] } }));
120        // `UNIQUE constraint failed: my.table.k` reads as table `my`.
121        let dotted = vec![vec![json!("name"), json!("SQLITE_CONSTRAINT_UNIQUE"), json!("columns"), json!("k")], vec![json!("name"), json!("SQLITE_CONSTRAINT_UNIQUE"), json!("table"), json!("my.table")]];
122        assert_eq!(narrowed(&dotted), None);
123    }
124}