Skip to main content

reylo_engine_sqlite/
capabilities.rs

1//! What running a SQLite statement may do ([`Capabilities`]), an upper bound: the tables it reads
2//! and writes as SQLite resolved them, through views too, and, from the database's schema, the
3//! tables a foreign key's action writes, the `sqlite_sequence` an AUTOINCREMENT table's insert
4//! writes, and a trigger's body, which the engine does not read and so may touch any table.
5
6use crate::sqlite_tree::{Node, Sel, Tree};
7use reylo_engine_core::api::{Analysis, Scope};
8use crate::host::Host;
9use reylo_engine_core::host::Lazy;
10use reylo_engine_core::dialect::Dialect;
11use reylo_engine_core::errors::has_word;
12use reylo_engine_core::types::{Access, Capabilities, CapabilityTables, StatementKind};
13use serde_json::Value;
14
15/// One row `('trigger', table)` for each trigger, `('autoincrement', table)` for each table with an
16/// AUTOINCREMENT key, `('virtual', table, sql)` for each virtual table, and `('key', child, parent,
17/// on update, on delete)` for each foreign key.
18pub const SCHEMA_QUERY: &str = "select 'trigger', tbl_name, null, null, null from sqlite_schema where type = 'trigger' \
19    union all select 'autoincrement', name, null, null, null from sqlite_schema where type = 'table' and sql like '%autoincrement%' \
20    union all select 'virtual', name, lower(sql), null, null from sqlite_schema where type = 'table' and sql like 'create virtual table%' \
21    union all select 'key', m.name, f.\"table\", f.on_update, f.on_delete from sqlite_schema m join pragma_foreign_key_list(m.name) f where m.type = 'table'";
22
23/// SQLite's own functions, as its core, its date and time, math, JSON, window and aggregate
24/// functions, and the extensions the engine's build holds, name them: a call to any other is to a
25/// function the application registers, whose code the engine does not read.
26const BUILT_IN: &[&str] = &[
27    "abs", "changes", "char", "coalesce", "concat", "concat_ws", "format", "glob", "hex", "if", "ifnull", "iif", "instr", "last_insert_rowid", "length", "like", "likelihood", "likely", "lower", "ltrim", "max", "min", "nullif", "octet_length", "printf", "quote", "random", "randomblob", "replace", "round", "rtrim", "sign", "soundex", "sqlite_compileoption_get", "sqlite_compileoption_used", "sqlite_offset", "sqlite_source_id", "sqlite_version", "substr", "substring", "total_changes", "trim", "typeof", "unhex", "unicode", "unistr", "unistr_quote", "unlikely", "upper", "zeroblob",
28    "date", "time", "datetime", "julianday", "unixepoch", "strftime", "timediff", "current_date", "current_time", "current_timestamp",
29    "avg", "count", "group_concat", "string_agg", "sum", "total", "median", "percentile", "percentile_cont", "percentile_disc",
30    "row_number", "rank", "dense_rank", "percent_rank", "cume_dist", "ntile", "lag", "lead", "first_value", "last_value", "nth_value",
31    "acos", "acosh", "asin", "asinh", "atan", "atan2", "atanh", "ceil", "ceiling", "cos", "cosh", "degrees", "exp", "floor", "ln", "log", "log10", "log2", "mod", "pi", "pow", "power", "radians", "sin", "sinh", "sqrt", "tan", "tanh", "trunc",
32    "json", "jsonb", "json_array", "jsonb_array", "json_array_length", "json_error_position", "json_extract", "jsonb_extract", "json_insert", "jsonb_insert", "json_object", "jsonb_object", "json_patch", "jsonb_patch", "json_pretty", "json_remove", "jsonb_remove", "json_replace", "jsonb_replace", "json_set", "jsonb_set", "json_type", "json_valid", "json_quote", "json_group_array", "jsonb_group_array", "json_group_object", "jsonb_group_object", "json_each", "json_tree", "jsonb_each", "jsonb_tree",
33    "highlight", "snippet", "bm25", "matchinfo", "offsets", "fts3_tokenizer", "rtreecheck", "rtreenode", "rtreedepth", "generate_series",
34    "geopoly_area", "geopoly_bbox", "geopoly_blob", "geopoly_ccw", "geopoly_contains_point", "geopoly_group_bbox", "geopoly_json", "geopoly_overlap", "geopoly_regular", "geopoly_svg", "geopoly_within", "geopoly_xform",
35];
36
37/// What a statement may do as far as the statement alone says: the tables it reads, through views
38/// too, and writes, and the functions it calls. [`refine`] adds what the schema says.
39pub fn of_statement(t: &Tree) -> Capabilities {
40    let mut capabilities = Capabilities::default();
41    let mut walk = Walk::default();
42    if let Some(s) = &t.statement {
43        walk.sel(s);
44    }
45    for c in t.returning.iter().flatten() {
46        walk.node(&c.expr);
47    }
48    if let Some(dml) = &t.dml {
49        let upsert = dml.upserts.iter().flat_map(|u| u.set.iter().map(|s| &s.expr).chain(&u.where_));
50        for n in dml.values.iter().flatten().chain(dml.set.iter().map(|s| &s.expr)).chain(&dml.where_).chain(upsert) {
51            walk.node(n);
52        }
53    }
54    let Walk { read, ctes, functions } = walk;
55    for table in read.into_iter().filter(|table| !ctes.iter().any(|cte| cte.eq_ignore_ascii_case(table))) {
56        capabilities.touch(table, Access::Read);
57    }
58    if let Some(dml) = &t.dml {
59        capabilities.touch(dml.table.clone(), Access::Write);
60    }
61    for f in &functions {
62        let name = f.to_ascii_lowercase();
63        if name == "load_extension" {
64            // Loads code the engine cannot read, from a file.
65            unread(&mut capabilities);
66        } else if let Some(pragma) = name.strip_prefix("pragma_") {
67            // A PRAGMA's table-valued form reads what the PRAGMA does: every table's rows, for one
68            // that checks them.
69            if !SCHEMA_PRAGMAS.contains(&pragma) {
70                capabilities.unknown_tables();
71            }
72        } else if !BUILT_IN.contains(&name.as_str()) {
73            unread(&mut capabilities);
74        }
75    }
76    capabilities
77}
78
79/// The PRAGMAs that, read without a value, answer with a setting or the schema alone.
80const SCHEMA_PRAGMAS: &[&str] = &[
81    "table_info", "table_xinfo", "table_list", "index_list", "index_info", "index_xinfo", "foreign_key_list", "database_list", "collation_list", "function_list", "module_list", "pragma_list", "compile_options",
82    "user_version", "application_id", "schema_version", "data_version", "page_count", "page_size", "max_page_count", "freelist_count", "encoding", "journal_mode", "journal_size_limit", "foreign_keys", "busy_timeout",
83    "cache_size", "cache_spill", "synchronous", "temp_store", "auto_vacuum", "automatic_index", "case_sensitive_like", "cell_size_check", "checkpoint_fullfsync", "defer_foreign_keys", "fullfsync", "hard_heap_limit",
84    "ignore_check_constraints", "legacy_alter_table", "locking_mode", "mmap_size", "query_only", "read_uncommitted", "recursive_triggers", "reverse_unordered_selects", "secure_delete", "soft_heap_limit", "threads", "trusted_schema", "writable_schema",
85];
86
87/// The PRAGMAs among them that take a table or an index to describe, in parentheses.
88const TABLE_ARGUMENT_PRAGMAS: &[&str] = &["table_info", "table_xinfo", "table_list", "index_list", "index_info", "index_xinfo", "foreign_key_list"];
89
90/// A PRAGMA's name, lowercased and its schema left off: `integrity_check` in
91/// `PRAGMA main.integrity_check(t)`.
92fn pragma_name(sql: &str) -> String {
93    // Past the comments before the statement, which may hold the word itself.
94    let mut rest = sql.trim_start();
95    loop {
96        if let Some(line) = rest.strip_prefix("--") {
97            rest = line.split_once('\n').map_or("", |(_, after)| after).trim_start();
98        } else if let Some(block) = rest.strip_prefix("/*") {
99            rest = block.split_once("*/").map_or("", |(_, after)| after).trim_start();
100        } else {
101            break;
102        }
103    }
104    let lower = rest.to_ascii_lowercase();
105    let after = lower.strip_prefix("pragma").unwrap_or("").trim_start();
106    let name: String = after.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '.').collect();
107    name.rsplit('.').next().unwrap_or("").to_string()
108}
109
110/// What a command (DDL, a PRAGMA, a transaction's control) does, by its first keyword.
111pub fn of_command(sql: &str, kind: &str) -> Capabilities {
112    let mut capabilities = Capabilities::default();
113    match kind {
114        "begin" | "commit" | "end" | "rollback" | "savepoint" | "release" => capabilities.transaction = true,
115        "pragma" => {
116            let name = pragma_name(sql);
117            // A value sets something: on the connection (`foreign_keys`), or in the file
118            // (`user_version`, `journal_mode`); a table to describe is no value.
119            let sets = sql.contains('=') || sql.contains('(') && !TABLE_ARGUMENT_PRAGMAS.contains(&name.as_str());
120            capabilities.session = sets;
121            capabilities.ddl = sets;
122            // Any PRAGMA but one of a setting or the schema may read every table's rows
123            // (`integrity_check`, `foreign_key_check`) or change the file (`optimize`, which may run
124            // ANALYZE, `wal_checkpoint`, `incremental_vacuum`), with or without an argument.
125            if !SCHEMA_PRAGMAS.contains(&name.as_str()) {
126                capabilities.ddl = true;
127                capabilities.unknown_tables();
128            }
129        }
130        // A plan: no rows of a table.
131        "explain" => {}
132        // A database file, attached to the connection or let go.
133        "attach" | "detach" => {
134            capabilities.session = true;
135            capabilities.external = true;
136        }
137        // `VACUUM INTO` writes another file.
138        "vacuum" => {
139            capabilities.ddl = true;
140            capabilities.unknown_tables();
141            if has_word(sql, Dialect::Sqlite, &["into"]) {
142                capabilities.external = true;
143            }
144        }
145        "create" | "drop" | "alter" | "reindex" | "analyze" => {
146            capabilities.ddl = true;
147            capabilities.unknown_tables();
148        }
149        _ => {
150            unread(&mut capabilities);
151            capabilities.transaction = true;
152        }
153    }
154    capabilities
155}
156
157/// The modules SQLite builds in, whose virtual tables run no code of the application's.
158const BUILT_IN_MODULES: &[&str] = &["fts3", "fts4", "fts5", "rtree", "rtree_i32", "geopoly"];
159
160/// The statement's capabilities, with what the database's schema adds: a trigger on a table it
161/// writes runs code the engine does not read, and so does a virtual table of a module the
162/// application registers; a write to a built-in virtual table writes the tables that hold its index,
163/// which the statement does not name; a foreign key's action writes the table that refers to it,
164/// and its check reads the other side; an AUTOINCREMENT table's insert counts in `sqlite_sequence`.
165pub fn refine(analysis: &Analysis, host: &Host) -> Lazy<Option<Capabilities>> {
166    let Some(mut capabilities) = analysis.capabilities.clone() else { return Some(None) };
167    let CapabilityTables::Named(tables) = &capabilities.tables else { return Some(Some(capabilities)) };
168    let written: Vec<String> = tables.iter().filter(|(_, access)| **access == Access::Write).map(|(name, _)| name.clone()).collect();
169    let named: Vec<String> = tables.keys().cloned().collect();
170    if named.is_empty() {
171        return Some(Some(capabilities));
172    }
173    let Ok(rows) = host.query(SCHEMA_QUERY, Vec::new(), Scope::Session)? else {
174        unread(&mut capabilities);
175        return Some(Some(capabilities));
176    };
177    let text = |row: &Vec<Value>, k: usize| row.get(k).and_then(Value::as_str).map(str::to_ascii_lowercase);
178    let tagged = |tag: &'static str| rows.iter().filter(move |row| row.first().and_then(Value::as_str) == Some(tag));
179    let is = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
180    for row in tagged("virtual") {
181        let (Some(table), Some(sql)) = (text(row, 1), text(row, 2)) else { continue };
182        if !named.iter().any(|n| is(n, &table)) {
183            continue;
184        }
185        let module = sql.split_once(" using ").map(|(_, rest)| rest.trim_start().split(|c: char| !c.is_alphanumeric() && c != '_').next().unwrap_or("").to_string()).unwrap_or_default();
186        if !BUILT_IN_MODULES.contains(&module.as_str()) {
187            unread(&mut capabilities);
188            return Some(Some(capabilities));
189        }
190        if written.iter().any(|w| is(w, &table)) {
191            capabilities.unknown_tables();
192            return Some(Some(capabilities));
193        }
194    }
195    if written.is_empty() {
196        return Some(Some(capabilities));
197    }
198    // An INSERT changes no key a foreign key refers to but as a REPLACE, which deletes the row it
199    // conflicts with (`INSERT OR REPLACE`, `REPLACE`, or a key the table declares ON CONFLICT
200    // REPLACE, as SQLite parsed it), or an upsert's UPDATE; a delete and an update may, and a key's
201    // action may set off another's.
202    let insert = analysis.kind == Some(StatementKind::Insert);
203    let cascades = !insert || has_word(&analysis.rewritten.sql, Dialect::Sqlite, &["replace", "update"]) || crate::sqlite::declares_replace(analysis, host)?;
204    let acts = |action: Option<String>| action.is_some_and(|a| matches!(a.as_str(), "cascade" | "set null" | "set default"));
205    // Only an insert takes a new AUTOINCREMENT key, and only into the table it names.
206    if insert && written.iter().any(|w| tagged("autoincrement").any(|row| text(row, 1).is_some_and(|t| is(&t, w)))) {
207        capabilities.touch("sqlite_sequence", Access::Write);
208    }
209    let mut reached: Vec<String> = Vec::new();
210    let mut queue = written;
211    while let Some(table) = queue.pop() {
212        if reached.iter().any(|t| is(t, &table)) {
213            continue;
214        }
215        reached.push(table.clone());
216        capabilities.touch(table.clone(), Access::Write);
217        if tagged("trigger").any(|row| text(row, 1).is_some_and(|t| is(&t, &table))) {
218            unread(&mut capabilities);
219            return Some(Some(capabilities));
220        }
221        for row in tagged("key") {
222            let (Some(child), Some(parent)) = (text(row, 1), text(row, 2)) else { continue };
223            // The check of a key the written table holds reads the table it refers to.
224            if is(&child, &table) {
225                capabilities.touch(parent.clone(), Access::Read);
226            }
227            // A change to a key the table holds sets off the key's action in the tables that refer
228            // to it, or its check, which reads them.
229            if cascades && is(&parent, &table) {
230                if acts(text(row, 3)) || acts(text(row, 4)) {
231                    queue.push(child.clone());
232                } else {
233                    capabilities.touch(child.clone(), Access::Read);
234                }
235            }
236        }
237    }
238    Some(Some(capabilities))
239}
240
241/// Code the engine does not read, which may touch any table, change what the database defines or
242/// the connection, and reach past it.
243fn unread(capabilities: &mut Capabilities) {
244    capabilities.unknown_tables();
245    capabilities.ddl = true;
246    capabilities.session = true;
247    capabilities.external = true;
248}
249
250/// The tables a statement reads, a view's included with what it reads, the names of its WITH
251/// queries, and the functions it calls.
252#[derive(Default)]
253struct Walk {
254    read: Vec<String>,
255    ctes: Vec<String>,
256    functions: Vec<String>,
257}
258
259impl Walk {
260    fn node(&mut self, n: &Node) {
261        if n.op == "function" {
262            if let Some(name) = &n.name {
263                self.functions.push(name.clone());
264            }
265        }
266        if let Some(q) = &n.select {
267            self.sel(q);
268        }
269        for child in n.left.iter().chain(&n.right) {
270            self.node(child);
271        }
272        for child in n.list.iter().chain(&n.args).chain(&n.order_by).chain(&n.partition_by) {
273            self.node(child);
274        }
275    }
276
277    fn sel(&mut self, s: &Sel) {
278        for c in &s.columns {
279            self.node(&c.expr);
280        }
281        for f in &s.from {
282            if f.cte {
283                self.ctes.extend(f.table.clone());
284            }
285            // A view keeps the name the statement writes, and reads what its subquery does.
286            if !f.cte && !f.tab_func {
287                self.read.extend(f.table.clone());
288            }
289            if f.tab_func {
290                self.functions.extend(f.table.clone());
291            }
292            if let Some(q) = &f.subquery {
293                self.sel(q);
294            }
295            for n in f.args.iter().chain(&f.on) {
296                self.node(n);
297            }
298        }
299        for n in s.rows.iter().flatten().chain(&s.where_).chain(&s.group_by).chain(&s.having).chain(&s.order_by).chain(&s.limit).chain(&s.offset) {
300            self.node(n);
301        }
302        if let Some(prior) = &s.prior {
303            self.sel(prior);
304        }
305    }
306}