Skip to main content

datumesh_store/
sqlite.rs

1//! `SqliteStore`: the store in one SQLite file (since 0.4.0).
2
3use 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_catalog_ext, check_key_values,
13    entry_ext, entry_from_columns, invalid, miss_text, parse_aliases, parse_args, parse_facets, rank, CatalogRow,
14    Words, SUMMARY_VALUES,
15};
16use crate::error::{Db, Error, Result};
17use crate::listings::{
18    check_listed_host, check_listing, listing_facets_json, parse_subjects, same_listing, subjects_json,
19};
20use crate::slices::{check_entry, cmp_keys, is_hash, is_instant, version_slice, Constraint, Kind, Pattern};
21use crate::sqlite_sql::L;
22use crate::{
23    later_than, not_canonical_class, parse_receipt, stored_value, unbound, Binding, CatalogEntry, CatalogEntryExt,
24    CatalogKind, ClassBinding, Dictionary, DictionaryValue, Embedding, FacetedEntry, FunctionTest, Hit, KeyValue,
25    MemberSet, Namespace, PendingEmbedding, SliceMember, SliceValue, Store, Summary, SummaryEntry, TestSummary,
26    Version, FIND_MISSES_CAP, WITHDRAWN_VALUE,
27};
28use crate::{ListedHost, Listing, ListingWrite};
29use datumesh_core::json::{self, Value};
30use datumesh_core::lexical::{check_dns_name, check_function_name, check_hex, check_instant};
31use datumesh_core::{
32    keys_from_response, sha256_hex, verify, Arg, Args, Cell, ClassDescriptor, ErrorCode, FunctionDescriptor, Keys,
33    Manifest, Resolver, Scalar, Slice, Type,
34};
35
36/// How a [`SqliteStore`] opens and uses its connections.
37///
38/// Builder style: `SqliteOptions::new().busy_timeout(Duration::from_secs(5))`.
39#[derive(Clone, PartialEq, Eq)]
40pub struct SqliteOptions {
41    max_size: usize,
42    busy_timeout: Duration,
43    durable: bool,
44    pub(crate) recording_clock: Option<crate::pool::ClockRef>,
45    /// How long the barrier waits for a write transaction in flight (decided 27 Nov, B2/B3).
46    pub(crate) barrier_timeout: Duration,
47}
48
49impl std::fmt::Debug for SqliteOptions {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        f.debug_struct("SqliteOptions")
52            .field("max_size", &self.max_size)
53            .field("busy_timeout", &self.busy_timeout)
54            .field("barrier_timeout", &self.barrier_timeout)
55            .field("durable", &self.durable)
56            .field("recording_clock", &self.recording_clock.is_some())
57            .finish()
58    }
59}
60
61impl Default for SqliteOptions {
62    fn default() -> SqliteOptions {
63        SqliteOptions::new()
64    }
65}
66
67impl SqliteOptions {
68    /// At most 8 idle connections kept; a writer waits at most 30 seconds for the
69    /// database's write lock (and a reader for a lock held in exclusive mode); every commit
70    /// durable (`synchronous = FULL`).
71    pub fn new() -> SqliteOptions {
72        SqliteOptions {
73            max_size: 8,
74            busy_timeout: Duration::from_secs(30),
75            durable: true,
76            recording_clock: None,
77            barrier_timeout: Duration::from_secs(5),
78        }
79    }
80
81    /// How long the barrier waits for a write transaction in flight, in this process or another, before it
82    /// fails with [`Error::Timeout`](crate::Error::Timeout). Default 5 s. Since 0.6.5.
83    pub fn barrier_timeout(mut self, d: Duration) -> SqliteOptions {
84        self.barrier_timeout = d;
85        self
86    }
87
88    /// The clock the store records its versions at (G9, [`RecordingClock`](crate::RecordingClock)): read at each insert,
89    /// `recorded = max(signed tx, clock())`. Without one a version is recorded at its signed tx.
90    /// Since 0.6.5.
91    pub fn recording_clock(mut self, clock: crate::RecordingClock) -> SqliteOptions {
92        self.recording_clock = Some(crate::pool::ClockRef(clock));
93        self
94    }
95
96    /// The most idle connections kept open for reuse (at least 1). More may be open at
97    /// once, one per concurrent call; SQLite connections are cheap, and readers do not
98    /// wait for each other or for the writer (WAL).
99    pub fn max_size(mut self, n: usize) -> SqliteOptions {
100        self.max_size = n.max(1);
101        self
102    }
103
104    /// How long a call waits for a lock another connection (of this process or another)
105    /// holds before failing with [`Error::Database`] (`SQLITE_BUSY`; reads through the
106    /// [`Resolver`]: `None`). Writers take the database's one write lock for the duration
107    /// of a `put_*`, so this is the longest a writer waits behind the others.
108    pub fn busy_timeout(mut self, d: Duration) -> SqliteOptions {
109        self.busy_timeout = d;
110        self
111    }
112
113    /// Whether each commit is flushed to disk before it returns (`synchronous = FULL`, the
114    /// default), or only at checkpoints (`synchronous = NORMAL`: a power loss can lose the
115    /// latest commits, never consistency; much faster for bulk loads, like PostgreSQL's
116    /// `synchronous_commit = off`). Either way an application crash loses nothing
117    /// committed.
118    pub fn durable(mut self, yes: bool) -> SqliteOptions {
119        self.durable = yes;
120        self
121    }
122}
123
124/// The store in one SQLite file (bundled SQLite, no server), with the same behaviour as
125/// [`PgStore`](crate::PgStore): every method, error and rule of [`Store`] and
126/// [`Resolver`]. `Send + Sync`: share one per process (behind an `Arc`); each call takes a
127/// connection for its duration. Since 0.4.0.
128///
129/// The file is in WAL mode (readers never wait for the writer), with a busy timeout
130/// ([`SqliteOptions::busy_timeout`]). Every `put_*` is one transaction begun with `BEGIN
131/// IMMEDIATE`: it takes the database's write lock first, so its checks (a version later
132/// than the latest, a key not yet taken) and its inserts are one atomic step against every
133/// other writer, threads of this process or other processes on the same machine. The
134/// append-only rules are also triggers in the file, so they hold for any connection. (A
135/// SQLite file on a network file system is not supported: its locks are not reliable.)
136///
137/// Every `put_*` is one transaction. [`Store`] methods return errors: a malformed argument
138/// is [`Error::Invalid`] (no query is made), a database failure [`Error::Database`]. The
139/// [`Resolver`] methods answer both with `None`; a database failure is logged with
140/// `tracing` (target `datumesh_store`, level `error`).
141pub struct SqliteStore {
142    path: PathBuf,
143    options: SqliteOptions,
144    idle: Mutex<Vec<Connection>>,
145    /// The store's own writers queue here before taking the database's write lock: SQLite's
146    /// busy handler polls with sleeps of up to 100 ms, so threads contending for the lock
147    /// would mostly sleep. Other stores and processes still meet at the database's lock.
148    writer: Mutex<()>,
149    /// Opened with `open_existing`: never creates the file, never changes its journal mode.
150    existing: bool,
151    /// Set once the versions table is found to have the recorded column (migration 13): cached (review item 6).
152    recorded_schema: std::sync::atomic::AtomicBool,
153}
154
155impl std::fmt::Debug for SqliteStore {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        f.debug_struct("SqliteStore").field("path", &self.path).finish_non_exhaustive()
158    }
159}
160
161/// A connection taken from the store, returned to it when dropped.
162struct Pooled<'a> {
163    store: &'a SqliteStore,
164    conn: Option<Connection>,
165}
166
167impl std::ops::Deref for Pooled<'_> {
168    type Target = Connection;
169    fn deref(&self) -> &Connection {
170        self.conn.as_ref().expect("a pooled connection")
171    }
172}
173
174impl Drop for Pooled<'_> {
175    fn drop(&mut self) {
176        if let Some(c) = self.conn.take() {
177            // A connection left inside a transaction (a failed rollback) is not reused.
178            if c.is_autocommit() {
179                if let Ok(mut idle) = self.store.idle.lock() {
180                    if idle.len() < self.store.options.max_size {
181                        idle.push(c);
182                    }
183                }
184            }
185        }
186    }
187}
188
189impl SqliteStore {
190    /// Opens the SQLite file at `path` with the default [`SqliteOptions`]; a missing file
191    /// is created (empty: apply [`migrate::sqlite::apply`](crate::migrate::sqlite::apply)
192    /// next), as a missing directory is not. [`open_existing`](Self::open_existing) creates
193    /// nothing.
194    pub fn open(path: impl AsRef<Path>) -> Result<SqliteStore> {
195        SqliteStore::open_with(path, SqliteOptions::new())
196    }
197
198    /// Opens the SQLite file at `path`, creating it when it is missing (its directory must
199    /// exist). One connection is opened at once (and
200    /// the file put in WAL mode), so a path that cannot be opened fails here
201    /// (`SQLITE_CANTOPEN`); the schema is not looked at, so a new or empty file is fine
202    /// (create the schema with [`migrate::sqlite::apply`](crate::migrate::sqlite::apply)).
203    pub fn open_with(path: impl AsRef<Path>, options: SqliteOptions) -> Result<SqliteStore> {
204        let store = SqliteStore {
205            path: path.as_ref().to_path_buf(),
206            options,
207            idle: Mutex::new(Vec::new()),
208            writer: Mutex::new(()),
209            existing: false,
210            recorded_schema: std::sync::atomic::AtomicBool::new(false),
211        };
212        let c = store.open_connection()?;
213        if let Ok(mut idle) = store.idle.lock() {
214            idle.push(c);
215        }
216        Ok(store)
217    }
218
219    /// Opens an existing SQLite file without changing anything: a path with no file is
220    /// [`Error::Database`] (`no such database file: <path>`, code `SQLITE_CANTOPEN`) and
221    /// nothing is created; the file's journal mode is left as it is. For checking a
222    /// database ([`migrate::sqlite::check`](crate::migrate::sqlite::check), the command's
223    /// `migrate --check`), which has no side effects. Writes through such a store work
224    /// as through any other. Since 0.4.0.
225    pub fn open_existing(path: impl AsRef<Path>) -> Result<SqliteStore> {
226        let path = path.as_ref();
227        if !path.is_file() {
228            return Err(Error::Database(crate::error::DatabaseError::no_such_file(path)));
229        }
230        let store = SqliteStore {
231            path: path.to_path_buf(),
232            options: SqliteOptions::new(),
233            idle: Mutex::new(Vec::new()),
234            writer: Mutex::new(()),
235            existing: true,
236            recorded_schema: std::sync::atomic::AtomicBool::new(false),
237        };
238        let c = store.open_connection()?;
239        if let Ok(mut idle) = store.idle.lock() {
240            idle.push(c);
241        }
242        Ok(store)
243    }
244
245    /// Opens a store named by a URL: `sqlite:<path>` or `sqlite://<path>` (so
246    /// `sqlite:///var/lib/datumesh/store.db` is an absolute path), or a plain file path.
247    /// Query parameters are not taken: the path is everything after the scheme.
248    pub fn connect(url: &str) -> Result<SqliteStore> {
249        SqliteStore::open(sqlite_path(url))
250    }
251
252    /// The database file's path.
253    pub fn path(&self) -> &Path {
254        &self.path
255    }
256
257    fn open_connection(&self) -> Result<Connection> {
258        let mut flags = OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_NO_MUTEX;
259        if !self.existing {
260            flags |= OpenFlags::SQLITE_OPEN_CREATE;
261        }
262        let c = Connection::open_with_flags(&self.path, flags).db()?;
263        register_text_functions(&c)?;
264        c.busy_timeout(self.options.busy_timeout).db()?;
265        c.set_prepared_statement_cache_capacity(L::ALL.len() + 16);
266        if self.existing {
267            // Nothing about the file changes: no journal mode, no synchronous setting.
268            c.execute_batch("PRAGMA foreign_keys = ON").db()?;
269            return Ok(c);
270        }
271        // WAL: readers and the writer do not block each other, and a commit appends to the
272        // log. Changing the mode needs a lock the busy handler does not always wait for (a
273        // new file opened by several processes at once), so it is retried here.
274        let start = Instant::now();
275        loop {
276            match c.query_row("PRAGMA journal_mode = WAL", [], |r| r.get::<_, String>(0)) {
277                Ok(mode) if mode.eq_ignore_ascii_case("wal") => break,
278                Ok(mode) => return Err(Error::Config(format!("SQLite: journal mode WAL refused (it is {mode})"))),
279                Err(e) if is_busy(&e) && start.elapsed() < self.options.busy_timeout => {
280                    std::thread::sleep(Duration::from_millis(5));
281                }
282                Err(e) => return Err(e).db(),
283            }
284        }
285        let sync = if self.options.durable { "FULL" } else { "NORMAL" };
286        c.execute_batch(&format!("PRAGMA foreign_keys = ON; PRAGMA synchronous = {sync};")).db()?;
287        Ok(c)
288    }
289
290    /// A connection: an idle one, or a new one.
291    fn conn(&self) -> Result<Pooled<'_>> {
292        let idle = self.idle.lock().ok().and_then(|mut v| v.pop());
293        let conn = match idle {
294            Some(c) => c,
295            None => self.open_connection()?,
296        };
297        Ok(Pooled { store: self, conn: Some(conn) })
298    }
299
300    /// Prepares every SQL statement the store uses against the live schema, on a new
301    /// connection, and returns how many there are. Fails with the first statement the
302    /// schema cannot serve.
303    pub fn check_statements(&self) -> Result<usize> {
304        let c = self.open_connection()?;
305        for q in L::ALL {
306            c.prepare(q.sql()).db()?;
307        }
308        Ok(L::ALL.len())
309    }
310
311    /// A connection held for a migration (one transaction on it), or a catalog read.
312    pub(crate) fn raw(&self) -> Result<impl std::ops::Deref<Target = Connection> + '_> {
313        self.conn()
314    }
315
316    /// A [`Resolver`] lookup: a failure (logged by `run`) becomes `None`.
317    fn resolve<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<Option<T>>) -> Option<T> {
318        self.run(op, f).ok().flatten()
319    }
320
321    /// Runs `f` on a connection; a database failure is logged.
322    fn run<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
323        let result = self.conn().and_then(|c| f(&c));
324        if let Err(e @ Error::Database(_)) = &result {
325            tracing::error!(target: "datumesh_store", op, error = %e, "database failure");
326        }
327        result
328    }
329
330    /// Runs `f` in a write transaction (`BEGIN IMMEDIATE`: the write lock first), committed
331    /// when `f` succeeds and rolled back otherwise; a database failure is logged.
332    fn write<T>(&self, op: &'static str, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
333        self.run(op, |c| {
334            let v = self.locked_write(c, f)?;
335            self.bound_wal(c);
336            Ok(v)
337        })
338    }
339
340    /// `write`, after the store's other writers.
341    fn locked_write<T>(&self, c: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
342        let _queue = self.writer.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
343        write(c, f)
344    }
345
346    /// Keeps the write-ahead log bounded. SQLite's automatic checkpoints copy the log into
347    /// the database but restart the log only when no reader is using it, which under a
348    /// steady load of concurrent readers may be never: the log then grows with every
349    /// commit. After a commit, when the log has outgrown `WAL_LIMIT`, this connection runs
350    /// a TRUNCATE checkpoint, which waits (the busy timeout) for the readers to move to the
351    /// latest snapshot, copies everything and empties the log. A failure (still busy) is
352    /// left to the next commit.
353    fn bound_wal(&self, c: &Connection) {
354        let mut wal = self.path.clone().into_os_string();
355        wal.push("-wal");
356        if std::fs::metadata(&wal).is_ok_and(|m| m.len() > WAL_LIMIT) {
357            if let Err(e) = c.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(())) {
358                tracing::debug!(target: "datumesh_store", error = %e, "checkpoint deferred");
359            }
360        }
361    }
362
363    /// A version from a query answering (tx, receipt_hash, asof) for (cell_id, asof).
364    fn asof_version(&self, op: &'static str, q: L, cell_id: &str, asof: &str) -> Result<Option<Version>> {
365        check_hex(cell_id, 64, "cell_id")?;
366        check_instant(asof, "asof")?;
367        self.run(op, |c| {
368            c.prepare_cached(q.sql())
369                .db()?
370                .query_row(rusqlite::params![cell_id, asof], |r| version_row(r, cell_id))
371                .optional()
372                .db()
373        })
374    }
375
376    /// A version and its receipt's bytes from a query answering (tx, receipt_hash, asof,
377    /// bytes) for (cell_id, asof).
378    fn asof_with_receipt(
379        &self,
380        op: &'static str,
381        q: L,
382        cell_id: &str,
383        asof: &str,
384    ) -> Result<Option<(Version, Vec<u8>)>> {
385        check_hex(cell_id, 64, "cell_id")?;
386        check_instant(asof, "asof")?;
387        self.run(op, |c| {
388            c.prepare_cached(q.sql())
389                .db()?
390                .query_row(rusqlite::params![cell_id, asof], |r| Ok((version_row(r, cell_id)?, r.get(5)?)))
391                .optional()
392                .db()
393        })
394    }
395}
396
397/// The size of the write-ahead log beyond which a commit checkpoints it and truncates it.
398const WAL_LIMIT: u64 = 64 << 20;
399
400/// Runs `f` in a `BEGIN IMMEDIATE` transaction on `c`.
401pub(crate) fn write<T>(c: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
402    c.execute_batch("BEGIN IMMEDIATE").db()?;
403    let result = f(c).and_then(|v| c.execute_batch("COMMIT").db().map(|()| v));
404    if result.is_err() && !c.is_autocommit() {
405        let _ = c.execute_batch("ROLLBACK");
406    }
407    result
408}
409
410impl SqliteStore {
411    /// The receipt hashes of the members of `slice` as of `asof`, at most `limit`, in no particular order
412    /// (decided 27 Nov, B6): one statement; with a `deadline`, a progress handler stops it past the deadline
413    /// (the call then fails with [`Error::Timeout`]).
414    fn member_hashes_by(
415        &self,
416        slice: &Slice,
417        asof: &str,
418        limit: usize,
419        deadline: Option<Instant>,
420        op: &'static str,
421    ) -> Result<Vec<String>> {
422        check_instant(asof, "asof")?;
423        let v = slice.to_value();
424        if version_slice(slice, &v)?.is_some() {
425            return Ok(crate::hashes_limited(self.slice_members(slice, asof)?, limit));
426        }
427        let p = Pattern::of(&v)?;
428        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
429        self.run(op, |c| {
430            // The deadline interrupts the statement from a timer thread (rusqlite's interrupt handle: the
431            // crate forbids unsafe code, so no progress handler).
432            let timer = deadline.map(|at| {
433                let handle = c.get_interrupt_handle();
434                let (stop, stopped) = std::sync::mpsc::channel::<()>();
435                let timer = std::thread::spawn(move || {
436                    if let Err(std::sync::mpsc::RecvTimeoutError::Timeout) =
437                        stopped.recv_timeout(at.saturating_duration_since(Instant::now()))
438                    {
439                        handle.interrupt();
440                    }
441                });
442                (stop, timer)
443            });
444            let out: Result<Vec<String>> = (|| {
445                let (d, _) = drive(&p, c, false)?;
446                let q = if d.is_some() { L::MemberHashesDrive } else { L::MemberHashesAll };
447                let mut binds = params(&p, asof, d);
448                binds.push((":limit", SqlValue::Integer(limit)));
449                let mut st = c.prepare_cached(q.sql()).db()?;
450                bind(&mut st, &binds)?;
451                let mut rows = st.raw_query();
452                let mut out = Vec::new();
453                while let Some(r) = rows.next().db()? {
454                    out.push(r.get::<_, String>(0).db()?);
455                }
456                Ok(out)
457            })();
458            if let Some((stop, timer)) = timer {
459                let _ = stop.send(());
460                let _ = timer.join();
461            }
462            match out {
463                Err(e) if deadline.is_some_and(|at| Instant::now() >= at) => {
464                    let _ = e;
465                    Err(Error::Timeout(op.to_string()))
466                }
467                other => other,
468            }
469        })
470    }
471}
472
473fn is_busy(e: &rusqlite::Error) -> bool {
474    matches!(e, rusqlite::Error::SqliteFailure(f, _) if f.code == rusqlite::ErrorCode::DatabaseBusy)
475}
476
477/// The path of a `sqlite:` URL (`sqlite:<path>`, `sqlite://<path>`), or `url` itself.
478pub(crate) fn sqlite_path(url: &str) -> &str {
479    match url.strip_prefix("sqlite:") {
480        Some(rest) => rest.strip_prefix("//").unwrap_or(rest),
481        None => url,
482    }
483}
484
485/// The name of a SQLite (extended) result code.
486pub(crate) fn result_code_name(code: std::os::raw::c_int) -> String {
487    let name = match code {
488        1 => "SQLITE_ERROR",
489        2 => "SQLITE_INTERNAL",
490        3 => "SQLITE_PERM",
491        4 => "SQLITE_ABORT",
492        5 => "SQLITE_BUSY",
493        6 => "SQLITE_LOCKED",
494        7 => "SQLITE_NOMEM",
495        8 => "SQLITE_READONLY",
496        9 => "SQLITE_INTERRUPT",
497        10 => "SQLITE_IOERR",
498        11 => "SQLITE_CORRUPT",
499        12 => "SQLITE_NOTFOUND",
500        13 => "SQLITE_FULL",
501        14 => "SQLITE_CANTOPEN",
502        15 => "SQLITE_PROTOCOL",
503        16 => "SQLITE_EMPTY",
504        17 => "SQLITE_SCHEMA",
505        18 => "SQLITE_TOOBIG",
506        19 => "SQLITE_CONSTRAINT",
507        20 => "SQLITE_MISMATCH",
508        21 => "SQLITE_MISUSE",
509        22 => "SQLITE_NOLFS",
510        23 => "SQLITE_AUTH",
511        24 => "SQLITE_FORMAT",
512        25 => "SQLITE_RANGE",
513        26 => "SQLITE_NOTADB",
514        261 => "SQLITE_BUSY_RECOVERY",
515        517 => "SQLITE_BUSY_SNAPSHOT",
516        773 => "SQLITE_BUSY_TIMEOUT",
517        262 => "SQLITE_LOCKED_SHAREDCACHE",
518        264 => "SQLITE_READONLY_RECOVERY",
519        520 => "SQLITE_READONLY_CANTLOCK",
520        270 => "SQLITE_CANTOPEN_NOTEMPDIR",
521        526 => "SQLITE_CANTOPEN_ISDIR",
522        782 => "SQLITE_CANTOPEN_FULLPATH",
523        267 => "SQLITE_CORRUPT_VTAB",
524        275 => "SQLITE_CONSTRAINT_CHECK",
525        531 => "SQLITE_CONSTRAINT_COMMITHOOK",
526        787 => "SQLITE_CONSTRAINT_FOREIGNKEY",
527        1043 => "SQLITE_CONSTRAINT_FUNCTION",
528        1299 => "SQLITE_CONSTRAINT_NOTNULL",
529        1555 => "SQLITE_CONSTRAINT_PRIMARYKEY",
530        1811 => "SQLITE_CONSTRAINT_TRIGGER",
531        2067 => "SQLITE_CONSTRAINT_UNIQUE",
532        2323 => "SQLITE_CONSTRAINT_VTAB",
533        2579 => "SQLITE_CONSTRAINT_ROWID",
534        3091 => "SQLITE_CONSTRAINT_DATATYPE",
535        _ => {
536            // Another extended code: its primary code's name and the number.
537            let primary = code & 0xff;
538            return if primary != code && primary != 0 {
539                format!("{}({code})", result_code_name(primary))
540            } else {
541                format!("SQLITE({code})")
542            };
543        }
544    };
545    name.to_string()
546}
547
548/// A version from a row of (tx, receipt_hash, asof, withdrawn, recorded, ...) (0.6.0: withdrawn is
549/// 0 or 1; 0.6.5: recorded is the version's recorded time).
550fn version_row(r: &rusqlite::Row<'_>, cell_id: &str) -> rusqlite::Result<Version> {
551    Ok(Version {
552        cell_id: cell_id.to_string(),
553        tx: r.get(0)?,
554        receipt_hash: r.get(1)?,
555        asof: r.get(2)?,
556        withdrawn: r.get(3)?,
557        recorded: r.get(4)?,
558        seq: r.get::<_, Option<i64>>("seq")?.unwrap_or(0),
559    })
560}
561
562/// The latest binding row of `name` for `q` (tx, and the hash, NULL when the name is closed).
563fn latest_binding_row(c: &Connection, q: L, name: &str) -> Result<Option<(String, Option<String>)>> {
564    c.prepare_cached(q.sql()).db()?.query_row([name], |r| Ok((r.get(0)?, r.get(1)?))).optional().db()
565}
566
567/// The method names a class binds (K5, as `bind_class` does): `<class name>/<m>` for each
568/// method the class adds or overrides, with its function hash.
569fn own_method_bindings(c: &Connection, class_name: &str, class_hash: &str) -> Result<Vec<(String, String)>> {
570    let Some(bytes) = get_bytes(c, L::ClassGet, class_hash)? else {
571        return Err(Error::NotFound { what: "class", key: class_hash.to_string() });
572    };
573    let flat = ClassDescriptor::from_json(&bytes)?;
574    let parent = match &flat.parent {
575        Some(p) => {
576            get_bytes(c, L::ClassGet, p)?.map(|b| ClassDescriptor::from_json(&b)).transpose()?.map(|d| d.methods)
577        }
578        None => None,
579    };
580    let methods: Vec<(String, String)> = flat.methods.into_iter().collect();
581    Ok(methods
582        .iter()
583        .filter(|(m, h)| parent.as_ref().and_then(|pm| pm.get(m)) != Some(h))
584        .map(|(m, h)| (format!("{class_name}/{m}"), h.clone()))
585        .collect())
586}
587
588/// The host of a fully qualified function name (`host/name`): what precedes the last `/`.
589fn name_host(fn_name: &str) -> &str {
590    fn_name.rsplit_once('/').map_or("", |(h, _)| h)
591}
592
593fn read_namespace(c: &Connection, host: &str) -> Result<Option<Namespace>> {
594    c.prepare_cached(L::NamespaceGet.sql())
595        .db()?
596        .query_row([host], |r| {
597            Ok(Namespace {
598                host: host.to_string(),
599                keydoc: r.get(0)?,
600                validated_at: r.get(1)?,
601                suspended_at: r.get(2)?,
602                consecutive_failures: r.get(3)?,
603                last_checked_at: r.get(4)?,
604            })
605        })
606        .optional()
607        .db()
608}
609
610fn get_bytes(c: &Connection, q: L, key: &str) -> Result<Option<Vec<u8>>> {
611    c.prepare_cached(q.sql()).db()?.query_row([key], |r| r.get(0)).optional().db()
612}
613
614fn get_strings(c: &Connection, q: L, key: &str) -> Result<Vec<String>> {
615    let mut st = c.prepare_cached(q.sql()).db()?;
616    let rows = st.query_map([key], |r| r.get(0)).db()?;
617    rows.collect::<rusqlite::Result<Vec<String>>>().db()
618}
619
620fn exists(c: &Connection, q: L, key: &str) -> Result<bool> {
621    c.prepare_cached(q.sql()).db()?.query_row([key], |r| r.get(0)).db()
622}
623
624/// Registers the functions of the text search on a connection (0.5.3): `datumesh_entry_total`
625/// and `datumesh_value_total` give a row's total score in tens for a query (see `Words` and
626/// `field_score`), or NULL when a word is in none of the row's fields. The search orders and
627/// cuts by them in SQL.
628pub(crate) fn register_text_functions(c: &Connection) -> Result<()> {
629    use rusqlite::functions::FunctionFlags;
630    let flags = FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_DETERMINISTIC;
631    // The sort key's part of one argument (0.6.4): the cells' trigger joins these parts.
632    c.create_scalar_function("datumesh_sort_item", 2, flags, |ctx| {
633        let ty: String = ctx.get(0)?;
634        let value: String = ctx.get(1)?;
635        Ok(crate::slices::sort_item(&ty, &value))
636    })
637    .db()?;
638    c.create_scalar_function("datumesh_entry_total", 5, flags, |ctx| {
639        let Some(words) = Words::new(&ctx.get::<String>(0)?) else { return Ok(None::<i64>) };
640        let name: String = ctx.get(1)?;
641        let label: String = ctx.get(2)?;
642        let description: String = ctx.get(3)?;
643        let args = parse_args(&ctx.get::<String>(4)?).map_err(|e| rusqlite::Error::UserFunctionError(e.into()))?;
644        let mut fields: Vec<&str> = vec![&name, &label, &description];
645        for (k, v) in &args {
646            fields.push(k);
647            fields.push(v);
648        }
649        Ok(words.total(&fields).map(i64::from))
650    })
651    .db()?;
652    c.create_scalar_function("datumesh_value_total", 4, flags, |ctx| {
653        let Some(words) = Words::new(&ctx.get::<String>(0)?) else { return Ok(None::<i64>) };
654        let value: String = ctx.get(1)?;
655        let label: String = ctx.get(2)?;
656        let aliases =
657            parse_aliases(&ctx.get::<String>(3)?).map_err(|e| rusqlite::Error::UserFunctionError(e.into()))?;
658        let mut fields: Vec<&str> = vec![&value, &label];
659        fields.extend(aliases.iter().map(String::as_str));
660        Ok(words.total(&fields).map(i64::from))
661    })
662    .db()?;
663    Ok(())
664}
665
666/// The counter's update of a row (0.5.3): `n` tests more (or fewer) and the deltas of their
667/// results, on the row of `fn_name` ('' for unnamed). The row is made first, with the hash's
668/// branch counts (or `init`).
669fn bump_counter(
670    c: &Connection,
671    fn_hash: &str,
672    fn_name: &str,
673    n: i64,
674    results: [i64; 4],
675    last_run_at: Option<&str>,
676    init: (i64, i64),
677) -> Result<()> {
678    exec(c, L::CounterEnsure, rusqlite::params![fn_hash, fn_name, init.0, init.1])?;
679    let [pass, fail, error, not_run] = results;
680    exec(c, L::CounterAdd, rusqlite::params![fn_hash, fn_name, n, pass, fail, error, not_run, last_run_at])?;
681    Ok(())
682}
683
684/// A test's name and last result, if the test is stored (0.5.3).
685fn function_test_old(c: &Connection, fn_hash: &str, case: &str) -> Result<Option<(Option<String>, Option<String>)>> {
686    let mut st = c.prepare_cached(L::FunctionTestOld.sql()).db()?;
687    let mut rows = st
688        .query_map(rusqlite::params![fn_hash, case], |r| {
689            Ok((r.get::<_, Option<String>>(0)?, r.get::<_, Option<String>>(1)?))
690        })
691        .db()?;
692    rows.next().transpose().db()
693}
694
695fn exec(c: &Connection, q: L, params: impl rusqlite::Params) -> Result<usize> {
696    c.prepare_cached(q.sql()).db()?.execute(params).db()
697}
698
699/// A stored value that does not parse back (a corrupt row).
700fn bad(what: &str) -> Error {
701    Error::Invalid(datumesh_core::Error::new(ErrorCode::CanonType, "$", format!("a stored {what}")))
702}
703
704/// A cell's arguments from the typed-argument index: a JSON array of `[name, type, value]`.
705fn args_of(text: &str) -> Result<Args> {
706    let Ok(Value::Array(list)) = json::parse(text.as_bytes()) else { return Err(bad("argument list")) };
707    let mut args = Args::new();
708    for a in &list {
709        let item = |i: usize| match a {
710            Value::Array(x) => x.get(i).and_then(Value::as_str).ok_or_else(|| bad("argument")),
711            _ => Err(bad("argument")),
712        };
713        let ty = Type::from_name(item(1)?).ok_or_else(|| bad("type"))?;
714        args.insert(item(0)?.to_string(), Arg::Value(Scalar::from_lexical(ty, item(2)?)?));
715    }
716    Ok(args)
717}
718
719/// The sort key of a typed value in the typed-argument index: for a number, a text that
720/// sorts (as bytes) as the decimal does; for every other type, its lexical form, which
721/// already sorts in the type's order.
722pub(crate) fn sort_key(ty: &str, lexical: &str) -> String {
723    if ty == "number" {
724        decimal_key(lexical)
725    } else {
726        lexical.to_string()
727    }
728}
729
730/// A decimal (SPEC 3.1 form: optional `-`, digits, optional `.` and digits) as a text that
731/// sorts as the number does: `0` for a negative number, `1` for zero, `2` for a positive
732/// one; then the decimal exponent `e` (the number is `0.d1d2... x 10^e`) plus 500, in three
733/// digits; then the significant digits `d1d2...`. Longer digit strings after a shared
734/// prefix are larger, as text and as numbers. For a negative number the exponent and the
735/// digits are complemented (`999 - x`, `9 - d`) and `~` appended, which reverses the order,
736/// prefixes included (`~` sorts after every digit). The specification's numbers have at
737/// most 128 characters, so `e` lies in -127..=128.
738pub(crate) fn decimal_key(lexical: &str) -> String {
739    let (negative, magnitude) = match lexical.strip_prefix('-') {
740        Some(m) => (true, m),
741        None => (false, lexical),
742    };
743    let (int, frac) = magnitude.split_once('.').unwrap_or((magnitude, ""));
744    let int = int.trim_start_matches('0');
745    let frac = frac.trim_end_matches('0');
746    let (exponent, digits): (i64, String) = if !int.is_empty() {
747        (int.len() as i64, format!("{int}{frac}").trim_end_matches('0').to_string())
748    } else {
749        let zeros = frac.len() - frac.trim_start_matches('0').len();
750        (-(zeros as i64), frac[zeros..].to_string())
751    };
752    if digits.is_empty() {
753        return "1".to_string();
754    }
755    let e = (exponent + 500).clamp(0, 999);
756    if negative {
757        let complement: String = digits.bytes().map(|d| char::from(b'9' - (d - b'0'))).collect();
758        format!("0{:03}{complement}~", 999 - e)
759    } else {
760        format!("2{e:03}{digits}")
761    }
762}
763
764impl Resolver for SqliteStore {
765    fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
766        if !is_hash(fn_hash) {
767            return None;
768        }
769        self.resolve("descriptor", |c| get_bytes(c, L::DescriptorGet, fn_hash)).map(Cow::Owned)
770    }
771
772    fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
773        if !is_hash(hash) {
774            return None;
775        }
776        self.resolve("receipt", |c| get_bytes(c, L::ReceiptGet, hash)).map(Cow::Owned)
777    }
778
779    /// The stored manifest of slice entry `entry` ([`Store::put_manifest`]), its canonical
780    /// form; `None` when there is none, or `entry` is not an entry.
781    fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
782        if check_entry(entry, "$").is_err() {
783            return None;
784        }
785        self.resolve("manifest", |c| get_bytes(c, L::ManifestGet, entry)).map(Cow::Owned)
786    }
787
788    /// `Some` only for a `stored` function, as [`PgStore`](crate::PgStore)'s: the value of
789    /// the receipt of [`stored_asof`](Store::stored_asof)'s version.
790    fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
791        if !is_instant(asof) {
792            return None;
793        }
794        self.resolve("evaluate", |c| {
795            let Some(desc) = get_bytes(c, L::DescriptorGet, &cell.fn_hash)? else { return Ok(None) };
796            match FunctionDescriptor::from_json(&desc) {
797                Ok(d) if d.lang == "stored" => {}
798                Ok(_) => return Ok(None),
799                Err(e) => {
800                    tracing::error!(target: "datumesh_store", fn_hash = %cell.fn_hash, error = %e, "stored descriptor does not parse");
801                    return Ok(None);
802                }
803            }
804            let bytes: Option<Vec<u8>> = c
805                .prepare_cached(L::ValueAsof.sql())
806                .db()?
807                .query_row(rusqlite::params![cell.id(), asof], |r| r.get(0))
808                .optional()
809                .db()?;
810            let Some(bytes) = bytes else { return Ok(None) };
811            match stored_value(&bytes) {
812                Ok(value) => Ok(value),
813                Err(e) => {
814                    tracing::error!(target: "datumesh_store", cell_id = %cell.id(), error = %e, "stored receipt does not parse");
815                    Ok(None)
816                }
817            }
818        })
819    }
820}
821
822impl SqliteStore {
823    /// A failed check (`threshold` is `Some`) or a successful one (`None`) at `checked_at`.
824    fn record_check(
825        &self,
826        op: &'static str,
827        host: &str,
828        checked_at: &str,
829        threshold: Option<u32>,
830    ) -> Result<Option<Namespace>> {
831        check_dns_name(host, "host")?;
832        check_instant(checked_at, "checked_at")?;
833        let out = self.write(op, |c| {
834            let Some(mut ns) = read_namespace(c, host)? else { return Ok(None) };
835            if let Some(at) = &ns.last_checked_at {
836                if checked_at < at.as_str() {
837                    return Err(Error::NotLater {
838                        what: "namespace",
839                        key: host.to_string(),
840                        given: checked_at.to_string(),
841                        latest: at.clone(),
842                    });
843                }
844            }
845            crate::apply_check(&mut ns, checked_at, threshold);
846            exec(c, L::NamespaceCheck, rusqlite::params![host, ns.consecutive_failures, checked_at, ns.suspended_at])?;
847            Ok(Some(ns))
848        })?;
849        tracing::debug!(target: "datumesh_store", host, checked_at, ok = threshold.is_none(), "namespace check");
850        Ok(out)
851    }
852}
853
854impl SqliteStore {
855    /// Writes catalogue rows, all or nothing, keyed by (kind, name) (the call's bounds are
856    /// checked by the caller). An operator's row never replaces a publisher's. An existing row
857    /// keeps its facets and `extends` unless `replace_ext` (the facets call), in which case
858    /// they are replaced.
859    fn write_catalog(&self, rows: &[CatalogRow<'_>], replace_ext: bool) -> Result<Vec<i64>> {
860        if rows.is_empty() {
861            return Ok(Vec::new());
862        }
863        let replace = if replace_ext {
864            ", facets = excluded.facets, extends = excluded.extends, source_name = excluded.source_name"
865        } else {
866            ""
867        };
868        let upsert = format!(
869            "INSERT INTO catalog_entries (kind, name, hash, label, description, args, examples, source, signed_by, facets, extends, source_name, updated_at)
870             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
871             ON CONFLICT (kind, name) DO UPDATE SET hash = excluded.hash, label = excluded.label,
872                 description = excluded.description, args = excluded.args, examples = excluded.examples,
873                 source = excluded.source, signed_by = excluded.signed_by, updated_at = excluded.updated_at{replace}
874             WHERE catalog_entries.source = 'operator' OR excluded.source = 'publisher'
875             RETURNING id"
876        );
877        self.write("upsert_catalog", |c| {
878            let mut ids = Vec::with_capacity(rows.len());
879            for row in rows {
880                let e = row.entry;
881                let args = args_json(&e.args);
882                let examples = canonical_examples(&e.examples)?;
883                let updated: Option<i64> = c
884                    .prepare_cached(&upsert)
885                    .db()?
886                    .query_row(
887                        rusqlite::params![
888                            e.kind.as_str(),
889                            e.name,
890                            e.hash,
891                            e.label,
892                            e.description,
893                            args,
894                            examples,
895                            e.source.as_str(),
896                            e.signed_by,
897                            row.facets,
898                            row.extends,
899                            row.source_name
900                        ],
901                        |r| r.get(0),
902                    )
903                    .optional()
904                    .db()?;
905                let id = match updated {
906                    Some(id) => id,
907                    // An operator's entry over a publisher's: kept as it is.
908                    None => c
909                        .prepare_cached("SELECT id FROM catalog_entries WHERE kind = ?1 AND name = ?2")
910                        .db()?
911                        .query_row([e.kind.as_str(), e.name.as_str()], |r| r.get(0))
912                        .db()?,
913                };
914                ids.push(id);
915            }
916            Ok(ids)
917        })
918    }
919}
920
921impl Store for SqliteStore {
922    fn put_member_set_checked(&self, set: &MemberSet) -> Result<bool> {
923        let members = i64::try_from(set.members).unwrap_or(i64::MAX);
924        let licences = crate::licences_text(&set.licences);
925        let seen_seq = set.seen_seq;
926        self.write("put_member_set", |c| {
927            let n = c
928                .prepare_cached(L::MemberSetPut.sql())
929                .db()?
930                .execute(rusqlite::params![
931                    set.entry,
932                    set.slice_id,
933                    set.members_hash,
934                    set.fn_hash,
935                    set.slice,
936                    members,
937                    set.tx,
938                    set.asof,
939                    licences,
940                    seen_seq
941                ])
942                .db()?;
943            Ok(n == 1)
944        })
945    }
946
947    fn member_set_checked(&self, entry: &str) -> Result<Option<MemberSet>> {
948        self.run("member_set", |c| {
949            let row = c
950                .prepare_cached(L::MemberSetGet.sql())
951                .db()?
952                .query_row([entry], |r| {
953                    Ok((
954                        r.get::<_, String>(0)?,
955                        r.get::<_, String>(1)?,
956                        r.get::<_, String>(2)?,
957                        r.get::<_, Vec<u8>>(3)?,
958                        r.get::<_, i64>(4)?,
959                        r.get::<_, Option<String>>(5)?,
960                        r.get::<_, String>(6)?,
961                        r.get::<_, String>(7)?,
962                        r.get::<_, i64>(8)?,
963                    ))
964                })
965                .optional()
966                .db()?;
967            let Some((slice_id, members_hash, fn_hash, slice, members, tx, asof, licences, seen_seq)) = row else {
968                return Ok(None);
969            };
970            Ok(Some(MemberSet {
971                entry: entry.to_string(),
972                slice_id,
973                members_hash,
974                fn_hash,
975                slice,
976                members: u64::try_from(members).unwrap_or(0),
977                tx,
978                asof,
979                licences: crate::licences_of(&licences)?,
980                seen_seq,
981            }))
982        })
983    }
984
985    fn put_slice_definition_checked(&self, slice: &Slice) -> Result<bool> {
986        let (id, fn_hash, bytes) = (slice.id().to_string(), slice.fn_hash().to_string(), slice.canonical());
987        self.write("put_slice_definition", |c| {
988            let n = c
989                .prepare_cached(L::SliceDefinitionPut.sql())
990                .db()?
991                .execute(rusqlite::params![id, fn_hash, bytes])
992                .db()?;
993            Ok(n == 1)
994        })
995    }
996
997    fn recording_clock_of(&self) -> Option<crate::RecordingClock> {
998        self.options.recording_clock.clone().map(|c| c.0)
999    }
1000
1001    fn slice_member_hashes(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<String>> {
1002        self.member_hashes_by(slice, asof, limit, None, "slice_member_hashes")
1003    }
1004
1005    fn slice_member_hashes_within_checked(
1006        &self,
1007        slice: &Slice,
1008        asof: &str,
1009        limit: usize,
1010        timeout: Duration,
1011    ) -> Result<Vec<String>> {
1012        self.member_hashes_by(slice, asof, limit, Some(Instant::now() + timeout), "slice_member_hashes_within")
1013    }
1014
1015    fn barrier_checked(&self) -> Result<()> {
1016        // A write transaction in flight (in this process or another) holds the write lock. The wait is the
1017        // barrier's own timeout, not the connections' busy timeout; the in-process queue is short (writes are).
1018        self.run("barrier", |c| {
1019            let _queue = self.writer.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
1020            c.busy_timeout(self.options.barrier_timeout).db()?;
1021            let begun = c.execute_batch("BEGIN IMMEDIATE");
1022            c.busy_timeout(self.options.busy_timeout).db()?;
1023            if let Err(e) = &begun {
1024                if is_busy(e) {
1025                    return Err(Error::Timeout("barrier".to_string()));
1026                }
1027            }
1028            begun.db()?;
1029            c.execute_batch("COMMIT").db()?;
1030            Ok(())
1031        })
1032    }
1033
1034    fn later_bound_checked(&self, cell_id: &str, recorded: &str) -> Result<Option<String>> {
1035        self.run("later_bound", |c| {
1036            c.prepare_cached(L::LaterBound.sql())
1037                .db()?
1038                .query_row(rusqlite::params![cell_id, recorded], |r| r.get::<_, Option<String>>(0))
1039                .db()
1040        })
1041    }
1042
1043    fn next_version_after_checked(&self, cell_id: &str, recorded: &str) -> Result<Option<Version>> {
1044        self.run("next_version_after", |c| {
1045            c.prepare_cached(L::VersionNextAfter.sql())
1046                .db()?
1047                .query_row(rusqlite::params![cell_id, recorded], |r| version_row(r, cell_id))
1048                .optional()
1049                .db()
1050        })
1051    }
1052
1053    fn fn_seq_checked(&self, fn_hash: &str) -> Result<i64> {
1054        self.run("fn_seq", |c| c.prepare_cached(L::FnSeq.sql()).db()?.query_row([fn_hash], |r| r.get(0)).db())
1055    }
1056
1057    fn slice_seq_checked(&self, slice: &Slice) -> Result<i64> {
1058        let v = slice.to_value();
1059        if let Some((cell_id, _, _)) = version_slice(slice, &v)? {
1060            check_hex(&cell_id, 64, "cell_id")?;
1061            return self.run("slice_seq", |c| {
1062                c.prepare_cached(L::VersionSeqMax.sql()).db()?.query_row([cell_id.as_str()], |r| r.get(0)).db()
1063            });
1064        }
1065        let p = Pattern::of(&v)?;
1066        self.run("slice_seq", |c| {
1067            let seqs = rows(&p, c, "", [L::SliceSeqAll, L::SliceSeqDrive], |r| r.get::<_, i64>(0))?;
1068            Ok(seqs.into_iter().max().unwrap_or(0))
1069        })
1070    }
1071
1072    fn slice_definition_checked(&self, slice_id: &str) -> Result<Option<Slice>> {
1073        let bytes: Option<Vec<u8>> = self.run("slice_definition", |c| {
1074            c.prepare_cached(L::SliceDefinitionGet.sql()).db()?.query_row([slice_id], |r| r.get(0)).optional().db()
1075        })?;
1076        bytes.map(|b| Slice::from_json(&b).map_err(Error::Invalid)).transpose()
1077    }
1078
1079    fn put_descriptor(&self, bytes: &[u8]) -> Result<String> {
1080        let d = FunctionDescriptor::from_json(bytes)?;
1081        let hash = d.hash();
1082        let canonical = d.canonical();
1083        // The descriptor (once) and its inputs' index (0.5.1), in one write transaction.
1084        self.run("put_descriptor", |c| {
1085            let fresh = !exists(c, L::DescriptorExists, &hash)?;
1086            if fresh || !d.inputs.is_empty() {
1087                self.locked_write(c, |c| {
1088                    exec(c, L::DescriptorPut, rusqlite::params![hash, canonical])?;
1089                    for input in &d.inputs {
1090                        exec(c, L::DescriptorInputPut, rusqlite::params![hash, input])?;
1091                    }
1092                    Ok(())
1093                })?;
1094                self.bound_wal(c);
1095            }
1096            Ok(())
1097        })?;
1098        tracing::debug!(target: "datumesh_store", fn_hash = %hash, "put_descriptor");
1099        Ok(hash)
1100    }
1101
1102    fn put_receipt(&self, bytes: &[u8]) -> Result<String> {
1103        // Steps 1-4 first (a valued receipt or a withdrawal): one that is neither is refused
1104        // without a query.
1105        let p = parse_receipt(bytes)?;
1106        let canonical = p.canonical.clone();
1107        let hash = p.hash.clone();
1108        let cell = &p.cell;
1109        let cell_id = p.cell_id.clone();
1110        let host = p.host.clone();
1111        let (mut entries, mut inputs) = (p.entries.clone(), p.inputs.clone());
1112        entries.sort();
1113        entries.dedup();
1114        inputs.sort();
1115        inputs.dedup();
1116        let mut args = Vec::with_capacity(cell.args.len());
1117        for (name, a) in &cell.args {
1118            let Some(s) = a.scalar() else {
1119                return Err(Error::Invalid(datumesh_core::Error::new(
1120                    ErrorCode::Schema,
1121                    "$.cell.args",
1122                    "a receipt's cell has no open argument",
1123                )));
1124            };
1125            let ty = s.ty().as_str();
1126            args.push((name.clone(), ty, s.lexical().to_string(), sort_key(ty, s.lexical())));
1127        }
1128        self.run("put_receipt", |c| {
1129            // Idempotent: the very receipt already stored verified when it was stored.
1130            if let Some(stored) = get_bytes(c, L::ReceiptGet, &hash)? {
1131                if stored == canonical {
1132                    return Ok(());
1133                }
1134            }
1135            // Steps 5-6 against the stored key document of the signer host (outside the
1136            // write lock: verifying is the slow part).
1137            let mut keys = Keys::new();
1138            if let Some(ns) = read_namespace(c, &host)? {
1139                // No new writes under a suspended namespace.
1140                if let Some(since) = ns.suspended_at {
1141                    return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
1142                }
1143                keys.insert_response(&host, 200, Some(&ns.keydoc));
1144            }
1145            let out = verify(bytes, &keys, None, None);
1146            if !out.ok {
1147                return Err(Error::Invalid(out.error().unwrap_or_else(|| {
1148                    datumesh_core::Error::new(ErrorCode::Signature, "$", "the receipt did not verify")
1149                })));
1150            }
1151            self.locked_write(c, |c| {
1152                // Under the write lock: another writer may have stored it meanwhile.
1153                if let Some(stored) = get_bytes(c, L::ReceiptGet, &hash)? {
1154                    return if stored == canonical { Ok(()) } else { Err(Error::Conflict { hash: hash.clone() }) };
1155                }
1156                // A withdrawal has no value: its columns are the empty text (0.6.0).
1157                let (value_type, value) = match &p.value {
1158                    Some((ty, lexical)) => (ty.as_str(), lexical.as_str()),
1159                    None => (WITHDRAWN_VALUE, WITHDRAWN_VALUE),
1160                };
1161                exec(
1162                    c,
1163                    L::ReceiptPut,
1164                    rusqlite::params![
1165                        hash,
1166                        canonical,
1167                        cell_id,
1168                        p.tx,
1169                        cell.fn_hash,
1170                        p.publisher,
1171                        p.asof,
1172                        value_type,
1173                        value
1174                    ],
1175                )?;
1176                for i in &inputs {
1177                    exec(c, L::EdgePut, rusqlite::params![hash, i])?;
1178                }
1179                for e in &entries {
1180                    exec(c, L::SliceEdgePut, rusqlite::params![hash, e])?;
1181                }
1182                if !exists(c, L::CellExists, &cell_id)? {
1183                    exec(
1184                        c,
1185                        L::CellPut,
1186                        rusqlite::params![cell_id, cell.fn_hash, cell.ns, cell.fn_name, args.len() as i64],
1187                    )?;
1188                    for (name, ty, value, key) in &args {
1189                        exec(c, L::CellArgPut, rusqlite::params![cell_id, name, ty, value, key, cell.fn_hash])?;
1190                    }
1191                }
1192                Ok(())
1193            })?;
1194            self.bound_wal(c);
1195            Ok(())
1196        })?;
1197        tracing::debug!(target: "datumesh_store", hash = %hash, cell_id = %cell_id, "put_receipt");
1198        Ok(hash)
1199    }
1200
1201    fn put_blob(&self, bytes: &[u8]) -> Result<String> {
1202        let sha = sha256_hex(bytes);
1203        let length = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
1204        self.run("put_blob", |c| {
1205            if exists(c, L::BlobExists, &sha)? {
1206                return Ok(());
1207            }
1208            self.locked_write(c, |c| exec(c, L::BlobPut, rusqlite::params![sha, bytes, length]).map(|_| ()))?;
1209            self.bound_wal(c);
1210            Ok(())
1211        })?;
1212        tracing::debug!(target: "datumesh_store", sha256 = %sha, length, "put_blob");
1213        Ok(sha)
1214    }
1215
1216    fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>> {
1217        check_hex(sha256, 64, "sha256")?;
1218        Ok(self.run("blob", |c| get_bytes(c, L::BlobGet, sha256))?.map(Cow::Owned))
1219    }
1220
1221    fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
1222        check_hex(cell_id, 64, "cell_id")?;
1223        check_instant(tx, "tx")?;
1224        check_hex(receipt_hash, 64, "receipt_hash")?;
1225        self.write("put_version", |c| {
1226            // A store on a schema older than migration 17 writes by tx, as 0.6.4 did (decision B).
1227            let has = if self.recorded_schema.load(std::sync::atomic::Ordering::Acquire) {
1228                true
1229            } else {
1230                let has = c.prepare_cached(L::HasRecorded.sql()).db()?.query_row([], |r| r.get::<_, i64>(0)).db()? == 1;
1231                if has {
1232                    self.recorded_schema.store(true, std::sync::atomic::Ordering::Release);
1233                }
1234                has
1235            };
1236            // Recorded after the cell's latest (decided 27 Nov, B5); this connection holds the write lock.
1237            let latest_now =
1238                get_strings(c, if has { L::VersionLatestTx } else { L::VersionLatestTxLegacy }, cell_id)?.pop();
1239            let recorded = if has {
1240                let base = crate::recorded_at(self.options.recording_clock.as_ref().map(|c| &c.0), tx);
1241                match &latest_now {
1242                    Some(l) => crate::later_of(&base, &crate::instant_after(l)),
1243                    None => base,
1244                }
1245            } else {
1246                tx.to_string()
1247            };
1248            let meta: Option<(String, String)> = c
1249                .prepare_cached(L::ReceiptMeta.sql())
1250                .db()?
1251                .query_row([receipt_hash], |r| Ok((r.get(0)?, r.get(1)?)))
1252                .optional()
1253                .db()?;
1254            let Some((r_cell, r_tx)) = meta else {
1255                return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
1256            };
1257            // No new versions of a receipt signed by a suspended namespace.
1258            let stored = get_bytes(c, L::ReceiptGet, receipt_hash)?
1259                .ok_or_else(|| Error::NotFound { what: "receipt", key: receipt_hash.to_string() })?;
1260            let signer = parse_receipt(&stored)?.host;
1261            if let Some(since) = read_namespace(c, &signer)?.and_then(|n| n.suspended_at) {
1262                return Err(Error::NamespaceSuspended { host: signer, suspended_at: since });
1263            }
1264            if r_cell != cell_id {
1265                return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
1266            }
1267            if r_tx != tx {
1268                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
1269            }
1270            // The cell already has a version at this tx: the same receipt writes nothing; another is refused
1271            // (review item 3).
1272            if let Some(held) = c
1273                .prepare_cached(L::VersionAt.sql())
1274                .db()?
1275                .query_row(rusqlite::params![cell_id, tx], |r| r.get::<_, String>(0))
1276                .optional()
1277                .db()?
1278            {
1279                if held == receipt_hash {
1280                    return Ok(());
1281                }
1282                return Err(Error::NotLater {
1283                    what: "version",
1284                    key: cell_id.to_string(),
1285                    given: tx.to_string(),
1286                    latest: tx.to_string(),
1287                });
1288            }
1289            // The cell's latest signed tx: a version not later is refused (decided by the user, 27 Nov).
1290            if let Some(l) = get_strings(c, L::VersionLatestSigned, cell_id)?.pop() {
1291                if tx <= l.as_str() {
1292                    return Err(Error::NotLater {
1293                        what: "version",
1294                        key: cell_id.to_string(),
1295                        given: tx.to_string(),
1296                        latest: l,
1297                    });
1298                }
1299            }
1300            if let Some(l) = &latest_now {
1301                if recorded.as_str() <= l.as_str() {
1302                    return Err(Error::NotLater {
1303                        what: "version",
1304                        key: cell_id.to_string(),
1305                        given: recorded.clone(),
1306                        latest: l.clone(),
1307                    });
1308                }
1309            }
1310            if has {
1311                exec(c, L::VersionPut, rusqlite::params![cell_id, tx, receipt_hash, recorded])?;
1312            } else {
1313                exec(c, L::VersionPutLegacy, rusqlite::params![cell_id, tx, receipt_hash])?;
1314            }
1315            Ok(())
1316        })?;
1317        tracing::debug!(target: "datumesh_store", cell_id, tx, receipt_hash, "put_version");
1318        Ok(())
1319    }
1320
1321    fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1322        self.asof_version("version_asof", L::VersionAsof, cell_id, asof)
1323    }
1324
1325    fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>> {
1326        check_hex(cell_id, 64, "cell_id")?;
1327        check_instant(from, "from")?;
1328        check_instant(to, "to")?;
1329        self.run("versions", |c| {
1330            let mut st = c.prepare_cached(L::VersionRange.sql()).db()?;
1331            let rows = st.query_map(rusqlite::params![cell_id, from, to], |r| version_row(r, cell_id)).db()?;
1332            rows.collect::<rusqlite::Result<Vec<Version>>>().db()
1333        })
1334    }
1335
1336    fn latest(&self, cell_id: &str) -> Result<Option<Version>> {
1337        check_hex(cell_id, 64, "cell_id")?;
1338        self.run("latest", |c| {
1339            c.prepare_cached(L::VersionLatest.sql())
1340                .db()?
1341                .query_row([cell_id], |r| version_row(r, cell_id))
1342                .optional()
1343                .db()
1344        })
1345    }
1346
1347    fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>> {
1348        check_hex(receipt_hash, 64, "receipt_hash")?;
1349        self.run("dependents", |c| get_strings(c, L::Dependents, receipt_hash))
1350    }
1351
1352    fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>> {
1353        check_hex(receipt_hash, 64, "receipt_hash")?;
1354        self.run("inputs", |c| get_strings(c, L::Inputs, receipt_hash))
1355    }
1356
1357    fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()> {
1358        keys_from_response(host, 200, Some(keydoc_bytes))?;
1359        check_instant(validated_at, "validated_at")?;
1360        let canonical = json::parse(keydoc_bytes)?.to_jcs();
1361        self.write("put_namespace", |c| {
1362            let at: Option<String> =
1363                c.prepare_cached(L::NamespaceGet.sql()).db()?.query_row([host], |r| r.get(1)).optional().db()?;
1364            if let Some(at) = at {
1365                if validated_at < at.as_str() {
1366                    return Err(Error::NotLater {
1367                        what: "namespace",
1368                        key: host.to_string(),
1369                        given: validated_at.to_string(),
1370                        latest: at,
1371                    });
1372                }
1373            }
1374            exec(c, L::NamespacePut, rusqlite::params![host, canonical, validated_at])?;
1375            Ok(())
1376        })?;
1377        tracing::debug!(target: "datumesh_store", host, validated_at, "put_namespace");
1378        Ok(())
1379    }
1380
1381    fn namespace(&self, host: &str) -> Result<Option<Namespace>> {
1382        check_dns_name(host, "host")?;
1383        self.run("namespace", |c| read_namespace(c, host))
1384    }
1385
1386    fn namespaces(&self) -> Result<Vec<Namespace>> {
1387        self.run("namespaces", |c| {
1388            let mut st = c.prepare_cached(L::NamespaceList.sql()).db()?;
1389            let rows = st
1390                .query_map([], |r| {
1391                    Ok(Namespace {
1392                        host: r.get(0)?,
1393                        keydoc: r.get(1)?,
1394                        validated_at: r.get(2)?,
1395                        suspended_at: r.get(3)?,
1396                        consecutive_failures: r.get(4)?,
1397                        last_checked_at: r.get(5)?,
1398                    })
1399                })
1400                .db()?;
1401            rows.collect::<rusqlite::Result<Vec<Namespace>>>().db()
1402        })
1403    }
1404
1405    fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>> {
1406        self.record_check("record_namespace_failure", host, checked_at, Some(threshold))
1407    }
1408
1409    fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>> {
1410        self.record_check("record_namespace_success", host, checked_at, None)
1411    }
1412
1413    fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()> {
1414        check_function_name(fn_name, "fn_name")?;
1415        check_hex(fn_hash, 64, "fn_hash")?;
1416        check_instant(tx, "tx")?;
1417        self.write("bind_name", |c| {
1418            // No new bindings under a suspended namespace.
1419            let host = name_host(fn_name);
1420            if let Some(since) = read_namespace(c, host)?.and_then(|n| n.suspended_at) {
1421                return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
1422            }
1423            // One namespace of names: a class name is not a function name.
1424            if exists(c, L::ClassNameBound, fn_name)? {
1425                return Err(Error::NameTaken { name: fn_name.to_string(), bound_as: "class" });
1426            }
1427            if !exists(c, L::DescriptorExists, fn_hash)? {
1428                return Err(Error::NotFound { what: "descriptor", key: fn_hash.to_string() });
1429            }
1430            if let Some(l) = get_strings(c, L::NameLatest, fn_name)?.pop() {
1431                if tx <= l.as_str() {
1432                    return Err(Error::NotLater {
1433                        what: "name",
1434                        key: fn_name.to_string(),
1435                        given: tx.to_string(),
1436                        latest: l,
1437                    });
1438                }
1439            }
1440            exec(c, L::NamePut, rusqlite::params![fn_name, tx, fn_hash])?;
1441            Ok(())
1442        })?;
1443        tracing::debug!(target: "datumesh_store", fn_name, fn_hash, tx, "bind_name");
1444        Ok(())
1445    }
1446
1447    fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>> {
1448        check_function_name(fn_name, "fn_name")?;
1449        check_instant(asof, "asof")?;
1450        self.run("resolve_name", |c| {
1451            // NULL for a closed binding (0.6.0): the name means nothing from then on.
1452            let hash: Option<Option<String>> =
1453                c.prepare_cached(L::NameAsof.sql()).db()?.query_row([fn_name, asof], |r| r.get(0)).optional().db()?;
1454            Ok(hash.flatten())
1455        })
1456    }
1457
1458    fn put_class(&self, bytes: &[u8]) -> Result<String> {
1459        // The core checks the descriptor (strict JSON, then 16.1); the bytes must be its
1460        // canonical form, since the class hash is the hash of the bytes stored.
1461        let d = ClassDescriptor::from_json(bytes)?;
1462        let canonical = d.canonical();
1463        if canonical != bytes {
1464            return Err(not_canonical_class());
1465        }
1466        let hash = d.hash();
1467        let host = d.steward.namespace.clone();
1468        self.write("put_class", |c| {
1469            // No new writes under a suspended namespace: the steward's (16.2).
1470            if let Some(since) = read_namespace(c, &host)?.and_then(|n| n.suspended_at) {
1471                return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
1472            }
1473            exec(c, L::ClassPut, rusqlite::params![hash, canonical])?;
1474            Ok(())
1475        })?;
1476        tracing::debug!(target: "datumesh_store", class_hash = %hash, "put_class");
1477        Ok(hash)
1478    }
1479
1480    fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>> {
1481        check_hex(class_hash, 64, "class_hash")?;
1482        self.run("class", |c| get_bytes(c, L::ClassGet, class_hash))
1483    }
1484
1485    fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()> {
1486        check_function_name(class_name, "class_name")?;
1487        check_hex(class_hash, 64, "class_hash")?;
1488        check_instant(tx, "tx")?;
1489        self.write("bind_class", |c| {
1490            // No new bindings under a suspended namespace: the host of the class name.
1491            let host = name_host(class_name);
1492            if let Some(since) = read_namespace(c, host)?.and_then(|n| n.suspended_at) {
1493                return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
1494            }
1495            let Some(bytes) = get_bytes(c, L::ClassGet, class_hash)? else {
1496                return Err(Error::NotFound { what: "class", key: class_hash.to_string() });
1497            };
1498            let flat = ClassDescriptor::from_json(&bytes)?;
1499            let methods: Vec<(String, String)> = flat.methods.into_iter().collect();
1500            // K5: only the methods this class adds or overrides are bound under its name: those
1501            // whose function hash the parent's flattened descriptor does not give.
1502            let parent = match &flat.parent {
1503                Some(p) => get_bytes(c, L::ClassGet, p)?
1504                    .map(|b| ClassDescriptor::from_json(&b))
1505                    .transpose()?
1506                    .map(|d| d.methods),
1507                None => None,
1508            };
1509            let own: Vec<(String, String)> =
1510                methods.iter().filter(|(m, h)| parent.as_ref().and_then(|pm| pm.get(m)) != Some(h)).cloned().collect();
1511            let own_names: Vec<String> = own.iter().map(|(m, _)| format!("{class_name}/{m}")).collect();
1512            // Every method's function descriptor is stored.
1513            for (_, h) in &methods {
1514                if !exists(c, L::DescriptorExists, h)? {
1515                    return Err(Error::NotFound { what: "descriptor", key: h.clone() });
1516                }
1517            }
1518            // One namespace of names: the class name is not a function name, and no method
1519            // name is a class name.
1520            if exists(c, L::NameBound, class_name)? {
1521                return Err(Error::NameTaken { name: class_name.to_string(), bound_as: "function" });
1522            }
1523            for name in &own_names {
1524                if exists(c, L::ClassNameBound, name)? {
1525                    return Err(Error::NameTaken { name: name.clone(), bound_as: "class" });
1526                }
1527            }
1528            // Later than the latest binding of the class name and of each method name.
1529            if let Some(l) = get_strings(c, L::ClassBindingLatest, class_name)?.pop() {
1530                if tx <= l.as_str() {
1531                    return Err(Error::NotLater {
1532                        what: "name",
1533                        key: class_name.to_string(),
1534                        given: tx.to_string(),
1535                        latest: l,
1536                    });
1537                }
1538            }
1539            for name in &own_names {
1540                if let Some(l) = get_strings(c, L::NameLatest, name)?.pop() {
1541                    if tx <= l.as_str() {
1542                        return Err(Error::NotLater {
1543                            what: "name",
1544                            key: name.clone(),
1545                            given: tx.to_string(),
1546                            latest: l,
1547                        });
1548                    }
1549                }
1550            }
1551            exec(c, L::ClassBindingPut, rusqlite::params![class_name, tx, class_hash])?;
1552            for ((_, h), name) in own.iter().zip(&own_names) {
1553                exec(c, L::NamePut, rusqlite::params![name.as_str(), tx, h.as_str()])?;
1554            }
1555            Ok(())
1556        })?;
1557        tracing::debug!(target: "datumesh_store", class_name, class_hash, tx, "bind_class");
1558        Ok(())
1559    }
1560
1561    fn close_binding(&self, name: &str, at: &str) -> Result<()> {
1562        check_function_name(name, "name")?;
1563        check_instant(at, "at")?;
1564        self.write("close_binding", |c| {
1565            // No new writes under a suspended namespace: the host of the name.
1566            let host = name_host(name);
1567            if let Some(since) = read_namespace(c, host)?.and_then(|n| n.suspended_at) {
1568                return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
1569            }
1570            if exists(c, L::ClassNameBound, name)? {
1571                // The class name, then the method names its binding bound and that are still bound.
1572                let (tx, class_hash) =
1573                    latest_binding_row(c, L::ClassBindingLatestRow, name)?.ok_or_else(|| unbound(name))?;
1574                let class_hash = class_hash.ok_or_else(|| unbound(name))?;
1575                later_than("name", name, at, &tx)?;
1576                let mut closing: Vec<String> = Vec::new();
1577                for (m, _) in own_method_bindings(c, name, &class_hash)? {
1578                    if let Some((mtx, mhash)) = latest_binding_row(c, L::NameLatestRow, &m)? {
1579                        if mhash.is_some() {
1580                            later_than("name", &m, at, &mtx)?;
1581                            closing.push(m);
1582                        }
1583                    }
1584                }
1585                exec(c, L::ClassBindingClose, rusqlite::params![name, at])?;
1586                for m in &closing {
1587                    exec(c, L::NameClose, rusqlite::params![m, at])?;
1588                }
1589            } else {
1590                let (tx, fn_hash) = latest_binding_row(c, L::NameLatestRow, name)?.ok_or_else(|| unbound(name))?;
1591                fn_hash.ok_or_else(|| unbound(name))?;
1592                later_than("name", name, at, &tx)?;
1593                exec(c, L::NameClose, rusqlite::params![name, at])?;
1594            }
1595            Ok(())
1596        })?;
1597        tracing::debug!(target: "datumesh_store", name, at, "close_binding");
1598        Ok(())
1599    }
1600
1601    fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>> {
1602        Ok(self.resolve_class_binding(class_name, asof)?.map(|b| b.class_hash))
1603    }
1604
1605    fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>> {
1606        check_function_name(class_name, "class_name")?;
1607        check_instant(asof, "asof")?;
1608        self.run("resolve_class_binding", |c| {
1609            // A closed binding (0.6.0) has no class hash: the name is unbound from its tx on.
1610            let row: Option<(Option<String>, String)> = c
1611                .prepare_cached(L::ClassBindingAsof.sql())
1612                .db()?
1613                .query_row([class_name, asof], |r| Ok((r.get(0)?, r.get(1)?)))
1614                .optional()
1615                .db()?;
1616            Ok(row.and_then(|(h, tx)| h.map(|class_hash| ClassBinding { class_hash, tx })))
1617        })
1618    }
1619
1620    fn class_names_bound_to(&self, class_hash: &str, at: &str) -> Result<Vec<String>> {
1621        check_hex(class_hash, 64, "class_hash")?;
1622        check_instant(at, "at")?;
1623        self.run("class_names_bound_to", |c| {
1624            let mut st = c.prepare_cached(L::ClassNamesBound.sql()).db()?;
1625            let rows = st.query_map([class_hash, at], |r| r.get::<_, String>(0)).db()?;
1626            rows.collect::<rusqlite::Result<Vec<_>>>().db()
1627        })
1628    }
1629
1630    fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>> {
1631        check_function_name(fn_name, "fn_name")?;
1632        check_instant(asof, "asof")?;
1633        self.run("resolve_binding", |c| {
1634            // A closed binding (0.6.0) has no function hash: the name is unbound from its tx on.
1635            let row: Option<(Option<String>, String)> = c
1636                .prepare_cached(L::BindingAsof.sql())
1637                .db()?
1638                .query_row([fn_name, asof], |r| Ok((r.get(0)?, r.get(1)?)))
1639                .optional()
1640                .db()?;
1641            Ok(row.and_then(|(h, tx)| h.map(|fn_hash| Binding { fn_hash, tx })))
1642        })
1643    }
1644
1645    fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
1646        check_hex(cell_id, 64, "cell_id")?;
1647        check_instant(tx, "tx")?;
1648        check_hex(receipt_hash, 64, "receipt_hash")?;
1649        let asof = self.write("put_computed", |c| {
1650            let meta: Option<(String, String, String, bool)> = c
1651                .prepare_cached(L::ReceiptMeta.sql())
1652                .db()?
1653                .query_row([receipt_hash], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
1654                .optional()
1655                .db()?;
1656            let Some((r_cell, r_tx, asof, withdrawn)) = meta else {
1657                return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
1658            };
1659            // A computed version states a value: a withdrawal is refused (0.6.0).
1660            if withdrawn {
1661                return Err(Error::Invalid(datumesh_core::Error::new(
1662                    ErrorCode::Schema,
1663                    "$",
1664                    "a withdrawal is not the receipt of a computed version",
1665                )));
1666            }
1667            if r_cell != cell_id {
1668                return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
1669            }
1670            if r_tx != tx {
1671                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
1672            }
1673            let stored: Option<String> = c
1674                .prepare_cached(L::ComputedGet.sql())
1675                .db()?
1676                .query_row([cell_id, tx, asof.as_str()], |r| r.get(0))
1677                .optional()
1678                .db()?;
1679            match stored {
1680                Some(h) if h == receipt_hash => {}
1681                Some(_) => return Err(Error::Conflict { hash: receipt_hash.to_string() }),
1682                None => {
1683                    exec(c, L::ComputedPut, rusqlite::params![cell_id, tx, asof, receipt_hash])?;
1684                }
1685            }
1686            Ok(asof)
1687        })?;
1688        tracing::debug!(target: "datumesh_store", cell_id, tx, asof, receipt_hash, "put_computed");
1689        Ok(())
1690    }
1691
1692    fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1693        self.asof_version("computed_asof", L::ComputedAsof, cell_id, asof)
1694    }
1695
1696    fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1697        self.asof_version("stored_asof", L::StoredAsof, cell_id, asof)
1698    }
1699
1700    fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>> {
1701        check_hex(cell_id, 64, "cell_id")?;
1702        self.run("cell_dependents", |c| get_strings(c, L::CellDependents, cell_id))
1703    }
1704
1705    /// One query: the version and its receipt's bytes.
1706    fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1707        Ok(self
1708            .asof_with_receipt("computed_asof_with_receipt", L::ComputedAsofReceipt, cell_id, asof)?
1709            .map(|(v, b)| (v, Cow::Owned(b))))
1710    }
1711
1712    /// One query: the version and its receipt's bytes.
1713    fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1714        Ok(self
1715            .asof_with_receipt("stored_asof_with_receipt", L::StoredAsofReceipt, cell_id, asof)?
1716            .map(|(v, b)| (v, Cow::Owned(b))))
1717    }
1718
1719    fn put_manifest(&self, bytes: &[u8]) -> Result<String> {
1720        let m = Manifest::from_json(bytes)?;
1721        let entry = m.entry();
1722        let canonical = m.canonical();
1723        let members = m.members();
1724        let n = i64::try_from(members.len()).unwrap_or(i64::MAX);
1725        self.run("put_manifest", |c| {
1726            // The entry hashes the content: a stored entry has these very bytes.
1727            if exists(c, L::ManifestExists, &entry)? {
1728                return Ok(());
1729            }
1730            self.locked_write(c, |c| {
1731                if exists(c, L::ManifestExists, &entry)? {
1732                    return Ok(());
1733                }
1734                exec(
1735                    c,
1736                    L::ManifestPut,
1737                    rusqlite::params![entry, m.slice().id(), m.members_hash(), m.slice().fn_hash(), n, canonical],
1738                )?;
1739                let mut st = c.prepare_cached(L::ManifestMemberPut.sql()).db()?;
1740                for h in members {
1741                    st.execute([entry.as_str(), h.as_str()]).db()?;
1742                }
1743                Ok(())
1744            })?;
1745            self.bound_wal(c);
1746            Ok(())
1747        })?;
1748        tracing::debug!(target: "datumesh_store", entry = %entry, members = n, "put_manifest");
1749        Ok(entry)
1750    }
1751
1752    fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>> {
1753        check_hex(receipt_hash, 64, "receipt_hash")?;
1754        self.run("member_manifests", |c| get_strings(c, L::MemberManifests, receipt_hash))
1755    }
1756
1757    fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>> {
1758        check_hex(receipt_hash, 64, "receipt_hash")?;
1759        self.run("slice_entries", |c| get_strings(c, L::SliceEntries, receipt_hash))
1760    }
1761
1762    fn slice_dependents(&self, entry: &str) -> Result<Vec<String>> {
1763        check_entry(entry, "entry")?;
1764        self.run("slice_dependents", |c| get_strings(c, L::SliceDependents, entry))
1765    }
1766
1767    fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>> {
1768        check_instant(asof, "asof")?;
1769        let v = slice.to_value();
1770        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1771            return self.versions_between(&cell_id, &from, &to, asof);
1772        }
1773        let p = Pattern::of(&v)?;
1774        self.run("slice_members", |c| {
1775            let rows = rows(&p, c, asof, [L::SliceMembersAll, L::SliceMembersDrive], |r| {
1776                let cell_id: String = r.get(5)?;
1777                Ok((
1778                    SliceMember {
1779                        // A slice's members leave the withdrawn versions out (the query does).
1780                        version: Version {
1781                            cell_id,
1782                            tx: r.get(0)?,
1783                            receipt_hash: r.get(1)?,
1784                            asof: r.get(2)?,
1785                            withdrawn: false,
1786                            recorded: r.get(3)?,
1787                            seq: r.get::<_, Option<i64>>("seq")?.unwrap_or(0),
1788                        },
1789                        receipt: r.get(4)?,
1790                    },
1791                    r.get::<_, String>(6)?,
1792                ))
1793            })?;
1794            in_key_order(&p, rows, |m| &m.version.cell_id)
1795        })
1796    }
1797
1798    fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>> {
1799        check_hex(cell_id, 64, "cell_id")?;
1800        check_instant(from, "from")?;
1801        check_instant(to, "to")?;
1802        check_instant(asof, "asof")?;
1803        self.run("versions_between", |c| {
1804            let mut st = c.prepare_cached(L::VersionsBetween.sql()).db()?;
1805            let rows = st
1806                .query_map(rusqlite::params![cell_id, from, to, asof], |r| {
1807                    Ok(SliceMember { version: version_row(r, cell_id)?, receipt: r.get(5)? })
1808                })
1809                .db()?;
1810            rows.collect::<rusqlite::Result<Vec<SliceMember>>>().db()
1811        })
1812    }
1813
1814    fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>> {
1815        check_instant(asof, "asof")?;
1816        let v = slice.to_value();
1817        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1818            return self.run("slice_values", |c| {
1819                let mut st = c.prepare_cached(L::VersionsBetweenValues.sql()).db()?;
1820                let rows = st.query_map(rusqlite::params![cell_id, from, to, asof], value_columns).db()?;
1821                let mut out = Vec::new();
1822                for r in rows {
1823                    out.push(value_of(r.db()?)?.0);
1824                }
1825                Ok(out)
1826            });
1827        }
1828        let p = Pattern::of(&v)?;
1829        self.run("slice_values", |c| {
1830            let rows = rows(&p, c, asof, [L::SliceValuesAll, L::SliceValuesDrive], value_columns)?;
1831            let mut values = Vec::with_capacity(rows.len());
1832            for row in rows {
1833                values.push(value_of(row)?);
1834            }
1835            in_key_order_parsed(&p, values, |m| &m.version.cell_id)
1836        })
1837    }
1838
1839    fn slice_withdrawn_latest(&self, slice: &Slice, asof: &str) -> Result<Option<(String, String)>> {
1840        check_instant(asof, "asof")?;
1841        let v = slice.to_value();
1842        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1843            // A version slice: its cell's version answering as of asof, when a withdrawal in range.
1844            return Ok(self
1845                .stored_asof(&cell_id, asof)?
1846                .filter(|s| s.withdrawn && from.as_str() <= s.tx.as_str() && s.tx.as_str() <= to.as_str())
1847                .map(|s| (s.tx, s.asof)));
1848        }
1849        let p = Pattern::of(&v)?;
1850        self.run("slice_withdrawn_latest", |c| withdrawn_latest(&p, c, asof))
1851    }
1852
1853    fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool> {
1854        check_instant(asof, "asof")?;
1855        let v = slice.to_value();
1856        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1857            return self.run("slice_changed_after", |c| {
1858                c.prepare_cached(L::VersionsChangedAfter.sql())
1859                    .db()?
1860                    .query_row(rusqlite::params![cell_id, from, to, asof], |r| r.get(0))
1861                    .db()
1862            });
1863        }
1864        let p = Pattern::of(&v)?;
1865        self.run("slice_changed_after", |c| changed_after(&p, c, asof))
1866    }
1867
1868    fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>> {
1869        check_instant(asof, "asof")?;
1870        let p = Pattern::of(&slice.to_value())?;
1871        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1872        self.run("computed_cells", |c| {
1873            let (d, _) = drive(&p, c, false)?;
1874            let q = if d.is_some() { L::ComputedCellsDrive } else { L::ComputedCellsAll };
1875            let mut binds = params(&p, asof, d);
1876            binds.push((":limit", SqlValue::Integer(limit)));
1877            let mut st = c.prepare_cached(q.sql()).db()?;
1878            bind(&mut st, &binds)?;
1879            let mut rows = st.raw_query();
1880            let mut out = Vec::new();
1881            while let Some(r) = rows.next().db()? {
1882                let args = args_of(&r.get::<_, String>(3).db()?)?;
1883                out.push(Cell {
1884                    args,
1885                    fn_hash: r.get::<_, String>(2).db()?,
1886                    fn_name: r.get::<_, String>(1).db()?,
1887                    ns: r.get::<_, String>(0).db()?,
1888                });
1889            }
1890            Ok(out)
1891        })
1892    }
1893
1894    fn has_bindings_under(&self, namespace: &str) -> Result<bool> {
1895        let prefix = format!("{namespace}/");
1896        self.run("has_bindings_under", |c| {
1897            c.prepare_cached(L::HasBindingsUnder.sql()).db()?.query_row([&prefix], |r| r.get(0)).db()
1898        })
1899    }
1900
1901    fn upsert_catalog(&self, entries: &[CatalogEntry]) -> Result<Vec<i64>> {
1902        for e in entries {
1903            check_catalog_entry(e)?;
1904        }
1905        let rows: Vec<CatalogRow> = entries.iter().map(CatalogRow::plain).collect();
1906        self.write_catalog(&rows, false)
1907    }
1908
1909    fn upsert_catalog_ext(&self, entries: &[CatalogEntryExt]) -> Result<Vec<i64>> {
1910        for e in entries {
1911            check_catalog_ext(e)?;
1912        }
1913        let rows: Vec<CatalogRow> = entries.iter().map(CatalogRow::ext).collect();
1914        self.write_catalog(&rows, true)
1915    }
1916
1917    fn upsert_key_values(&self, owner: &str, key: &str, values: &[KeyValue]) -> Result<Vec<i64>> {
1918        check_key_values(owner, key, values)?;
1919        if values.is_empty() {
1920            return Ok(Vec::new());
1921        }
1922        self.write("upsert_key_values", |c| {
1923            let mut ids = Vec::with_capacity(values.len());
1924            for v in values {
1925                let aliases = aliases_json(&v.aliases);
1926                let id: i64 = c
1927                    .prepare_cached(
1928                        "INSERT INTO key_values (owner, key, value, label, aliases) VALUES (?1, ?2, ?3, ?4, ?5)
1929                         ON CONFLICT (owner, key, value) DO UPDATE SET label = excluded.label, aliases = excluded.aliases
1930                         RETURNING id",
1931                    )
1932                    .db()?
1933                    .query_row(rusqlite::params![owner, key, v.value, v.label, aliases], |r| r.get(0))
1934                    .db()?;
1935                ids.push(id);
1936            }
1937            Ok(ids)
1938        })
1939    }
1940
1941    fn refresh_value_counts(&self) -> Result<u64> {
1942        self.write("refresh_value_counts", |c| {
1943            let n = c
1944                .prepare_cached(
1945                    "UPDATE key_values SET n_cells = COALESCE((
1946                         SELECT count(*) FROM catalog_entries e JOIN cell_args a
1947                           ON a.fn_hash = e.hash AND a.name = key_values.key AND a.value = key_values.value
1948                          WHERE e.kind = 'function' AND e.name = key_values.owner), 0)",
1949                )
1950                .db()?
1951                .execute([])
1952                .db()?;
1953            Ok(n as u64)
1954        })
1955    }
1956
1957    fn text_find(&self, query: &str, limit: usize) -> Result<Vec<Hit>> {
1958        let Some(words) = Words::new(query) else { return Ok(Vec::new()) };
1959        if limit == 0 {
1960            return Ok(Vec::new());
1961        }
1962        // The query is $1 (the scores are computed by the functions registered on each
1963        // connection, which split the query the same way); the prefilter's patterns follow;
1964        // the LIMIT is last. Each table is ordered and cut in SQL (0.5.3).
1965        let entry_where = like_where_sqlite(&words, &["name", "label", "description", "args"], 2);
1966        let value_where = like_where_sqlite(&words, &["value", "label", "aliases"], 2);
1967        let cap = limit;
1968        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1969        self.run("text_find", |c| {
1970            let mut hits = Vec::new();
1971            let mut params: Vec<SqlValue> = vec![SqlValue::Text(query.to_string())];
1972            params.extend(entry_where.1.iter().map(|p| SqlValue::Text(p.clone())));
1973            params.push(SqlValue::Integer(limit));
1974            let sql = format!(
1975                "SELECT * FROM (SELECT id, kind, name, hash, label, description, args, examples, source, signed_by,
1976                        datumesh_entry_total(?1, name, label, description, args) AS total
1977                   FROM catalog_entries WHERE 1 = 1{}) e
1978                  WHERE total IS NOT NULL ORDER BY total DESC, name LIMIT ?{}",
1979                entry_where.0,
1980                params.len()
1981            );
1982            let rows: Vec<HitRow> = {
1983                let mut st = c.prepare(&sql).db()?;
1984                let mapped = st
1985                    .query_map(rusqlite::params_from_iter(params.iter()), |r| {
1986                        Ok((
1987                            r.get(0)?,
1988                            r.get(1)?,
1989                            r.get(2)?,
1990                            r.get(3)?,
1991                            r.get(4)?,
1992                            r.get(5)?,
1993                            r.get(6)?,
1994                            r.get(7)?,
1995                            r.get(8)?,
1996                            r.get(9)?,
1997                            r.get(10)?,
1998                        ))
1999                    })
2000                    .db()?;
2001                mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
2002            };
2003            for (id, kind, name, hash, label, description, args, examples, source, signed_by, total) in rows {
2004                let entry =
2005                    entry_from_columns(&kind, name, hash, label, description, &args, &examples, &source, signed_by)?;
2006                hits.push(Hit::Entry { id, entry, score: words.score_of(total as u32) });
2007            }
2008            let mut params: Vec<SqlValue> = vec![SqlValue::Text(query.to_string())];
2009            params.extend(value_where.1.iter().map(|p| SqlValue::Text(p.clone())));
2010            params.push(SqlValue::Integer(limit));
2011            let sql = format!(
2012                "SELECT * FROM (SELECT id, owner, key, value, label, aliases,
2013                        datumesh_value_total(?1, value, label, aliases) AS total
2014                   FROM key_values WHERE 1 = 1{}) v
2015                  WHERE total IS NOT NULL
2016                  ORDER BY total DESC, owner || char(1) || key || char(1) || value LIMIT ?{}",
2017                value_where.0,
2018                params.len()
2019            );
2020            let rows: Vec<(i64, String, String, String, String, String, i64)> = {
2021                let mut st = c.prepare(&sql).db()?;
2022                let mapped = st
2023                    .query_map(rusqlite::params_from_iter(params.iter()), |r| {
2024                        Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?, r.get(6)?))
2025                    })
2026                    .db()?;
2027                mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
2028            };
2029            for (id, owner, key, value, label, aliases_text, total) in rows {
2030                let aliases = parse_aliases(&aliases_text)?;
2031                hits.push(Hit::Value { id, owner, key, value, label, aliases, score: words.score_of(total as u32) });
2032            }
2033            Ok(rank(hits, cap))
2034        })
2035    }
2036
2037    fn vector_find(&self, _model: &str, _vec: &[f32], _limit: usize) -> Result<Vec<Hit>> {
2038        Err(unsupported_vectors())
2039    }
2040
2041    fn put_embeddings(&self, _model: &str, _items: &[Embedding]) -> Result<()> {
2042        Err(unsupported_vectors())
2043    }
2044
2045    fn pending_embeddings(&self, _model: &str, _limit: usize) -> Result<Vec<PendingEmbedding>> {
2046        Ok(Vec::new())
2047    }
2048
2049    fn vector_available(&self) -> bool {
2050        false
2051    }
2052
2053    fn log_miss(&self, query: &str) -> Result<()> {
2054        let Some(q) = miss_text(query) else { return Ok(()) };
2055        self.write("log_miss", |c| {
2056            c.prepare_cached("INSERT INTO find_misses (query) VALUES (?1)").db()?.execute([q]).db()?;
2057            // Keep the newest FIND_MISSES_CAP rows: prune the oldest beyond that.
2058            c.prepare_cached(
2059                "DELETE FROM find_misses WHERE rowid IN (SELECT rowid FROM find_misses ORDER BY at
2060                     LIMIT max((SELECT count(*) FROM find_misses) - ?1, 0))",
2061            )
2062            .db()?
2063            .execute([as_i64(FIND_MISSES_CAP)])
2064            .db()?;
2065            Ok(())
2066        })
2067    }
2068
2069    fn put_function_test(&self, test: &FunctionTest) -> Result<bool> {
2070        let (total, covered) = crate::functions::check_test(test)?;
2071        self.write("put_function_test", |c| {
2072            let n = exec(
2073                c,
2074                L::FunctionTestPut,
2075                rusqlite::params![
2076                    &test.fn_hash,
2077                    &test.case,
2078                    &test.test_json,
2079                    &test.signed_by,
2080                    &test.last_run_at,
2081                    &test.last_result,
2082                    &test.last_detail,
2083                    total,
2084                    covered
2085                ],
2086            )?;
2087            if n == 1 {
2088                let results = crate::functions::result_counts(test.last_result.as_deref());
2089                bump_counter(
2090                    c,
2091                    &test.fn_hash,
2092                    "",
2093                    1,
2094                    results,
2095                    test.last_run_at.as_deref(),
2096                    (total.into(), covered.into()),
2097                )?;
2098            }
2099            Ok(n == 1)
2100        })
2101    }
2102
2103    fn function_test(&self, fn_hash: &str, case: &str) -> Result<Option<FunctionTest>> {
2104        check_hex(fn_hash, 64, "fn_hash")?;
2105        crate::functions::check_case(case)?;
2106        self.run("function_test", |c| {
2107            let mut st = c.prepare_cached(L::FunctionTestOne.sql()).db()?;
2108            let mut rows = st.query_map(rusqlite::params![fn_hash, case], function_test_row).db()?;
2109            rows.next().transpose().db()
2110        })
2111    }
2112
2113    fn function_tests_failing(&self, fn_hash: &str, fn_name: Option<&str>, limit: usize) -> Result<Vec<FunctionTest>> {
2114        check_hex(fn_hash, 64, "fn_hash")?;
2115        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2116        self.run("function_tests_failing", |c| {
2117            let mut st = c.prepare_cached(L::FunctionTestsFailing.sql()).db()?;
2118            let rows = st.query_map(rusqlite::params![fn_hash, fn_name, limit], function_test_row).db()?;
2119            rows.collect::<rusqlite::Result<Vec<FunctionTest>>>().db()
2120        })
2121    }
2122
2123    fn false_test_cells(&self, fn_hash: &str, limit: usize) -> Result<Vec<(String, Vec<u8>)>> {
2124        check_hex(fn_hash, 64, "fn_hash")?;
2125        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2126        self.run("false_test_cells", |c| {
2127            let mut st = c.prepare_cached(L::FalseTestCells.sql()).db()?;
2128            let rows = st.query_map(rusqlite::params![fn_hash, limit], |r| Ok((r.get(0)?, r.get(1)?))).db()?;
2129            rows.collect::<rusqlite::Result<Vec<(String, Vec<u8>)>>>().db()
2130        })
2131    }
2132
2133    fn dependants_of(&self, name: &str, at: &str, limit: usize) -> Result<Vec<(String, String)>> {
2134        check_function_name(name, "name")?;
2135        check_instant(at, "at")?;
2136        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2137        self.run("dependants_of", |c| {
2138            let mut st = c.prepare_cached(L::DependantsOf.sql()).db()?;
2139            let rows = st.query_map(rusqlite::params![name, at, limit], |r| Ok((r.get(0)?, r.get(1)?))).db()?;
2140            rows.collect::<rusqlite::Result<Vec<(String, String)>>>().db()
2141        })
2142    }
2143
2144    fn catalog_entries_all(&self, limit: usize) -> Result<Vec<(CatalogKind, String, String, String)>> {
2145        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2146        self.run("catalog_entries_all", |c| {
2147            let mut st = c.prepare_cached(L::CatalogEntriesAll.sql()).db()?;
2148            let rows = st.query_map([limit], |r| Ok((r.get::<_, String>(0)?, r.get(1)?, r.get(2)?, r.get(3)?))).db()?;
2149            rows.map(|row| {
2150                let (kind, name, label, description): (String, String, String, String) = row.db()?;
2151                let kind =
2152                    CatalogKind::parse(&kind).ok_or_else(|| invalid("catalog", "a stored entry has a bad kind"))?;
2153                Ok((kind, name, label, description))
2154            })
2155            .collect()
2156        })
2157    }
2158
2159    fn dictionary_values_ordered(&self, owner: &str, key: &str, limit: usize) -> Result<Vec<String>> {
2160        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2161        self.run("dictionary_values_ordered", |c| {
2162            let mut st = c.prepare_cached(L::DictionaryValuesOrdered.sql()).db()?;
2163            let rows = st.query_map(rusqlite::params![owner, key, limit], |r| r.get::<_, String>(0)).db()?;
2164            rows.collect::<rusqlite::Result<Vec<String>>>().db()
2165        })
2166    }
2167
2168    fn function_tests(&self, fn_hash: &str) -> Result<Vec<FunctionTest>> {
2169        check_hex(fn_hash, 64, "fn_hash")?;
2170        self.run("function_tests", |c| {
2171            let mut st = c.prepare_cached(L::FunctionTestsOf.sql()).db()?;
2172            let rows = st.query_map([fn_hash], function_test_row).db()?;
2173            rows.collect::<rusqlite::Result<Vec<FunctionTest>>>().db()
2174        })
2175    }
2176
2177    fn record_function_test(
2178        &self,
2179        fn_hash: &str,
2180        case: &str,
2181        run_at: &str,
2182        result: &str,
2183        detail: &str,
2184    ) -> Result<bool> {
2185        check_hex(fn_hash, 64, "fn_hash")?;
2186        crate::functions::check_case(case)?;
2187        check_instant(run_at, "run_at")?;
2188        crate::functions::check_result(result)?;
2189        self.write("record_function_test", |c| {
2190            let Some((old_name, old_result)) = function_test_old(c, fn_hash, case)? else { return Ok(false) };
2191            let n = exec(c, L::FunctionTestRecord, rusqlite::params![run_at, result, detail, fn_hash, case])?;
2192            if n == 1 {
2193                // The test moves within its row: the row's counts change by the difference.
2194                let (before, after) = (
2195                    crate::functions::result_counts(old_result.as_deref()),
2196                    crate::functions::result_counts(Some(result)),
2197                );
2198                let row = old_name.unwrap_or_default();
2199                let d = [after[0] - before[0], after[1] - before[1], after[2] - before[2], after[3] - before[3]];
2200                bump_counter(c, fn_hash, &row, 0, d, None, (0, 0))?;
2201                exec(c, L::CounterRunRecompute, rusqlite::params![fn_hash, row])?;
2202            }
2203            Ok(n == 1)
2204        })
2205    }
2206
2207    fn set_function_branches(&self, fn_hash: &str, total: u32, covered: u32) -> Result<()> {
2208        check_hex(fn_hash, 64, "fn_hash")?;
2209        let (total, covered) = crate::functions::branch_counts(total, covered)?;
2210        self.write("set_function_branches", |c| {
2211            exec(c, L::FunctionBranches, rusqlite::params![fn_hash, total, covered]).map(|_| ())
2212        })
2213    }
2214
2215    fn function_readers(&self, name: &str) -> Result<Vec<String>> {
2216        check_function_name(name, "name")?;
2217        self.run("function_readers", |c| get_strings(c, L::FunctionReaders, name))
2218    }
2219
2220    fn bound_names(&self, fn_hash: &str) -> Result<Vec<String>> {
2221        check_hex(fn_hash, 64, "fn_hash")?;
2222        self.run("bound_names", |c| get_strings(c, L::BoundNames, fn_hash))
2223    }
2224
2225    fn name_function_tests(&self, fn_hash: &str, names: &[(String, String)]) -> Result<u64> {
2226        check_hex(fn_hash, 64, "fn_hash")?;
2227        for (case, name) in names {
2228            crate::functions::check_case(case)?;
2229            check_function_name(name, "name")?;
2230        }
2231        if names.is_empty() {
2232            return Ok(0);
2233        }
2234        self.write("name_function_tests", |c| {
2235            let mut named = 0u64;
2236            // The rows moved from unnamed to their names, with their results: [tests, pass,
2237            // fail, error, not_run] per name (0.5.3: the counters move with them).
2238            let mut moved: std::collections::BTreeMap<String, [i64; 5]> = std::collections::BTreeMap::new();
2239            for (case, name) in names {
2240                let Some((old_name, result)) = function_test_old(c, fn_hash, case)? else { continue };
2241                if old_name.is_some() {
2242                    continue;
2243                }
2244                if exec(c, L::FunctionTestName, rusqlite::params![fn_hash, case, name])? == 1 {
2245                    named += 1;
2246                    let d = crate::functions::result_counts(result.as_deref());
2247                    let e = moved.entry(name.clone()).or_insert([0; 5]);
2248                    e[0] += 1;
2249                    for (i, x) in d.iter().enumerate() {
2250                        e[i + 1] += x;
2251                    }
2252                }
2253            }
2254            for (name, d) in &moved {
2255                bump_counter(c, fn_hash, name, d[0], [d[1], d[2], d[3], d[4]], None, (0, 0))?;
2256                bump_counter(c, fn_hash, "", -d[0], [-d[1], -d[2], -d[3], -d[4]], None, (0, 0))?;
2257                exec(c, L::CounterRunRecompute, rusqlite::params![fn_hash, name])?;
2258            }
2259            if !moved.is_empty() {
2260                exec(c, L::CounterRunRecompute, rusqlite::params![fn_hash, ""])?;
2261            }
2262            Ok(named)
2263        })
2264    }
2265
2266    fn unnamed_function_tests(&self, limit: usize) -> Result<Vec<FunctionTest>> {
2267        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2268        self.run("unnamed_function_tests", |c| {
2269            let mut st = c.prepare_cached(L::FunctionTestsUnnamed.sql()).db()?;
2270            let rows = st.query_map([limit], function_test_row).db()?;
2271            rows.collect::<rusqlite::Result<Vec<FunctionTest>>>().db()
2272        })
2273    }
2274
2275    fn function_test_summary(&self, fn_hash: &str, fn_name: Option<&str>) -> Result<TestSummary> {
2276        check_hex(fn_hash, 64, "fn_hash")?;
2277        self.run("function_test_summary", |c| {
2278            let mut st = c.prepare_cached(L::FunctionTestSummary.sql()).db()?;
2279            let (count, pass, fail, error, not_run, last_run_at, total, covered) = st
2280                .query_row(rusqlite::params![fn_hash, fn_name], |r| {
2281                    Ok((
2282                        r.get::<_, i64>(0)?,
2283                        r.get::<_, i64>(1)?,
2284                        r.get::<_, i64>(2)?,
2285                        r.get::<_, i64>(3)?,
2286                        r.get::<_, i64>(4)?,
2287                        r.get::<_, Option<String>>(5)?,
2288                        r.get::<_, i64>(6)?,
2289                        r.get::<_, i64>(7)?,
2290                    ))
2291                })
2292                .db()?;
2293            // The branch counts are integer with a check of at least zero: an `as` is exact.
2294            Ok(TestSummary {
2295                count: count as u64,
2296                pass: pass as u64,
2297                fail: fail as u64,
2298                error: error as u64,
2299                not_run: not_run as u64,
2300                last_run_at,
2301                branches_total: total as u32,
2302                branches_covered: covered as u32,
2303            })
2304        })
2305    }
2306
2307    fn function_tests_page(
2308        &self,
2309        fn_hash: &str,
2310        fn_name: Option<&str>,
2311        after_case: Option<&str>,
2312        limit: usize,
2313    ) -> Result<Vec<FunctionTest>> {
2314        check_hex(fn_hash, 64, "fn_hash")?;
2315        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2316        self.run("function_tests_page", |c| {
2317            let rows: Vec<FunctionTest> = match fn_name {
2318                None => {
2319                    let mut st = c.prepare_cached(L::FunctionTestsPage.sql()).db()?;
2320                    let mapped = st.query_map(rusqlite::params![fn_hash, after_case, limit], function_test_row).db()?;
2321                    mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
2322                }
2323                Some(name) => {
2324                    let mut st = c.prepare_cached(L::FunctionTestsPageNamed.sql()).db()?;
2325                    let mapped =
2326                        st.query_map(rusqlite::params![fn_hash, name, after_case, limit], function_test_row).db()?;
2327                    mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
2328                }
2329            };
2330            Ok(rows)
2331        })
2332    }
2333
2334    fn stored_receipts_of(&self, ns: &str, fn_name: &str, fn_hash: &str, limit: usize) -> Result<Vec<Vec<u8>>> {
2335        check_hex(fn_hash, 64, "fn_hash")?;
2336        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2337        self.run("stored_receipts_of", |c| {
2338            let mut st = c.prepare_cached(L::StoredReceiptsOf.sql()).db()?;
2339            let rows = st.query_map(rusqlite::params![fn_hash, ns, fn_name, limit], |r| r.get::<_, Vec<u8>>(0)).db()?;
2340            rows.collect::<rusqlite::Result<Vec<Vec<u8>>>>().db()
2341        })
2342    }
2343
2344    fn slice_values_page(
2345        &self,
2346        slice: &Slice,
2347        asof: &str,
2348        after_cell_id: Option<&str>,
2349        limit: usize,
2350    ) -> Result<Vec<SliceValue>> {
2351        check_instant(asof, "asof")?;
2352        if limit == 0 {
2353            return Ok(Vec::new());
2354        }
2355        let v = slice.to_value();
2356        if version_slice(slice, &v)?.is_some() {
2357            // A version slice is one cell's versions: paged here, from its values.
2358            let mut values = self.slice_values(slice, asof)?;
2359            values.retain(|x| after_cell_id.is_none_or(|a| x.version.cell_id.as_str() > a));
2360            values.sort_by(|a, b| a.version.cell_id.cmp(&b.version.cell_id));
2361            values.truncate(limit);
2362            return Ok(values);
2363        }
2364        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2365        let p = Pattern::of(&v)?;
2366        self.run("slice_values_page", |c| values_page(&p, c, asof, after_cell_id, limit))
2367    }
2368
2369    fn slice_page(&self, slice: &Slice, asof: &str, after: Option<&[u8]>, limit: usize) -> Result<Vec<SliceValue>> {
2370        check_instant(asof, "asof")?;
2371        if limit == 0 {
2372            return Ok(Vec::new());
2373        }
2374        let v = slice.to_value();
2375        if version_slice(slice, &v)?.is_some() {
2376            return Err(Error::Unsupported("a version slice has no key order to page by".into()));
2377        }
2378        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2379        let p = Pattern::of(&v)?;
2380        self.run("slice_page", |c| slice_page_rows(&p, c, asof, after, limit))
2381    }
2382
2383    fn slice_values_limit(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<SliceValue>> {
2384        check_instant(asof, "asof")?;
2385        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2386        let v = slice.to_value();
2387        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
2388            return self.run("slice_values_limit", |c| {
2389                // The statement of slice_values, with its LIMIT: the same order (tx).
2390                let sql = format!("{} LIMIT ?5", L::VersionsBetweenValues.sql());
2391                let mut st = c.prepare(&sql).db()?;
2392                let mut rows = st.query(rusqlite::params![cell_id, from, to, asof, limit]).db()?;
2393                let mut out = Vec::new();
2394                while let Some(r) = rows.next().db()? {
2395                    out.push(value_of(value_columns(r).db()?)?.0);
2396                }
2397                Ok(out)
2398            });
2399        }
2400        let p = Pattern::of(&v)?;
2401        self.run("slice_values_limit", |c| values_limited(&p, c, asof, limit))
2402    }
2403
2404    fn versions_limit(&self, cell_id: &str, from: &str, to: &str, limit: usize) -> Result<Vec<Version>> {
2405        check_hex(cell_id, 64, "cell_id")?;
2406        check_instant(from, "from")?;
2407        check_instant(to, "to")?;
2408        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2409        self.run("versions_limit", |c| {
2410            let mut st = c.prepare_cached(L::VersionRangeLimit.sql()).db()?;
2411            let rows = st.query_map(rusqlite::params![cell_id, from, to, limit], |r| version_row(r, cell_id)).db()?;
2412            rows.collect::<rusqlite::Result<Vec<Version>>>().db()
2413        })
2414    }
2415
2416    fn stored_cell_count(&self, ns: &str, fn_name: &str, fn_hash: &str) -> Result<u64> {
2417        check_hex(fn_hash, 64, "fn_hash")?;
2418        self.run("stored_cell_count", |c| {
2419            let n: i64 = c
2420                .prepare_cached(L::StoredCellCount.sql())
2421                .db()?
2422                .query_row(rusqlite::params![fn_hash, ns, fn_name], |r| r.get(0))
2423                .db()?;
2424            Ok(n as u64)
2425        })
2426    }
2427
2428    fn has_key_value(&self, owner: &str, key: &str, value: &str) -> Result<bool> {
2429        self.run("has_key_value", |c| {
2430            c.prepare_cached(L::DictionaryHas.sql())
2431                .db()?
2432                .query_row(rusqlite::params![owner, key, value], |r| r.get(0))
2433                .db()
2434        })
2435    }
2436
2437    fn key_value_count(&self, owner: &str, key: &str) -> Result<u64> {
2438        self.run("key_value_count", |c| {
2439            let n: i64 = c
2440                .prepare_cached(L::DictionaryCount.sql())
2441                .db()?
2442                .query_row(rusqlite::params![owner, key], |r| r.get(0))
2443                .db()?;
2444            Ok(n as u64)
2445        })
2446    }
2447
2448    fn mark_key_open(&self, owner: &str, key: &str) -> Result<()> {
2449        if owner.is_empty() || owner.len() > 512 || key.is_empty() || key.len() > 128 {
2450            return Err(invalid("key", "an owner of 1 to 512 bytes and a key of 1 to 128 bytes"));
2451        }
2452        self.write("mark_key_open", |c| exec(c, L::KeyOpenPut, rusqlite::params![owner, key]).map(|_| ()))
2453    }
2454
2455    fn open_key_count(&self) -> Result<u64> {
2456        self.run("open_key_count", |c| {
2457            let n: i64 = c.prepare_cached(L::OpenKeyCount.sql()).db()?.query_row([], |r| r.get(0)).db()?;
2458            Ok(n as u64)
2459        })
2460    }
2461
2462    fn key_is_open(&self, owner: &str, key: &str) -> Result<bool> {
2463        self.run("key_is_open", |c| {
2464            c.prepare_cached(L::KeyIsOpen.sql()).db()?.query_row(rusqlite::params![owner, key], |r| r.get(0)).db()
2465        })
2466    }
2467
2468    fn catalog_entry(&self, name: &str) -> Result<Option<CatalogEntry>> {
2469        self.run("catalog_entry", |c| {
2470            let mut st = c.prepare_cached(L::CatalogEntryNamed.sql()).db()?;
2471            let row = st
2472                .query_row([name], |r| {
2473                    Ok((
2474                        r.get::<_, String>(0)?,
2475                        r.get::<_, String>(1)?,
2476                        r.get::<_, Option<String>>(2)?,
2477                        r.get::<_, String>(3)?,
2478                        r.get::<_, String>(4)?,
2479                        r.get::<_, String>(5)?,
2480                        r.get::<_, String>(6)?,
2481                        r.get::<_, String>(7)?,
2482                        r.get::<_, Option<String>>(8)?,
2483                    ))
2484                })
2485                .optional()
2486                .db()?;
2487            let Some((kind, name, hash, label, description, args, examples, source, signed_by)) = row else {
2488                return Ok(None);
2489            };
2490            entry_from_columns(&kind, name, hash, label, description, &args, &examples, &source, signed_by).map(Some)
2491        })
2492    }
2493
2494    fn catalog_entry_ext(&self, kind: CatalogKind, name: &str) -> Result<Option<CatalogEntryExt>> {
2495        self.run("catalog_entry_ext", |c| {
2496            let mut st = c.prepare_cached(CATALOG_EXT_SELECT_BY_KIND_NAME).db()?;
2497            st.query_row(rusqlite::params![kind.as_str(), name], ext_from_row).optional().db()?.transpose()
2498        })
2499    }
2500
2501    fn catalog_entries_with_facets(&self) -> Result<Vec<FacetedEntry>> {
2502        self.run("catalog_entries_with_facets", |c| {
2503            let mut st = c
2504                .prepare(
2505                    "SELECT e.kind, e.name, e.hash, e.facets,
2506                            CASE WHEN e.kind = 'class'
2507                                 THEN (SELECT min(b.tx) FROM class_bindings b WHERE b.class_name = e.name)
2508                                 ELSE (SELECT min(b.tx) FROM name_bindings b WHERE b.fn_name = e.name) END,
2509                            e.source_name
2510                       FROM catalog_entries e
2511                      WHERE e.facets <> '{}'
2512                      ORDER BY e.kind, e.name",
2513                )
2514                .db()?;
2515            type FacetRow = (String, String, Option<String>, String, Option<String>, Option<String>);
2516            let rows: Vec<FacetRow> = st
2517                .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?, r.get(5)?)))
2518                .db()?
2519                .collect::<rusqlite::Result<_>>()
2520                .db()?;
2521            rows.into_iter()
2522                .map(|(kind, name, hash, facets, first_bound, source_name)| {
2523                    Ok(FacetedEntry {
2524                        kind: CatalogKind::parse(&kind)
2525                            .ok_or_else(|| invalid("catalog", "a stored entry has a bad kind"))?,
2526                        name,
2527                        hash,
2528                        facets: parse_facets(&facets)?,
2529                        first_bound,
2530                        source_name,
2531                    })
2532                })
2533                .collect()
2534        })
2535    }
2536
2537    fn extensions_of(&self, class: &str) -> Result<Vec<CatalogEntryExt>> {
2538        check_function_name(class, "class")?;
2539        self.run("extensions_of", |c| {
2540            let mut st = c
2541                .prepare_cached(
2542                    "SELECT kind, name, hash, label, description, args, examples, source, signed_by, facets, extends, source_name
2543                       FROM catalog_entries WHERE extends = ?1 ORDER BY name",
2544                )
2545                .db()?;
2546            let rows = st.query_map([class], ext_from_row).db()?.collect::<rusqlite::Result<Vec<_>>>().db()?;
2547            rows.into_iter().collect()
2548        })
2549    }
2550
2551    fn extensions_of_limit(&self, class: &str, limit: usize) -> Result<Vec<CatalogEntryExt>> {
2552        check_function_name(class, "class")?;
2553        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2554        self.run("extensions_of", |c| {
2555            let mut st = c
2556                .prepare_cached(
2557                    "SELECT kind, name, hash, label, description, args, examples, source, signed_by, facets, extends, source_name
2558                       FROM catalog_entries WHERE extends = ?1 ORDER BY name LIMIT ?2",
2559                )
2560                .db()?;
2561            let rows = st
2562                .query_map(rusqlite::params![class, limit], ext_from_row)
2563                .db()?
2564                .collect::<rusqlite::Result<Vec<_>>>()
2565                .db()?;
2566            rows.into_iter().collect()
2567        })
2568    }
2569
2570    fn catalog_summary(&self) -> Result<Summary> {
2571        self.run("catalog_summary", |c| {
2572            let rows: Vec<(String, String, String, i64)> = {
2573                let mut st = c
2574                    .prepare(
2575                        "SELECT kind, name, label, CASE WHEN kind = 'function'
2576                             THEN (SELECT COALESCE(sum(x.n), 0) FROM cell_counts x WHERE x.fn_hash = e.hash) ELSE 0 END
2577                           FROM catalog_entries e ORDER BY kind, name",
2578                    )
2579                    .db()?;
2580                let mapped = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))).db()?;
2581                mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
2582            };
2583            let mut entries = Vec::with_capacity(rows.len());
2584            for (kind, name, label, n_cells) in rows {
2585                let kind = CatalogKind::parse(&kind).ok_or_else(|| invalid("catalog", "a stored entry has a bad kind"))?;
2586                entries.push(SummaryEntry { kind, name, label, n_cells });
2587            }
2588            let groups: Vec<(String, String, i64)> = {
2589                let mut st = c.prepare("SELECT owner, key, count(*) FROM key_values GROUP BY owner, key ORDER BY owner, key").db()?;
2590                let mapped = st.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?))).db()?;
2591                mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
2592            };
2593            let mut dictionaries = Vec::with_capacity(groups.len());
2594            for (owner, key, n_values) in groups {
2595                let values: Vec<DictionaryValue> = {
2596                    let mut st = c
2597                        .prepare("SELECT value, label, n_cells FROM key_values WHERE owner = ?1 AND key = ?2 ORDER BY value LIMIT ?3")
2598                        .db()?;
2599                    let mapped = st
2600                        .query_map(rusqlite::params![owner, key, as_i64(SUMMARY_VALUES)], |r| {
2601                            Ok(DictionaryValue { value: r.get(0)?, label: r.get(1)?, n_cells: r.get(2)? })
2602                        })
2603                        .db()?;
2604                    mapped.collect::<rusqlite::Result<Vec<_>>>().db()?
2605                };
2606                dictionaries.push(Dictionary { owner, key, n_values, values });
2607            }
2608            Ok(Summary { entries, dictionaries })
2609        })
2610    }
2611
2612    // ---- Listings (0.7.0; CONTRACT-http-listing L3) ----------------------------------------------
2613
2614    fn put_listing(&self, l: &Listing) -> Result<ListingWrite> {
2615        check_listing(l)?;
2616        let d = FunctionDescriptor::from_json(&l.descriptor)?;
2617        let canonical = d.canonical();
2618        let subjects = subjects_json(&l.subjects);
2619        let facets = listing_facets_json(&l.subjects);
2620        self.write("put_listing", |c| {
2621            let stored = select_listing(c, &l.name)?;
2622            if stored.as_ref().is_some_and(|s| same_listing(s, l)) {
2623                return Ok(ListingWrite::Unchanged);
2624            }
2625            // The descriptor (once) and its inputs, as put_descriptor writes them.
2626            exec(c, L::DescriptorPut, rusqlite::params![l.fn_hash, canonical])?;
2627            for input in &d.inputs {
2628                exec(c, L::DescriptorInputPut, rusqlite::params![l.fn_hash, input])?;
2629            }
2630            // The row: listed_at is kept by a change.
2631            c.prepare_cached(
2632                "INSERT INTO listings (name, host, fn_hash, subjects, descriptor, key_id, label, description, fetched_at, listed_at)
2633                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
2634                 ON CONFLICT (name) DO UPDATE SET host = excluded.host, fn_hash = excluded.fn_hash,
2635                     subjects = excluded.subjects, descriptor = excluded.descriptor, key_id = excluded.key_id,
2636                     label = excluded.label, description = excluded.description, fetched_at = excluded.fetched_at",
2637            )
2638            .db()?
2639            .execute(rusqlite::params![
2640                l.name,
2641                l.host,
2642                l.fn_hash,
2643                subjects,
2644                l.descriptor,
2645                l.key_id,
2646                l.label,
2647                l.description,
2648                l.fetched_at,
2649                l.listed_at
2650            ])
2651            .db()?;
2652            // The catalogue entry (source listed; SQLite keeps no embeddings).
2653            let written = c
2654                .prepare_cached(
2655                "INSERT INTO catalog_entries (kind, name, hash, label, description, args, examples, source, signed_by, facets, extends, source_name, updated_at)
2656                 VALUES ('function', ?1, ?2, ?3, ?4, '{}', '[]', 'listed', ?5, ?6, NULL, NULL, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
2657                 ON CONFLICT (kind, name) DO UPDATE SET hash = excluded.hash, label = excluded.label,
2658                     description = excluded.description, args = excluded.args, examples = excluded.examples,
2659                     source = excluded.source, signed_by = excluded.signed_by, facets = excluded.facets,
2660                     extends = NULL, source_name = NULL, updated_at = excluded.updated_at
2661                     WHERE catalog_entries.source = 'listed'",
2662            )
2663            .db()?
2664            .execute(rusqlite::params![l.name, l.fn_hash, l.label, l.description, l.host, facets])
2665            .db()?;
2666            if written == 0 {
2667                // Another source's entry has this name (decided 27 Nov, C3): nothing is written.
2668                return Err(crate::catalogue::invalid("name", "a catalogue entry of another source has this name"));
2669            }
2670            Ok(if stored.is_some() { ListingWrite::Changed } else { ListingWrite::Inserted })
2671        })
2672    }
2673
2674    fn listing(&self, name: &str) -> Result<Option<Listing>> {
2675        self.run("listing", |c| select_listing(c, name))
2676    }
2677
2678    fn listings_of(&self, host: &str) -> Result<Vec<Listing>> {
2679        self.run("listings_of", |c| {
2680            let sql = format!("SELECT {LISTING_COLUMNS} FROM listings WHERE host = ?1 ORDER BY name");
2681            let mut st = c.prepare_cached(&sql).db()?;
2682            let mut rows = st.query([host]).db()?;
2683            let mut out = Vec::new();
2684            while let Some(r) = rows.next().db()? {
2685                out.push(listing_from_sqlite(r)?);
2686            }
2687            Ok(out)
2688        })
2689    }
2690
2691    fn listing_count(&self) -> Result<u64> {
2692        self.run("listing_count", |c| {
2693            let n: i64 = c.query_row("SELECT count(*) FROM listings", [], |r| r.get(0)).db()?;
2694            Ok(u64::try_from(n).unwrap_or(0))
2695        })
2696    }
2697
2698    fn delete_listing(&self, name: &str) -> Result<bool> {
2699        self.write("delete_listing", |c| {
2700            c.prepare_cached("DELETE FROM catalog_entries WHERE kind = 'function' AND source = 'listed' AND name = ?1")
2701                .db()?
2702                .execute([name])
2703                .db()?;
2704            let removed = c.prepare_cached("DELETE FROM listings WHERE name = ?1").db()?.execute([name]).db()?;
2705            Ok(removed > 0)
2706        })
2707    }
2708
2709    fn set_listing_unreached(&self, name: &str, since: Option<&str>) -> Result<bool> {
2710        if since.is_some_and(|s| !is_instant(s)) {
2711            return Err(crate::catalogue::invalid("since", "an instant (YYYY-MM-DDThh:mm:ss.ffffffZ)"));
2712        }
2713        self.write("set_listing_unreached", |c| {
2714            let stored: Option<Option<String>> = c
2715                .query_row("SELECT unreached_since FROM listings WHERE name = ?1", [name], |r| r.get(0))
2716                .optional()
2717                .db()?;
2718            let Some(stored) = stored else {
2719                return Err(Error::NotFound { what: "listing", key: name.to_string() });
2720            };
2721            if stored.as_deref() == since {
2722                return Ok(false);
2723            }
2724            c.prepare_cached("UPDATE listings SET unreached_since = ?2 WHERE name = ?1")
2725                .db()?
2726                .execute(rusqlite::params![name, since])
2727                .db()?;
2728            Ok(true)
2729        })
2730    }
2731
2732    fn listing_unreached(&self, name: &str) -> Result<Option<String>> {
2733        self.run("listing_unreached", |c| {
2734            let row: Option<Option<String>> = c
2735                .query_row("SELECT unreached_since FROM listings WHERE name = ?1", [name], |r| r.get(0))
2736                .optional()
2737                .db()?;
2738            Ok(row.flatten())
2739        })
2740    }
2741
2742    fn put_listed_host(&self, h: &ListedHost) -> Result<bool> {
2743        check_listed_host(h)?;
2744        self.write("put_listed_host", |c| {
2745            if listed_host_row(c, &h.host)?.as_ref() == Some(h) {
2746                return Ok(false);
2747            }
2748            c.prepare_cached(
2749                "INSERT INTO listed_hosts (host, last_seen, unreachable_since) VALUES (?1, ?2, ?3)
2750                 ON CONFLICT (host) DO UPDATE SET last_seen = excluded.last_seen,
2751                     unreachable_since = excluded.unreachable_since",
2752            )
2753            .db()?
2754            .execute(rusqlite::params![h.host, h.last_seen, h.unreachable_since])
2755            .db()?;
2756            Ok(true)
2757        })
2758    }
2759
2760    fn listed_host(&self, host: &str) -> Result<Option<ListedHost>> {
2761        self.run("listed_host", |c| listed_host_row(c, host))
2762    }
2763
2764    fn listed_hosts(&self) -> Result<Vec<ListedHost>> {
2765        self.run("listed_hosts", |c| {
2766            let mut st =
2767                c.prepare_cached("SELECT host, last_seen, unreachable_since FROM listed_hosts ORDER BY host").db()?;
2768            let mut rows = st.query([]).db()?;
2769            let mut out = Vec::new();
2770            while let Some(r) = rows.next().db()? {
2771                out.push(listed_host_sqlite(r)?);
2772            }
2773            Ok(out)
2774        })
2775    }
2776
2777    fn delete_listed_host(&self, host: &str) -> Result<bool> {
2778        self.write("delete_listed_host", |c| {
2779            c.prepare_cached(
2780                "DELETE FROM catalog_entries WHERE kind = 'function' AND source = 'listed'
2781                 AND name IN (SELECT name FROM listings WHERE host = ?1)",
2782            )
2783            .db()?
2784            .execute([host])
2785            .db()?;
2786            c.prepare_cached("DELETE FROM listings WHERE host = ?1").db()?.execute([host]).db()?;
2787            let gone = c.prepare_cached("DELETE FROM listed_hosts WHERE host = ?1").db()?.execute([host]).db()?;
2788            Ok(gone > 0)
2789        })
2790    }
2791}
2792
2793/// The columns of a value row: (tx, receipt_hash, asof, value_type, value, cell_id,
2794/// arguments, ns, fn, fn_hash, sort_key).
2795type ValueColumns =
2796    (String, String, String, String, String, String, String, String, String, String, String, Vec<u8>, i64);
2797
2798fn value_columns(r: &rusqlite::Row<'_>) -> rusqlite::Result<ValueColumns> {
2799    Ok((
2800        r.get(0)?,
2801        r.get(1)?,
2802        r.get(2)?,
2803        r.get(3)?,
2804        r.get(4)?,
2805        r.get(5)?,
2806        r.get(6)?,
2807        r.get(7)?,
2808        r.get(8)?,
2809        r.get(9)?,
2810        r.get(10)?,
2811        r.get(11)?,
2812        r.get::<_, Option<i64>>("seq")?.unwrap_or(0),
2813    ))
2814}
2815
2816/// A member's value and cell, rebuilt from the typed-argument index (with its arguments).
2817fn value_of(c: ValueColumns) -> Result<(SliceValue, Args)> {
2818    let (tx, receipt_hash, asof, recorded, ty, value, cell_id, args, ns, fn_name, fn_hash, sort_key, seq) = c;
2819    let ty = Type::from_name(&ty).ok_or_else(|| bad("type"))?;
2820    let args = args_of(&args)?;
2821    let cell = Cell { args: args.clone(), fn_hash, fn_name, ns };
2822    Ok((
2823        SliceValue {
2824            // A slice's values leave the withdrawn versions out (the query does).
2825            version: Version { cell_id, tx, receipt_hash, asof, withdrawn: false, recorded, seq },
2826            value: Scalar::from_lexical(ty, &value)?,
2827            cell,
2828            sort_key,
2829        },
2830        args,
2831    ))
2832}
2833
2834/// The constraints of a slice as the queries take them (`:cons`): `[name, kind, type, lo,
2835/// hi]`, a number range's ends as sort keys, a bound value's lexical form as `lo`.
2836fn constraints(p: &Pattern) -> String {
2837    let items: Vec<Value> = p
2838        .args
2839        .iter()
2840        .map(|a| {
2841            let (lo, hi) = match a.kind {
2842                Kind::Range => (sort_key(&a.ty, &a.lo), sort_key(&a.ty, &a.hi)),
2843                _ => (a.lo.clone(), a.hi.clone()),
2844            };
2845            Value::Array(
2846                [a.name.clone(), a.kind.as_str().to_string(), a.ty.clone(), lo, hi]
2847                    .into_iter()
2848                    .map(Value::String)
2849                    .collect(),
2850            )
2851        })
2852        .collect();
2853    String::from_utf8(Value::Array(items).to_jcs()).unwrap_or_default()
2854}
2855
2856/// Binds the named parameters a statement has, from `params` (skipping the others).
2857fn bind(st: &mut rusqlite::CachedStatement<'_>, params: &[(&str, SqlValue)]) -> Result<()> {
2858    for (name, value) in params {
2859        if let Some(i) = st.parameter_index(name).db()? {
2860            st.raw_bind_parameter(i, value).db()?;
2861        }
2862    }
2863    Ok(())
2864}
2865
2866/// The bound or ranged argument holding the fewest cells (probed, up to 10,001, when there
2867/// are several, or when `count` asks), else none (every cell of the function); and the
2868/// number of candidates when probed.
2869fn drive<'p>(p: &'p Pattern, c: &Connection, count: bool) -> Result<(Option<&'p Constraint>, Option<i64>)> {
2870    let probe = |a: Option<&Constraint>| -> Result<i64> {
2871        match a {
2872            None => c.prepare_cached(L::ProbeCells.sql()).db()?.query_row([&p.fn_hash], |r| r.get(0)).db(),
2873            Some(a) => {
2874                let (lo, hi) = (sort_key(&a.ty, &a.lo), sort_key(&a.ty, &a.hi));
2875                c.prepare_cached(L::SliceProbe.sql())
2876                    .db()?
2877                    .query_row(rusqlite::params![p.fn_hash, a.name, a.ty, lo, hi], |r| r.get(0))
2878                    .db()
2879            }
2880        }
2881    };
2882    let constrained: Vec<&Constraint> = p.args.iter().filter(|a| a.kind != Kind::Open).collect();
2883    Ok(match constrained.as_slice() {
2884        [] => (None, if count { Some(probe(None)?) } else { None }),
2885        [one] => (Some(*one), if count { Some(probe(Some(one))?) } else { None }),
2886        several => {
2887            let mut best: Option<(i64, &Constraint)> = None;
2888            for a in several {
2889                let n = probe(Some(a))?;
2890                if best.is_none_or(|(m, _)| n < m) {
2891                    best = Some((n, a));
2892                }
2893            }
2894            (best.map(|(_, a)| a), best.map(|(n, _)| n))
2895        }
2896    })
2897}
2898
2899/// The parameters of a slice query: the slice's, and the driving argument's range.
2900fn params(p: &Pattern, asof: &str, drive: Option<&Constraint>) -> Vec<(&'static str, SqlValue)> {
2901    let text = |s: &str| SqlValue::Text(s.to_string());
2902    let mut out = vec![
2903        (":fn_hash", text(&p.fn_hash)),
2904        (":ns", text(&p.ns)),
2905        (":fn", text(&p.fn_name)),
2906        (":nargs", SqlValue::Integer(p.args.len() as i64)),
2907        (":asof", text(asof)),
2908        (":cons", SqlValue::Text(constraints(p))),
2909    ];
2910    if let Some(a) = drive {
2911        out.push((":d_name", text(&a.name)));
2912        out.push((":d_type", text(&a.ty)));
2913        out.push((":d_lo", SqlValue::Text(sort_key(&a.ty, &a.lo))));
2914        out.push((":d_hi", SqlValue::Text(sort_key(&a.ty, &a.hi))));
2915    }
2916    out
2917}
2918
2919/// The latest withdrawal among a slice's members as of `asof`: the (tx, asof) of the greatest,
2920/// one indexed query (0.6.0; SPEC 8.2).
2921fn withdrawn_latest(p: &Pattern, c: &Connection, asof: &str) -> Result<Option<(String, String)>> {
2922    let (d, _) = drive(p, c, false)?;
2923    let q = if d.is_some() { L::SliceWithdrawnDrive } else { L::SliceWithdrawnAll };
2924    let mut st = c.prepare_cached(q.sql()).db()?;
2925    bind(&mut st, &params(p, asof, d))?;
2926    let mut rows = st.raw_query();
2927    match rows.next().db()? {
2928        Some(r) => Ok(Some((r.get::<_, String>(0).db()?, r.get::<_, String>(1).db()?))),
2929        None => Ok(None),
2930    }
2931}
2932
2933/// The rows of one of the member queries `qs` (all cells, driven), each made by `make`.
2934fn rows<T>(
2935    p: &Pattern,
2936    c: &Connection,
2937    asof: &str,
2938    qs: [L; 2],
2939    make: impl Fn(&rusqlite::Row<'_>) -> rusqlite::Result<T>,
2940) -> Result<Vec<T>> {
2941    let (d, _) = drive(p, c, false)?;
2942    let q = if d.is_some() { qs[1] } else { qs[0] };
2943    let mut st = c.prepare_cached(q.sql()).db()?;
2944    bind(&mut st, &params(p, asof, d))?;
2945    let mut rows = st.raw_query();
2946    let mut out = Vec::new();
2947    while let Some(r) = rows.next().db()? {
2948        out.push(make(r).db()?);
2949    }
2950    Ok(out)
2951}
2952
2953/// The key of a member: the "type:value" of its open and ranged arguments, by name.
2954fn key_of(p: &Pattern, args: &Args) -> Vec<String> {
2955    p.args
2956        .iter()
2957        .filter(|a| a.kind != Kind::Value)
2958        .filter_map(|a| args.get(&a.name).and_then(Arg::scalar))
2959        .map(|s| format!("{}:{}", s.ty().as_str(), s.lexical()))
2960        .collect()
2961}
2962
2963/// Members with their argument lists (JSON), in key order (then by cell id).
2964fn in_key_order<T>(p: &Pattern, rows: Vec<(T, String)>, cell_of: impl Fn(&T) -> &String) -> Result<Vec<T>> {
2965    let mut keyed = Vec::with_capacity(rows.len());
2966    for (m, args) in rows {
2967        keyed.push((key_of(p, &args_of(&args)?), m));
2968    }
2969    keyed.sort_by(|(a, ma), (b, mb)| cmp_keys(a, b).then_with(|| cell_of(ma).cmp(cell_of(mb))));
2970    Ok(keyed.into_iter().map(|(_, m)| m).collect())
2971}
2972
2973/// Members with their parsed arguments, in key order (then by cell id).
2974fn in_key_order_parsed<T>(p: &Pattern, rows: Vec<(T, Args)>, cell_of: impl Fn(&T) -> &String) -> Result<Vec<T>> {
2975    let mut keyed: Vec<(Vec<String>, T)> = rows.into_iter().map(|(m, args)| (key_of(p, &args), m)).collect();
2976    keyed.sort_by(|(a, ma), (b, mb)| cmp_keys(a, b).then_with(|| cell_of(ma).cmp(cell_of(mb))));
2977    Ok(keyed.into_iter().map(|(_, m)| m).collect())
2978}
2979
2980/// The members' values of a slice of cells as of `asof`, in key order, at most `limit`: the
2981/// statement of `slice_values` with the key order and the LIMIT in SQL. The order of `cmp_keys`
2982/// is, per key argument by name, the type's name, then the sort key (which sorts as the value
2983/// does, a number's as the decimal does).
2984/// The members' values as of `asof` in cell id order, after `after` (exclusive), at most
2985/// `limit`: the statement of the members with the cell id order and the LIMIT in SQL (0.5.3).
2986fn values_page(p: &Pattern, c: &Connection, asof: &str, after: Option<&str>, limit: i64) -> Result<Vec<SliceValue>> {
2987    let (d, _) = drive(p, c, false)?;
2988    let base = if d.is_some() { L::SliceValuesDrive } else { L::SliceValuesAll };
2989    let sql = format!("{} AND (:after IS NULL OR c.cell_id > :after) ORDER BY c.cell_id LIMIT :limit", base.sql());
2990    let mut binds: Vec<(String, SqlValue)> = params(p, asof, d).into_iter().map(|(k, v)| (k.to_string(), v)).collect();
2991    binds.push((":after".to_string(), after.map_or(SqlValue::Null, |a| SqlValue::Text(a.to_string()))));
2992    binds.push((":limit".to_string(), SqlValue::Integer(limit)));
2993    let mut st = c.prepare(&sql).db()?;
2994    for (name, value) in &binds {
2995        if let Some(i) = st.parameter_index(name).db()? {
2996            st.raw_bind_parameter(i, value).db()?;
2997        }
2998    }
2999    let mut rows = st.raw_query();
3000    let mut out = Vec::new();
3001    while let Some(r) = rows.next().db()? {
3002        out.push(value_of(value_columns(r).db()?)?.0);
3003    }
3004    Ok(out)
3005}
3006
3007/// A page of the members of a slice of cells in sort-key order (CONTRACT-0.5.1 S2), after
3008/// `after` (exclusive), at most `limit`. The candidates are the sort-key range of the slice's
3009/// leading arguments when there is one (`slices::key_bounds`: O(limit) rows); else those of its
3010/// most selective bound argument, ordered by key (O(members)); else the function's index walked
3011/// from its start. Withdrawn and absent members are left out before the LIMIT counts them.
3012fn slice_page_rows(
3013    p: &Pattern,
3014    c: &Connection,
3015    asof: &str,
3016    after: Option<&[u8]>,
3017    limit: i64,
3018) -> Result<Vec<SliceValue>> {
3019    let bounds = crate::slices::key_bounds(&p.args);
3020    let d = if bounds.is_some() { None } else { drive(p, c, false)?.0 };
3021    let mut sql = if d.is_some() { L::SliceValuesDrive.sql().to_string() } else { L::SliceKeyBase.sql().to_string() };
3022    let mut binds: Vec<(String, SqlValue)> = params(p, asof, d).into_iter().map(|(k, v)| (k.to_string(), v)).collect();
3023    if let Some((lo, hi)) = &bounds {
3024        sql += " AND c.sort_key >= :lo";
3025        binds.push((":lo".to_string(), SqlValue::Blob(lo.clone())));
3026        if let Some(hi) = hi {
3027            sql += " AND c.sort_key < :hi";
3028            binds.push((":hi".to_string(), SqlValue::Blob(hi.clone())));
3029        }
3030    }
3031    if let Some(a) = after {
3032        sql += " AND c.sort_key > :after";
3033        binds.push((":after".to_string(), SqlValue::Blob(a.to_vec())));
3034    }
3035    sql += " ORDER BY c.sort_key LIMIT :limit";
3036    binds.push((":limit".to_string(), SqlValue::Integer(limit)));
3037    let mut st = c.prepare(&sql).db()?;
3038    for (name, value) in &binds {
3039        if let Some(i) = st.parameter_index(name).db()? {
3040            st.raw_bind_parameter(i, value).db()?;
3041        }
3042    }
3043    let mut rows = st.raw_query();
3044    let mut out = Vec::new();
3045    while let Some(r) = rows.next().db()? {
3046        out.push(value_of(value_columns(r).db()?)?.0);
3047    }
3048    Ok(out)
3049}
3050
3051fn values_limited(p: &Pattern, c: &Connection, asof: &str, limit: i64) -> Result<Vec<SliceValue>> {
3052    let (d, _) = drive(p, c, false)?;
3053    let base = if d.is_some() { L::SliceValuesDrive } else { L::SliceValuesAll };
3054    let keys: Vec<&Constraint> = p.args.iter().filter(|a| a.kind != Kind::Value).collect();
3055    let mut order = Vec::with_capacity(keys.len() * 2 + 1);
3056    for i in 0..keys.len() {
3057        let of =
3058            |col: &str| format!("(SELECT x.{col} FROM cell_args x WHERE x.cell_id = c.cell_id AND x.name = :k{i})");
3059        order.push(of("type"));
3060        order.push(of("sort_key"));
3061    }
3062    order.push("c.cell_id".to_string());
3063    let sql = format!("{} ORDER BY {} LIMIT :limit", base.sql(), order.join(", "));
3064    let mut binds: Vec<(String, SqlValue)> = params(p, asof, d).into_iter().map(|(k, v)| (k.to_string(), v)).collect();
3065    for (i, a) in keys.iter().enumerate() {
3066        binds.push((format!(":k{i}"), SqlValue::Text(a.name.clone())));
3067    }
3068    binds.push((":limit".to_string(), SqlValue::Integer(limit)));
3069    let mut st = c.prepare(&sql).db()?;
3070    for (name, value) in &binds {
3071        if let Some(i) = st.parameter_index(name).db()? {
3072            st.raw_bind_parameter(i, value).db()?;
3073        }
3074    }
3075    let mut rows = st.raw_query();
3076    let mut out = Vec::new();
3077    while let Some(r) = rows.next().db()? {
3078        out.push(value_of(value_columns(r).db()?)?.0);
3079    }
3080    Ok(out)
3081}
3082
3083/// Whether a matching cell has a stored version answering from after `asof`: from
3084/// whichever side is smaller (both probed, up to 10,001), the function's receipts with an
3085/// asof after `asof`, or the slice's candidate cells.
3086fn changed_after(p: &Pattern, c: &Connection, asof: &str) -> Result<bool> {
3087    let (d, candidates) = drive(p, c, true)?;
3088    let recent: i64 = c
3089        .prepare_cached(L::ProbeRecent.sql())
3090        .db()?
3091        .query_row(rusqlite::params![p.fn_hash, asof], |r| r.get(0))
3092        .db()?;
3093    let q = if recent <= candidates.unwrap_or(i64::MAX) {
3094        L::ChangedRecent
3095    } else if d.is_some() {
3096        L::ChangedCandDrive
3097    } else {
3098        L::ChangedCandAll
3099    };
3100    let d = if q == L::ChangedCandDrive { d } else { None };
3101    let mut st = c.prepare_cached(q.sql()).db()?;
3102    bind(&mut st, &params(p, asof, d))?;
3103    let mut rows = st.raw_query();
3104    Ok(rows.next().db()?.is_some())
3105}
3106
3107/// A text search's entry hit as its columns: id, kind, name, hash, label, description, args,
3108/// examples, source, signed_by, and the total score (0.5.3).
3109type HitRow = (i64, String, String, Option<String>, String, String, String, String, String, Option<String>, i64);
3110
3111/// The `AND (...)` prefilter of a text search over `fields` (SQL expressions): one clause per
3112/// word the SQL can match exactly (ASCII, no `"`, `\` or control characters: SQLite's LIKE
3113/// folds ASCII only, and JSON text escapes those), with its parameters numbered from ?1.
3114fn like_where_sqlite(words: &Words, fields: &[&str], first: usize) -> (String, Vec<String>) {
3115    let mut sql = String::new();
3116    let mut params = Vec::new();
3117    for i in 0..words.len() {
3118        if let Some(p) = words.pattern(i, sqlite_safe) {
3119            params.push(p);
3120            let n = first + params.len() - 1;
3121            let ors: Vec<String> = fields.iter().map(|f| format!("{f} LIKE ?{n} ESCAPE '!'")).collect();
3122            sql.push_str(&format!(" AND ({})", ors.join(" OR ")));
3123        }
3124    }
3125    (sql, params)
3126}
3127
3128fn sqlite_safe(word: &str) -> bool {
3129    word.is_ascii() && !word.chars().any(|c| c == '"' || c == '\\' || c.is_control())
3130}
3131
3132fn unsupported_vectors() -> Error {
3133    Error::Unsupported("vectors need PostgreSQL with the vector extension; SQLite has none".into())
3134}
3135
3136/// A function test row of `function_tests`, in the column order of `FunctionTestsOf`.
3137fn function_test_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<FunctionTest> {
3138    Ok(FunctionTest {
3139        fn_hash: r.get(0)?,
3140        case: r.get(1)?,
3141        test_json: r.get(2)?,
3142        signed_by: r.get(3)?,
3143        last_run_at: r.get(4)?,
3144        last_result: r.get(5)?,
3145        last_detail: r.get(6)?,
3146        branches_total: r.get(7)?,
3147        branches_covered: r.get(8)?,
3148    })
3149}
3150
3151/// The columns of a catalogue entry with its facets and `extends`, by kind and name.
3152const CATALOG_EXT_SELECT_BY_KIND_NAME: &str =
3153    "SELECT kind, name, hash, label, description, args, examples, source, signed_by, facets, extends, source_name
3154       FROM catalog_entries WHERE kind = ?1 AND name = ?2";
3155
3156/// A catalogue entry with its facets, `extends` and `source_name` from a row with the twelve
3157/// columns of [`CATALOG_EXT_SELECT_BY_KIND_NAME`] (or of any query with those columns in that order).
3158fn ext_from_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<Result<CatalogEntryExt>> {
3159    let entry = entry_from_columns(
3160        &r.get::<_, String>(0)?,
3161        r.get(1)?,
3162        r.get(2)?,
3163        r.get(3)?,
3164        r.get(4)?,
3165        &r.get::<_, String>(5)?,
3166        &r.get::<_, String>(6)?,
3167        &r.get::<_, String>(7)?,
3168        r.get(8)?,
3169    );
3170    let facets: String = r.get(9)?;
3171    let extends: Option<String> = r.get(10)?;
3172    let source_name: Option<String> = r.get(11)?;
3173    Ok(entry.and_then(|entry| entry_ext(entry, &facets, extends, source_name)))
3174}
3175
3176// ---- Listings (0.7.0) --------------------------------------------------------------------------
3177
3178/// The columns of a listing, in the order [`listing_from_sqlite`] reads them.
3179const LISTING_COLUMNS: &str =
3180    "name, host, fn_hash, subjects, descriptor, key_id, label, description, fetched_at, listed_at";
3181
3182fn listing_from_sqlite(r: &rusqlite::Row<'_>) -> Result<Listing> {
3183    let subjects: String = r.get(3).db()?;
3184    Ok(Listing {
3185        name: r.get(0).db()?,
3186        host: r.get(1).db()?,
3187        fn_hash: r.get(2).db()?,
3188        subjects: parse_subjects(&subjects)?,
3189        descriptor: r.get(4).db()?,
3190        key_id: r.get(5).db()?,
3191        label: r.get(6).db()?,
3192        description: r.get(7).db()?,
3193        fetched_at: r.get(8).db()?,
3194        listed_at: r.get(9).db()?,
3195    })
3196}
3197
3198fn select_listing(c: &Connection, name: &str) -> Result<Option<Listing>> {
3199    let sql = format!("SELECT {LISTING_COLUMNS} FROM listings WHERE name = ?1");
3200    let mut st = c.prepare_cached(&sql).db()?;
3201    let mut rows = st.query([name]).db()?;
3202    match rows.next().db()? {
3203        Some(r) => listing_from_sqlite(r).map(Some),
3204        None => Ok(None),
3205    }
3206}
3207
3208fn listed_host_sqlite(r: &rusqlite::Row<'_>) -> Result<ListedHost> {
3209    Ok(ListedHost { host: r.get(0).db()?, last_seen: r.get(1).db()?, unreachable_since: r.get(2).db()? })
3210}
3211
3212fn listed_host_row(c: &Connection, host: &str) -> Result<Option<ListedHost>> {
3213    let mut st =
3214        c.prepare_cached("SELECT host, last_seen, unreachable_since FROM listed_hosts WHERE host = ?1").db()?;
3215    let mut rows = st.query([host]).db()?;
3216    match rows.next().db()? {
3217        Some(r) => listed_host_sqlite(r).map(Some),
3218        None => Ok(None),
3219    }
3220}
3221
3222#[cfg(test)]
3223mod tests {
3224    use super::*;
3225    use crate::slices::cmp_decimal;
3226
3227    #[test]
3228    fn decimal_keys_sort_as_the_numbers() {
3229        let mut numbers: Vec<String> = [
3230            "0", "9", "10", "-1.5", "-1", "-1.25", "-1.11", "-1.1", "-0.1", "-0.099", "0.099", "0.1", "0.109", "0.11",
3231            "1", "1.1", "1.109", "1.11", "9.5", "99.999", "100", "-100", "-10", "-9", "123", "-123", "0.0001",
3232            "-0.0001", "1000000", "-1000000", "12.5", "12.05", "-12.5", "-12.05", "120", "-120", "1.2", "-1.2",
3233        ]
3234        .iter()
3235        .map(|s| s.to_string())
3236        .collect();
3237        numbers.push("9".repeat(128));
3238        numbers.push(format!("-{}", "9".repeat(127)));
3239        numbers.push(format!("1{}", "0".repeat(127)));
3240        numbers.push(format!("-1{}", "0".repeat(126)));
3241        numbers.push(format!("0.{}1", "0".repeat(125)));
3242        numbers.push(format!("-0.{}1", "0".repeat(124)));
3243        numbers.push(format!("{}.{}", "1".repeat(64), "1".repeat(63)));
3244        numbers.push(format!("-{}.{}", "1".repeat(63), "1".repeat(63)));
3245        for a in &numbers {
3246            assert!(a.len() <= 128, "{a}");
3247            for b in &numbers {
3248                assert_eq!(decimal_key(a).cmp(&decimal_key(b)), cmp_decimal(a, b), "{a} vs {b}");
3249            }
3250        }
3251        // Equal numbers, equal keys; the forms.
3252        assert_eq!(decimal_key("0"), "1");
3253        assert_eq!(decimal_key("100"), "25031");
3254        assert_eq!(decimal_key("0.0012"), "249812");
3255        assert_eq!(decimal_key("-1.5"), "049884~");
3256        assert_eq!(decimal_key(&"9".repeat(128)), format!("2628{}", "9".repeat(128)));
3257    }
3258
3259    #[test]
3260    fn result_codes_have_names() {
3261        assert_eq!(result_code_name(5), "SQLITE_BUSY");
3262        assert_eq!(result_code_name(1811), "SQLITE_CONSTRAINT_TRIGGER");
3263        assert_eq!(result_code_name(14), "SQLITE_CANTOPEN");
3264        assert_eq!(result_code_name(10 | (99 << 8)), "SQLITE_IOERR(25354)");
3265    }
3266
3267    #[test]
3268    fn sqlite_urls_name_paths() {
3269        assert_eq!(sqlite_path("sqlite:store.db"), "store.db");
3270        assert_eq!(sqlite_path("sqlite://store.db"), "store.db");
3271        assert_eq!(sqlite_path("sqlite:///var/lib/x.db"), "/var/lib/x.db");
3272        assert_eq!(sqlite_path("/var/lib/x.db"), "/var/lib/x.db");
3273        assert_eq!(sqlite_path("x.db"), "x.db");
3274    }
3275
3276    /// The plan of a statement, one line per step (`EXPLAIN QUERY PLAN`).
3277    fn plan(c: &Connection, sql: &str) -> Vec<String> {
3278        let mut st = c.prepare(&format!("EXPLAIN QUERY PLAN {sql}")).unwrap();
3279        let n = st.parameter_count();
3280        for i in 1..=n {
3281            st.raw_bind_parameter(i, "x").unwrap();
3282        }
3283        let mut rows = st.raw_query();
3284        let mut out = Vec::new();
3285        while let Some(r) = rows.next().unwrap() {
3286            out.push(r.get::<_, String>(3).unwrap());
3287        }
3288        out
3289    }
3290
3291    /// The statements of bounded slices and of the probes look tables up by index only: no
3292    /// step scans a table or a whole index (SQLite's counterpart of the PostgreSQL tests'
3293    /// sequential-scan counters). Planned on the migrated schema with statistics of a
3294    /// loaded store's shape (100,000 cells of one function).
3295    #[test]
3296    fn bounded_slices_use_indexes() {
3297        let c = Connection::open_in_memory().unwrap();
3298        for m in crate::migrate::sqlite::MIGRATIONS {
3299            c.execute_batch(m.sql).unwrap();
3300        }
3301        // Statistics as ANALYZE leaves them for 100,000 cells, 2 arguments each.
3302        c.execute_batch(
3303            "ANALYZE sqlite_schema;
3304             INSERT INTO sqlite_stat1 (tbl, idx, stat) VALUES
3305               ('cells', 'cells_fn_hash', '100000 100000 1'),
3306               ('cells', 'sqlite_autoindex_cells_1', '100000 1'),
3307               ('cell_args', 'cell_args_key', '200000 200000 100000 100000 1 1'),
3308               ('cell_args', 'sqlite_autoindex_cell_args_1', '200000 2 1'),
3309               ('versions', 'sqlite_autoindex_versions_1', '100000 1 1'),
3310               ('versions', 'versions_receipt_hash', '100000 1'),
3311               ('receipts', 'sqlite_autoindex_receipts_1', '100000 1'),
3312               ('receipts', 'receipts_cell_tx', '100000 1 1'),
3313               ('receipts', 'receipts_fn_hash_asof', '100000 100000 1'),
3314               ('receipts', 'receipts_cell_asof', '100000 1 1');
3315             ANALYZE sqlite_schema;",
3316        )
3317        .unwrap();
3318        // A scan of the constraints (json_each) or of a subquery's rows is fine; of a table
3319        // or an index, not.
3320        let scans = |s: &str| s.starts_with("SCAN ") && !s.starts_with("SCAN k") && !s.starts_with("SCAN (subquery");
3321        for q in [
3322            L::SliceMembersDrive,
3323            L::SliceValuesDrive,
3324            L::ChangedCandDrive,
3325            L::ChangedRecent,
3326            L::SliceProbe,
3327            L::ProbeRecent,
3328            L::ProbeCells,
3329            L::VersionsBetween,
3330            L::VersionsBetweenValues,
3331            L::StoredAsof,
3332            L::ComputedAsof,
3333            L::CellDependents,
3334        ] {
3335            let steps = plan(&c, q.sql());
3336            assert!(!steps.iter().any(|s| scans(s)), "{q:?} scans:\n{steps:#?}");
3337        }
3338        // The unbounded ones walk the function's cells by index, and nothing else.
3339        for q in [L::SliceMembersAll, L::SliceValuesAll, L::ChangedCandAll] {
3340            let steps = plan(&c, q.sql());
3341            assert!(
3342                steps.iter().any(|s| s.contains("SEARCH c USING") && s.contains("cells_fn_hash")),
3343                "{q:?}: {steps:#?}"
3344            );
3345            assert!(!steps.iter().any(|s| scans(s)), "{q:?} scans:\n{steps:#?}");
3346        }
3347    }
3348}