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::catalogue::{
12 aliases_json, args_json, as_i64, canonical_examples, check_catalog_entry, check_key_values, entry_fields,
13 entry_from_columns, invalid, miss_text, parse_aliases, rank, Words, SUMMARY_VALUES,
14};
15use crate::error::{Db, Error, Result};
16use crate::slices::{check_entry, cmp_keys, is_hash, is_instant, version_slice, Constraint, Kind, Pattern};
17use crate::sqlite_sql::L;
18use crate::{
19 not_canonical_class, Binding, CatalogEntry, CatalogKind, ClassBinding, Dictionary, DictionaryValue, Embedding,
20 FunctionTest, Hit, KeyValue, Namespace, PendingEmbedding, SliceMember, SliceValue, Store, Summary, SummaryEntry,
21 TestSummary, Version, FIND_MISSES_CAP,
22};
23use datumesh_core::json::{self, Value};
24use datumesh_core::lexical::{check_dns_name, check_function_name, check_hex, check_instant};
25use datumesh_core::{
26 keys_from_response, sha256_hex, verify, Arg, Args, Cell, ClassDescriptor, ErrorCode, FunctionDescriptor, Keys,
27 Manifest, Receipt, Resolver, Scalar, Slice, Type,
28};
29
30#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct SqliteOptions {
35 max_size: usize,
36 busy_timeout: Duration,
37 durable: bool,
38}
39
40impl Default for SqliteOptions {
41 fn default() -> SqliteOptions {
42 SqliteOptions::new()
43 }
44}
45
46impl SqliteOptions {
47 pub fn new() -> SqliteOptions {
51 SqliteOptions { max_size: 8, busy_timeout: Duration::from_secs(30), durable: true }
52 }
53
54 pub fn max_size(mut self, n: usize) -> SqliteOptions {
58 self.max_size = n.max(1);
59 self
60 }
61
62 pub fn busy_timeout(mut self, d: Duration) -> SqliteOptions {
67 self.busy_timeout = d;
68 self
69 }
70
71 pub fn durable(mut self, yes: bool) -> SqliteOptions {
77 self.durable = yes;
78 self
79 }
80}
81
82pub struct SqliteStore {
100 path: PathBuf,
101 options: SqliteOptions,
102 idle: Mutex<Vec<Connection>>,
103 writer: Mutex<()>,
107 existing: bool,
109}
110
111impl std::fmt::Debug for SqliteStore {
112 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
113 f.debug_struct("SqliteStore").field("path", &self.path).finish_non_exhaustive()
114 }
115}
116
117struct Pooled<'a> {
119 store: &'a SqliteStore,
120 conn: Option<Connection>,
121}
122
123impl std::ops::Deref for Pooled<'_> {
124 type Target = Connection;
125 fn deref(&self) -> &Connection {
126 self.conn.as_ref().expect("a pooled connection")
127 }
128}
129
130impl Drop for Pooled<'_> {
131 fn drop(&mut self) {
132 if let Some(c) = self.conn.take() {
133 if c.is_autocommit() {
135 if let Ok(mut idle) = self.store.idle.lock() {
136 if idle.len() < self.store.options.max_size {
137 idle.push(c);
138 }
139 }
140 }
141 }
142 }
143}
144
145impl SqliteStore {
146 pub fn open(path: impl AsRef<Path>) -> Result<SqliteStore> {
151 SqliteStore::open_with(path, SqliteOptions::new())
152 }
153
154 pub fn open_with(path: impl AsRef<Path>, options: SqliteOptions) -> Result<SqliteStore> {
160 let store = SqliteStore {
161 path: path.as_ref().to_path_buf(),
162 options,
163 idle: Mutex::new(Vec::new()),
164 writer: Mutex::new(()),
165 existing: false,
166 };
167 let c = store.open_connection()?;
168 if let Ok(mut idle) = store.idle.lock() {
169 idle.push(c);
170 }
171 Ok(store)
172 }
173
174 pub fn open_existing(path: impl AsRef<Path>) -> Result<SqliteStore> {
181 let path = path.as_ref();
182 if !path.is_file() {
183 return Err(Error::Database(crate::error::DatabaseError::no_such_file(path)));
184 }
185 let store = SqliteStore {
186 path: path.to_path_buf(),
187 options: SqliteOptions::new(),
188 idle: Mutex::new(Vec::new()),
189 writer: Mutex::new(()),
190 existing: true,
191 };
192 let c = store.open_connection()?;
193 if let Ok(mut idle) = store.idle.lock() {
194 idle.push(c);
195 }
196 Ok(store)
197 }
198
199 pub fn connect(url: &str) -> Result<SqliteStore> {
203 SqliteStore::open(sqlite_path(url))
204 }
205
206 pub fn path(&self) -> &Path {
208 &self.path
209 }
210
211 fn open_connection(&self) -> Result<Connection> {
212 let mut flags = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX;
213 if !self.existing {
214 flags |= OpenFlags::SQLITE_OPEN_CREATE;
215 }
216 let c = Connection::open_with_flags(&self.path, flags).db()?;
217 c.busy_timeout(self.options.busy_timeout).db()?;
218 c.set_prepared_statement_cache_capacity(L::ALL.len() + 16);
219 if self.existing {
220 c.execute_batch("PRAGMA foreign_keys = ON").db()?;
222 return Ok(c);
223 }
224 let start = Instant::now();
228 loop {
229 match c.query_row("PRAGMA journal_mode = WAL", [], |r| r.get::<_, String>(0)) {
230 Ok(mode) if mode.eq_ignore_ascii_case("wal") => break,
231 Ok(mode) => return Err(Error::Config(format!("SQLite: journal mode WAL refused (it is {mode})"))),
232 Err(e) if is_busy(&e) && start.elapsed() < self.options.busy_timeout => {
233 std::thread::sleep(Duration::from_millis(5));
234 }
235 Err(e) => return Err(e).db(),
236 }
237 }
238 let sync = if self.options.durable { "FULL" } else { "NORMAL" };
239 c.execute_batch(&format!("PRAGMA foreign_keys = ON; PRAGMA synchronous = {sync};")).db()?;
240 Ok(c)
241 }
242
243 fn conn(&self) -> Result<Pooled<'_>> {
245 let idle = self.idle.lock().ok().and_then(|mut v| v.pop());
246 let conn = match idle {
247 Some(c) => c,
248 None => self.open_connection()?,
249 };
250 Ok(Pooled { store: self, conn: Some(conn) })
251 }
252
253 pub fn check_statements(&self) -> Result<usize> {
257 let c = self.open_connection()?;
258 for q in L::ALL {
259 c.prepare(q.sql()).db()?;
260 }
261 Ok(L::ALL.len())
262 }
263
264 pub(crate) fn raw(&self) -> Result<impl std::ops::Deref<Target = Connection> + '_> {
266 self.conn()
267 }
268
269 fn resolve<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<Option<T>>) -> Option<T> {
271 self.run(op, f).ok().flatten()
272 }
273
274 fn run<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
276 let result = self.conn().and_then(|c| f(&c));
277 if let Err(e @ Error::Database(_)) = &result {
278 tracing::error!(target: "datumesh_store", op, error = %e, "database failure");
279 }
280 result
281 }
282
283 fn write<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
286 self.run(op, |c| {
287 let v = self.locked_write(c, f)?;
288 self.bound_wal(c);
289 Ok(v)
290 })
291 }
292
293 fn locked_write<T>(&self, c: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
295 let _queue = self.writer.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
296 write(c, f)
297 }
298
299 fn bound_wal(&self, c: &Connection) {
307 let mut wal = self.path.clone().into_os_string();
308 wal.push("-wal");
309 if std::fs::metadata(&wal).is_ok_and(|m| m.len() > WAL_LIMIT) {
310 if let Err(e) = c.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(())) {
311 tracing::debug!(target: "datumesh_store", error = %e, "checkpoint deferred");
312 }
313 }
314 }
315
316 fn asof_version(&self, op: &'static str, q: L, cell_id: &str, asof: &str) -> Result<Option<Version>> {
318 check_hex(cell_id, 64, "cell_id")?;
319 check_instant(asof, "asof")?;
320 self.run(op, |c| {
321 c.prepare_cached(q.sql())
322 .db()?
323 .query_row(rusqlite::params![cell_id, asof], |r| version_row(r, cell_id))
324 .optional()
325 .db()
326 })
327 }
328
329 fn asof_with_receipt(
332 &self,
333 op: &'static str,
334 q: L,
335 cell_id: &str,
336 asof: &str,
337 ) -> Result<Option<(Version, Vec<u8>)>> {
338 check_hex(cell_id, 64, "cell_id")?;
339 check_instant(asof, "asof")?;
340 self.run(op, |c| {
341 c.prepare_cached(q.sql())
342 .db()?
343 .query_row(rusqlite::params![cell_id, asof], |r| Ok((version_row(r, cell_id)?, r.get(3)?)))
344 .optional()
345 .db()
346 })
347 }
348}
349
350const WAL_LIMIT: u64 = 64 << 20;
352
353pub(crate) fn write<T>(c: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
355 c.execute_batch("BEGIN IMMEDIATE").db()?;
356 let result = f(c).and_then(|v| c.execute_batch("COMMIT").db().map(|()| v));
357 if result.is_err() && !c.is_autocommit() {
358 let _ = c.execute_batch("ROLLBACK");
359 }
360 result
361}
362
363fn is_busy(e: &rusqlite::Error) -> bool {
364 matches!(e, rusqlite::Error::SqliteFailure(f, _) if f.code == rusqlite::ErrorCode::DatabaseBusy)
365}
366
367pub(crate) fn sqlite_path(url: &str) -> &str {
369 match url.strip_prefix("sqlite:") {
370 Some(rest) => rest.strip_prefix("//").unwrap_or(rest),
371 None => url,
372 }
373}
374
375pub(crate) fn result_code_name(code: std::os::raw::c_int) -> String {
377 let name = match code {
378 1 => "SQLITE_ERROR",
379 2 => "SQLITE_INTERNAL",
380 3 => "SQLITE_PERM",
381 4 => "SQLITE_ABORT",
382 5 => "SQLITE_BUSY",
383 6 => "SQLITE_LOCKED",
384 7 => "SQLITE_NOMEM",
385 8 => "SQLITE_READONLY",
386 9 => "SQLITE_INTERRUPT",
387 10 => "SQLITE_IOERR",
388 11 => "SQLITE_CORRUPT",
389 12 => "SQLITE_NOTFOUND",
390 13 => "SQLITE_FULL",
391 14 => "SQLITE_CANTOPEN",
392 15 => "SQLITE_PROTOCOL",
393 16 => "SQLITE_EMPTY",
394 17 => "SQLITE_SCHEMA",
395 18 => "SQLITE_TOOBIG",
396 19 => "SQLITE_CONSTRAINT",
397 20 => "SQLITE_MISMATCH",
398 21 => "SQLITE_MISUSE",
399 22 => "SQLITE_NOLFS",
400 23 => "SQLITE_AUTH",
401 24 => "SQLITE_FORMAT",
402 25 => "SQLITE_RANGE",
403 26 => "SQLITE_NOTADB",
404 261 => "SQLITE_BUSY_RECOVERY",
405 517 => "SQLITE_BUSY_SNAPSHOT",
406 773 => "SQLITE_BUSY_TIMEOUT",
407 262 => "SQLITE_LOCKED_SHAREDCACHE",
408 264 => "SQLITE_READONLY_RECOVERY",
409 520 => "SQLITE_READONLY_CANTLOCK",
410 270 => "SQLITE_CANTOPEN_NOTEMPDIR",
411 526 => "SQLITE_CANTOPEN_ISDIR",
412 782 => "SQLITE_CANTOPEN_FULLPATH",
413 267 => "SQLITE_CORRUPT_VTAB",
414 275 => "SQLITE_CONSTRAINT_CHECK",
415 531 => "SQLITE_CONSTRAINT_COMMITHOOK",
416 787 => "SQLITE_CONSTRAINT_FOREIGNKEY",
417 1043 => "SQLITE_CONSTRAINT_FUNCTION",
418 1299 => "SQLITE_CONSTRAINT_NOTNULL",
419 1555 => "SQLITE_CONSTRAINT_PRIMARYKEY",
420 1811 => "SQLITE_CONSTRAINT_TRIGGER",
421 2067 => "SQLITE_CONSTRAINT_UNIQUE",
422 2323 => "SQLITE_CONSTRAINT_VTAB",
423 2579 => "SQLITE_CONSTRAINT_ROWID",
424 3091 => "SQLITE_CONSTRAINT_DATATYPE",
425 _ => {
426 let primary = code & 0xff;
428 return if primary != code && primary != 0 {
429 format!("{}({code})", result_code_name(primary))
430 } else {
431 format!("SQLITE({code})")
432 };
433 }
434 };
435 name.to_string()
436}
437
438fn version_row(r: &rusqlite::Row<'_>, cell_id: &str) -> rusqlite::Result<Version> {
439 Ok(Version { cell_id: cell_id.to_string(), tx: r.get(0)?, receipt_hash: r.get(1)?, asof: r.get(2)? })
440}
441
442fn name_host(fn_name: &str) -> &str {
444 fn_name.rsplit_once('/').map_or("", |(h, _)| h)
445}
446
447fn read_namespace(c: &Connection, host: &str) -> Result<Option<Namespace>> {
448 c.prepare_cached(L::NamespaceGet.sql())
449 .db()?
450 .query_row([host], |r| {
451 Ok(Namespace {
452 host: host.to_string(),
453 keydoc: r.get(0)?,
454 validated_at: r.get(1)?,
455 suspended_at: r.get(2)?,
456 consecutive_failures: r.get(3)?,
457 last_checked_at: r.get(4)?,
458 })
459 })
460 .optional()
461 .db()
462}
463
464fn get_bytes(c: &Connection, q: L, key: &str) -> Result<Option<Vec<u8>>> {
465 c.prepare_cached(q.sql()).db()?.query_row([key], |r| r.get(0)).optional().db()
466}
467
468fn get_strings(c: &Connection, q: L, key: &str) -> Result<Vec<String>> {
469 let mut st = c.prepare_cached(q.sql()).db()?;
470 let rows = st.query_map([key], |r| r.get(0)).db()?;
471 rows.collect::<rusqlite::Result<Vec<String>>>().db()
472}
473
474fn exists(c: &Connection, q: L, key: &str) -> Result<bool> {
475 c.prepare_cached(q.sql()).db()?.query_row([key], |r| r.get(0)).db()
476}
477
478fn exec(c: &Connection, q: L, params: impl rusqlite::Params) -> Result<usize> {
479 c.prepare_cached(q.sql()).db()?.execute(params).db()
480}
481
482fn bad(what: &str) -> Error {
484 Error::Invalid(datumesh_core::Error::new(ErrorCode::CanonType, "$", format!("a stored {what}")))
485}
486
487fn args_of(text: &str) -> Result<Args> {
489 let Ok(Value::Array(list)) = json::parse(text.as_bytes()) else { return Err(bad("argument list")) };
490 let mut args = Args::new();
491 for a in &list {
492 let item = |i: usize| match a {
493 Value::Array(x) => x.get(i).and_then(Value::as_str).ok_or_else(|| bad("argument")),
494 _ => Err(bad("argument")),
495 };
496 let ty = Type::from_name(item(1)?).ok_or_else(|| bad("type"))?;
497 args.insert(item(0)?.to_string(), Arg::Value(Scalar::from_lexical(ty, item(2)?)?));
498 }
499 Ok(args)
500}
501
502pub(crate) fn sort_key(ty: &str, lexical: &str) -> String {
506 if ty == "number" {
507 decimal_key(lexical)
508 } else {
509 lexical.to_string()
510 }
511}
512
513pub(crate) fn decimal_key(lexical: &str) -> String {
522 let (negative, magnitude) = match lexical.strip_prefix('-') {
523 Some(m) => (true, m),
524 None => (false, lexical),
525 };
526 let (int, frac) = magnitude.split_once('.').unwrap_or((magnitude, ""));
527 let int = int.trim_start_matches('0');
528 let frac = frac.trim_end_matches('0');
529 let (exponent, digits): (i64, String) = if !int.is_empty() {
530 (int.len() as i64, format!("{int}{frac}").trim_end_matches('0').to_string())
531 } else {
532 let zeros = frac.len() - frac.trim_start_matches('0').len();
533 (-(zeros as i64), frac[zeros..].to_string())
534 };
535 if digits.is_empty() {
536 return "1".to_string();
537 }
538 let e = (exponent + 500).clamp(0, 999);
539 if negative {
540 let complement: String = digits.bytes().map(|d| char::from(b'9' - (d - b'0'))).collect();
541 format!("0{:03}{complement}~", 999 - e)
542 } else {
543 format!("2{e:03}{digits}")
544 }
545}
546
547impl Resolver for SqliteStore {
548 fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
549 if !is_hash(fn_hash) {
550 return None;
551 }
552 self.resolve("descriptor", |c| get_bytes(c, L::DescriptorGet, fn_hash)).map(Cow::Owned)
553 }
554
555 fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
556 if !is_hash(hash) {
557 return None;
558 }
559 self.resolve("receipt", |c| get_bytes(c, L::ReceiptGet, hash)).map(Cow::Owned)
560 }
561
562 fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
565 if check_entry(entry, "$").is_err() {
566 return None;
567 }
568 self.resolve("manifest", |c| get_bytes(c, L::ManifestGet, entry)).map(Cow::Owned)
569 }
570
571 fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
574 if !is_instant(asof) {
575 return None;
576 }
577 self.resolve("evaluate", |c| {
578 let Some(desc) = get_bytes(c, L::DescriptorGet, &cell.fn_hash)? else { return Ok(None) };
579 match FunctionDescriptor::from_json(&desc) {
580 Ok(d) if d.lang == "stored" => {}
581 Ok(_) => return Ok(None),
582 Err(e) => {
583 tracing::error!(target: "datumesh_store", fn_hash = %cell.fn_hash, error = %e, "stored descriptor does not parse");
584 return Ok(None);
585 }
586 }
587 let bytes: Option<Vec<u8>> = c
588 .prepare_cached(L::ValueAsof.sql())
589 .db()?
590 .query_row(rusqlite::params![cell.id(), asof], |r| r.get(0))
591 .optional()
592 .db()?;
593 let Some(bytes) = bytes else { return Ok(None) };
594 match Receipt::from_json(&bytes) {
595 Ok(r) => Ok(Some(r.value().clone())),
596 Err(e) => {
597 tracing::error!(target: "datumesh_store", cell_id = %cell.id(), error = %e, "stored receipt does not parse");
598 Ok(None)
599 }
600 }
601 })
602 }
603}
604
605impl SqliteStore {
606 fn record_check(
608 &self,
609 op: &'static str,
610 host: &str,
611 checked_at: &str,
612 threshold: Option<u32>,
613 ) -> Result<Option<Namespace>> {
614 check_dns_name(host, "host")?;
615 check_instant(checked_at, "checked_at")?;
616 let out = self.write(op, |c| {
617 let Some(mut ns) = read_namespace(c, host)? else { return Ok(None) };
618 if let Some(at) = &ns.last_checked_at {
619 if checked_at < at.as_str() {
620 return Err(Error::NotLater {
621 what: "namespace",
622 key: host.to_string(),
623 given: checked_at.to_string(),
624 latest: at.clone(),
625 });
626 }
627 }
628 crate::apply_check(&mut ns, checked_at, threshold);
629 exec(c, L::NamespaceCheck, rusqlite::params![host, ns.consecutive_failures, checked_at, ns.suspended_at])?;
630 Ok(Some(ns))
631 })?;
632 tracing::debug!(target: "datumesh_store", host, checked_at, ok = threshold.is_none(), "namespace check");
633 Ok(out)
634 }
635}
636
637impl Store for SqliteStore {
638 fn put_descriptor(&self, bytes: &[u8]) -> Result<String> {
639 let d = FunctionDescriptor::from_json(bytes)?;
640 let hash = d.hash();
641 let canonical = d.canonical();
642 self.run("put_descriptor", |c| {
644 let fresh = !exists(c, L::DescriptorExists, &hash)?;
645 if fresh || !d.inputs.is_empty() {
646 self.locked_write(c, |c| {
647 exec(c, L::DescriptorPut, rusqlite::params![hash, canonical])?;
648 for input in &d.inputs {
649 exec(c, L::DescriptorInputPut, rusqlite::params![hash, input])?;
650 }
651 Ok(())
652 })?;
653 self.bound_wal(c);
654 }
655 Ok(())
656 })?;
657 tracing::debug!(target: "datumesh_store", fn_hash = %hash, "put_descriptor");
658 Ok(hash)
659 }
660
661 fn put_receipt(&self, bytes: &[u8]) -> Result<String> {
662 let r = Receipt::from_json(bytes)?;
664 let canonical = json::parse(bytes)?.to_jcs();
665 let hash = r.hash().to_string();
666 let cell = r.cell();
667 let cell_id = cell.id();
668 let host = r.signer_host().to_string();
669 let (mut entries, mut inputs): (Vec<String>, Vec<String>) =
670 r.inputs().iter().cloned().partition(|e| e.starts_with("slice:"));
671 entries.sort();
672 entries.dedup();
673 inputs.sort();
674 inputs.dedup();
675 let mut args = Vec::with_capacity(cell.args.len());
676 for (name, a) in &cell.args {
677 let Some(s) = a.scalar() else {
678 return Err(Error::Invalid(datumesh_core::Error::new(
679 ErrorCode::Schema,
680 "$.cell.args",
681 "a receipt's cell has no open argument",
682 )));
683 };
684 let ty = s.ty().as_str();
685 args.push((name.clone(), ty, s.lexical().to_string(), sort_key(ty, s.lexical())));
686 }
687 self.run("put_receipt", |c| {
688 if let Some(stored) = get_bytes(c, L::ReceiptGet, &hash)? {
690 if stored == canonical {
691 return Ok(());
692 }
693 }
694 let mut keys = Keys::new();
697 if let Some(ns) = read_namespace(c, &host)? {
698 if let Some(since) = ns.suspended_at {
700 return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
701 }
702 keys.insert_response(&host, 200, Some(&ns.keydoc));
703 }
704 let out = verify(bytes, &keys, None, None);
705 if !out.ok {
706 return Err(Error::Invalid(out.error().unwrap_or_else(|| {
707 datumesh_core::Error::new(ErrorCode::Signature, "$", "the receipt did not verify")
708 })));
709 }
710 self.locked_write(c, |c| {
711 if let Some(stored) = get_bytes(c, L::ReceiptGet, &hash)? {
713 return if stored == canonical { Ok(()) } else { Err(Error::Conflict { hash: hash.clone() }) };
714 }
715 let value = r.value();
716 exec(
717 c,
718 L::ReceiptPut,
719 rusqlite::params![
720 hash,
721 canonical,
722 cell_id,
723 r.tx(),
724 cell.fn_hash,
725 r.publisher(),
726 r.asof(),
727 value.ty().as_str(),
728 value.lexical()
729 ],
730 )?;
731 for i in &inputs {
732 exec(c, L::EdgePut, rusqlite::params![hash, i])?;
733 }
734 for e in &entries {
735 exec(c, L::SliceEdgePut, rusqlite::params![hash, e])?;
736 }
737 if !exists(c, L::CellExists, &cell_id)? {
738 exec(
739 c,
740 L::CellPut,
741 rusqlite::params![cell_id, cell.fn_hash, cell.ns, cell.fn_name, args.len() as i64],
742 )?;
743 for (name, ty, value, key) in &args {
744 exec(c, L::CellArgPut, rusqlite::params![cell_id, name, ty, value, key, cell.fn_hash])?;
745 }
746 }
747 Ok(())
748 })?;
749 self.bound_wal(c);
750 Ok(())
751 })?;
752 tracing::debug!(target: "datumesh_store", hash = %hash, cell_id = %cell_id, "put_receipt");
753 Ok(hash)
754 }
755
756 fn put_blob(&self, bytes: &[u8]) -> Result<String> {
757 let sha = sha256_hex(bytes);
758 let length = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
759 self.run("put_blob", |c| {
760 if exists(c, L::BlobExists, &sha)? {
761 return Ok(());
762 }
763 self.locked_write(c, |c| exec(c, L::BlobPut, rusqlite::params![sha, bytes, length]).map(|_| ()))?;
764 self.bound_wal(c);
765 Ok(())
766 })?;
767 tracing::debug!(target: "datumesh_store", sha256 = %sha, length, "put_blob");
768 Ok(sha)
769 }
770
771 fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>> {
772 check_hex(sha256, 64, "sha256")?;
773 Ok(self.run("blob", |c| get_bytes(c, L::BlobGet, sha256))?.map(Cow::Owned))
774 }
775
776 fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
777 check_hex(cell_id, 64, "cell_id")?;
778 check_instant(tx, "tx")?;
779 check_hex(receipt_hash, 64, "receipt_hash")?;
780 self.write("put_version", |c| {
781 let meta: Option<(String, String)> = c
782 .prepare_cached(L::ReceiptMeta.sql())
783 .db()?
784 .query_row([receipt_hash], |r| Ok((r.get(0)?, r.get(1)?)))
785 .optional()
786 .db()?;
787 let Some((r_cell, r_tx)) = meta else {
788 return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
789 };
790 let stored = get_bytes(c, L::ReceiptGet, receipt_hash)?
792 .ok_or_else(|| Error::NotFound { what: "receipt", key: receipt_hash.to_string() })?;
793 let signer = Receipt::from_json(&stored)?.signer_host().to_string();
794 if let Some(since) = read_namespace(c, &signer)?.and_then(|n| n.suspended_at) {
795 return Err(Error::NamespaceSuspended { host: signer, suspended_at: since });
796 }
797 if r_cell != cell_id {
798 return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
799 }
800 if r_tx != tx {
801 return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
802 }
803 if let Some(l) = get_strings(c, L::VersionLatestTx, cell_id)?.pop() {
804 if tx <= l.as_str() {
805 return Err(Error::NotLater {
806 what: "version",
807 key: cell_id.to_string(),
808 given: tx.to_string(),
809 latest: l,
810 });
811 }
812 }
813 exec(c, L::VersionPut, rusqlite::params![cell_id, tx, receipt_hash])?;
814 Ok(())
815 })?;
816 tracing::debug!(target: "datumesh_store", cell_id, tx, receipt_hash, "put_version");
817 Ok(())
818 }
819
820 fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
821 self.asof_version("version_asof", L::VersionAsof, cell_id, asof)
822 }
823
824 fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>> {
825 check_hex(cell_id, 64, "cell_id")?;
826 check_instant(from, "from")?;
827 check_instant(to, "to")?;
828 self.run("versions", |c| {
829 let mut st = c.prepare_cached(L::VersionRange.sql()).db()?;
830 let rows = st.query_map(rusqlite::params![cell_id, from, to], |r| version_row(r, cell_id)).db()?;
831 rows.collect::<rusqlite::Result<Vec<Version>>>().db()
832 })
833 }
834
835 fn latest(&self, cell_id: &str) -> Result<Option<Version>> {
836 check_hex(cell_id, 64, "cell_id")?;
837 self.run("latest", |c| {
838 c.prepare_cached(L::VersionLatest.sql())
839 .db()?
840 .query_row([cell_id], |r| version_row(r, cell_id))
841 .optional()
842 .db()
843 })
844 }
845
846 fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>> {
847 check_hex(receipt_hash, 64, "receipt_hash")?;
848 self.run("dependents", |c| get_strings(c, L::Dependents, receipt_hash))
849 }
850
851 fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>> {
852 check_hex(receipt_hash, 64, "receipt_hash")?;
853 self.run("inputs", |c| get_strings(c, L::Inputs, receipt_hash))
854 }
855
856 fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()> {
857 keys_from_response(host, 200, Some(keydoc_bytes))?;
858 check_instant(validated_at, "validated_at")?;
859 let canonical = json::parse(keydoc_bytes)?.to_jcs();
860 self.write("put_namespace", |c| {
861 let at: Option<String> =
862 c.prepare_cached(L::NamespaceGet.sql()).db()?.query_row([host], |r| r.get(1)).optional().db()?;
863 if let Some(at) = at {
864 if validated_at < at.as_str() {
865 return Err(Error::NotLater {
866 what: "namespace",
867 key: host.to_string(),
868 given: validated_at.to_string(),
869 latest: at,
870 });
871 }
872 }
873 exec(c, L::NamespacePut, rusqlite::params![host, canonical, validated_at])?;
874 Ok(())
875 })?;
876 tracing::debug!(target: "datumesh_store", host, validated_at, "put_namespace");
877 Ok(())
878 }
879
880 fn namespace(&self, host: &str) -> Result<Option<Namespace>> {
881 check_dns_name(host, "host")?;
882 self.run("namespace", |c| read_namespace(c, host))
883 }
884
885 fn namespaces(&self) -> Result<Vec<Namespace>> {
886 self.run("namespaces", |c| {
887 let mut st = c.prepare_cached(L::NamespaceList.sql()).db()?;
888 let rows = st
889 .query_map([], |r| {
890 Ok(Namespace {
891 host: r.get(0)?,
892 keydoc: r.get(1)?,
893 validated_at: r.get(2)?,
894 suspended_at: r.get(3)?,
895 consecutive_failures: r.get(4)?,
896 last_checked_at: r.get(5)?,
897 })
898 })
899 .db()?;
900 rows.collect::<rusqlite::Result<Vec<Namespace>>>().db()
901 })
902 }
903
904 fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>> {
905 self.record_check("record_namespace_failure", host, checked_at, Some(threshold))
906 }
907
908 fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>> {
909 self.record_check("record_namespace_success", host, checked_at, None)
910 }
911
912 fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()> {
913 check_function_name(fn_name, "fn_name")?;
914 check_hex(fn_hash, 64, "fn_hash")?;
915 check_instant(tx, "tx")?;
916 self.write("bind_name", |c| {
917 let host = name_host(fn_name);
919 if let Some(since) = read_namespace(c, host)?.and_then(|n| n.suspended_at) {
920 return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
921 }
922 if exists(c, L::ClassNameBound, fn_name)? {
924 return Err(Error::NameTaken { name: fn_name.to_string(), bound_as: "class" });
925 }
926 if !exists(c, L::DescriptorExists, fn_hash)? {
927 return Err(Error::NotFound { what: "descriptor", key: fn_hash.to_string() });
928 }
929 if let Some(l) = get_strings(c, L::NameLatest, fn_name)?.pop() {
930 if tx <= l.as_str() {
931 return Err(Error::NotLater {
932 what: "name",
933 key: fn_name.to_string(),
934 given: tx.to_string(),
935 latest: l,
936 });
937 }
938 }
939 exec(c, L::NamePut, rusqlite::params![fn_name, tx, fn_hash])?;
940 Ok(())
941 })?;
942 tracing::debug!(target: "datumesh_store", fn_name, fn_hash, tx, "bind_name");
943 Ok(())
944 }
945
946 fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>> {
947 check_function_name(fn_name, "fn_name")?;
948 check_instant(asof, "asof")?;
949 self.run("resolve_name", |c| {
950 c.prepare_cached(L::NameAsof.sql()).db()?.query_row([fn_name, asof], |r| r.get(0)).optional().db()
951 })
952 }
953
954 fn put_class(&self, bytes: &[u8]) -> Result<String> {
955 let d = ClassDescriptor::from_json(bytes)?;
958 let canonical = d.canonical();
959 if canonical != bytes {
960 return Err(not_canonical_class());
961 }
962 let hash = d.hash();
963 let host = d.steward.namespace.clone();
964 self.write("put_class", |c| {
965 if let Some(since) = read_namespace(c, &host)?.and_then(|n| n.suspended_at) {
967 return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
968 }
969 exec(c, L::ClassPut, rusqlite::params![hash, canonical])?;
970 Ok(())
971 })?;
972 tracing::debug!(target: "datumesh_store", class_hash = %hash, "put_class");
973 Ok(hash)
974 }
975
976 fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>> {
977 check_hex(class_hash, 64, "class_hash")?;
978 self.run("class", |c| get_bytes(c, L::ClassGet, class_hash))
979 }
980
981 fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()> {
982 check_function_name(class_name, "class_name")?;
983 check_hex(class_hash, 64, "class_hash")?;
984 check_instant(tx, "tx")?;
985 self.write("bind_class", |c| {
986 let host = name_host(class_name);
988 if let Some(since) = read_namespace(c, host)?.and_then(|n| n.suspended_at) {
989 return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
990 }
991 let Some(bytes) = get_bytes(c, L::ClassGet, class_hash)? else {
992 return Err(Error::NotFound { what: "class", key: class_hash.to_string() });
993 };
994 let flat = ClassDescriptor::from_json(&bytes)?;
995 let methods: Vec<(String, String)> = flat.methods.into_iter().collect();
996 let method_names: Vec<String> = methods.iter().map(|(m, _)| format!("{class_name}/{m}")).collect();
997 for (_, h) in &methods {
999 if !exists(c, L::DescriptorExists, h)? {
1000 return Err(Error::NotFound { what: "descriptor", key: h.clone() });
1001 }
1002 }
1003 if exists(c, L::NameBound, class_name)? {
1006 return Err(Error::NameTaken { name: class_name.to_string(), bound_as: "function" });
1007 }
1008 for name in &method_names {
1009 if exists(c, L::ClassNameBound, name)? {
1010 return Err(Error::NameTaken { name: name.clone(), bound_as: "class" });
1011 }
1012 }
1013 if let Some(l) = get_strings(c, L::ClassBindingLatest, class_name)?.pop() {
1015 if tx <= l.as_str() {
1016 return Err(Error::NotLater {
1017 what: "name",
1018 key: class_name.to_string(),
1019 given: tx.to_string(),
1020 latest: l,
1021 });
1022 }
1023 }
1024 for name in &method_names {
1025 if let Some(l) = get_strings(c, L::NameLatest, name)?.pop() {
1026 if tx <= l.as_str() {
1027 return Err(Error::NotLater {
1028 what: "name",
1029 key: name.clone(),
1030 given: tx.to_string(),
1031 latest: l,
1032 });
1033 }
1034 }
1035 }
1036 exec(c, L::ClassBindingPut, rusqlite::params![class_name, tx, class_hash])?;
1037 for ((_, h), name) in methods.iter().zip(&method_names) {
1038 exec(c, L::NamePut, rusqlite::params![name.as_str(), tx, h.as_str()])?;
1039 }
1040 Ok(())
1041 })?;
1042 tracing::debug!(target: "datumesh_store", class_name, class_hash, tx, "bind_class");
1043 Ok(())
1044 }
1045
1046 fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>> {
1047 Ok(self.resolve_class_binding(class_name, asof)?.map(|b| b.class_hash))
1048 }
1049
1050 fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>> {
1051 check_function_name(class_name, "class_name")?;
1052 check_instant(asof, "asof")?;
1053 self.run("resolve_class_binding", |c| {
1054 c.prepare_cached(L::ClassBindingAsof.sql())
1055 .db()?
1056 .query_row([class_name, asof], |r| Ok(ClassBinding { class_hash: r.get(0)?, tx: r.get(1)? }))
1057 .optional()
1058 .db()
1059 })
1060 }
1061
1062 fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>> {
1063 check_function_name(fn_name, "fn_name")?;
1064 check_instant(asof, "asof")?;
1065 self.run("resolve_binding", |c| {
1066 c.prepare_cached(L::BindingAsof.sql())
1067 .db()?
1068 .query_row([fn_name, asof], |r| Ok(Binding { fn_hash: r.get(0)?, tx: r.get(1)? }))
1069 .optional()
1070 .db()
1071 })
1072 }
1073
1074 fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
1075 check_hex(cell_id, 64, "cell_id")?;
1076 check_instant(tx, "tx")?;
1077 check_hex(receipt_hash, 64, "receipt_hash")?;
1078 let asof = self.write("put_computed", |c| {
1079 let meta: Option<(String, String, String)> = c
1080 .prepare_cached(L::ReceiptMeta.sql())
1081 .db()?
1082 .query_row([receipt_hash], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
1083 .optional()
1084 .db()?;
1085 let Some((r_cell, r_tx, asof)) = meta else {
1086 return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
1087 };
1088 if r_cell != cell_id {
1089 return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
1090 }
1091 if r_tx != tx {
1092 return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
1093 }
1094 let stored: Option<String> = c
1095 .prepare_cached(L::ComputedGet.sql())
1096 .db()?
1097 .query_row([cell_id, tx, asof.as_str()], |r| r.get(0))
1098 .optional()
1099 .db()?;
1100 match stored {
1101 Some(h) if h == receipt_hash => {}
1102 Some(_) => return Err(Error::Conflict { hash: receipt_hash.to_string() }),
1103 None => {
1104 exec(c, L::ComputedPut, rusqlite::params![cell_id, tx, asof, receipt_hash])?;
1105 }
1106 }
1107 Ok(asof)
1108 })?;
1109 tracing::debug!(target: "datumesh_store", cell_id, tx, asof, receipt_hash, "put_computed");
1110 Ok(())
1111 }
1112
1113 fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1114 self.asof_version("computed_asof", L::ComputedAsof, cell_id, asof)
1115 }
1116
1117 fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1118 self.asof_version("stored_asof", L::StoredAsof, cell_id, asof)
1119 }
1120
1121 fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>> {
1122 check_hex(cell_id, 64, "cell_id")?;
1123 self.run("cell_dependents", |c| get_strings(c, L::CellDependents, cell_id))
1124 }
1125
1126 fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1128 Ok(self
1129 .asof_with_receipt("computed_asof_with_receipt", L::ComputedAsofReceipt, cell_id, asof)?
1130 .map(|(v, b)| (v, Cow::Owned(b))))
1131 }
1132
1133 fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1135 Ok(self
1136 .asof_with_receipt("stored_asof_with_receipt", L::StoredAsofReceipt, cell_id, asof)?
1137 .map(|(v, b)| (v, Cow::Owned(b))))
1138 }
1139
1140 fn put_manifest(&self, bytes: &[u8]) -> Result<String> {
1141 let m = Manifest::from_json(bytes)?;
1142 let entry = m.entry();
1143 let canonical = m.canonical();
1144 let members = m.members();
1145 let n = i64::try_from(members.len()).unwrap_or(i64::MAX);
1146 self.run("put_manifest", |c| {
1147 if exists(c, L::ManifestExists, &entry)? {
1149 return Ok(());
1150 }
1151 self.locked_write(c, |c| {
1152 if exists(c, L::ManifestExists, &entry)? {
1153 return Ok(());
1154 }
1155 exec(
1156 c,
1157 L::ManifestPut,
1158 rusqlite::params![entry, m.slice().id(), m.members_hash(), m.slice().fn_hash(), n, canonical],
1159 )?;
1160 let mut st = c.prepare_cached(L::ManifestMemberPut.sql()).db()?;
1161 for h in members {
1162 st.execute([entry.as_str(), h.as_str()]).db()?;
1163 }
1164 Ok(())
1165 })?;
1166 self.bound_wal(c);
1167 Ok(())
1168 })?;
1169 tracing::debug!(target: "datumesh_store", entry = %entry, members = n, "put_manifest");
1170 Ok(entry)
1171 }
1172
1173 fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>> {
1174 check_hex(receipt_hash, 64, "receipt_hash")?;
1175 self.run("member_manifests", |c| get_strings(c, L::MemberManifests, receipt_hash))
1176 }
1177
1178 fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>> {
1179 check_hex(receipt_hash, 64, "receipt_hash")?;
1180 self.run("slice_entries", |c| get_strings(c, L::SliceEntries, receipt_hash))
1181 }
1182
1183 fn slice_dependents(&self, entry: &str) -> Result<Vec<String>> {
1184 check_entry(entry, "entry")?;
1185 self.run("slice_dependents", |c| get_strings(c, L::SliceDependents, entry))
1186 }
1187
1188 fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>> {
1189 check_instant(asof, "asof")?;
1190 let v = slice.to_value();
1191 if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1192 return self.versions_between(&cell_id, &from, &to, asof);
1193 }
1194 let p = Pattern::of(&v)?;
1195 self.run("slice_members", |c| {
1196 let rows = rows(&p, c, asof, [L::SliceMembersAll, L::SliceMembersDrive], |r| {
1197 let cell_id: String = r.get(4)?;
1198 Ok((
1199 SliceMember {
1200 version: Version { cell_id, tx: r.get(0)?, receipt_hash: r.get(1)?, asof: r.get(2)? },
1201 receipt: r.get(3)?,
1202 },
1203 r.get::<_, String>(5)?,
1204 ))
1205 })?;
1206 in_key_order(&p, rows, |m| &m.version.cell_id)
1207 })
1208 }
1209
1210 fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>> {
1211 check_hex(cell_id, 64, "cell_id")?;
1212 check_instant(from, "from")?;
1213 check_instant(to, "to")?;
1214 check_instant(asof, "asof")?;
1215 self.run("versions_between", |c| {
1216 let mut st = c.prepare_cached(L::VersionsBetween.sql()).db()?;
1217 let rows = st
1218 .query_map(rusqlite::params![cell_id, from, to, asof], |r| {
1219 Ok(SliceMember { version: version_row(r, cell_id)?, receipt: r.get(3)? })
1220 })
1221 .db()?;
1222 rows.collect::<rusqlite::Result<Vec<SliceMember>>>().db()
1223 })
1224 }
1225
1226 fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>> {
1227 check_instant(asof, "asof")?;
1228 let v = slice.to_value();
1229 if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1230 return self.run("slice_values", |c| {
1231 let mut st = c.prepare_cached(L::VersionsBetweenValues.sql()).db()?;
1232 let rows = st.query_map(rusqlite::params![cell_id, from, to, asof], value_columns).db()?;
1233 let mut out = Vec::new();
1234 for r in rows {
1235 out.push(value_of(r.db()?)?.0);
1236 }
1237 Ok(out)
1238 });
1239 }
1240 let p = Pattern::of(&v)?;
1241 self.run("slice_values", |c| {
1242 let rows = rows(&p, c, asof, [L::SliceValuesAll, L::SliceValuesDrive], value_columns)?;
1243 let mut values = Vec::with_capacity(rows.len());
1244 for row in rows {
1245 values.push(value_of(row)?);
1246 }
1247 in_key_order_parsed(&p, values, |m| &m.version.cell_id)
1248 })
1249 }
1250
1251 fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool> {
1252 check_instant(asof, "asof")?;
1253 let v = slice.to_value();
1254 if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1255 return self.run("slice_changed_after", |c| {
1256 c.prepare_cached(L::VersionsChangedAfter.sql())
1257 .db()?
1258 .query_row(rusqlite::params![cell_id, from, to, asof], |r| r.get(0))
1259 .db()
1260 });
1261 }
1262 let p = Pattern::of(&v)?;
1263 self.run("slice_changed_after", |c| changed_after(&p, c, asof))
1264 }
1265
1266 fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>> {
1267 check_instant(asof, "asof")?;
1268 let p = Pattern::of(&slice.to_value())?;
1269 let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1270 self.run("computed_cells", |c| {
1271 let (d, _) = drive(&p, c, false)?;
1272 let q = if d.is_some() { L::ComputedCellsDrive } else { L::ComputedCellsAll };
1273 let mut binds = params(&p, asof, d);
1274 binds.push((":limit", SqlValue::Integer(limit)));
1275 let mut st = c.prepare_cached(q.sql()).db()?;
1276 bind(&mut st, &binds)?;
1277 let mut rows = st.raw_query();
1278 let mut out = Vec::new();
1279 while let Some(r) = rows.next().db()? {
1280 let args = args_of(&r.get::<_, String>(3).db()?)?;
1281 out.push(Cell {
1282 args,
1283 fn_hash: r.get::<_, String>(2).db()?,
1284 fn_name: r.get::<_, String>(1).db()?,
1285 ns: r.get::<_, String>(0).db()?,
1286 });
1287 }
1288 Ok(out)
1289 })
1290 }
1291
1292 fn has_bindings_under(&self, namespace: &str) -> Result<bool> {
1293 let prefix = format!("{namespace}/");
1294 self.run("has_bindings_under", |c| {
1295 c.prepare_cached(L::HasBindingsUnder.sql()).db()?.query_row([&prefix], |r| r.get(0)).db()
1296 })
1297 }
1298
1299 fn upsert_catalog(&self, entries: &[CatalogEntry]) -> Result<Vec<i64>> {
1300 for e in entries {
1301 check_catalog_entry(e)?;
1302 }
1303 if entries.is_empty() {
1304 return Ok(Vec::new());
1305 }
1306 self.write("upsert_catalog", |c| {
1307 let mut ids = Vec::with_capacity(entries.len());
1308 for e in entries {
1309 let args = args_json(&e.args);
1310 let examples = canonical_examples(&e.examples)?;
1311 let updated: Option<i64> = c
1312 .prepare_cached(
1313 "INSERT INTO catalog_entries (kind, name, hash, label, description, args, examples, source, signed_by, updated_at)
1314 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
1315 ON CONFLICT (kind, name) DO UPDATE SET hash = excluded.hash, label = excluded.label,
1316 description = excluded.description, args = excluded.args, examples = excluded.examples,
1317 source = excluded.source, signed_by = excluded.signed_by, updated_at = excluded.updated_at
1318 WHERE catalog_entries.source = 'operator' OR excluded.source = 'publisher'
1319 RETURNING id",
1320 )
1321 .db()?
1322 .query_row(
1323 rusqlite::params![e.kind.as_str(), e.name, e.hash, e.label, e.description, args, examples, e.source.as_str(), e.signed_by],
1324 |r| r.get(0),
1325 )
1326 .optional()
1327 .db()?;
1328 let id = match updated {
1329 Some(id) => id,
1330 None => c
1332 .prepare_cached("SELECT id FROM catalog_entries WHERE kind = ?1 AND name = ?2")
1333 .db()?
1334 .query_row([e.kind.as_str(), e.name.as_str()], |r| r.get(0))
1335 .db()?,
1336 };
1337 ids.push(id);
1338 }
1339 Ok(ids)
1340 })
1341 }
1342
1343 fn upsert_key_values(&self, owner: &str, key: &str, values: &[KeyValue]) -> Result<Vec<i64>> {
1344 check_key_values(owner, key, values)?;
1345 if values.is_empty() {
1346 return Ok(Vec::new());
1347 }
1348 self.write("upsert_key_values", |c| {
1349 let mut ids = Vec::with_capacity(values.len());
1350 for v in values {
1351 let aliases = aliases_json(&v.aliases);
1352 let id: i64 = c
1353 .prepare_cached(
1354 "INSERT INTO key_values (owner, key, value, label, aliases) VALUES (?1, ?2, ?3, ?4, ?5)
1355 ON CONFLICT (owner, key, value) DO UPDATE SET label = excluded.label, aliases = excluded.aliases
1356 RETURNING id",
1357 )
1358 .db()?
1359 .query_row(rusqlite::params![owner, key, v.value, v.label, aliases], |r| r.get(0))
1360 .db()?;
1361 ids.push(id);
1362 }
1363 Ok(ids)
1364 })
1365 }
1366
1367 fn refresh_value_counts(&self) -> Result<u64> {
1368 self.write("refresh_value_counts", |c| {
1369 let n = c
1370 .prepare_cached(
1371 "UPDATE key_values SET n_cells = COALESCE((
1372 SELECT count(*) FROM catalog_entries e JOIN cell_args a
1373 ON a.fn_hash = e.hash AND a.name = key_values.key AND a.value = key_values.value
1374 WHERE e.kind = 'function' AND e.name = key_values.owner), 0)",
1375 )
1376 .db()?
1377 .execute([])
1378 .db()?;
1379 Ok(n as u64)
1380 })
1381 }
1382
1383 fn text_find(&self, query: &str, limit: usize) -> Result<Vec<Hit>> {
1384 let Some(words) = Words::new(query) else { return Ok(Vec::new()) };
1385 if limit == 0 {
1386 return Ok(Vec::new());
1387 }
1388 let entry_where = like_where_sqlite(&words, &["name", "label", "description", "args"]);
1389 let value_where = like_where_sqlite(&words, &["value", "label", "aliases"]);
1390 self.run("text_find", |c| {
1391 let mut hits = Vec::new();
1392 let sql = format!(
1393 "SELECT id, kind, name, hash, label, description, args, examples, source, signed_by FROM catalog_entries WHERE 1 = 1{}",
1394 entry_where.0
1395 );
1396 let rows: Vec<EntryRow> = {
1397 let mut st = c.prepare(&sql).db()?;
1398 let mapped = st.query_map(rusqlite::params_from_iter(entry_where.1.iter()), entry_columns).db()?;
1399 mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
1400 };
1401 for (id, kind, name, hash, label, description, args, examples, source, signed_by) in rows {
1402 let entry = entry_from_columns(&kind, name, hash, label, description, &args, &examples, &source, signed_by)?;
1403 let score = words.score(&entry_fields(&entry));
1404 if let Some(score) = score {
1405 hits.push(Hit::Entry { id, entry, score });
1406 }
1407 }
1408 let sql = format!("SELECT id, owner, key, value, label, aliases FROM key_values WHERE 1 = 1{}", value_where.0);
1409 let rows: Vec<ValueRow> = {
1410 let mut st = c.prepare(&sql).db()?;
1411 let mapped = st.query_map(rusqlite::params_from_iter(value_where.1.iter()), value_columns_of).db()?;
1412 mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
1413 };
1414 for (id, owner, key, value, label, aliases_text) in rows {
1415 let aliases = parse_aliases(&aliases_text)?;
1416 let score = {
1417 let mut fields: Vec<&str> = vec![&value, &label];
1418 fields.extend(aliases.iter().map(String::as_str));
1419 words.score(&fields)
1420 };
1421 if let Some(score) = score {
1422 hits.push(Hit::Value { id, owner, key, value, label, aliases, score });
1423 }
1424 }
1425 Ok(rank(hits, limit))
1426 })
1427 }
1428
1429 fn vector_find(&self, _model: &str, _vec: &[f32], _limit: usize) -> Result<Vec<Hit>> {
1430 Err(unsupported_vectors())
1431 }
1432
1433 fn put_embeddings(&self, _model: &str, _items: &[Embedding]) -> Result<()> {
1434 Err(unsupported_vectors())
1435 }
1436
1437 fn pending_embeddings(&self, _model: &str, _limit: usize) -> Result<Vec<PendingEmbedding>> {
1438 Ok(Vec::new())
1439 }
1440
1441 fn vector_available(&self) -> bool {
1442 false
1443 }
1444
1445 fn log_miss(&self, query: &str) -> Result<()> {
1446 let Some(q) = miss_text(query) else { return Ok(()) };
1447 self.write("log_miss", |c| {
1448 c.prepare_cached("INSERT INTO find_misses (query) VALUES (?1)").db()?.execute([q]).db()?;
1449 c.prepare_cached(
1451 "DELETE FROM find_misses WHERE rowid IN (SELECT rowid FROM find_misses ORDER BY at
1452 LIMIT max((SELECT count(*) FROM find_misses) - ?1, 0))",
1453 )
1454 .db()?
1455 .execute([as_i64(FIND_MISSES_CAP)])
1456 .db()?;
1457 Ok(())
1458 })
1459 }
1460
1461 fn put_function_test(&self, test: &FunctionTest) -> Result<bool> {
1462 let (total, covered) = crate::functions::check_test(test)?;
1463 self.write("put_function_test", |c| {
1464 let n = exec(
1465 c,
1466 L::FunctionTestPut,
1467 rusqlite::params![
1468 &test.fn_hash,
1469 &test.case,
1470 &test.test_json,
1471 &test.signed_by,
1472 &test.last_run_at,
1473 &test.last_result,
1474 &test.last_detail,
1475 total,
1476 covered
1477 ],
1478 )?;
1479 Ok(n == 1)
1480 })
1481 }
1482
1483 fn function_tests(&self, fn_hash: &str) -> Result<Vec<FunctionTest>> {
1484 check_hex(fn_hash, 64, "fn_hash")?;
1485 self.run("function_tests", |c| {
1486 let mut st = c.prepare_cached(L::FunctionTestsOf.sql()).db()?;
1487 let rows = st.query_map([fn_hash], function_test_row).db()?;
1488 rows.collect::<rusqlite::Result<Vec<FunctionTest>>>().db()
1489 })
1490 }
1491
1492 fn record_function_test(
1493 &self,
1494 fn_hash: &str,
1495 case: &str,
1496 run_at: &str,
1497 result: &str,
1498 detail: &str,
1499 ) -> Result<bool> {
1500 check_hex(fn_hash, 64, "fn_hash")?;
1501 crate::functions::check_case(case)?;
1502 check_instant(run_at, "run_at")?;
1503 crate::functions::check_result(result)?;
1504 self.write("record_function_test", |c| {
1505 let n = exec(c, L::FunctionTestRecord, rusqlite::params![run_at, result, detail, fn_hash, case])?;
1506 Ok(n == 1)
1507 })
1508 }
1509
1510 fn set_function_branches(&self, fn_hash: &str, total: u32, covered: u32) -> Result<()> {
1511 check_hex(fn_hash, 64, "fn_hash")?;
1512 let (total, covered) = crate::functions::branch_counts(total, covered)?;
1513 self.write("set_function_branches", |c| {
1514 exec(c, L::FunctionBranches, rusqlite::params![fn_hash, total, covered]).map(|_| ())
1515 })
1516 }
1517
1518 fn function_readers(&self, name: &str) -> Result<Vec<String>> {
1519 check_function_name(name, "name")?;
1520 self.run("function_readers", |c| get_strings(c, L::FunctionReaders, name))
1521 }
1522
1523 fn bound_names(&self, fn_hash: &str) -> Result<Vec<String>> {
1524 check_hex(fn_hash, 64, "fn_hash")?;
1525 self.run("bound_names", |c| get_strings(c, L::BoundNames, fn_hash))
1526 }
1527
1528 fn name_function_tests(&self, fn_hash: &str, names: &[(String, String)]) -> Result<u64> {
1529 check_hex(fn_hash, 64, "fn_hash")?;
1530 for (case, name) in names {
1531 crate::functions::check_case(case)?;
1532 check_function_name(name, "name")?;
1533 }
1534 if names.is_empty() {
1535 return Ok(0);
1536 }
1537 self.write("name_function_tests", |c| {
1538 let mut st = c.prepare_cached(L::FunctionTestName.sql()).db()?;
1539 let mut named = 0u64;
1540 for (case, name) in names {
1541 named += st.execute(rusqlite::params![fn_hash, case, name]).db()? as u64;
1542 }
1543 Ok(named)
1544 })
1545 }
1546
1547 fn unnamed_function_tests(&self, limit: usize) -> Result<Vec<FunctionTest>> {
1548 let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1549 self.run("unnamed_function_tests", |c| {
1550 let mut st = c.prepare_cached(L::FunctionTestsUnnamed.sql()).db()?;
1551 let rows = st.query_map([limit], function_test_row).db()?;
1552 rows.collect::<rusqlite::Result<Vec<FunctionTest>>>().db()
1553 })
1554 }
1555
1556 fn function_test_summary(&self, fn_hash: &str, fn_name: Option<&str>) -> Result<TestSummary> {
1557 check_hex(fn_hash, 64, "fn_hash")?;
1558 self.run("function_test_summary", |c| {
1559 let mut st = c.prepare_cached(L::FunctionTestSummary.sql()).db()?;
1560 let (count, pass, fail, error, not_run, last_run_at, total, covered) = st
1561 .query_row(rusqlite::params![fn_hash, fn_name], |r| {
1562 Ok((
1563 r.get::<_, i64>(0)?,
1564 r.get::<_, i64>(1)?,
1565 r.get::<_, i64>(2)?,
1566 r.get::<_, i64>(3)?,
1567 r.get::<_, i64>(4)?,
1568 r.get::<_, Option<String>>(5)?,
1569 r.get::<_, i64>(6)?,
1570 r.get::<_, i64>(7)?,
1571 ))
1572 })
1573 .db()?;
1574 Ok(TestSummary {
1576 count: count as u64,
1577 pass: pass as u64,
1578 fail: fail as u64,
1579 error: error as u64,
1580 not_run: not_run as u64,
1581 last_run_at,
1582 branches_total: total as u32,
1583 branches_covered: covered as u32,
1584 })
1585 })
1586 }
1587
1588 fn function_tests_page(
1589 &self,
1590 fn_hash: &str,
1591 fn_name: Option<&str>,
1592 after_case: Option<&str>,
1593 limit: usize,
1594 ) -> Result<Vec<FunctionTest>> {
1595 check_hex(fn_hash, 64, "fn_hash")?;
1596 let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1597 self.run("function_tests_page", |c| {
1598 let rows: Vec<FunctionTest> = match fn_name {
1599 None => {
1600 let mut st = c.prepare_cached(L::FunctionTestsPage.sql()).db()?;
1601 let mapped = st.query_map(rusqlite::params![fn_hash, after_case, limit], function_test_row).db()?;
1602 mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
1603 }
1604 Some(name) => {
1605 let mut st = c.prepare_cached(L::FunctionTestsPageNamed.sql()).db()?;
1606 let mapped =
1607 st.query_map(rusqlite::params![fn_hash, name, after_case, limit], function_test_row).db()?;
1608 mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
1609 }
1610 };
1611 Ok(rows)
1612 })
1613 }
1614
1615 fn stored_receipts_of(&self, ns: &str, fn_name: &str, fn_hash: &str, limit: usize) -> Result<Vec<Vec<u8>>> {
1616 check_hex(fn_hash, 64, "fn_hash")?;
1617 let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1618 self.run("stored_receipts_of", |c| {
1619 let mut st = c.prepare_cached(L::StoredReceiptsOf.sql()).db()?;
1620 let rows = st.query_map(rusqlite::params![fn_hash, ns, fn_name, limit], |r| r.get::<_, Vec<u8>>(0)).db()?;
1621 rows.collect::<rusqlite::Result<Vec<Vec<u8>>>>().db()
1622 })
1623 }
1624
1625 fn slice_values_limit(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<SliceValue>> {
1626 check_instant(asof, "asof")?;
1627 let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1628 let v = slice.to_value();
1629 if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1630 return self.run("slice_values_limit", |c| {
1631 let sql = format!("{} LIMIT ?5", L::VersionsBetweenValues.sql());
1633 let mut st = c.prepare(&sql).db()?;
1634 let mut rows = st.query(rusqlite::params![cell_id, from, to, asof, limit]).db()?;
1635 let mut out = Vec::new();
1636 while let Some(r) = rows.next().db()? {
1637 out.push(value_of(value_columns(r).db()?)?.0);
1638 }
1639 Ok(out)
1640 });
1641 }
1642 let p = Pattern::of(&v)?;
1643 self.run("slice_values_limit", |c| values_limited(&p, c, asof, limit))
1644 }
1645
1646 fn versions_limit(&self, cell_id: &str, from: &str, to: &str, limit: usize) -> Result<Vec<Version>> {
1647 check_hex(cell_id, 64, "cell_id")?;
1648 check_instant(from, "from")?;
1649 check_instant(to, "to")?;
1650 let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1651 self.run("versions_limit", |c| {
1652 let mut st = c.prepare_cached(L::VersionRangeLimit.sql()).db()?;
1653 let rows = st.query_map(rusqlite::params![cell_id, from, to, limit], |r| version_row(r, cell_id)).db()?;
1654 rows.collect::<rusqlite::Result<Vec<Version>>>().db()
1655 })
1656 }
1657
1658 fn stored_cell_count(&self, ns: &str, fn_name: &str, fn_hash: &str) -> Result<u64> {
1659 check_hex(fn_hash, 64, "fn_hash")?;
1660 self.run("stored_cell_count", |c| {
1661 let n: i64 = c
1662 .prepare_cached(L::StoredCellCount.sql())
1663 .db()?
1664 .query_row(rusqlite::params![fn_hash, ns, fn_name], |r| r.get(0))
1665 .db()?;
1666 Ok(n as u64)
1667 })
1668 }
1669
1670 fn has_key_value(&self, owner: &str, key: &str, value: &str) -> Result<bool> {
1671 self.run("has_key_value", |c| {
1672 c.prepare_cached(L::DictionaryHas.sql())
1673 .db()?
1674 .query_row(rusqlite::params![owner, key, value], |r| r.get(0))
1675 .db()
1676 })
1677 }
1678
1679 fn key_value_count(&self, owner: &str, key: &str) -> Result<u64> {
1680 self.run("key_value_count", |c| {
1681 let n: i64 = c
1682 .prepare_cached(L::DictionaryCount.sql())
1683 .db()?
1684 .query_row(rusqlite::params![owner, key], |r| r.get(0))
1685 .db()?;
1686 Ok(n as u64)
1687 })
1688 }
1689
1690 fn mark_key_open(&self, owner: &str, key: &str) -> Result<()> {
1691 if owner.is_empty() || owner.len() > 512 || key.is_empty() || key.len() > 128 {
1692 return Err(invalid("key", "an owner of 1 to 512 bytes and a key of 1 to 128 bytes"));
1693 }
1694 self.write("mark_key_open", |c| exec(c, L::KeyOpenPut, rusqlite::params![owner, key]).map(|_| ()))
1695 }
1696
1697 fn open_key_count(&self) -> Result<u64> {
1698 self.run("open_key_count", |c| {
1699 let n: i64 = c.prepare_cached(L::OpenKeyCount.sql()).db()?.query_row([], |r| r.get(0)).db()?;
1700 Ok(n as u64)
1701 })
1702 }
1703
1704 fn key_is_open(&self, owner: &str, key: &str) -> Result<bool> {
1705 self.run("key_is_open", |c| {
1706 c.prepare_cached(L::KeyIsOpen.sql()).db()?.query_row(rusqlite::params![owner, key], |r| r.get(0)).db()
1707 })
1708 }
1709
1710 fn catalog_entry(&self, name: &str) -> Result<Option<CatalogEntry>> {
1711 self.run("catalog_entry", |c| {
1712 let mut st = c.prepare_cached(L::CatalogEntryNamed.sql()).db()?;
1713 let row = st
1714 .query_row([name], |r| {
1715 Ok((
1716 r.get::<_, String>(0)?,
1717 r.get::<_, String>(1)?,
1718 r.get::<_, Option<String>>(2)?,
1719 r.get::<_, String>(3)?,
1720 r.get::<_, String>(4)?,
1721 r.get::<_, String>(5)?,
1722 r.get::<_, String>(6)?,
1723 r.get::<_, String>(7)?,
1724 r.get::<_, Option<String>>(8)?,
1725 ))
1726 })
1727 .optional()
1728 .db()?;
1729 let Some((kind, name, hash, label, description, args, examples, source, signed_by)) = row else {
1730 return Ok(None);
1731 };
1732 entry_from_columns(&kind, name, hash, label, description, &args, &examples, &source, signed_by).map(Some)
1733 })
1734 }
1735
1736 fn catalog_summary(&self) -> Result<Summary> {
1737 self.run("catalog_summary", |c| {
1738 let rows: Vec<(String, String, String, i64)> = {
1739 let mut st = c
1740 .prepare(
1741 "SELECT kind, name, label, CASE WHEN kind = 'function'
1742 THEN (SELECT count(*) FROM cells x WHERE x.fn_hash = e.hash) ELSE 0 END
1743 FROM catalog_entries e ORDER BY kind, name",
1744 )
1745 .db()?;
1746 let mapped = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))).db()?;
1747 mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
1748 };
1749 let mut entries = Vec::with_capacity(rows.len());
1750 for (kind, name, label, n_cells) in rows {
1751 let kind = CatalogKind::parse(&kind).ok_or_else(|| invalid("catalog", "a stored entry has a bad kind"))?;
1752 entries.push(SummaryEntry { kind, name, label, n_cells });
1753 }
1754 let groups: Vec<(String, String, i64)> = {
1755 let mut st = c.prepare("SELECT owner, key, count(*) FROM key_values GROUP BY owner, key ORDER BY owner, key").db()?;
1756 let mapped = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).db()?;
1757 mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
1758 };
1759 let mut dictionaries = Vec::with_capacity(groups.len());
1760 for (owner, key, n_values) in groups {
1761 let values: Vec<DictionaryValue> = {
1762 let mut st = c
1763 .prepare("SELECT value, label, n_cells FROM key_values WHERE owner = ?1 AND key = ?2 ORDER BY value LIMIT ?3")
1764 .db()?;
1765 let mapped = st
1766 .query_map(rusqlite::params![owner, key, as_i64(SUMMARY_VALUES)], |r| {
1767 Ok(DictionaryValue { value: r.get(0)?, label: r.get(1)?, n_cells: r.get(2)? })
1768 })
1769 .db()?;
1770 mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
1771 };
1772 dictionaries.push(Dictionary { owner, key, n_values, values });
1773 }
1774 Ok(Summary { entries, dictionaries })
1775 })
1776 }
1777}
1778
1779type ValueColumns = (String, String, String, String, String, String, String, String, String, String);
1782
1783fn value_columns(r: &rusqlite::Row<'_>) -> rusqlite::Result<ValueColumns> {
1784 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)?))
1785}
1786
1787fn value_of(c: ValueColumns) -> Result<(SliceValue, Args)> {
1789 let (tx, receipt_hash, asof, ty, value, cell_id, args, ns, fn_name, fn_hash) = c;
1790 let ty = Type::from_name(&ty).ok_or_else(|| bad("type"))?;
1791 let args = args_of(&args)?;
1792 let cell = Cell { args: args.clone(), fn_hash, fn_name, ns };
1793 Ok((
1794 SliceValue {
1795 version: Version { cell_id, tx, receipt_hash, asof },
1796 value: Scalar::from_lexical(ty, &value)?,
1797 cell,
1798 },
1799 args,
1800 ))
1801}
1802
1803fn constraints(p: &Pattern) -> String {
1806 let items: Vec<Value> = p
1807 .args
1808 .iter()
1809 .map(|a| {
1810 let (lo, hi) = match a.kind {
1811 Kind::Range => (sort_key(&a.ty, &a.lo), sort_key(&a.ty, &a.hi)),
1812 _ => (a.lo.clone(), a.hi.clone()),
1813 };
1814 Value::Array(
1815 [a.name.clone(), a.kind.as_str().to_string(), a.ty.clone(), lo, hi]
1816 .into_iter()
1817 .map(Value::String)
1818 .collect(),
1819 )
1820 })
1821 .collect();
1822 String::from_utf8(Value::Array(items).to_jcs()).unwrap_or_default()
1823}
1824
1825fn bind(st: &mut rusqlite::CachedStatement<'_>, params: &[(&str, SqlValue)]) -> Result<()> {
1827 for (name, value) in params {
1828 if let Some(i) = st.parameter_index(name).db()? {
1829 st.raw_bind_parameter(i, value).db()?;
1830 }
1831 }
1832 Ok(())
1833}
1834
1835fn drive<'p>(p: &'p Pattern, c: &Connection, count: bool) -> Result<(Option<&'p Constraint>, Option<i64>)> {
1839 let probe = |a: Option<&Constraint>| -> Result<i64> {
1840 match a {
1841 None => c.prepare_cached(L::ProbeCells.sql()).db()?.query_row([&p.fn_hash], |r| r.get(0)).db(),
1842 Some(a) => {
1843 let (lo, hi) = (sort_key(&a.ty, &a.lo), sort_key(&a.ty, &a.hi));
1844 c.prepare_cached(L::SliceProbe.sql())
1845 .db()?
1846 .query_row(rusqlite::params![p.fn_hash, a.name, a.ty, lo, hi], |r| r.get(0))
1847 .db()
1848 }
1849 }
1850 };
1851 let constrained: Vec<&Constraint> = p.args.iter().filter(|a| a.kind != Kind::Open).collect();
1852 Ok(match constrained.as_slice() {
1853 [] => (None, if count { Some(probe(None)?) } else { None }),
1854 [one] => (Some(*one), if count { Some(probe(Some(one))?) } else { None }),
1855 several => {
1856 let mut best: Option<(i64, &Constraint)> = None;
1857 for a in several {
1858 let n = probe(Some(a))?;
1859 if best.is_none_or(|(m, _)| n < m) {
1860 best = Some((n, a));
1861 }
1862 }
1863 (best.map(|(_, a)| a), best.map(|(n, _)| n))
1864 }
1865 })
1866}
1867
1868fn params(p: &Pattern, asof: &str, drive: Option<&Constraint>) -> Vec<(&'static str, SqlValue)> {
1870 let text = |s: &str| SqlValue::Text(s.to_string());
1871 let mut out = vec![
1872 (":fn_hash", text(&p.fn_hash)),
1873 (":ns", text(&p.ns)),
1874 (":fn", text(&p.fn_name)),
1875 (":nargs", SqlValue::Integer(p.args.len() as i64)),
1876 (":asof", text(asof)),
1877 (":cons", SqlValue::Text(constraints(p))),
1878 ];
1879 if let Some(a) = drive {
1880 out.push((":d_name", text(&a.name)));
1881 out.push((":d_type", text(&a.ty)));
1882 out.push((":d_lo", SqlValue::Text(sort_key(&a.ty, &a.lo))));
1883 out.push((":d_hi", SqlValue::Text(sort_key(&a.ty, &a.hi))));
1884 }
1885 out
1886}
1887
1888fn rows<T>(
1890 p: &Pattern,
1891 c: &Connection,
1892 asof: &str,
1893 qs: [L; 2],
1894 make: impl Fn(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
1895) -> Result<Vec<T>> {
1896 let (d, _) = drive(p, c, false)?;
1897 let q = if d.is_some() { qs[1] } else { qs[0] };
1898 let mut st = c.prepare_cached(q.sql()).db()?;
1899 bind(&mut st, ¶ms(p, asof, d))?;
1900 let mut rows = st.raw_query();
1901 let mut out = Vec::new();
1902 while let Some(r) = rows.next().db()? {
1903 out.push(make(r).db()?);
1904 }
1905 Ok(out)
1906}
1907
1908fn key_of(p: &Pattern, args: &Args) -> Vec<String> {
1910 p.args
1911 .iter()
1912 .filter(|a| a.kind != Kind::Value)
1913 .filter_map(|a| args.get(&a.name).and_then(Arg::scalar))
1914 .map(|s| format!("{}:{}", s.ty().as_str(), s.lexical()))
1915 .collect()
1916}
1917
1918fn in_key_order<T>(p: &Pattern, rows: Vec<(T, String)>, cell_of: impl Fn(&T) -> &String) -> Result<Vec<T>> {
1920 let mut keyed = Vec::with_capacity(rows.len());
1921 for (m, args) in rows {
1922 keyed.push((key_of(p, &args_of(&args)?), m));
1923 }
1924 keyed.sort_by(|(a, ma), (b, mb)| cmp_keys(a, b).then_with(|| cell_of(ma).cmp(cell_of(mb))));
1925 Ok(keyed.into_iter().map(|(_, m)| m).collect())
1926}
1927
1928fn in_key_order_parsed<T>(p: &Pattern, rows: Vec<(T, Args)>, cell_of: impl Fn(&T) -> &String) -> Result<Vec<T>> {
1930 let mut keyed: Vec<(Vec<String>, T)> = rows.into_iter().map(|(m, args)| (key_of(p, &args), m)).collect();
1931 keyed.sort_by(|(a, ma), (b, mb)| cmp_keys(a, b).then_with(|| cell_of(ma).cmp(cell_of(mb))));
1932 Ok(keyed.into_iter().map(|(_, m)| m).collect())
1933}
1934
1935fn values_limited(p: &Pattern, c: &Connection, asof: &str, limit: i64) -> Result<Vec<SliceValue>> {
1940 let (d, _) = drive(p, c, false)?;
1941 let base = if d.is_some() { L::SliceValuesDrive } else { L::SliceValuesAll };
1942 let keys: Vec<&Constraint> = p.args.iter().filter(|a| a.kind != Kind::Value).collect();
1943 let mut order = Vec::with_capacity(keys.len() * 2 + 1);
1944 for i in 0..keys.len() {
1945 let of =
1946 |col: &str| format!("(SELECT x.{col} FROM cell_args x WHERE x.cell_id = c.cell_id AND x.name = :k{i})");
1947 order.push(of("type"));
1948 order.push(of("sort_key"));
1949 }
1950 order.push("c.cell_id".to_string());
1951 let sql = format!("{} ORDER BY {} LIMIT :limit", base.sql(), order.join(", "));
1952 let mut binds: Vec<(String, SqlValue)> = params(p, asof, d).into_iter().map(|(k, v)| (k.to_string(), v)).collect();
1953 for (i, a) in keys.iter().enumerate() {
1954 binds.push((format!(":k{i}"), SqlValue::Text(a.name.clone())));
1955 }
1956 binds.push((":limit".to_string(), SqlValue::Integer(limit)));
1957 let mut st = c.prepare(&sql).db()?;
1958 for (name, value) in &binds {
1959 if let Some(i) = st.parameter_index(name).db()? {
1960 st.raw_bind_parameter(i, value).db()?;
1961 }
1962 }
1963 let mut rows = st.raw_query();
1964 let mut out = Vec::new();
1965 while let Some(r) = rows.next().db()? {
1966 out.push(value_of(value_columns(r).db()?)?.0);
1967 }
1968 Ok(out)
1969}
1970
1971fn changed_after(p: &Pattern, c: &Connection, asof: &str) -> Result<bool> {
1975 let (d, candidates) = drive(p, c, true)?;
1976 let recent: i64 = c
1977 .prepare_cached(L::ProbeRecent.sql())
1978 .db()?
1979 .query_row(rusqlite::params![p.fn_hash, asof], |r| r.get(0))
1980 .db()?;
1981 let q = if recent <= candidates.unwrap_or(i64::MAX) {
1982 L::ChangedRecent
1983 } else if d.is_some() {
1984 L::ChangedCandDrive
1985 } else {
1986 L::ChangedCandAll
1987 };
1988 let d = if q == L::ChangedCandDrive { d } else { None };
1989 let mut st = c.prepare_cached(q.sql()).db()?;
1990 bind(&mut st, ¶ms(p, asof, d))?;
1991 let mut rows = st.raw_query();
1992 Ok(rows.next().db()?.is_some())
1993}
1994
1995type EntryRow = (i64, String, String, Option<String>, String, String, String, String, String, Option<String>);
1997
1998fn entry_columns(r: &rusqlite::Row<'_>) -> rusqlite::Result<EntryRow> {
1999 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)?))
2000}
2001
2002type ValueRow = (i64, String, String, String, String, String);
2004
2005fn value_columns_of(r: &rusqlite::Row<'_>) -> rusqlite::Result<ValueRow> {
2006 Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?))
2007}
2008
2009fn like_where_sqlite(words: &Words, fields: &[&str]) -> (String, Vec<String>) {
2013 let mut sql = String::new();
2014 let mut params = Vec::new();
2015 for i in 0..words.len() {
2016 if let Some(p) = words.pattern(i, sqlite_safe) {
2017 params.push(p);
2018 let n = params.len();
2019 let ors: Vec<String> = fields.iter().map(|f| format!("{f} LIKE ?{n} ESCAPE '!'")).collect();
2020 sql.push_str(&format!(" AND ({})", ors.join(" OR ")));
2021 }
2022 }
2023 (sql, params)
2024}
2025
2026fn sqlite_safe(word: &str) -> bool {
2027 word.is_ascii() && !word.chars().any(|c| c == '"' || c == '\\' || c.is_control())
2028}
2029
2030fn unsupported_vectors() -> Error {
2031 Error::Unsupported("vectors need PostgreSQL with the vector extension; SQLite has none".into())
2032}
2033
2034fn function_test_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<FunctionTest> {
2036 Ok(FunctionTest {
2037 fn_hash: r.get(0)?,
2038 case: r.get(1)?,
2039 test_json: r.get(2)?,
2040 signed_by: r.get(3)?,
2041 last_run_at: r.get(4)?,
2042 last_result: r.get(5)?,
2043 last_detail: r.get(6)?,
2044 branches_total: r.get(7)?,
2045 branches_covered: r.get(8)?,
2046 })
2047}
2048
2049#[cfg(test)]
2050mod tests {
2051 use super::*;
2052 use crate::slices::cmp_decimal;
2053
2054 #[test]
2055 fn decimal_keys_sort_as_the_numbers() {
2056 let mut numbers: Vec<String> = [
2057 "0", "9", "10", "-1.5", "-1", "-1.25", "-1.11", "-1.1", "-0.1", "-0.099", "0.099", "0.1", "0.109", "0.11",
2058 "1", "1.1", "1.109", "1.11", "9.5", "99.999", "100", "-100", "-10", "-9", "123", "-123", "0.0001",
2059 "-0.0001", "1000000", "-1000000", "12.5", "12.05", "-12.5", "-12.05", "120", "-120", "1.2", "-1.2",
2060 ]
2061 .iter()
2062 .map(|s| s.to_string())
2063 .collect();
2064 numbers.push("9".repeat(128));
2065 numbers.push(format!("-{}", "9".repeat(127)));
2066 numbers.push(format!("1{}", "0".repeat(127)));
2067 numbers.push(format!("-1{}", "0".repeat(126)));
2068 numbers.push(format!("0.{}1", "0".repeat(125)));
2069 numbers.push(format!("-0.{}1", "0".repeat(124)));
2070 numbers.push(format!("{}.{}", "1".repeat(64), "1".repeat(63)));
2071 numbers.push(format!("-{}.{}", "1".repeat(63), "1".repeat(63)));
2072 for a in &numbers {
2073 assert!(a.len() <= 128, "{a}");
2074 for b in &numbers {
2075 assert_eq!(decimal_key(a).cmp(&decimal_key(b)), cmp_decimal(a, b), "{a} vs {b}");
2076 }
2077 }
2078 assert_eq!(decimal_key("0"), "1");
2080 assert_eq!(decimal_key("100"), "25031");
2081 assert_eq!(decimal_key("0.0012"), "249812");
2082 assert_eq!(decimal_key("-1.5"), "049884~");
2083 assert_eq!(decimal_key(&"9".repeat(128)), format!("2628{}", "9".repeat(128)));
2084 }
2085
2086 #[test]
2087 fn result_codes_have_names() {
2088 assert_eq!(result_code_name(5), "SQLITE_BUSY");
2089 assert_eq!(result_code_name(1811), "SQLITE_CONSTRAINT_TRIGGER");
2090 assert_eq!(result_code_name(14), "SQLITE_CANTOPEN");
2091 assert_eq!(result_code_name(10 | (99 << 8)), "SQLITE_IOERR(25354)");
2092 }
2093
2094 #[test]
2095 fn sqlite_urls_name_paths() {
2096 assert_eq!(sqlite_path("sqlite:store.db"), "store.db");
2097 assert_eq!(sqlite_path("sqlite://store.db"), "store.db");
2098 assert_eq!(sqlite_path("sqlite:///var/lib/x.db"), "/var/lib/x.db");
2099 assert_eq!(sqlite_path("/var/lib/x.db"), "/var/lib/x.db");
2100 assert_eq!(sqlite_path("x.db"), "x.db");
2101 }
2102
2103 fn plan(c: &Connection, sql: &str) -> Vec<String> {
2105 let mut st = c.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap();
2106 let n = st.parameter_count();
2107 for i in 1..=n {
2108 st.raw_bind_parameter(i, "x").unwrap();
2109 }
2110 let mut rows = st.raw_query();
2111 let mut out = Vec::new();
2112 while let Some(r) = rows.next().unwrap() {
2113 out.push(r.get::<_, String>(3).unwrap());
2114 }
2115 out
2116 }
2117
2118 #[test]
2123 fn bounded_slices_use_indexes() {
2124 let c = Connection::open_in_memory().unwrap();
2125 for m in crate::migrate::sqlite::MIGRATIONS {
2126 c.execute_batch(m.sql).unwrap();
2127 }
2128 c.execute_batch(
2130 "ANALYZE sqlite_schema;
2131 INSERT INTO sqlite_stat1 (tbl, idx, stat) VALUES
2132 ('cells', 'cells_fn_hash', '100000 100000 1'),
2133 ('cells', 'sqlite_autoindex_cells_1', '100000 1'),
2134 ('cell_args', 'cell_args_key', '200000 200000 100000 100000 1 1'),
2135 ('cell_args', 'sqlite_autoindex_cell_args_1', '200000 2 1'),
2136 ('versions', 'sqlite_autoindex_versions_1', '100000 1 1'),
2137 ('versions', 'versions_receipt_hash', '100000 1'),
2138 ('receipts', 'sqlite_autoindex_receipts_1', '100000 1'),
2139 ('receipts', 'receipts_cell_tx', '100000 1 1'),
2140 ('receipts', 'receipts_fn_hash_asof', '100000 100000 1'),
2141 ('receipts', 'receipts_cell_asof', '100000 1 1');
2142 ANALYZE sqlite_schema;",
2143 )
2144 .unwrap();
2145 let scans = |s: &str| s.starts_with("SCAN ") && !s.starts_with("SCAN k") && !s.starts_with("SCAN (subquery");
2148 for q in [
2149 L::SliceMembersDrive,
2150 L::SliceValuesDrive,
2151 L::ChangedCandDrive,
2152 L::ChangedRecent,
2153 L::SliceProbe,
2154 L::ProbeRecent,
2155 L::ProbeCells,
2156 L::VersionsBetween,
2157 L::VersionsBetweenValues,
2158 L::StoredAsof,
2159 L::ComputedAsof,
2160 L::CellDependents,
2161 ] {
2162 let steps = plan(&c, q.sql());
2163 assert!(!steps.iter().any(|s| scans(s)), "{q:?} scans:\n{steps:#?}");
2164 }
2165 for q in [L::SliceMembersAll, L::SliceValuesAll, L::ChangedCandAll] {
2167 let steps = plan(&c, q.sql());
2168 assert!(
2169 steps.iter().any(|s| s.contains("SEARCH c USING") && s.contains("cells_fn_hash")),
2170 "{q:?}: {steps:#?}"
2171 );
2172 assert!(!steps.iter().any(|s| scans(s)), "{q:?} scans:\n{steps:#?}");
2173 }
2174 }
2175}