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 json_columns = Vec::new();
76 let mut pk_cols: Vec<(i64, usize)> = Vec::new();
77 let mut column_types: Vec<String> = Vec::new();
78 {
79 let mut stmt = conn.prepare(&format!("PRAGMA table_info({})", quote_ident(&name)))?;
80 let mut rows = stmt.query([])?;
81 while let Some(r) = rows.next()? {
82 let col: String = r.get(1)?;
83 let declared: String = r.get(2)?;
84 let pk: i64 = r.get(5)?;
85 if pk > 0 {
86 pk_cols.push((pk, columns.len()));
87 }
88 if declared.trim().eq_ignore_ascii_case("json")
91 || declared.trim().eq_ignore_ascii_case("jsonb")
92 {
93 json_columns.push(columns.len());
94 }
95 columns.push(col);
96 column_types.push(declared);
97 }
98 }
99 pk_cols.sort();
100 let pk = (pk_cols.len() == 1)
106 .then(|| pk_cols[0].1)
107 .or_else(|| (is_view && columns.len() == 1).then_some(0));
108
109 let mut fks = Vec::new();
112 {
113 let mut stmt =
114 conn.prepare(&format!("PRAGMA foreign_key_list({})", quote_ident(&name)))?;
115 let mut rows = stmt.query([])?;
116 while let Some(r) = rows.next()? {
117 let target: String = r.get(2)?;
118 let from: String = r.get(3)?;
119 let to: Option<String> = r.get(4)?;
120 if let Some(idx) = columns.iter().position(|c| *c == from) {
121 fks.push((idx, target, to.unwrap_or_default()));
122 }
123 }
124 }
125 for (field, container) in refs {
129 let col = match field.split_once('.') {
130 Some((table, col)) if table == name => col,
131 Some(_) => continue,
132 None => field.as_str(),
133 };
134 if let Some(idx) = columns.iter().position(|c| c == col)
135 && !fks.iter().any(|(i, _, _)| *i == idx)
136 && !(*container == name && pk == Some(idx))
139 {
140 fks.push((idx, container.clone(), String::new()));
141 }
142 }
143 out.push(TableSpec {
144 name,
145 columns,
146 pk,
147 fks,
148 json_columns,
149 column_types,
150 });
151 }
152 Ok(out)
153}
154
155fn fetch_rows_where(
158 conn: &Connection,
159 spec: &TableSpec,
160 where_sql: Option<&str>,
161) -> Result<Vec<RowSpec>, SqliteError> {
162 let cols = spec
163 .columns
164 .iter()
165 .map(|c| quote_ident(c))
166 .collect::<Vec<_>>()
167 .join(", ");
168 let table = quote_ident(&spec.name);
169 let filter = match where_sql {
170 Some(w) => format!(" WHERE {w}"),
171 None => String::new(),
172 };
173 let with_rowid = format!("SELECT rowid, {cols} FROM {table}{filter} ORDER BY rowid");
179 if let Ok(mut stmt) = conn.prepare(&with_rowid) {
180 let mut rows = stmt.query([])?;
181 let mut out = Vec::new();
182 while let Some(r) = rows.next()? {
183 let rowid: i64 = r.get(0)?;
184 let values: Vec<Value> = (0..spec.columns.len())
185 .map(|i| to_value(r.get_ref(i + 1).expect("column in range")))
186 .collect();
187 out.push(RowSpec {
188 rowid: Some(rowid),
189 values,
190 });
191 }
192 return Ok(out);
193 }
194 let order = match spec.pk {
198 Some(i) => quote_ident(&spec.columns[i]),
199 None => cols.clone(),
200 };
201 let mut stmt = conn.prepare(&format!(
202 "SELECT {cols} FROM {table}{filter} ORDER BY {order}"
203 ))?;
204 let mut rows = stmt.query([])?;
205 let mut out = Vec::new();
206 let mut rowid = 0i64;
207 while let Some(r) = rows.next()? {
208 rowid += 1;
209 let values: Vec<Value> = (0..spec.columns.len())
210 .map(|i| to_value(r.get_ref(i).expect("column in range")))
211 .collect();
212 out.push(RowSpec {
213 rowid: Some(rowid),
214 values,
215 });
216 }
217 Ok(out)
218}
219
220fn fetch_rows_keyed(
231 conn: &Connection,
232 spec: &TableSpec,
233 filter: Option<&str>,
234 col: Option<usize>,
235 values: &[Value],
236) -> Result<Vec<RowSpec>, String> {
237 use rusqlite::types::Value as Sql;
238 let column = match col.or(spec.pk) {
239 Some(i) => quote_ident(&spec.columns[i]),
240 None => "rowid".to_string(),
241 };
242 let mut binds: Vec<Sql> = Vec::new();
243 for v in values {
244 match v {
245 Value::Int(i) => {
246 binds.push(Sql::Integer(*i));
247 binds.push(Sql::Text(i.to_string()));
248 }
249 Value::Float(f) => {
250 binds.push(Sql::Real(*f));
251 binds.push(Sql::Text(v.to_string()));
252 }
253 Value::Bool(b) => binds.push(Sql::Integer(*b as i64)),
254 Value::Null => {}
255 other => {
256 let text = other.to_string();
257 if let Ok(i) = text.parse::<i64>() {
258 binds.push(Sql::Integer(i));
259 } else if let Ok(f) = text.parse::<f64>() {
260 binds.push(Sql::Real(f));
261 }
262 binds.push(Sql::Text(text));
263 }
264 }
265 }
266 if binds.is_empty() {
267 return Ok(Vec::new());
268 }
269 let cols = spec
270 .columns
271 .iter()
272 .map(|c| quote_ident(c))
273 .collect::<Vec<_>>()
274 .join(", ");
275 let marks = vec!["?"; binds.len()].join(", ");
276 let filter = match filter {
277 Some(w) => format!("({w}) AND "),
278 None => String::new(),
279 };
280 let sql = format!(
281 "SELECT rowid, {cols} FROM {} WHERE {filter}{column} IN ({marks}) ORDER BY rowid",
282 quote_ident(&spec.name)
283 );
284 let mut stmt = conn.prepare(&sql).map_err(|e| e.to_string())?;
285 let mut rows = stmt
286 .query(rusqlite::params_from_iter(binds.iter()))
287 .map_err(|e| e.to_string())?;
288 let mut out = Vec::new();
289 while let Some(r) = rows.next().map_err(|e| e.to_string())? {
290 let rowid: i64 = r.get(0).map_err(|e| e.to_string())?;
291 let values: Vec<Value> = (0..spec.columns.len())
292 .map(|i| to_value(r.get_ref(i + 1).expect("column in range")))
293 .collect();
294 out.push(RowSpec {
295 rowid: Some(rowid),
296 values,
297 });
298 }
299 Ok(out)
300}
301
302fn index_rows_per_key(conn: &Connection, table: &str, column: &str) -> Result<u64, String> {
307 let mut list = conn
308 .prepare(&format!("PRAGMA index_list({})", quote_ident(table)))
309 .map_err(|e| e.to_string())?;
310 let names: Vec<String> = list
311 .query_map([], |r| r.get::<_, String>(1))
312 .map_err(|e| e.to_string())?
313 .filter_map(Result::ok)
314 .collect();
315 for idx in names {
316 let first: Option<String> = conn
317 .query_row(
318 &format!("PRAGMA index_info({})", quote_ident(&idx)),
319 [],
320 |r| r.get(2),
321 )
322 .ok();
323 if first.as_deref() != Some(column) {
324 continue;
325 }
326 let stat: String = conn
327 .query_row(
328 "SELECT stat FROM sqlite_stat1 WHERE tbl = ?1 AND idx = ?2",
329 [table, idx.as_str()],
330 |r| r.get(0),
331 )
332 .map_err(|e| e.to_string())?;
333 return stat
334 .split_whitespace()
335 .nth(1)
336 .and_then(|t| t.parse().ok())
337 .ok_or_else(|| "no per-key figure in sqlite_stat1".to_string());
338 }
339 Err(format!("no index opens with {column}"))
340}
341
342impl SqliteAdapter {
343 pub fn open(path: &std::path::Path) -> Result<Self, SqliteError> {
347 Self::open_impl(path, None, &[])
348 }
349
350 pub fn open_with_refs(
354 path: &std::path::Path,
355 refs: &[(String, String)],
356 ) -> Result<Self, SqliteError> {
357 Self::open_impl(path, None, refs)
358 }
359
360 pub fn open_filtered(
363 path: &std::path::Path,
364 table: &str,
365 where_sql: &str,
366 ) -> Result<Self, SqliteError> {
367 Self::open_impl(path, Some((table.to_string(), where_sql.to_string())), &[])
368 }
369
370 pub fn open_filtered_with_refs(
372 path: &std::path::Path,
373 table: &str,
374 where_sql: &str,
375 refs: &[(String, String)],
376 ) -> Result<Self, SqliteError> {
377 Self::open_impl(path, Some((table.to_string(), where_sql.to_string())), refs)
378 }
379
380 fn open_impl(
381 path: &std::path::Path,
382 filter: Option<(String, String)>,
383 refs: &[(String, String)],
384 ) -> Result<Self, SqliteError> {
385 let conn = std::rc::Rc::new(Connection::open_with_flags(
386 path,
387 rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
388 )?);
389 let specs = specs(&conn, refs)?;
390 let (whole, keyed, stats, listed) = (conn.clone(), conn.clone(), conn.clone(), conn);
391 let mut model = RelationalModel::lazy(
392 specs,
393 Box::new(move |_, spec| {
394 fetch_rows_where(&whole, spec, None).map_err(|e| e.to_string())
395 }),
396 )
397 .with_key_fetcher(Box::new(move |_, spec, col, values| {
399 fetch_rows_keyed(&keyed, spec, None, col, values)
400 }))
401 .with_estimator(std::rc::Rc::new(move |_, spec, equals| {
408 let stat: String = stats
409 .query_row(
410 "SELECT stat FROM sqlite_stat1 WHERE tbl = ?1 \
411 ORDER BY idx IS NULL DESC LIMIT 1",
412 [spec.name.as_str()],
413 |r| r.get(0),
414 )
415 .map_err(|e| e.to_string())?;
416 let n: u64 = stat
417 .split_whitespace()
418 .next()
419 .and_then(|t| t.parse().ok())
420 .ok_or("no row count in sqlite_stat1")?;
421 let mut per_key: Option<u64> = None;
426 for (col, _) in equals {
427 let column = &spec.columns[*col];
428 if let Ok(k) = index_rows_per_key(&stats, &spec.name, column) {
429 per_key = Some(per_key.map_or(k, |p| p.min(k)));
430 }
431 }
432 Ok(quarb::Estimate {
433 nodes: match (equals.is_empty(), per_key) {
434 (true, _) => (n, n),
435 (false, Some(k)) => (0, k.min(n)),
436 (false, None) => (0, n),
437 },
438 bytes: None,
439 requests: Some(0),
440 latency: quarb::Latency::Local,
441 confidence: quarb::Confidence::Guess,
442 })
443 }));
444 if let Some((table, where_sql)) = filter {
447 model = model.with_filtered_listing(
448 &table,
449 Box::new(move |_, spec| {
450 fetch_rows_where(&listed, spec, Some(&where_sql)).map_err(|e| e.to_string())
451 }),
452 );
453 }
454 Ok(SqliteAdapter { model })
455 }
456
457 pub fn from_bytes(bytes: &[u8]) -> Result<Self, SqliteError> {
462 let mut conn = Connection::open_in_memory()?;
463 conn.deserialize_read_exact(rusqlite::MAIN_DB, bytes, bytes.len(), true)?;
464 Self::load(&conn)
465 }
466
467 pub fn load(conn: &Connection) -> Result<Self, SqliteError> {
470 Self::load_with_refs(conn, &[])
471 }
472
473 pub fn load_with_refs(
475 conn: &Connection,
476 refs: &[(String, String)],
477 ) -> Result<Self, SqliteError> {
478 let mut input = Vec::new();
479 for spec in specs(conn, refs)? {
480 let rows = fetch_rows_where(conn, &spec, None)?;
481 input.push((spec, rows));
482 }
483 Ok(SqliteAdapter {
484 model: RelationalModel::build(input),
485 })
486 }
487
488 pub fn prefetch(&self, table: &str) -> Result<(), String> {
493 self.model.prefetch(table)
494 }
495
496 pub fn locator(&self, node: NodeId) -> String {
497 self.model.locator(node)
498 }
499}
500
501fn unique_key(conn: &Connection, table: &str, cols: &[String]) -> Result<bool, SqliteError> {
509 use std::collections::HashSet;
510 let want: HashSet<&str> = cols.iter().map(|s| s.as_str()).collect();
511 if want.is_empty() {
512 return Ok(false);
513 }
514 let mut stmt = conn.prepare(&format!("PRAGMA table_info({})", quote_ident(table)))?;
516 let mut pk: HashSet<String> = HashSet::new();
517 let mut rows = stmt.query([])?;
518 while let Some(r) = rows.next()? {
519 let name: String = r.get(1)?;
520 let ord: i64 = r.get(5)?;
521 if ord > 0 {
522 pk.insert(name);
523 }
524 }
525 if !pk.is_empty() && pk.iter().all(|c| want.contains(c.as_str())) {
526 return Ok(true);
527 }
528 let mut stmt = conn.prepare(&format!("PRAGMA index_list({})", quote_ident(table)))?;
530 let mut uniques: Vec<String> = Vec::new();
531 let mut rows = stmt.query([])?;
532 while let Some(r) = rows.next()? {
533 let name: String = r.get(1)?;
534 let is_unique: i64 = r.get(2)?;
535 let partial: i64 = r.get(4).unwrap_or(0);
536 if is_unique == 1 && partial == 0 {
537 uniques.push(name);
538 }
539 }
540 for idx in uniques {
541 let mut stmt = conn.prepare(&format!("PRAGMA index_info({})", quote_ident(&idx)))?;
542 let mut cols_of: Vec<String> = Vec::new();
543 let mut rows = stmt.query([])?;
544 while let Some(r) = rows.next()? {
545 cols_of.push(r.get(2)?);
546 }
547 if !cols_of.is_empty() && cols_of.iter().all(|c| want.contains(c.as_str())) {
548 return Ok(true);
549 }
550 }
551 Ok(false)
552}
553
554pub fn column_catalog(
563 path: &std::path::Path,
564 tables: &[&str],
565) -> Result<Vec<(String, bool, bool)>, SqliteError> {
566 let conn = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
567 let mut catalog = Vec::new();
568 for table in tables {
569 let mut stmt = conn.prepare(&format!("PRAGMA table_info({})", quote_ident(table)))?;
570 let rows = stmt.query_map([], |r| Ok((r.get::<_, String>(1)?, r.get::<_, String>(2)?)))?;
571 for row in rows {
572 let (name, declared) = row?;
573 let json = matches!(
577 declared.trim().to_ascii_lowercase().as_str(),
578 "json" | "jsonb"
579 );
580 catalog.push((name, numeric_affinity(&declared), json));
581 }
582 }
583 Ok(catalog)
584}
585
586fn numeric_affinity(declared: &str) -> bool {
589 let d = declared.to_ascii_uppercase();
590 if d.contains("INT") {
591 true
592 } else if d.contains("CHAR") || d.contains("CLOB") || d.contains("TEXT") {
593 false
594 } else {
595 !(d.contains("BLOB") || d.trim().is_empty())
596 }
597}
598
599pub fn raw_query(
600 path: &std::path::Path,
601 sql: &str,
602 order_table: Option<&str>,
603 join_left: Option<(&str, &[String])>,
604) -> Result<(Vec<String>, Vec<Vec<Value>>), SqliteError> {
605 let conn = Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)?;
606 if let Some((table, cols)) = join_left
611 && !unique_key(&conn, table, cols)?
612 {
613 return Err(SqliteError::Plan(format!(
614 "join ON does not bind {table} by a unique key; \
615 the SQL JOIN would multiply rows"
616 )));
617 }
618 let sql = match order_table {
619 Some(t) => {
620 let key = specs(&conn, &[])?
621 .into_iter()
622 .find(|s| s.name == t)
623 .and_then(|s| s.pk.map(|i| s.columns[i].clone()))
624 .unwrap_or_else(|| "rowid".to_string());
625 format!("{sql} ORDER BY {t}.{key}")
626 }
627 None => sql.to_string(),
628 };
629 quarb_relational::record_executed(&sql);
633 let mut stmt = conn.prepare(&sql)?;
634 let cols: Vec<String> = stmt.column_names().iter().map(|c| c.to_string()).collect();
635 let n = cols.len();
636 let mut rows = stmt.query([])?;
637 let mut out = Vec::new();
638 while let Some(r) = rows.next()? {
639 out.push(
640 (0..n)
641 .map(|i| to_value(r.get_ref(i).expect("column in range")))
642 .collect(),
643 );
644 }
645 Ok((cols, out))
646}
647
648impl AstAdapter for SqliteAdapter {
649 quarb::forward_ast_adapter!(model);
652}