1use std::borrow::Cow;
4use std::path::{Path, PathBuf};
5use std::sync::Mutex;
6use std::time::{Duration, Instant};
7
8use rusqlite::types::Value as SqlValue;
9use rusqlite::{Connection, OpenFlags, OptionalExtension};
10
11use crate::error::{Db, Error, Result};
12use crate::slices::{check_entry, cmp_keys, is_hash, is_instant, version_slice, Constraint, Kind, Pattern};
13use crate::sqlite_sql::L;
14use crate::{not_canonical_class, Binding, ClassBinding, Namespace, SliceMember, SliceValue, Store, Version};
15use datumesh_core::json::{self, Value};
16use datumesh_core::lexical::{check_dns_name, check_function_name, check_hex, check_instant};
17use datumesh_core::{
18 keys_from_response, sha256_hex, verify, Arg, Args, Cell, ClassDescriptor, ErrorCode, FunctionDescriptor, Keys,
19 Manifest, Receipt, Resolver, Scalar, Slice, Type,
20};
21
22#[derive(Clone, Debug, PartialEq, Eq)]
26pub struct SqliteOptions {
27 max_size: usize,
28 busy_timeout: Duration,
29 durable: bool,
30}
31
32impl Default for SqliteOptions {
33 fn default() -> SqliteOptions {
34 SqliteOptions::new()
35 }
36}
37
38impl SqliteOptions {
39 pub fn new() -> SqliteOptions {
43 SqliteOptions { max_size: 8, busy_timeout: Duration::from_secs(30), durable: true }
44 }
45
46 pub fn max_size(mut self, n: usize) -> SqliteOptions {
50 self.max_size = n.max(1);
51 self
52 }
53
54 pub fn busy_timeout(mut self, d: Duration) -> SqliteOptions {
59 self.busy_timeout = d;
60 self
61 }
62
63 pub fn durable(mut self, yes: bool) -> SqliteOptions {
69 self.durable = yes;
70 self
71 }
72}
73
74pub struct SqliteStore {
92 path: PathBuf,
93 options: SqliteOptions,
94 idle: Mutex<Vec<Connection>>,
95 writer: Mutex<()>,
99 existing: bool,
101}
102
103impl std::fmt::Debug for SqliteStore {
104 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105 f.debug_struct("SqliteStore").field("path", &self.path).finish_non_exhaustive()
106 }
107}
108
109struct Pooled<'a> {
111 store: &'a SqliteStore,
112 conn: Option<Connection>,
113}
114
115impl std::ops::Deref for Pooled<'_> {
116 type Target = Connection;
117 fn deref(&self) -> &Connection {
118 self.conn.as_ref().expect("a pooled connection")
119 }
120}
121
122impl Drop for Pooled<'_> {
123 fn drop(&mut self) {
124 if let Some(c) = self.conn.take() {
125 if c.is_autocommit() {
127 if let Ok(mut idle) = self.store.idle.lock() {
128 if idle.len() < self.store.options.max_size {
129 idle.push(c);
130 }
131 }
132 }
133 }
134 }
135}
136
137impl SqliteStore {
138 pub fn open(path: impl AsRef<Path>) -> Result<SqliteStore> {
143 SqliteStore::open_with(path, SqliteOptions::new())
144 }
145
146 pub fn open_with(path: impl AsRef<Path>, options: SqliteOptions) -> Result<SqliteStore> {
152 let store = SqliteStore {
153 path: path.as_ref().to_path_buf(),
154 options,
155 idle: Mutex::new(Vec::new()),
156 writer: Mutex::new(()),
157 existing: false,
158 };
159 let c = store.open_connection()?;
160 if let Ok(mut idle) = store.idle.lock() {
161 idle.push(c);
162 }
163 Ok(store)
164 }
165
166 pub fn open_existing(path: impl AsRef<Path>) -> Result<SqliteStore> {
173 let path = path.as_ref();
174 if !path.is_file() {
175 return Err(Error::Database(crate::error::DatabaseError::no_such_file(path)));
176 }
177 let store = SqliteStore {
178 path: path.to_path_buf(),
179 options: SqliteOptions::new(),
180 idle: Mutex::new(Vec::new()),
181 writer: Mutex::new(()),
182 existing: true,
183 };
184 let c = store.open_connection()?;
185 if let Ok(mut idle) = store.idle.lock() {
186 idle.push(c);
187 }
188 Ok(store)
189 }
190
191 pub fn connect(url: &str) -> Result<SqliteStore> {
195 SqliteStore::open(sqlite_path(url))
196 }
197
198 pub fn path(&self) -> &Path {
200 &self.path
201 }
202
203 fn open_connection(&self) -> Result<Connection> {
204 let mut flags = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX;
205 if !self.existing {
206 flags |= OpenFlags::SQLITE_OPEN_CREATE;
207 }
208 let c = Connection::open_with_flags(&self.path, flags).db()?;
209 c.busy_timeout(self.options.busy_timeout).db()?;
210 c.set_prepared_statement_cache_capacity(L::ALL.len() + 16);
211 if self.existing {
212 c.execute_batch("PRAGMA foreign_keys = ON").db()?;
214 return Ok(c);
215 }
216 let start = Instant::now();
220 loop {
221 match c.query_row("PRAGMA journal_mode = WAL", [], |r| r.get::<_, String>(0)) {
222 Ok(mode) if mode.eq_ignore_ascii_case("wal") => break,
223 Ok(mode) => return Err(Error::Config(format!("SQLite: journal mode WAL refused (it is {mode})"))),
224 Err(e) if is_busy(&e) && start.elapsed() < self.options.busy_timeout => {
225 std::thread::sleep(Duration::from_millis(5));
226 }
227 Err(e) => return Err(e).db(),
228 }
229 }
230 let sync = if self.options.durable { "FULL" } else { "NORMAL" };
231 c.execute_batch(&format!("PRAGMA foreign_keys = ON; PRAGMA synchronous = {sync};")).db()?;
232 Ok(c)
233 }
234
235 fn conn(&self) -> Result<Pooled<'_>> {
237 let idle = self.idle.lock().ok().and_then(|mut v| v.pop());
238 let conn = match idle {
239 Some(c) => c,
240 None => self.open_connection()?,
241 };
242 Ok(Pooled { store: self, conn: Some(conn) })
243 }
244
245 pub fn check_statements(&self) -> Result<usize> {
249 let c = self.open_connection()?;
250 for q in L::ALL {
251 c.prepare(q.sql()).db()?;
252 }
253 Ok(L::ALL.len())
254 }
255
256 pub(crate) fn raw(&self) -> Result<impl std::ops::Deref<Target = Connection> + '_> {
258 self.conn()
259 }
260
261 fn resolve<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<Option<T>>) -> Option<T> {
263 self.run(op, f).ok().flatten()
264 }
265
266 fn run<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
268 let result = self.conn().and_then(|c| f(&c));
269 if let Err(e @ Error::Database(_)) = &result {
270 tracing::error!(target: "datumesh_store", op, error = %e, "database failure");
271 }
272 result
273 }
274
275 fn write<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
278 self.run(op, |c| {
279 let v = self.locked_write(c, f)?;
280 self.bound_wal(c);
281 Ok(v)
282 })
283 }
284
285 fn locked_write<T>(&self, c: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
287 let _queue = self.writer.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
288 write(c, f)
289 }
290
291 fn bound_wal(&self, c: &Connection) {
299 let mut wal = self.path.clone().into_os_string();
300 wal.push("-wal");
301 if std::fs::metadata(&wal).is_ok_and(|m| m.len() > WAL_LIMIT) {
302 if let Err(e) = c.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(())) {
303 tracing::debug!(target: "datumesh_store", error = %e, "checkpoint deferred");
304 }
305 }
306 }
307
308 fn asof_version(&self, op: &'static str, q: L, cell_id: &str, asof: &str) -> Result<Option<Version>> {
310 check_hex(cell_id, 64, "cell_id")?;
311 check_instant(asof, "asof")?;
312 self.run(op, |c| {
313 c.prepare_cached(q.sql())
314 .db()?
315 .query_row(rusqlite::params![cell_id, asof], |r| version_row(r, cell_id))
316 .optional()
317 .db()
318 })
319 }
320
321 fn asof_with_receipt(
324 &self,
325 op: &'static str,
326 q: L,
327 cell_id: &str,
328 asof: &str,
329 ) -> Result<Option<(Version, Vec<u8>)>> {
330 check_hex(cell_id, 64, "cell_id")?;
331 check_instant(asof, "asof")?;
332 self.run(op, |c| {
333 c.prepare_cached(q.sql())
334 .db()?
335 .query_row(rusqlite::params![cell_id, asof], |r| Ok((version_row(r, cell_id)?, r.get(3)?)))
336 .optional()
337 .db()
338 })
339 }
340}
341
342const WAL_LIMIT: u64 = 64 << 20;
344
345pub(crate) fn write<T>(c: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
347 c.execute_batch("BEGIN IMMEDIATE").db()?;
348 let result = f(c).and_then(|v| c.execute_batch("COMMIT").db().map(|()| v));
349 if result.is_err() && !c.is_autocommit() {
350 let _ = c.execute_batch("ROLLBACK");
351 }
352 result
353}
354
355fn is_busy(e: &rusqlite::Error) -> bool {
356 matches!(e, rusqlite::Error::SqliteFailure(f, _) if f.code == rusqlite::ErrorCode::DatabaseBusy)
357}
358
359pub(crate) fn sqlite_path(url: &str) -> &str {
361 match url.strip_prefix("sqlite:") {
362 Some(rest) => rest.strip_prefix("//").unwrap_or(rest),
363 None => url,
364 }
365}
366
367pub(crate) fn result_code_name(code: std::os::raw::c_int) -> String {
369 let name = match code {
370 1 => "SQLITE_ERROR",
371 2 => "SQLITE_INTERNAL",
372 3 => "SQLITE_PERM",
373 4 => "SQLITE_ABORT",
374 5 => "SQLITE_BUSY",
375 6 => "SQLITE_LOCKED",
376 7 => "SQLITE_NOMEM",
377 8 => "SQLITE_READONLY",
378 9 => "SQLITE_INTERRUPT",
379 10 => "SQLITE_IOERR",
380 11 => "SQLITE_CORRUPT",
381 12 => "SQLITE_NOTFOUND",
382 13 => "SQLITE_FULL",
383 14 => "SQLITE_CANTOPEN",
384 15 => "SQLITE_PROTOCOL",
385 16 => "SQLITE_EMPTY",
386 17 => "SQLITE_SCHEMA",
387 18 => "SQLITE_TOOBIG",
388 19 => "SQLITE_CONSTRAINT",
389 20 => "SQLITE_MISMATCH",
390 21 => "SQLITE_MISUSE",
391 22 => "SQLITE_NOLFS",
392 23 => "SQLITE_AUTH",
393 24 => "SQLITE_FORMAT",
394 25 => "SQLITE_RANGE",
395 26 => "SQLITE_NOTADB",
396 261 => "SQLITE_BUSY_RECOVERY",
397 517 => "SQLITE_BUSY_SNAPSHOT",
398 773 => "SQLITE_BUSY_TIMEOUT",
399 262 => "SQLITE_LOCKED_SHAREDCACHE",
400 264 => "SQLITE_READONLY_RECOVERY",
401 520 => "SQLITE_READONLY_CANTLOCK",
402 270 => "SQLITE_CANTOPEN_NOTEMPDIR",
403 526 => "SQLITE_CANTOPEN_ISDIR",
404 782 => "SQLITE_CANTOPEN_FULLPATH",
405 267 => "SQLITE_CORRUPT_VTAB",
406 275 => "SQLITE_CONSTRAINT_CHECK",
407 531 => "SQLITE_CONSTRAINT_COMMITHOOK",
408 787 => "SQLITE_CONSTRAINT_FOREIGNKEY",
409 1043 => "SQLITE_CONSTRAINT_FUNCTION",
410 1299 => "SQLITE_CONSTRAINT_NOTNULL",
411 1555 => "SQLITE_CONSTRAINT_PRIMARYKEY",
412 1811 => "SQLITE_CONSTRAINT_TRIGGER",
413 2067 => "SQLITE_CONSTRAINT_UNIQUE",
414 2323 => "SQLITE_CONSTRAINT_VTAB",
415 2579 => "SQLITE_CONSTRAINT_ROWID",
416 3091 => "SQLITE_CONSTRAINT_DATATYPE",
417 _ => {
418 let primary = code & 0xff;
420 return if primary != code && primary != 0 {
421 format!("{}({code})", result_code_name(primary))
422 } else {
423 format!("SQLITE({code})")
424 };
425 }
426 };
427 name.to_string()
428}
429
430fn version_row(r: &rusqlite::Row<'_>, cell_id: &str) -> rusqlite::Result<Version> {
431 Ok(Version { cell_id: cell_id.to_string(), tx: r.get(0)?, receipt_hash: r.get(1)?, asof: r.get(2)? })
432}
433
434fn name_host(fn_name: &str) -> &str {
436 fn_name.rsplit_once('/').map_or("", |(h, _)| h)
437}
438
439fn read_namespace(c: &Connection, host: &str) -> Result<Option<Namespace>> {
440 c.prepare_cached(L::NamespaceGet.sql())
441 .db()?
442 .query_row([host], |r| {
443 Ok(Namespace {
444 host: host.to_string(),
445 keydoc: r.get(0)?,
446 validated_at: r.get(1)?,
447 suspended_at: r.get(2)?,
448 consecutive_failures: r.get(3)?,
449 last_checked_at: r.get(4)?,
450 })
451 })
452 .optional()
453 .db()
454}
455
456fn get_bytes(c: &Connection, q: L, key: &str) -> Result<Option<Vec<u8>>> {
457 c.prepare_cached(q.sql()).db()?.query_row([key], |r| r.get(0)).optional().db()
458}
459
460fn get_strings(c: &Connection, q: L, key: &str) -> Result<Vec<String>> {
461 let mut st = c.prepare_cached(q.sql()).db()?;
462 let rows = st.query_map([key], |r| r.get(0)).db()?;
463 rows.collect::<rusqlite::Result<Vec<String>>>().db()
464}
465
466fn exists(c: &Connection, q: L, key: &str) -> Result<bool> {
467 c.prepare_cached(q.sql()).db()?.query_row([key], |r| r.get(0)).db()
468}
469
470fn exec(c: &Connection, q: L, params: impl rusqlite::Params) -> Result<usize> {
471 c.prepare_cached(q.sql()).db()?.execute(params).db()
472}
473
474fn bad(what: &str) -> Error {
476 Error::Invalid(datumesh_core::Error::new(ErrorCode::CanonType, "$", format!("a stored {what}")))
477}
478
479fn args_of(text: &str) -> Result<Args> {
481 let Ok(Value::Array(list)) = json::parse(text.as_bytes()) else { return Err(bad("argument list")) };
482 let mut args = Args::new();
483 for a in &list {
484 let item = |i: usize| match a {
485 Value::Array(x) => x.get(i).and_then(Value::as_str).ok_or_else(|| bad("argument")),
486 _ => Err(bad("argument")),
487 };
488 let ty = Type::from_name(item(1)?).ok_or_else(|| bad("type"))?;
489 args.insert(item(0)?.to_string(), Arg::Value(Scalar::from_lexical(ty, item(2)?)?));
490 }
491 Ok(args)
492}
493
494pub(crate) fn sort_key(ty: &str, lexical: &str) -> String {
498 if ty == "number" {
499 decimal_key(lexical)
500 } else {
501 lexical.to_string()
502 }
503}
504
505pub(crate) fn decimal_key(lexical: &str) -> String {
514 let (negative, magnitude) = match lexical.strip_prefix('-') {
515 Some(m) => (true, m),
516 None => (false, lexical),
517 };
518 let (int, frac) = magnitude.split_once('.').unwrap_or((magnitude, ""));
519 let int = int.trim_start_matches('0');
520 let frac = frac.trim_end_matches('0');
521 let (exponent, digits): (i64, String) = if !int.is_empty() {
522 (int.len() as i64, format!("{int}{frac}").trim_end_matches('0').to_string())
523 } else {
524 let zeros = frac.len() - frac.trim_start_matches('0').len();
525 (-(zeros as i64), frac[zeros..].to_string())
526 };
527 if digits.is_empty() {
528 return "1".to_string();
529 }
530 let e = (exponent + 500).clamp(0, 999);
531 if negative {
532 let complement: String = digits.bytes().map(|d| char::from(b'9' - (d - b'0'))).collect();
533 format!("0{:03}{complement}~", 999 - e)
534 } else {
535 format!("2{e:03}{digits}")
536 }
537}
538
539impl Resolver for SqliteStore {
540 fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
541 if !is_hash(fn_hash) {
542 return None;
543 }
544 self.resolve("descriptor", |c| get_bytes(c, L::DescriptorGet, fn_hash)).map(Cow::Owned)
545 }
546
547 fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
548 if !is_hash(hash) {
549 return None;
550 }
551 self.resolve("receipt", |c| get_bytes(c, L::ReceiptGet, hash)).map(Cow::Owned)
552 }
553
554 fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
557 if check_entry(entry, "$").is_err() {
558 return None;
559 }
560 self.resolve("manifest", |c| get_bytes(c, L::ManifestGet, entry)).map(Cow::Owned)
561 }
562
563 fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
566 if !is_instant(asof) {
567 return None;
568 }
569 self.resolve("evaluate", |c| {
570 let Some(desc) = get_bytes(c, L::DescriptorGet, &cell.fn_hash)? else { return Ok(None) };
571 match FunctionDescriptor::from_json(&desc) {
572 Ok(d) if d.lang == "stored" => {}
573 Ok(_) => return Ok(None),
574 Err(e) => {
575 tracing::error!(target: "datumesh_store", fn_hash = %cell.fn_hash, error = %e, "stored descriptor does not parse");
576 return Ok(None);
577 }
578 }
579 let bytes: Option<Vec<u8>> = c
580 .prepare_cached(L::ValueAsof.sql())
581 .db()?
582 .query_row(rusqlite::params![cell.id(), asof], |r| r.get(0))
583 .optional()
584 .db()?;
585 let Some(bytes) = bytes else { return Ok(None) };
586 match Receipt::from_json(&bytes) {
587 Ok(r) => Ok(Some(r.value().clone())),
588 Err(e) => {
589 tracing::error!(target: "datumesh_store", cell_id = %cell.id(), error = %e, "stored receipt does not parse");
590 Ok(None)
591 }
592 }
593 })
594 }
595}
596
597impl SqliteStore {
598 fn record_check(
600 &self,
601 op: &'static str,
602 host: &str,
603 checked_at: &str,
604 threshold: Option<u32>,
605 ) -> Result<Option<Namespace>> {
606 check_dns_name(host, "host")?;
607 check_instant(checked_at, "checked_at")?;
608 let out = self.write(op, |c| {
609 let Some(mut ns) = read_namespace(c, host)? else { return Ok(None) };
610 if let Some(at) = &ns.last_checked_at {
611 if checked_at < at.as_str() {
612 return Err(Error::NotLater {
613 what: "namespace",
614 key: host.to_string(),
615 given: checked_at.to_string(),
616 latest: at.clone(),
617 });
618 }
619 }
620 crate::apply_check(&mut ns, checked_at, threshold);
621 exec(c, L::NamespaceCheck, rusqlite::params![host, ns.consecutive_failures, checked_at, ns.suspended_at])?;
622 Ok(Some(ns))
623 })?;
624 tracing::debug!(target: "datumesh_store", host, checked_at, ok = threshold.is_none(), "namespace check");
625 Ok(out)
626 }
627}
628
629impl Store for SqliteStore {
630 fn put_descriptor(&self, bytes: &[u8]) -> Result<String> {
631 let d = FunctionDescriptor::from_json(bytes)?;
632 let hash = d.hash();
633 let canonical = d.canonical();
634 self.run("put_descriptor", |c| {
635 if exists(c, L::DescriptorExists, &hash)? {
636 return Ok(());
637 }
638 self.locked_write(c, |c| exec(c, L::DescriptorPut, rusqlite::params![hash, canonical]).map(|_| ()))?;
639 self.bound_wal(c);
640 Ok(())
641 })?;
642 tracing::debug!(target: "datumesh_store", fn_hash = %hash, "put_descriptor");
643 Ok(hash)
644 }
645
646 fn put_receipt(&self, bytes: &[u8]) -> Result<String> {
647 let r = Receipt::from_json(bytes)?;
649 let canonical = json::parse(bytes)?.to_jcs();
650 let hash = r.hash().to_string();
651 let cell = r.cell();
652 let cell_id = cell.id();
653 let host = r.signer_host().to_string();
654 let (mut entries, mut inputs): (Vec<String>, Vec<String>) =
655 r.inputs().iter().cloned().partition(|e| e.starts_with("slice:"));
656 entries.sort();
657 entries.dedup();
658 inputs.sort();
659 inputs.dedup();
660 let mut args = Vec::with_capacity(cell.args.len());
661 for (name, a) in &cell.args {
662 let Some(s) = a.scalar() else {
663 return Err(Error::Invalid(datumesh_core::Error::new(
664 ErrorCode::Schema,
665 "$.cell.args",
666 "a receipt's cell has no open argument",
667 )));
668 };
669 let ty = s.ty().as_str();
670 args.push((name.clone(), ty, s.lexical().to_string(), sort_key(ty, s.lexical())));
671 }
672 self.run("put_receipt", |c| {
673 if let Some(stored) = get_bytes(c, L::ReceiptGet, &hash)? {
675 if stored == canonical {
676 return Ok(());
677 }
678 }
679 let mut keys = Keys::new();
682 if let Some(ns) = read_namespace(c, &host)? {
683 if let Some(since) = ns.suspended_at {
685 return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
686 }
687 keys.insert_response(&host, 200, Some(&ns.keydoc));
688 }
689 let out = verify(bytes, &keys, None, None);
690 if !out.ok {
691 return Err(Error::Invalid(out.error().unwrap_or_else(|| {
692 datumesh_core::Error::new(ErrorCode::Signature, "$", "the receipt did not verify")
693 })));
694 }
695 self.locked_write(c, |c| {
696 if let Some(stored) = get_bytes(c, L::ReceiptGet, &hash)? {
698 return if stored == canonical { Ok(()) } else { Err(Error::Conflict { hash: hash.clone() }) };
699 }
700 let value = r.value();
701 exec(
702 c,
703 L::ReceiptPut,
704 rusqlite::params![
705 hash,
706 canonical,
707 cell_id,
708 r.tx(),
709 cell.fn_hash,
710 r.publisher(),
711 r.asof(),
712 value.ty().as_str(),
713 value.lexical()
714 ],
715 )?;
716 for i in &inputs {
717 exec(c, L::EdgePut, rusqlite::params![hash, i])?;
718 }
719 for e in &entries {
720 exec(c, L::SliceEdgePut, rusqlite::params![hash, e])?;
721 }
722 if !exists(c, L::CellExists, &cell_id)? {
723 exec(
724 c,
725 L::CellPut,
726 rusqlite::params![cell_id, cell.fn_hash, cell.ns, cell.fn_name, args.len() as i64],
727 )?;
728 for (name, ty, value, key) in &args {
729 exec(c, L::CellArgPut, rusqlite::params![cell_id, name, ty, value, key, cell.fn_hash])?;
730 }
731 }
732 Ok(())
733 })?;
734 self.bound_wal(c);
735 Ok(())
736 })?;
737 tracing::debug!(target: "datumesh_store", hash = %hash, cell_id = %cell_id, "put_receipt");
738 Ok(hash)
739 }
740
741 fn put_blob(&self, bytes: &[u8]) -> Result<String> {
742 let sha = sha256_hex(bytes);
743 let length = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
744 self.run("put_blob", |c| {
745 if exists(c, L::BlobExists, &sha)? {
746 return Ok(());
747 }
748 self.locked_write(c, |c| exec(c, L::BlobPut, rusqlite::params![sha, bytes, length]).map(|_| ()))?;
749 self.bound_wal(c);
750 Ok(())
751 })?;
752 tracing::debug!(target: "datumesh_store", sha256 = %sha, length, "put_blob");
753 Ok(sha)
754 }
755
756 fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>> {
757 check_hex(sha256, 64, "sha256")?;
758 Ok(self.run("blob", |c| get_bytes(c, L::BlobGet, sha256))?.map(Cow::Owned))
759 }
760
761 fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
762 check_hex(cell_id, 64, "cell_id")?;
763 check_instant(tx, "tx")?;
764 check_hex(receipt_hash, 64, "receipt_hash")?;
765 self.write("put_version", |c| {
766 let meta: Option<(String, String)> = c
767 .prepare_cached(L::ReceiptMeta.sql())
768 .db()?
769 .query_row([receipt_hash], |r| Ok((r.get(0)?, r.get(1)?)))
770 .optional()
771 .db()?;
772 let Some((r_cell, r_tx)) = meta else {
773 return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
774 };
775 let stored = get_bytes(c, L::ReceiptGet, receipt_hash)?
777 .ok_or_else(|| Error::NotFound { what: "receipt", key: receipt_hash.to_string() })?;
778 let signer = Receipt::from_json(&stored)?.signer_host().to_string();
779 if let Some(since) = read_namespace(c, &signer)?.and_then(|n| n.suspended_at) {
780 return Err(Error::NamespaceSuspended { host: signer, suspended_at: since });
781 }
782 if r_cell != cell_id {
783 return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
784 }
785 if r_tx != tx {
786 return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
787 }
788 if let Some(l) = get_strings(c, L::VersionLatestTx, cell_id)?.pop() {
789 if tx <= l.as_str() {
790 return Err(Error::NotLater {
791 what: "version",
792 key: cell_id.to_string(),
793 given: tx.to_string(),
794 latest: l,
795 });
796 }
797 }
798 exec(c, L::VersionPut, rusqlite::params![cell_id, tx, receipt_hash])?;
799 Ok(())
800 })?;
801 tracing::debug!(target: "datumesh_store", cell_id, tx, receipt_hash, "put_version");
802 Ok(())
803 }
804
805 fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
806 self.asof_version("version_asof", L::VersionAsof, cell_id, asof)
807 }
808
809 fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>> {
810 check_hex(cell_id, 64, "cell_id")?;
811 check_instant(from, "from")?;
812 check_instant(to, "to")?;
813 self.run("versions", |c| {
814 let mut st = c.prepare_cached(L::VersionRange.sql()).db()?;
815 let rows = st.query_map(rusqlite::params![cell_id, from, to], |r| version_row(r, cell_id)).db()?;
816 rows.collect::<rusqlite::Result<Vec<Version>>>().db()
817 })
818 }
819
820 fn latest(&self, cell_id: &str) -> Result<Option<Version>> {
821 check_hex(cell_id, 64, "cell_id")?;
822 self.run("latest", |c| {
823 c.prepare_cached(L::VersionLatest.sql())
824 .db()?
825 .query_row([cell_id], |r| version_row(r, cell_id))
826 .optional()
827 .db()
828 })
829 }
830
831 fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>> {
832 check_hex(receipt_hash, 64, "receipt_hash")?;
833 self.run("dependents", |c| get_strings(c, L::Dependents, receipt_hash))
834 }
835
836 fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>> {
837 check_hex(receipt_hash, 64, "receipt_hash")?;
838 self.run("inputs", |c| get_strings(c, L::Inputs, receipt_hash))
839 }
840
841 fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()> {
842 keys_from_response(host, 200, Some(keydoc_bytes))?;
843 check_instant(validated_at, "validated_at")?;
844 let canonical = json::parse(keydoc_bytes)?.to_jcs();
845 self.write("put_namespace", |c| {
846 let at: Option<String> =
847 c.prepare_cached(L::NamespaceGet.sql()).db()?.query_row([host], |r| r.get(1)).optional().db()?;
848 if let Some(at) = at {
849 if validated_at < at.as_str() {
850 return Err(Error::NotLater {
851 what: "namespace",
852 key: host.to_string(),
853 given: validated_at.to_string(),
854 latest: at,
855 });
856 }
857 }
858 exec(c, L::NamespacePut, rusqlite::params![host, canonical, validated_at])?;
859 Ok(())
860 })?;
861 tracing::debug!(target: "datumesh_store", host, validated_at, "put_namespace");
862 Ok(())
863 }
864
865 fn namespace(&self, host: &str) -> Result<Option<Namespace>> {
866 check_dns_name(host, "host")?;
867 self.run("namespace", |c| read_namespace(c, host))
868 }
869
870 fn namespaces(&self) -> Result<Vec<Namespace>> {
871 self.run("namespaces", |c| {
872 let mut st = c.prepare_cached(L::NamespaceList.sql()).db()?;
873 let rows = st
874 .query_map([], |r| {
875 Ok(Namespace {
876 host: r.get(0)?,
877 keydoc: r.get(1)?,
878 validated_at: r.get(2)?,
879 suspended_at: r.get(3)?,
880 consecutive_failures: r.get(4)?,
881 last_checked_at: r.get(5)?,
882 })
883 })
884 .db()?;
885 rows.collect::<rusqlite::Result<Vec<Namespace>>>().db()
886 })
887 }
888
889 fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>> {
890 self.record_check("record_namespace_failure", host, checked_at, Some(threshold))
891 }
892
893 fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>> {
894 self.record_check("record_namespace_success", host, checked_at, None)
895 }
896
897 fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()> {
898 check_function_name(fn_name, "fn_name")?;
899 check_hex(fn_hash, 64, "fn_hash")?;
900 check_instant(tx, "tx")?;
901 self.write("bind_name", |c| {
902 let host = name_host(fn_name);
904 if let Some(since) = read_namespace(c, host)?.and_then(|n| n.suspended_at) {
905 return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
906 }
907 if exists(c, L::ClassNameBound, fn_name)? {
909 return Err(Error::NameTaken { name: fn_name.to_string(), bound_as: "class" });
910 }
911 if !exists(c, L::DescriptorExists, fn_hash)? {
912 return Err(Error::NotFound { what: "descriptor", key: fn_hash.to_string() });
913 }
914 if let Some(l) = get_strings(c, L::NameLatest, fn_name)?.pop() {
915 if tx <= l.as_str() {
916 return Err(Error::NotLater {
917 what: "name",
918 key: fn_name.to_string(),
919 given: tx.to_string(),
920 latest: l,
921 });
922 }
923 }
924 exec(c, L::NamePut, rusqlite::params![fn_name, tx, fn_hash])?;
925 Ok(())
926 })?;
927 tracing::debug!(target: "datumesh_store", fn_name, fn_hash, tx, "bind_name");
928 Ok(())
929 }
930
931 fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>> {
932 check_function_name(fn_name, "fn_name")?;
933 check_instant(asof, "asof")?;
934 self.run("resolve_name", |c| {
935 c.prepare_cached(L::NameAsof.sql()).db()?.query_row([fn_name, asof], |r| r.get(0)).optional().db()
936 })
937 }
938
939 fn put_class(&self, bytes: &[u8]) -> Result<String> {
940 let d = ClassDescriptor::from_json(bytes)?;
943 let canonical = d.canonical();
944 if canonical != bytes {
945 return Err(not_canonical_class());
946 }
947 let hash = d.hash();
948 let host = d.steward.namespace.clone();
949 self.write("put_class", |c| {
950 if let Some(since) = read_namespace(c, &host)?.and_then(|n| n.suspended_at) {
952 return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
953 }
954 exec(c, L::ClassPut, rusqlite::params![hash, canonical])?;
955 Ok(())
956 })?;
957 tracing::debug!(target: "datumesh_store", class_hash = %hash, "put_class");
958 Ok(hash)
959 }
960
961 fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>> {
962 check_hex(class_hash, 64, "class_hash")?;
963 self.run("class", |c| get_bytes(c, L::ClassGet, class_hash))
964 }
965
966 fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()> {
967 check_function_name(class_name, "class_name")?;
968 check_hex(class_hash, 64, "class_hash")?;
969 check_instant(tx, "tx")?;
970 self.write("bind_class", |c| {
971 let host = name_host(class_name);
973 if let Some(since) = read_namespace(c, host)?.and_then(|n| n.suspended_at) {
974 return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
975 }
976 let Some(bytes) = get_bytes(c, L::ClassGet, class_hash)? else {
977 return Err(Error::NotFound { what: "class", key: class_hash.to_string() });
978 };
979 let flat = ClassDescriptor::from_json(&bytes)?;
980 let methods: Vec<(String, String)> = flat.methods.into_iter().collect();
981 let method_names: Vec<String> = methods.iter().map(|(m, _)| format!("{class_name}/{m}")).collect();
982 for (_, h) in &methods {
984 if !exists(c, L::DescriptorExists, h)? {
985 return Err(Error::NotFound { what: "descriptor", key: h.clone() });
986 }
987 }
988 if exists(c, L::NameBound, class_name)? {
991 return Err(Error::NameTaken { name: class_name.to_string(), bound_as: "function" });
992 }
993 for name in &method_names {
994 if exists(c, L::ClassNameBound, name)? {
995 return Err(Error::NameTaken { name: name.clone(), bound_as: "class" });
996 }
997 }
998 if let Some(l) = get_strings(c, L::ClassBindingLatest, class_name)?.pop() {
1000 if tx <= l.as_str() {
1001 return Err(Error::NotLater {
1002 what: "name",
1003 key: class_name.to_string(),
1004 given: tx.to_string(),
1005 latest: l,
1006 });
1007 }
1008 }
1009 for name in &method_names {
1010 if let Some(l) = get_strings(c, L::NameLatest, name)?.pop() {
1011 if tx <= l.as_str() {
1012 return Err(Error::NotLater {
1013 what: "name",
1014 key: name.clone(),
1015 given: tx.to_string(),
1016 latest: l,
1017 });
1018 }
1019 }
1020 }
1021 exec(c, L::ClassBindingPut, rusqlite::params![class_name, tx, class_hash])?;
1022 for ((_, h), name) in methods.iter().zip(&method_names) {
1023 exec(c, L::NamePut, rusqlite::params![name.as_str(), tx, h.as_str()])?;
1024 }
1025 Ok(())
1026 })?;
1027 tracing::debug!(target: "datumesh_store", class_name, class_hash, tx, "bind_class");
1028 Ok(())
1029 }
1030
1031 fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>> {
1032 Ok(self.resolve_class_binding(class_name, asof)?.map(|b| b.class_hash))
1033 }
1034
1035 fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>> {
1036 check_function_name(class_name, "class_name")?;
1037 check_instant(asof, "asof")?;
1038 self.run("resolve_class_binding", |c| {
1039 c.prepare_cached(L::ClassBindingAsof.sql())
1040 .db()?
1041 .query_row([class_name, asof], |r| Ok(ClassBinding { class_hash: r.get(0)?, tx: r.get(1)? }))
1042 .optional()
1043 .db()
1044 })
1045 }
1046
1047 fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>> {
1048 check_function_name(fn_name, "fn_name")?;
1049 check_instant(asof, "asof")?;
1050 self.run("resolve_binding", |c| {
1051 c.prepare_cached(L::BindingAsof.sql())
1052 .db()?
1053 .query_row([fn_name, asof], |r| Ok(Binding { fn_hash: r.get(0)?, tx: r.get(1)? }))
1054 .optional()
1055 .db()
1056 })
1057 }
1058
1059 fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
1060 check_hex(cell_id, 64, "cell_id")?;
1061 check_instant(tx, "tx")?;
1062 check_hex(receipt_hash, 64, "receipt_hash")?;
1063 let asof = self.write("put_computed", |c| {
1064 let meta: Option<(String, String, String)> = c
1065 .prepare_cached(L::ReceiptMeta.sql())
1066 .db()?
1067 .query_row([receipt_hash], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
1068 .optional()
1069 .db()?;
1070 let Some((r_cell, r_tx, asof)) = meta else {
1071 return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
1072 };
1073 if r_cell != cell_id {
1074 return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
1075 }
1076 if r_tx != tx {
1077 return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
1078 }
1079 let stored: Option<String> = c
1080 .prepare_cached(L::ComputedGet.sql())
1081 .db()?
1082 .query_row([cell_id, tx, asof.as_str()], |r| r.get(0))
1083 .optional()
1084 .db()?;
1085 match stored {
1086 Some(h) if h == receipt_hash => {}
1087 Some(_) => return Err(Error::Conflict { hash: receipt_hash.to_string() }),
1088 None => {
1089 exec(c, L::ComputedPut, rusqlite::params![cell_id, tx, asof, receipt_hash])?;
1090 }
1091 }
1092 Ok(asof)
1093 })?;
1094 tracing::debug!(target: "datumesh_store", cell_id, tx, asof, receipt_hash, "put_computed");
1095 Ok(())
1096 }
1097
1098 fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1099 self.asof_version("computed_asof", L::ComputedAsof, cell_id, asof)
1100 }
1101
1102 fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1103 self.asof_version("stored_asof", L::StoredAsof, cell_id, asof)
1104 }
1105
1106 fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>> {
1107 check_hex(cell_id, 64, "cell_id")?;
1108 self.run("cell_dependents", |c| get_strings(c, L::CellDependents, cell_id))
1109 }
1110
1111 fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1113 Ok(self
1114 .asof_with_receipt("computed_asof_with_receipt", L::ComputedAsofReceipt, cell_id, asof)?
1115 .map(|(v, b)| (v, Cow::Owned(b))))
1116 }
1117
1118 fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1120 Ok(self
1121 .asof_with_receipt("stored_asof_with_receipt", L::StoredAsofReceipt, cell_id, asof)?
1122 .map(|(v, b)| (v, Cow::Owned(b))))
1123 }
1124
1125 fn put_manifest(&self, bytes: &[u8]) -> Result<String> {
1126 let m = Manifest::from_json(bytes)?;
1127 let entry = m.entry();
1128 let canonical = m.canonical();
1129 let members = m.members();
1130 let n = i64::try_from(members.len()).unwrap_or(i64::MAX);
1131 self.run("put_manifest", |c| {
1132 if exists(c, L::ManifestExists, &entry)? {
1134 return Ok(());
1135 }
1136 self.locked_write(c, |c| {
1137 if exists(c, L::ManifestExists, &entry)? {
1138 return Ok(());
1139 }
1140 exec(
1141 c,
1142 L::ManifestPut,
1143 rusqlite::params![entry, m.slice().id(), m.members_hash(), m.slice().fn_hash(), n, canonical],
1144 )?;
1145 let mut st = c.prepare_cached(L::ManifestMemberPut.sql()).db()?;
1146 for h in members {
1147 st.execute([entry.as_str(), h.as_str()]).db()?;
1148 }
1149 Ok(())
1150 })?;
1151 self.bound_wal(c);
1152 Ok(())
1153 })?;
1154 tracing::debug!(target: "datumesh_store", entry = %entry, members = n, "put_manifest");
1155 Ok(entry)
1156 }
1157
1158 fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>> {
1159 check_hex(receipt_hash, 64, "receipt_hash")?;
1160 self.run("member_manifests", |c| get_strings(c, L::MemberManifests, receipt_hash))
1161 }
1162
1163 fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>> {
1164 check_hex(receipt_hash, 64, "receipt_hash")?;
1165 self.run("slice_entries", |c| get_strings(c, L::SliceEntries, receipt_hash))
1166 }
1167
1168 fn slice_dependents(&self, entry: &str) -> Result<Vec<String>> {
1169 check_entry(entry, "entry")?;
1170 self.run("slice_dependents", |c| get_strings(c, L::SliceDependents, entry))
1171 }
1172
1173 fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>> {
1174 check_instant(asof, "asof")?;
1175 let v = slice.to_value();
1176 if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1177 return self.versions_between(&cell_id, &from, &to, asof);
1178 }
1179 let p = Pattern::of(&v)?;
1180 self.run("slice_members", |c| {
1181 let rows = rows(&p, c, asof, [L::SliceMembersAll, L::SliceMembersDrive], |r| {
1182 let cell_id: String = r.get(4)?;
1183 Ok((
1184 SliceMember {
1185 version: Version { cell_id, tx: r.get(0)?, receipt_hash: r.get(1)?, asof: r.get(2)? },
1186 receipt: r.get(3)?,
1187 },
1188 r.get::<_, String>(5)?,
1189 ))
1190 })?;
1191 in_key_order(&p, rows, |m| &m.version.cell_id)
1192 })
1193 }
1194
1195 fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>> {
1196 check_hex(cell_id, 64, "cell_id")?;
1197 check_instant(from, "from")?;
1198 check_instant(to, "to")?;
1199 check_instant(asof, "asof")?;
1200 self.run("versions_between", |c| {
1201 let mut st = c.prepare_cached(L::VersionsBetween.sql()).db()?;
1202 let rows = st
1203 .query_map(rusqlite::params![cell_id, from, to, asof], |r| {
1204 Ok(SliceMember { version: version_row(r, cell_id)?, receipt: r.get(3)? })
1205 })
1206 .db()?;
1207 rows.collect::<rusqlite::Result<Vec<SliceMember>>>().db()
1208 })
1209 }
1210
1211 fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>> {
1212 check_instant(asof, "asof")?;
1213 let v = slice.to_value();
1214 if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1215 return self.run("slice_values", |c| {
1216 let mut st = c.prepare_cached(L::VersionsBetweenValues.sql()).db()?;
1217 let rows = st.query_map(rusqlite::params![cell_id, from, to, asof], value_columns).db()?;
1218 let mut out = Vec::new();
1219 for r in rows {
1220 out.push(value_of(r.db()?)?.0);
1221 }
1222 Ok(out)
1223 });
1224 }
1225 let p = Pattern::of(&v)?;
1226 self.run("slice_values", |c| {
1227 let rows = rows(&p, c, asof, [L::SliceValuesAll, L::SliceValuesDrive], value_columns)?;
1228 let mut values = Vec::with_capacity(rows.len());
1229 for row in rows {
1230 values.push(value_of(row)?);
1231 }
1232 in_key_order_parsed(&p, values, |m| &m.version.cell_id)
1233 })
1234 }
1235
1236 fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool> {
1237 check_instant(asof, "asof")?;
1238 let v = slice.to_value();
1239 if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1240 return self.run("slice_changed_after", |c| {
1241 c.prepare_cached(L::VersionsChangedAfter.sql())
1242 .db()?
1243 .query_row(rusqlite::params![cell_id, from, to, asof], |r| r.get(0))
1244 .db()
1245 });
1246 }
1247 let p = Pattern::of(&v)?;
1248 self.run("slice_changed_after", |c| changed_after(&p, c, asof))
1249 }
1250
1251 fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>> {
1252 check_instant(asof, "asof")?;
1253 let p = Pattern::of(&slice.to_value())?;
1254 let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1255 self.run("computed_cells", |c| {
1256 let (d, _) = drive(&p, c, false)?;
1257 let q = if d.is_some() { L::ComputedCellsDrive } else { L::ComputedCellsAll };
1258 let mut binds = params(&p, asof, d);
1259 binds.push((":limit", SqlValue::Integer(limit)));
1260 let mut st = c.prepare_cached(q.sql()).db()?;
1261 bind(&mut st, &binds)?;
1262 let mut rows = st.raw_query();
1263 let mut out = Vec::new();
1264 while let Some(r) = rows.next().db()? {
1265 let args = args_of(&r.get::<_, String>(3).db()?)?;
1266 out.push(Cell {
1267 args,
1268 fn_hash: r.get::<_, String>(2).db()?,
1269 fn_name: r.get::<_, String>(1).db()?,
1270 ns: r.get::<_, String>(0).db()?,
1271 });
1272 }
1273 Ok(out)
1274 })
1275 }
1276
1277 fn has_bindings_under(&self, namespace: &str) -> Result<bool> {
1278 let prefix = format!("{namespace}/");
1279 self.run("has_bindings_under", |c| {
1280 c.prepare_cached(L::HasBindingsUnder.sql()).db()?.query_row([&prefix], |r| r.get(0)).db()
1281 })
1282 }
1283}
1284
1285type ValueColumns = (String, String, String, String, String, String, String, String, String, String);
1288
1289fn value_columns(r: &rusqlite::Row<'_>) -> rusqlite::Result<ValueColumns> {
1290 Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?, r.get(7)?, r.get(8)?, r.get(9)?))
1291}
1292
1293fn value_of(c: ValueColumns) -> Result<(SliceValue, Args)> {
1295 let (tx, receipt_hash, asof, ty, value, cell_id, args, ns, fn_name, fn_hash) = c;
1296 let ty = Type::from_name(&ty).ok_or_else(|| bad("type"))?;
1297 let args = args_of(&args)?;
1298 let cell = Cell { args: args.clone(), fn_hash, fn_name, ns };
1299 Ok((
1300 SliceValue {
1301 version: Version { cell_id, tx, receipt_hash, asof },
1302 value: Scalar::from_lexical(ty, &value)?,
1303 cell,
1304 },
1305 args,
1306 ))
1307}
1308
1309fn constraints(p: &Pattern) -> String {
1312 let items: Vec<Value> = p
1313 .args
1314 .iter()
1315 .map(|a| {
1316 let (lo, hi) = match a.kind {
1317 Kind::Range => (sort_key(&a.ty, &a.lo), sort_key(&a.ty, &a.hi)),
1318 _ => (a.lo.clone(), a.hi.clone()),
1319 };
1320 Value::Array(
1321 [a.name.clone(), a.kind.as_str().to_string(), a.ty.clone(), lo, hi]
1322 .into_iter()
1323 .map(Value::String)
1324 .collect(),
1325 )
1326 })
1327 .collect();
1328 String::from_utf8(Value::Array(items).to_jcs()).unwrap_or_default()
1329}
1330
1331fn bind(st: &mut rusqlite::CachedStatement<'_>, params: &[(&str, SqlValue)]) -> Result<()> {
1333 for (name, value) in params {
1334 if let Some(i) = st.parameter_index(name).db()? {
1335 st.raw_bind_parameter(i, value).db()?;
1336 }
1337 }
1338 Ok(())
1339}
1340
1341fn drive<'p>(p: &'p Pattern, c: &Connection, count: bool) -> Result<(Option<&'p Constraint>, Option<i64>)> {
1345 let probe = |a: Option<&Constraint>| -> Result<i64> {
1346 match a {
1347 None => c.prepare_cached(L::ProbeCells.sql()).db()?.query_row([&p.fn_hash], |r| r.get(0)).db(),
1348 Some(a) => {
1349 let (lo, hi) = (sort_key(&a.ty, &a.lo), sort_key(&a.ty, &a.hi));
1350 c.prepare_cached(L::SliceProbe.sql())
1351 .db()?
1352 .query_row(rusqlite::params![p.fn_hash, a.name, a.ty, lo, hi], |r| r.get(0))
1353 .db()
1354 }
1355 }
1356 };
1357 let constrained: Vec<&Constraint> = p.args.iter().filter(|a| a.kind != Kind::Open).collect();
1358 Ok(match constrained.as_slice() {
1359 [] => (None, if count { Some(probe(None)?) } else { None }),
1360 [one] => (Some(*one), if count { Some(probe(Some(one))?) } else { None }),
1361 several => {
1362 let mut best: Option<(i64, &Constraint)> = None;
1363 for a in several {
1364 let n = probe(Some(a))?;
1365 if best.is_none_or(|(m, _)| n < m) {
1366 best = Some((n, a));
1367 }
1368 }
1369 (best.map(|(_, a)| a), best.map(|(n, _)| n))
1370 }
1371 })
1372}
1373
1374fn params(p: &Pattern, asof: &str, drive: Option<&Constraint>) -> Vec<(&'static str, SqlValue)> {
1376 let text = |s: &str| SqlValue::Text(s.to_string());
1377 let mut out = vec![
1378 (":fn_hash", text(&p.fn_hash)),
1379 (":ns", text(&p.ns)),
1380 (":fn", text(&p.fn_name)),
1381 (":nargs", SqlValue::Integer(p.args.len() as i64)),
1382 (":asof", text(asof)),
1383 (":cons", SqlValue::Text(constraints(p))),
1384 ];
1385 if let Some(a) = drive {
1386 out.push((":d_name", text(&a.name)));
1387 out.push((":d_type", text(&a.ty)));
1388 out.push((":d_lo", SqlValue::Text(sort_key(&a.ty, &a.lo))));
1389 out.push((":d_hi", SqlValue::Text(sort_key(&a.ty, &a.hi))));
1390 }
1391 out
1392}
1393
1394fn rows<T>(
1396 p: &Pattern,
1397 c: &Connection,
1398 asof: &str,
1399 qs: [L; 2],
1400 make: impl Fn(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
1401) -> Result<Vec<T>> {
1402 let (d, _) = drive(p, c, false)?;
1403 let q = if d.is_some() { qs[1] } else { qs[0] };
1404 let mut st = c.prepare_cached(q.sql()).db()?;
1405 bind(&mut st, ¶ms(p, asof, d))?;
1406 let mut rows = st.raw_query();
1407 let mut out = Vec::new();
1408 while let Some(r) = rows.next().db()? {
1409 out.push(make(r).db()?);
1410 }
1411 Ok(out)
1412}
1413
1414fn key_of(p: &Pattern, args: &Args) -> Vec<String> {
1416 p.args
1417 .iter()
1418 .filter(|a| a.kind != Kind::Value)
1419 .filter_map(|a| args.get(&a.name).and_then(Arg::scalar))
1420 .map(|s| format!("{}:{}", s.ty().as_str(), s.lexical()))
1421 .collect()
1422}
1423
1424fn in_key_order<T>(p: &Pattern, rows: Vec<(T, String)>, cell_of: impl Fn(&T) -> &String) -> Result<Vec<T>> {
1426 let mut keyed = Vec::with_capacity(rows.len());
1427 for (m, args) in rows {
1428 keyed.push((key_of(p, &args_of(&args)?), m));
1429 }
1430 keyed.sort_by(|(a, ma), (b, mb)| cmp_keys(a, b).then_with(|| cell_of(ma).cmp(cell_of(mb))));
1431 Ok(keyed.into_iter().map(|(_, m)| m).collect())
1432}
1433
1434fn in_key_order_parsed<T>(p: &Pattern, rows: Vec<(T, Args)>, cell_of: impl Fn(&T) -> &String) -> Result<Vec<T>> {
1436 let mut keyed: Vec<(Vec<String>, T)> = rows.into_iter().map(|(m, args)| (key_of(p, &args), m)).collect();
1437 keyed.sort_by(|(a, ma), (b, mb)| cmp_keys(a, b).then_with(|| cell_of(ma).cmp(cell_of(mb))));
1438 Ok(keyed.into_iter().map(|(_, m)| m).collect())
1439}
1440
1441fn changed_after(p: &Pattern, c: &Connection, asof: &str) -> Result<bool> {
1445 let (d, candidates) = drive(p, c, true)?;
1446 let recent: i64 = c
1447 .prepare_cached(L::ProbeRecent.sql())
1448 .db()?
1449 .query_row(rusqlite::params![p.fn_hash, asof], |r| r.get(0))
1450 .db()?;
1451 let q = if recent <= candidates.unwrap_or(i64::MAX) {
1452 L::ChangedRecent
1453 } else if d.is_some() {
1454 L::ChangedCandDrive
1455 } else {
1456 L::ChangedCandAll
1457 };
1458 let d = if q == L::ChangedCandDrive { d } else { None };
1459 let mut st = c.prepare_cached(q.sql()).db()?;
1460 bind(&mut st, ¶ms(p, asof, d))?;
1461 let mut rows = st.raw_query();
1462 Ok(rows.next().db()?.is_some())
1463}
1464
1465#[cfg(test)]
1466mod tests {
1467 use super::*;
1468 use crate::slices::cmp_decimal;
1469
1470 #[test]
1471 fn decimal_keys_sort_as_the_numbers() {
1472 let mut numbers: Vec<String> = [
1473 "0", "9", "10", "-1.5", "-1", "-1.25", "-1.11", "-1.1", "-0.1", "-0.099", "0.099", "0.1", "0.109", "0.11",
1474 "1", "1.1", "1.109", "1.11", "9.5", "99.999", "100", "-100", "-10", "-9", "123", "-123", "0.0001",
1475 "-0.0001", "1000000", "-1000000", "12.5", "12.05", "-12.5", "-12.05", "120", "-120", "1.2", "-1.2",
1476 ]
1477 .iter()
1478 .map(|s| s.to_string())
1479 .collect();
1480 numbers.push("9".repeat(128));
1481 numbers.push(format!("-{}", "9".repeat(127)));
1482 numbers.push(format!("1{}", "0".repeat(127)));
1483 numbers.push(format!("-1{}", "0".repeat(126)));
1484 numbers.push(format!("0.{}1", "0".repeat(125)));
1485 numbers.push(format!("-0.{}1", "0".repeat(124)));
1486 numbers.push(format!("{}.{}", "1".repeat(64), "1".repeat(63)));
1487 numbers.push(format!("-{}.{}", "1".repeat(63), "1".repeat(63)));
1488 for a in &numbers {
1489 assert!(a.len() <= 128, "{a}");
1490 for b in &numbers {
1491 assert_eq!(decimal_key(a).cmp(&decimal_key(b)), cmp_decimal(a, b), "{a} vs {b}");
1492 }
1493 }
1494 assert_eq!(decimal_key("0"), "1");
1496 assert_eq!(decimal_key("100"), "25031");
1497 assert_eq!(decimal_key("0.0012"), "249812");
1498 assert_eq!(decimal_key("-1.5"), "049884~");
1499 assert_eq!(decimal_key(&"9".repeat(128)), format!("2628{}", "9".repeat(128)));
1500 }
1501
1502 #[test]
1503 fn result_codes_have_names() {
1504 assert_eq!(result_code_name(5), "SQLITE_BUSY");
1505 assert_eq!(result_code_name(1811), "SQLITE_CONSTRAINT_TRIGGER");
1506 assert_eq!(result_code_name(14), "SQLITE_CANTOPEN");
1507 assert_eq!(result_code_name(10 | (99 << 8)), "SQLITE_IOERR(25354)");
1508 }
1509
1510 #[test]
1511 fn sqlite_urls_name_paths() {
1512 assert_eq!(sqlite_path("sqlite:store.db"), "store.db");
1513 assert_eq!(sqlite_path("sqlite://store.db"), "store.db");
1514 assert_eq!(sqlite_path("sqlite:///var/lib/x.db"), "/var/lib/x.db");
1515 assert_eq!(sqlite_path("/var/lib/x.db"), "/var/lib/x.db");
1516 assert_eq!(sqlite_path("x.db"), "x.db");
1517 }
1518
1519 fn plan(c: &Connection, sql: &str) -> Vec<String> {
1521 let mut st = c.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap();
1522 let n = st.parameter_count();
1523 for i in 1..=n {
1524 st.raw_bind_parameter(i, "x").unwrap();
1525 }
1526 let mut rows = st.raw_query();
1527 let mut out = Vec::new();
1528 while let Some(r) = rows.next().unwrap() {
1529 out.push(r.get::<_, String>(3).unwrap());
1530 }
1531 out
1532 }
1533
1534 #[test]
1539 fn bounded_slices_use_indexes() {
1540 let c = Connection::open_in_memory().unwrap();
1541 for m in crate::migrate::sqlite::MIGRATIONS {
1542 c.execute_batch(m.sql).unwrap();
1543 }
1544 c.execute_batch(
1546 "ANALYZE sqlite_schema;
1547 INSERT INTO sqlite_stat1 (tbl, idx, stat) VALUES
1548 ('cells', 'cells_fn_hash', '100000 100000 1'),
1549 ('cells', 'sqlite_autoindex_cells_1', '100000 1'),
1550 ('cell_args', 'cell_args_key', '200000 200000 100000 100000 1 1'),
1551 ('cell_args', 'sqlite_autoindex_cell_args_1', '200000 2 1'),
1552 ('versions', 'sqlite_autoindex_versions_1', '100000 1 1'),
1553 ('versions', 'versions_receipt_hash', '100000 1'),
1554 ('receipts', 'sqlite_autoindex_receipts_1', '100000 1'),
1555 ('receipts', 'receipts_cell_tx', '100000 1 1'),
1556 ('receipts', 'receipts_fn_hash_asof', '100000 100000 1'),
1557 ('receipts', 'receipts_cell_asof', '100000 1 1');
1558 ANALYZE sqlite_schema;",
1559 )
1560 .unwrap();
1561 let scans = |s: &str| s.starts_with("SCAN ") && !s.starts_with("SCAN k") && !s.starts_with("SCAN (subquery");
1564 for q in [
1565 L::SliceMembersDrive,
1566 L::SliceValuesDrive,
1567 L::ChangedCandDrive,
1568 L::ChangedRecent,
1569 L::SliceProbe,
1570 L::ProbeRecent,
1571 L::ProbeCells,
1572 L::VersionsBetween,
1573 L::VersionsBetweenValues,
1574 L::StoredAsof,
1575 L::ComputedAsof,
1576 L::CellDependents,
1577 ] {
1578 let steps = plan(&c, q.sql());
1579 assert!(!steps.iter().any(|s| scans(s)), "{q:?} scans:\n{steps:#?}");
1580 }
1581 for q in [L::SliceMembersAll, L::SliceValuesAll, L::ChangedCandAll] {
1583 let steps = plan(&c, q.sql());
1584 assert!(
1585 steps.iter().any(|s| s.contains("SEARCH c USING") && s.contains("cells_fn_hash")),
1586 "{q:?}: {steps:#?}"
1587 );
1588 assert!(!steps.iter().any(|s| scans(s)), "{q:?} scans:\n{steps:#?}");
1589 }
1590 }
1591}