1use 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
16const 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
44fn literal(s: &str) -> String {
46 format!("'{}'", s.replace('\'', "''"))
47}
48
49pub fn errors(analysis: &Analysis, host: &Host) -> Lazy<Option<Errors>> {
52 let Some(tables) = &analysis.tables else { return Some(None) };
53 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 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
74fn 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 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 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}