1use quarb::{AstAdapter, NodeId, Value};
16use quarb_relational::{RelationalModel, RowSpec, TableSpec};
17use rusqlite::Connection;
18use rusqlite::types::ValueRef;
19
20#[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
29pub 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
44fn quote_ident(name: &str) -> String {
48 quarb_relational::quote_double(name)
49}
50
51fn 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 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 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 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 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 && !(*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
142fn 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 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 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
207fn 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 pub fn open(path: &std::path::Path) -> Result<Self, SqliteError> {
294 Self::open_impl(path, None, &[])
295 }
296
297 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 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 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 .with_key_fetcher(Box::new(move |_, spec, col, values| {
346 fetch_rows_keyed(&keyed, spec, None, col, values)
347 }));
348 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 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 pub fn load(conn: &Connection) -> Result<Self, SqliteError> {
374 Self::load_with_refs(conn, &[])
375 }
376
377 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 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
405fn 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 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 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
458pub 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
483fn 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 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 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}