Skip to main content

datumesh_store/
pg.rs

1//! `PgStore`: the store on PostgreSQL.
2
3use std::borrow::Cow;
4
5use crate::error::{Db, Error, Result};
6use crate::pg_unstable::Connector;
7use crate::pool::{Conn, Pool, PoolOptions, Pooled};
8use crate::slices::{check_entry, cmp_keys, is_hash, is_instant, version_slice, Constraint, Kind, Pattern};
9use crate::sql::Q;
10use crate::{not_canonical_class, Binding, ClassBinding, Namespace, SliceMember, SliceValue, Store, Version};
11use datumesh_core::lexical::{check_dns_name, check_function_name, check_hex, check_instant};
12use datumesh_core::{
13    json, keys_from_response, sha256_hex, verify, Cell, ClassDescriptor, ErrorCode, FunctionDescriptor, Keys, Manifest,
14    Receipt, Resolver, Scalar, Slice, Type,
15};
16
17/// The store on PostgreSQL, with a connection pool. `Send + Sync`: share one per process
18/// (behind an `Arc`); each call checks a connection out for its duration.
19///
20/// Every `put_*` is one transaction. [`Store`] methods return errors: a malformed argument
21/// is [`Error::Invalid`] (no query is made), a database failure [`Error::Database`]. The
22/// [`Resolver`] methods answer both with `None`; a database failure is logged with
23/// `tracing` (target `datumesh_store`, level `error`).
24pub struct PgStore {
25    pool: Pool,
26}
27
28impl std::fmt::Debug for PgStore {
29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30        f.debug_struct("PgStore").finish_non_exhaustive()
31    }
32}
33
34impl PgStore {
35    /// Connects to a `postgres://` URL or `key=value` connection string with the default
36    /// [`PoolOptions`]: [`connect_with(url, PoolOptions::new())`](Self::connect_with).
37    pub fn connect(url: &str) -> Result<PgStore> {
38        PgStore::connect_with(url, PoolOptions::new())
39    }
40
41    /// Connects to a `postgres://` URL or `key=value` connection string, with a pool and TLS
42    /// roots as `options` say. One connection is opened at once, so a wrong URL, an
43    /// unreachable server or a refused certificate fails here; nothing else is done on it
44    /// (no statement is prepared, the schema is not looked at), so an empty database is fine
45    /// (create the schema with [`migrate::apply`](crate::migrate::apply)).
46    ///
47    /// TLS (rustls) is used as the URL's `sslmode` says: `disable` never, `prefer` (the
48    /// default) when the server offers it, `require` always. Whenever it is used, the
49    /// server's certificate and host name are verified, against the Mozilla roots plus the
50    /// roots added with [`PoolOptions::tls_root_certificates_pem`]; there is no way to
51    /// accept any certificate. So a server with `ssl=on` and a self-signed certificate (or
52    /// one from a private CA) fails even under the default `prefer`: add its CA, or connect
53    /// with `sslmode=disable`.
54    pub fn connect_with(url: &str, options: PoolOptions) -> Result<PgStore> {
55        let config = url.parse::<postgres::Config>().db()?;
56        let connector = Connector::new(config, &options)?;
57        PgStore::from_pool(Pool::new(Box::new(move || connector.connect()), options))
58    }
59
60    /// A store on `pool`, after opening one connection.
61    pub(crate) fn from_pool(pool: Pool) -> Result<PgStore> {
62        let store = PgStore { pool };
63        drop(store.pool.get()?);
64        Ok(store)
65    }
66
67    /// A pooled connection, held until dropped (migrations hold one throughout).
68    pub(crate) fn conn(&self) -> Result<Pooled<'_>> {
69        self.pool.get()
70    }
71
72    /// Prepares every SQL statement the store uses against the live schema, on a fresh
73    /// connection's behalf (no cached statement is reused), and returns how many there are.
74    /// Fails with the first statement the schema cannot serve.
75    pub fn check_statements(&self) -> Result<usize> {
76        let mut c = self.pool.get()?;
77        for q in Q::ALL {
78            c.client.prepare_typed(q.sql(), q.types()).db()?;
79        }
80        Ok(Q::ALL.len())
81    }
82
83    /// A [`Resolver`] lookup: a failure (logged by `run`) becomes `None`.
84    fn resolve<T>(&self, op: &'static str, f: impl FnOnce(&mut Conn) -> Result<Option<T>>) -> Option<T> {
85        self.run(op, f).ok().flatten()
86    }
87
88    /// Runs `f` on a pooled connection; a database or pool failure is logged.
89    fn run<T>(&self, op: &'static str, f: impl FnOnce(&mut Conn) -> Result<T>) -> Result<T> {
90        let result = self.pool.get().and_then(|mut c| f(&mut c));
91        if let Err(e @ (Error::Database(_) | Error::PoolTimeout)) = &result {
92            tracing::error!(target: "datumesh_store", op, error = %e, "database failure");
93        }
94        result
95    }
96
97    /// Versions from rows of (tx, receipt_hash, asof).
98    fn version_rows(rows: &[postgres::Row], cell_id: &str) -> Result<Vec<Version>> {
99        rows.iter().map(|r| version_row(r, cell_id)).collect()
100    }
101
102    /// A version (and its receipt's bytes) from a query answering
103    /// (tx, receipt_hash, asof, bytes) for (cell_id, asof).
104    fn asof_with_receipt(
105        &self,
106        op: &'static str,
107        q: Q,
108        cell_id: &str,
109        asof: &str,
110    ) -> Result<Option<(Version, Vec<u8>)>> {
111        check_hex(cell_id, 64, "cell_id")?;
112        check_instant(asof, "asof")?;
113        self.run(op, |c| {
114            let st = c.stmt(q)?;
115            let Some(row) = c.client.query_opt(&st, &[&cell_id, &asof]).db()? else { return Ok(None) };
116            Ok(Some((version_row(&row, cell_id)?, row.try_get(3).db()?)))
117        })
118    }
119
120    /// A version from a query answering (tx, receipt_hash, asof) for (cell_id, asof).
121    fn asof_version(&self, op: &'static str, q: Q, cell_id: &str, asof: &str) -> Result<Option<Version>> {
122        check_hex(cell_id, 64, "cell_id")?;
123        check_instant(asof, "asof")?;
124        self.run(op, |c| {
125            let st = c.stmt(q)?;
126            let rows = c.client.query(&st, &[&cell_id, &asof]).db()?;
127            Ok(PgStore::version_rows(&rows, cell_id)?.pop())
128        })
129    }
130}
131
132fn version_row(r: &postgres::Row, cell_id: &str) -> Result<Version> {
133    Ok(Version {
134        cell_id: cell_id.to_string(),
135        tx: r.try_get(0).db()?,
136        receipt_hash: r.try_get(1).db()?,
137        asof: r.try_get(2).db()?,
138    })
139}
140
141/// A member from a row of (tx, receipt_hash, asof, bytes, ...).
142fn member_row(r: &postgres::Row, cell_id: &str) -> Result<SliceMember> {
143    Ok(SliceMember { version: version_row(r, cell_id)?, receipt: r.try_get(3).db()? })
144}
145
146/// A cell's arguments from the "name:type:value" items of the typed-argument index
147/// (`cell_args` holds every argument's type and lexical form).
148fn cell_args(items: Vec<String>) -> Result<datumesh_core::Args> {
149    let bad =
150        |what: &str| Error::Invalid(datumesh_core::Error::new(ErrorCode::CanonType, "$", format!("a stored {what}")));
151    let mut args = datumesh_core::Args::new();
152    for a in items {
153        let mut parts = a.splitn(3, ':');
154        let (Some(name), Some(t), Some(v)) = (parts.next(), parts.next(), parts.next()) else {
155            return Err(bad("argument"));
156        };
157        let ty = Type::from_name(t).ok_or_else(|| bad("type"))?;
158        args.insert(name.to_string(), datumesh_core::Arg::Value(Scalar::from_lexical(ty, v)?));
159    }
160    Ok(args)
161}
162
163/// A member's value and cell from a row of (tx, receipt_hash, asof, value_type, value, ns,
164/// fn, fn_hash, "name:type:value" of each argument, ...): the cell is rebuilt from the
165/// typed-argument index.
166fn value_row(r: &postgres::Row, cell_id: &str) -> Result<SliceValue> {
167    let bad =
168        |what: &str| Error::Invalid(datumesh_core::Error::new(ErrorCode::CanonType, "$", format!("a stored {what}")));
169    let (ty, value): (String, String) = (r.try_get(3).db()?, r.try_get(4).db()?);
170    let ty = Type::from_name(&ty).ok_or_else(|| bad("type"))?;
171    let args = cell_args(r.try_get::<_, Vec<String>>(8).db()?)?;
172    let cell = Cell { args, fn_hash: r.try_get(7).db()?, fn_name: r.try_get(6).db()?, ns: r.try_get(5).db()? };
173    Ok(SliceValue { version: version_row(r, cell_id)?, value: Scalar::from_lexical(ty, &value)?, cell })
174}
175
176/// A cell from a row of (ns, fn, fn_hash, "name:type:value" of each argument).
177fn cell_row(r: &postgres::Row) -> Result<Cell> {
178    Ok(Cell {
179        args: cell_args(r.try_get::<_, Vec<String>>(3).db()?)?,
180        fn_hash: r.try_get(2).db()?,
181        fn_name: r.try_get(1).db()?,
182        ns: r.try_get(0).db()?,
183    })
184}
185
186fn get_bytes(c: &mut Conn, q: Q, key: &str) -> Result<Option<Vec<u8>>> {
187    let st = c.stmt(q)?;
188    let row = c.client.query_opt(&st, &[&key]).db()?;
189    Ok(match row {
190        Some(r) => Some(r.try_get(0).db()?),
191        None => None,
192    })
193}
194
195fn get_strings(c: &mut Conn, q: Q, key: &str) -> Result<Vec<String>> {
196    let st = c.stmt(q)?;
197    let rows = c.client.query(&st, &[&key]).db()?;
198    rows.iter().map(|r| r.try_get(0).db()).collect()
199}
200
201impl Resolver for PgStore {
202    fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
203        if !is_hash(fn_hash) {
204            return None;
205        }
206        self.resolve("descriptor", |c| get_bytes(c, Q::DescriptorGet, fn_hash)).map(Cow::Owned)
207    }
208
209    fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
210        if !is_hash(hash) {
211            return None;
212        }
213        self.resolve("receipt", |c| get_bytes(c, Q::ReceiptGet, hash)).map(Cow::Owned)
214    }
215
216    /// The stored manifest of slice entry `entry` ([`Store::put_manifest`]), its canonical
217    /// form; `None` when there is none, or `entry` is not an entry (since 0.3.1).
218    fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
219        if check_entry(entry, "$").is_err() {
220            return None;
221        }
222        self.resolve("manifest", |c| get_bytes(c, Q::ManifestGet, entry)).map(Cow::Owned)
223    }
224
225    /// `Some` only for a `stored` function (descriptor `code.lang` is `stored`, and the store
226    /// has the descriptor): the value of the receipt of the version that answers as of
227    /// `asof`, [`stored_asof`](Store::stored_asof)'s: the latest version (by tx) with `tx <=
228    /// asof` whose receipt's asof is also `<= asof` (the core's testkit
229    /// `AnswerRule::TxAndAsof`). `None` for every other function, and when no version
230    /// answers. (Until 0.2.0 it looked at `tx` only, as [`version_asof`](Store::version_asof)
231    /// still does; the same when every receipt's asof is its tx.)
232    fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
233        if !is_instant(asof) {
234            return None;
235        }
236        self.resolve("evaluate", |c| {
237            let Some(desc) = get_bytes(c, Q::DescriptorGet, &cell.fn_hash)? else { return Ok(None) };
238            match FunctionDescriptor::from_json(&desc) {
239                Ok(d) if d.lang == "stored" => {}
240                Ok(_) => return Ok(None),
241                Err(e) => {
242                    tracing::error!(target: "datumesh_store", fn_hash = %cell.fn_hash, error = %e, "stored descriptor does not parse");
243                    return Ok(None);
244                }
245            }
246            let st = c.stmt(Q::ValueAsof)?;
247            let Some(row) = c.client.query_opt(&st, &[&cell.id(), &asof]).db()? else { return Ok(None) };
248            let bytes: Vec<u8> = row.try_get(0).db()?;
249            match Receipt::from_json(&bytes) {
250                Ok(r) => Ok(Some(r.value().clone())),
251                Err(e) => {
252                    tracing::error!(target: "datumesh_store", cell_id = %cell.id(), error = %e, "stored receipt does not parse");
253                    Ok(None)
254                }
255            }
256        })
257    }
258}
259
260/// The host of a fully qualified function name (`host/name`): what precedes the last `/`.
261fn name_host(fn_name: &str) -> &str {
262    fn_name.rsplit_once('/').map_or("", |(h, _)| h)
263}
264
265/// The namespace in `row`, whose columns from `at` are keydoc, validated_at, suspended_at,
266/// consecutive_failures, last_checked_at.
267fn namespace_row(host: &str, row: &postgres::Row, at: usize) -> Result<Namespace> {
268    let failures: i32 = row.try_get(at + 3).db()?;
269    Ok(Namespace {
270        host: host.to_string(),
271        keydoc: row.try_get(at).db()?,
272        validated_at: row.try_get(at + 1).db()?,
273        suspended_at: row.try_get(at + 2).db()?,
274        consecutive_failures: u32::try_from(failures).unwrap_or(0),
275        last_checked_at: row.try_get(at + 4).db()?,
276    })
277}
278
279impl PgStore {
280    /// A failed check (`threshold` is `Some`) or a successful one (`None`) at `checked_at`.
281    fn record_check(
282        &self,
283        op: &'static str,
284        host: &str,
285        checked_at: &str,
286        threshold: Option<u32>,
287    ) -> Result<Option<Namespace>> {
288        check_dns_name(host, "host")?;
289        check_instant(checked_at, "checked_at")?;
290        let out = self.run(op, |c| {
291            let lock = c.stmt(Q::Lock)?;
292            let get = c.stmt(Q::NamespaceGet)?;
293            let put = c.stmt(Q::NamespaceCheck)?;
294            let mut t = c.client.transaction().db()?;
295            t.execute(&lock, &[&"namespaces", &host]).db()?;
296            let Some(row) = t.query_opt(&get, &[&host]).db()? else { return Ok(None) };
297            let mut ns = namespace_row(host, &row, 0)?;
298            if let Some(at) = &ns.last_checked_at {
299                if checked_at < at.as_str() {
300                    return Err(Error::NotLater {
301                        what: "namespace",
302                        key: host.to_string(),
303                        given: checked_at.to_string(),
304                        latest: at.clone(),
305                    });
306                }
307            }
308            crate::apply_check(&mut ns, checked_at, threshold);
309            let failures = i32::try_from(ns.consecutive_failures).unwrap_or(i32::MAX);
310            t.execute(&put, &[&host, &failures, &checked_at, &ns.suspended_at]).db()?;
311            t.commit().db()?;
312            Ok(Some(ns))
313        })?;
314        tracing::debug!(target: "datumesh_store", host, checked_at, ok = threshold.is_none(), "namespace check");
315        Ok(out)
316    }
317}
318
319impl Store for PgStore {
320    fn put_descriptor(&self, bytes: &[u8]) -> Result<String> {
321        // spec-0.4.0's descriptor: `signature.order` and argument `extent` allowed.
322        let d = FunctionDescriptor::from_json(bytes)?;
323        let hash = d.hash();
324        let canonical = d.canonical();
325        self.run("put_descriptor", |c| {
326            let st = c.stmt(Q::DescriptorPut)?;
327            c.client.execute(&st, &[&hash, &canonical]).db()?;
328            Ok(())
329        })?;
330        tracing::debug!(target: "datumesh_store", fn_hash = %hash, "put_descriptor");
331        Ok(hash)
332    }
333
334    fn put_receipt(&self, bytes: &[u8]) -> Result<String> {
335        // Steps 1-4 first: a receipt that is not one is refused without a query.
336        let r = Receipt::from_json(bytes)?;
337        // Steps 1-4 passed, so the text parses; its JCS is the canonical form.
338        let canonical = json::parse(bytes)?.to_jcs();
339        let hash = r.hash().to_string();
340        let cell_id = r.cell().id();
341        let host = r.signer_host().to_string();
342        // Receipt hashes are edges; slice entries (spec-0.4.0) slice edges.
343        let (entries, inputs): (Vec<String>, Vec<String>) =
344            r.inputs().iter().cloned().partition(|e| e.starts_with("slice:"));
345        self.run("put_receipt", |c| {
346            let ns = c.stmt(Q::NamespaceGet)?;
347            let put = c.stmt(Q::ReceiptPut)?;
348            let get = c.stmt(Q::ReceiptGet)?;
349            let edges = c.stmt(Q::EdgesPut)?;
350            let slice_edges = c.stmt(Q::SliceEdgesPut)?;
351            let mut t = c.client.transaction().db()?;
352            // Idempotent: the very receipt already stored verified when it was stored, and
353            // the stored copy is unchanged, so it is not checked again (even if its key has
354            // since been revoked).
355            if let Some(row) = t.query_opt(&get, &[&hash]).db()? {
356                let stored: Vec<u8> = row.try_get(0).db()?;
357                if stored == canonical {
358                    return Ok(());
359                }
360            }
361            // Steps 5-6 against the stored key document of the signer host; none stored is
362            // a host without keys (E_KEY_UNAVAILABLE).
363            let mut keys = Keys::new();
364            if let Some(row) = t.query_opt(&ns, &[&host]).db()? {
365                // No new writes under a suspended namespace.
366                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
367                    return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
368                }
369                let doc: Vec<u8> = row.try_get(0).db()?;
370                keys.insert_response(&host, 200, Some(&doc));
371            }
372            let out = verify(bytes, &keys, None, None);
373            if !out.ok {
374                return Err(Error::Invalid(out.error().unwrap_or_else(|| {
375                    datumesh_core::Error::new(ErrorCode::Signature, "$", "the receipt did not verify")
376                })));
377            }
378            let n = t
379                .execute(&put, &[&hash, &canonical, &cell_id, &r.tx(), &r.asof(), &r.cell().fn_hash, &r.publisher()])
380                .db()?;
381            if n == 0 {
382                let row = t.query_one(&get, &[&hash]).db()?;
383                let stored: Vec<u8> = row.try_get(0).db()?;
384                if stored != canonical {
385                    return Err(Error::Conflict { hash: hash.clone() });
386                }
387            }
388            if !inputs.is_empty() {
389                t.execute(&edges, &[&hash, &inputs]).db()?;
390            }
391            if !entries.is_empty() {
392                t.execute(&slice_edges, &[&hash, &entries]).db()?;
393            }
394            t.commit().db()?;
395            Ok(())
396        })?;
397        tracing::debug!(target: "datumesh_store", hash = %hash, cell_id = %cell_id, "put_receipt");
398        Ok(hash)
399    }
400
401    fn put_blob(&self, bytes: &[u8]) -> Result<String> {
402        let sha = sha256_hex(bytes);
403        let length = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
404        self.run("put_blob", |c| {
405            let st = c.stmt(Q::BlobPut)?;
406            c.client.execute(&st, &[&sha, &bytes, &length]).db()?;
407            Ok(())
408        })?;
409        tracing::debug!(target: "datumesh_store", sha256 = %sha, length, "put_blob");
410        Ok(sha)
411    }
412
413    fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>> {
414        check_hex(sha256, 64, "sha256")?;
415        Ok(self.run("blob", |c| get_bytes(c, Q::BlobGet, sha256))?.map(Cow::Owned))
416    }
417
418    fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
419        check_hex(cell_id, 64, "cell_id")?;
420        check_instant(tx, "tx")?;
421        check_hex(receipt_hash, 64, "receipt_hash")?;
422        self.run("put_version", |c| {
423            let lock = c.stmt(Q::Lock)?;
424            let meta = c.stmt(Q::ReceiptMeta)?;
425            let get = c.stmt(Q::ReceiptGet)?;
426            let ns = c.stmt(Q::NamespaceGet)?;
427            let latest = c.stmt(Q::VersionLatestTx)?;
428            let put = c.stmt(Q::VersionPut)?;
429            let mut t = c.client.transaction().db()?;
430            t.execute(&lock, &[&"versions", &cell_id]).db()?;
431            let Some(row) = t.query_opt(&meta, &[&receipt_hash]).db()? else {
432                return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
433            };
434            // No new versions of a receipt signed by a suspended namespace.
435            let stored: Vec<u8> = t.query_one(&get, &[&receipt_hash]).db()?.try_get(0).db()?;
436            let signer = Receipt::from_json(&stored)?.signer_host().to_string();
437            if let Some(row) = t.query_opt(&ns, &[&signer]).db()? {
438                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
439                    return Err(Error::NamespaceSuspended { host: signer, suspended_at: since });
440                }
441            }
442            let (r_cell, r_tx): (String, String) = (row.try_get(0).db()?, row.try_get(1).db()?);
443            if r_cell != cell_id {
444                return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
445            }
446            if r_tx != tx {
447                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
448            }
449            if let Some(row) = t.query_opt(&latest, &[&cell_id]).db()? {
450                let l: String = row.try_get(0).db()?;
451                if tx <= l.as_str() {
452                    return Err(Error::NotLater {
453                        what: "version",
454                        key: cell_id.to_string(),
455                        given: tx.to_string(),
456                        latest: l,
457                    });
458                }
459            }
460            t.execute(&put, &[&cell_id, &tx, &receipt_hash]).db()?;
461            t.commit().db()?;
462            Ok(())
463        })?;
464        tracing::debug!(target: "datumesh_store", cell_id, tx, receipt_hash, "put_version");
465        Ok(())
466    }
467
468    fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
469        self.asof_version("version_asof", Q::VersionAsof, cell_id, asof)
470    }
471
472    fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>> {
473        check_hex(cell_id, 64, "cell_id")?;
474        check_instant(from, "from")?;
475        check_instant(to, "to")?;
476        self.run("versions", |c| {
477            let st = c.stmt(Q::VersionRange)?;
478            let rows = c.client.query(&st, &[&cell_id, &from, &to]).db()?;
479            PgStore::version_rows(&rows, cell_id)
480        })
481    }
482
483    fn latest(&self, cell_id: &str) -> Result<Option<Version>> {
484        check_hex(cell_id, 64, "cell_id")?;
485        self.run("latest", |c| {
486            let st = c.stmt(Q::VersionLatest)?;
487            let rows = c.client.query(&st, &[&cell_id]).db()?;
488            Ok(PgStore::version_rows(&rows, cell_id)?.pop())
489        })
490    }
491
492    fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>> {
493        check_hex(receipt_hash, 64, "receipt_hash")?;
494        self.run("dependents", |c| get_strings(c, Q::Dependents, receipt_hash))
495    }
496
497    fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>> {
498        check_hex(receipt_hash, 64, "receipt_hash")?;
499        self.run("inputs", |c| get_strings(c, Q::Inputs, receipt_hash))
500    }
501
502    fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()> {
503        // SPEC 9.3: a 200 with this body, for this host (a DNS name equal to the document's).
504        keys_from_response(host, 200, Some(keydoc_bytes))?;
505        check_instant(validated_at, "validated_at")?;
506        let canonical = json::parse(keydoc_bytes)?.to_jcs();
507        self.run("put_namespace", |c| {
508            let lock = c.stmt(Q::Lock)?;
509            let get = c.stmt(Q::NamespaceGet)?;
510            let put = c.stmt(Q::NamespacePut)?;
511            let mut t = c.client.transaction().db()?;
512            t.execute(&lock, &[&"namespaces", &host]).db()?;
513            if let Some(row) = t.query_opt(&get, &[&host]).db()? {
514                let at: String = row.try_get(1).db()?;
515                if validated_at < at.as_str() {
516                    return Err(Error::NotLater {
517                        what: "namespace",
518                        key: host.to_string(),
519                        given: validated_at.to_string(),
520                        latest: at,
521                    });
522                }
523            }
524            t.execute(&put, &[&host, &canonical, &validated_at]).db()?;
525            t.commit().db()?;
526            Ok(())
527        })?;
528        tracing::debug!(target: "datumesh_store", host, validated_at, "put_namespace");
529        Ok(())
530    }
531
532    fn namespace(&self, host: &str) -> Result<Option<Namespace>> {
533        check_dns_name(host, "host")?;
534        self.run("namespace", |c| {
535            let st = c.stmt(Q::NamespaceGet)?;
536            let Some(row) = c.client.query_opt(&st, &[&host]).db()? else { return Ok(None) };
537            Ok(Some(namespace_row(host, &row, 0)?))
538        })
539    }
540
541    fn namespaces(&self) -> Result<Vec<Namespace>> {
542        self.run("namespaces", |c| {
543            let st = c.stmt(Q::NamespaceList)?;
544            let mut out = Vec::new();
545            for row in c.client.query(&st, &[]).db()? {
546                let host: String = row.try_get(0).db()?;
547                out.push(namespace_row(&host, &row, 1)?);
548            }
549            Ok(out)
550        })
551    }
552
553    fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>> {
554        self.record_check("record_namespace_failure", host, checked_at, Some(threshold))
555    }
556
557    fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>> {
558        self.record_check("record_namespace_success", host, checked_at, None)
559    }
560
561    fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()> {
562        check_function_name(fn_name, "fn_name")?;
563        check_hex(fn_hash, 64, "fn_hash")?;
564        check_instant(tx, "tx")?;
565        self.run("bind_name", |c| {
566            let lock = c.stmt(Q::Lock)?;
567            let exists = c.stmt(Q::DescriptorExists)?;
568            let ns = c.stmt(Q::NamespaceGet)?;
569            let latest = c.stmt(Q::NameLatest)?;
570            let put = c.stmt(Q::NamePut)?;
571            let class_bound = c.stmt(Q::ClassNameBound)?;
572            let mut t = c.client.transaction().db()?;
573            t.execute(&lock, &[&"names", &fn_name]).db()?;
574            // No new bindings under a suspended namespace.
575            if let Some(row) = t.query_opt(&ns, &[&name_host(fn_name)]).db()? {
576                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
577                    return Err(Error::NamespaceSuspended {
578                        host: name_host(fn_name).to_string(),
579                        suspended_at: since,
580                    });
581                }
582            }
583            // One namespace of names: a class name is not a function name.
584            let class: bool = t.query_one(&class_bound, &[&fn_name]).db()?.try_get(0).db()?;
585            if class {
586                return Err(Error::NameTaken { name: fn_name.to_string(), bound_as: "class" });
587            }
588            let found: bool = t.query_one(&exists, &[&fn_hash]).db()?.try_get(0).db()?;
589            if !found {
590                return Err(Error::NotFound { what: "descriptor", key: fn_hash.to_string() });
591            }
592            if let Some(row) = t.query_opt(&latest, &[&fn_name]).db()? {
593                let l: String = row.try_get(0).db()?;
594                if tx <= l.as_str() {
595                    return Err(Error::NotLater {
596                        what: "name",
597                        key: fn_name.to_string(),
598                        given: tx.to_string(),
599                        latest: l,
600                    });
601                }
602            }
603            t.execute(&put, &[&fn_name, &tx, &fn_hash]).db()?;
604            t.commit().db()?;
605            Ok(())
606        })?;
607        tracing::debug!(target: "datumesh_store", fn_name, fn_hash, tx, "bind_name");
608        Ok(())
609    }
610
611    fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
612        check_hex(cell_id, 64, "cell_id")?;
613        check_instant(tx, "tx")?;
614        check_hex(receipt_hash, 64, "receipt_hash")?;
615        // No lock: the primary key serialises writers of one (cell_id, tx, asof). An insert
616        // that meets a concurrent one waits for it; if it committed, nothing is inserted and
617        // the row it wrote (visible to the next statement under READ COMMITTED) decides.
618        let asof = self.run("put_computed", |c| {
619            let meta = c.stmt(Q::ReceiptMeta)?;
620            let put = c.stmt(Q::ComputedPut)?;
621            let get = c.stmt(Q::ComputedGet)?;
622            let mut t = c.client.transaction().db()?;
623            let Some(row) = t.query_opt(&meta, &[&receipt_hash]).db()? else {
624                return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
625            };
626            let (r_cell, r_tx, asof): (String, String, String) =
627                (row.try_get(0).db()?, row.try_get(1).db()?, row.try_get(2).db()?);
628            if r_cell != cell_id {
629                return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
630            }
631            if r_tx != tx {
632                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
633            }
634            if t.execute(&put, &[&cell_id, &tx, &asof, &receipt_hash]).db()? == 0 {
635                let stored: String = t.query_one(&get, &[&cell_id, &tx, &asof]).db()?.try_get(0).db()?;
636                if stored != receipt_hash {
637                    return Err(Error::Conflict { hash: receipt_hash.to_string() });
638                }
639            }
640            t.commit().db()?;
641            Ok(asof)
642        })?;
643        tracing::debug!(target: "datumesh_store", cell_id, tx, asof, receipt_hash, "put_computed");
644        Ok(())
645    }
646
647    fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
648        self.asof_version("computed_asof", Q::ComputedAsof, cell_id, asof)
649    }
650
651    fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
652        self.asof_version("stored_asof", Q::StoredAsof, cell_id, asof)
653    }
654
655    fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>> {
656        check_hex(cell_id, 64, "cell_id")?;
657        self.run("cell_dependents", |c| get_strings(c, Q::CellDependents, cell_id))
658    }
659
660    /// One query: the version and its receipt's bytes.
661    fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
662        Ok(self
663            .asof_with_receipt("computed_asof_with_receipt", Q::ComputedAsofReceipt, cell_id, asof)?
664            .map(|(v, b)| (v, Cow::Owned(b))))
665    }
666
667    /// One query: the version and its receipt's bytes.
668    fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
669        Ok(self
670            .asof_with_receipt("stored_asof_with_receipt", Q::StoredAsofReceipt, cell_id, asof)?
671            .map(|(v, b)| (v, Cow::Owned(b))))
672    }
673
674    fn put_manifest(&self, bytes: &[u8]) -> Result<String> {
675        let m = Manifest::from_json(bytes)?;
676        let entry = m.entry();
677        let canonical = m.canonical();
678        let members = m.members();
679        let n = i32::try_from(members.len()).unwrap_or(i32::MAX);
680        self.run("put_manifest", |c| {
681            let put = c.stmt(Q::ManifestPut)?;
682            let put_members = c.stmt(Q::ManifestMembersPut)?;
683            let mut t = c.client.transaction().db()?;
684            // The entry hashes the content: a stored entry has these very bytes. A concurrent
685            // insert of it waits for the other; if that one committed, nothing is inserted
686            // here, members included (it inserted them).
687            let inserted = t
688                .execute(&put, &[&entry, &m.slice().id(), &m.members_hash(), &m.slice().fn_hash(), &n, &canonical])
689                .db()?;
690            if inserted == 1 && !members.is_empty() {
691                t.execute(&put_members, &[&entry, &members]).db()?;
692            }
693            t.commit().db()?;
694            Ok(())
695        })?;
696        tracing::debug!(target: "datumesh_store", entry = %entry, members = n, "put_manifest");
697        Ok(entry)
698    }
699
700    fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>> {
701        check_hex(receipt_hash, 64, "receipt_hash")?;
702        self.run("member_manifests", |c| get_strings(c, Q::MemberManifests, receipt_hash))
703    }
704
705    fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>> {
706        check_hex(receipt_hash, 64, "receipt_hash")?;
707        self.run("slice_entries", |c| get_strings(c, Q::SliceEntries, receipt_hash))
708    }
709
710    fn slice_dependents(&self, entry: &str) -> Result<Vec<String>> {
711        check_entry(entry, "entry")?;
712        self.run("slice_dependents", |c| get_strings(c, Q::SliceDependents, entry))
713    }
714
715    fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>> {
716        check_instant(asof, "asof")?;
717        let v = slice.to_value();
718        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
719            return self.versions_between(&cell_id, &from, &to, asof);
720        }
721        let pattern = Pattern::of(&v)?;
722        self.run("slice_members", |c| pattern.members(c, asof))
723    }
724
725    fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>> {
726        check_hex(cell_id, 64, "cell_id")?;
727        check_instant(from, "from")?;
728        check_instant(to, "to")?;
729        check_instant(asof, "asof")?;
730        self.run("versions_between", |c| {
731            let st = c.stmt(Q::VersionsBetween)?;
732            let rows = c.client.query(&st, &[&cell_id, &from, &to, &asof]).db()?;
733            rows.iter().map(|r| member_row(r, cell_id)).collect()
734        })
735    }
736
737    fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>> {
738        check_instant(asof, "asof")?;
739        let v = slice.to_value();
740        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
741            return self.run("slice_values", |c| {
742                let st = c.stmt(Q::VersionsBetweenValues)?;
743                let rows = c.client.query(&st, &[&cell_id, &from, &to, &asof]).db()?;
744                rows.iter().map(|r| value_row(r, &cell_id)).collect()
745            });
746        }
747        let pattern = Pattern::of(&v)?;
748        self.run("slice_values", |c| pattern.values(c, asof))
749    }
750
751    fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool> {
752        check_instant(asof, "asof")?;
753        let v = slice.to_value();
754        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
755            return self.run("slice_changed_after", |c| {
756                let st = c.stmt(Q::VersionsChangedAfter)?;
757                c.client.query_one(&st, &[&cell_id, &from, &to, &asof]).db()?.try_get(0).db()
758            });
759        }
760        let pattern = Pattern::of(&v)?;
761        self.run("slice_changed_after", |c| pattern.changed_after(c, asof))
762    }
763
764    fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>> {
765        check_instant(asof, "asof")?;
766        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
767        let pattern = Pattern::of(&slice.to_value())?;
768        self.run("computed_cells", |c| pattern.computed_cells(c, asof, limit))
769    }
770
771    fn has_bindings_under(&self, namespace: &str) -> Result<bool> {
772        let prefix = format!("{namespace}/");
773        self.run("has_bindings_under", |c| {
774            let st = c.stmt(Q::HasBindingsUnder)?;
775            c.client.query_one(&st, &[&prefix]).db()?.try_get(0).db()
776        })
777    }
778
779    fn put_class(&self, bytes: &[u8]) -> Result<String> {
780        // The core checks the descriptor (strict JSON, then 16.1); the bytes must be its
781        // canonical form, since the class hash is the hash of the bytes stored.
782        let d = ClassDescriptor::from_json(bytes)?;
783        let canonical = d.canonical();
784        if canonical != bytes {
785            return Err(not_canonical_class());
786        }
787        let hash = d.hash();
788        let host = d.steward.namespace.clone();
789        self.run("put_class", |c| {
790            // No new writes under a suspended namespace: the steward's (16.2).
791            let ns = c.stmt(Q::NamespaceGet)?;
792            if let Some(row) = c.client.query_opt(&ns, &[&host]).db()? {
793                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
794                    return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
795                }
796            }
797            let put = c.stmt(Q::ClassPut)?;
798            c.client.execute(&put, &[&hash, &canonical]).db()?;
799            Ok(())
800        })?;
801        tracing::debug!(target: "datumesh_store", class_hash = %hash, "put_class");
802        Ok(hash)
803    }
804
805    fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>> {
806        check_hex(class_hash, 64, "class_hash")?;
807        self.run("class", |c| get_bytes(c, Q::ClassGet, class_hash))
808    }
809
810    fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()> {
811        check_function_name(class_name, "class_name")?;
812        check_hex(class_hash, 64, "class_hash")?;
813        check_instant(tx, "tx")?;
814        self.run("bind_class", |c| {
815            let lock = c.stmt(Q::Lock)?;
816            let ns = c.stmt(Q::NamespaceGet)?;
817            let get = c.stmt(Q::ClassGet)?;
818            let exists = c.stmt(Q::DescriptorExists)?;
819            let name_bound = c.stmt(Q::NameBound)?;
820            let class_bound = c.stmt(Q::ClassNameBound)?;
821            let class_latest = c.stmt(Q::ClassBindingLatest)?;
822            let latest = c.stmt(Q::NameLatest)?;
823            let class_put = c.stmt(Q::ClassBindingPut)?;
824            let name_put = c.stmt(Q::NamePut)?;
825            let mut t = c.client.transaction().db()?;
826            // Every name this binding makes is locked before it is read: the class name, then
827            // its method names (the flattened descriptor's, in JCS order).
828            t.execute(&lock, &[&"names", &class_name]).db()?;
829            // No new bindings under a suspended namespace: the host of the class name.
830            let host = name_host(class_name);
831            if let Some(row) = t.query_opt(&ns, &[&host]).db()? {
832                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
833                    return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
834                }
835            }
836            let Some(row) = t.query_opt(&get, &[&class_hash]).db()? else {
837                return Err(Error::NotFound { what: "class", key: class_hash.to_string() });
838            };
839            let flat = ClassDescriptor::from_json(&row.try_get::<_, Vec<u8>>(0).db()?)?;
840            let methods: Vec<(String, String)> = flat.methods.into_iter().collect();
841            let method_names: Vec<String> = methods.iter().map(|(m, _)| format!("{class_name}/{m}")).collect();
842            for name in &method_names {
843                t.execute(&lock, &[&"names", &name.as_str()]).db()?;
844            }
845            // Every method's function descriptor is stored.
846            for (_, h) in &methods {
847                let found: bool = t.query_one(&exists, &[h]).db()?.try_get(0).db()?;
848                if !found {
849                    return Err(Error::NotFound { what: "descriptor", key: h.clone() });
850                }
851            }
852            // One namespace of names: the class name is not a function name, and no method
853            // name is a class name.
854            let function: bool = t.query_one(&name_bound, &[&class_name]).db()?.try_get(0).db()?;
855            if function {
856                return Err(Error::NameTaken { name: class_name.to_string(), bound_as: "function" });
857            }
858            for name in &method_names {
859                let class: bool = t.query_one(&class_bound, &[&name.as_str()]).db()?.try_get(0).db()?;
860                if class {
861                    return Err(Error::NameTaken { name: name.clone(), bound_as: "class" });
862                }
863            }
864            // Later than the latest binding of the class name and of each method name.
865            if let Some(row) = t.query_opt(&class_latest, &[&class_name]).db()? {
866                let l: String = row.try_get(0).db()?;
867                if tx <= l.as_str() {
868                    return Err(Error::NotLater {
869                        what: "name",
870                        key: class_name.to_string(),
871                        given: tx.to_string(),
872                        latest: l,
873                    });
874                }
875            }
876            for name in &method_names {
877                if let Some(row) = t.query_opt(&latest, &[&name.as_str()]).db()? {
878                    let l: String = row.try_get(0).db()?;
879                    if tx <= l.as_str() {
880                        return Err(Error::NotLater {
881                            what: "name",
882                            key: name.clone(),
883                            given: tx.to_string(),
884                            latest: l,
885                        });
886                    }
887                }
888            }
889            t.execute(&class_put, &[&class_name, &tx, &class_hash]).db()?;
890            for ((_, h), name) in methods.iter().zip(&method_names) {
891                t.execute(&name_put, &[&name.as_str(), &tx, &h.as_str()]).db()?;
892            }
893            t.commit().db()?;
894            Ok(())
895        })?;
896        tracing::debug!(target: "datumesh_store", class_name, class_hash, tx, "bind_class");
897        Ok(())
898    }
899
900    fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>> {
901        Ok(self.resolve_class_binding(class_name, asof)?.map(|b| b.class_hash))
902    }
903
904    fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>> {
905        check_function_name(class_name, "class_name")?;
906        check_instant(asof, "asof")?;
907        self.run("resolve_class_binding", |c| {
908            let st = c.stmt(Q::ClassBindingAsof)?;
909            let Some(row) = c.client.query_opt(&st, &[&class_name, &asof]).db()? else { return Ok(None) };
910            Ok(Some(ClassBinding { class_hash: row.try_get(0).db()?, tx: row.try_get(1).db()? }))
911        })
912    }
913
914    fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>> {
915        check_function_name(fn_name, "fn_name")?;
916        check_instant(asof, "asof")?;
917        self.run("resolve_binding", |c| {
918            let st = c.stmt(Q::BindingAsof)?;
919            let Some(row) = c.client.query_opt(&st, &[&fn_name, &asof]).db()? else { return Ok(None) };
920            Ok(Some(Binding { fn_hash: row.try_get(0).db()?, tx: row.try_get(1).db()? }))
921        })
922    }
923
924    fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>> {
925        check_function_name(fn_name, "fn_name")?;
926        check_instant(asof, "asof")?;
927        self.run("resolve_name", |c| {
928            let st = c.stmt(Q::NameAsof)?;
929            let row = c.client.query_opt(&st, &[&fn_name, &asof]).db()?;
930            Ok(match row {
931                Some(r) => Some(r.try_get(0).db()?),
932                None => None,
933            })
934        })
935    }
936}
937
938impl Pattern {
939    /// The members as of `asof`, in key order.
940    fn members(&self, c: &mut Conn, asof: &str) -> Result<Vec<SliceMember>> {
941        let qs = [Q::SliceMembersAll, Q::SliceMembersText, Q::SliceMembersNum];
942        self.rows(c, asof, qs, 4, member_row, |m| &m.version.cell_id)
943    }
944
945    /// The members' values as of `asof`, in key order.
946    fn values(&self, c: &mut Conn, asof: &str) -> Result<Vec<SliceValue>> {
947        let qs = [Q::SliceValuesAll, Q::SliceValuesText, Q::SliceValuesNum];
948        self.rows(c, asof, qs, 9, value_row, |m| &m.version.cell_id)
949    }
950
951    /// The cells with a computed version answering as of `asof`, in cell id order, at most
952    /// `limit` (`computed_cells`); the candidates narrowed as the member queries narrow them.
953    fn computed_cells(&self, c: &mut Conn, asof: &str, limit: i64) -> Result<Vec<Cell>> {
954        let (drive, _) = self.drive(c, false)?;
955        let [names, kinds, types, los, his] = self.columns();
956        let keys: Vec<String> = self.args.iter().filter(|a| a.kind != Kind::Value).map(|a| a.name.clone()).collect();
957        let nargs = i32::try_from(self.args.len()).unwrap_or(i32::MAX);
958        let (q, d_name, d_ty, d_lo, d_hi) = match drive {
959            None => (Q::ComputedCellsAll, "", "", "", ""),
960            Some(a) => {
961                let q = if a.ty == "number" { Q::ComputedCellsNum } else { Q::ComputedCellsText };
962                (q, a.name.as_str(), a.ty.as_str(), a.lo.as_str(), a.hi.as_str())
963            }
964        };
965        let st = c.stmt(q)?;
966        let rows = c
967            .client
968            .query(
969                &st,
970                &[
971                    &self.fn_hash,
972                    &self.ns,
973                    &self.fn_name,
974                    &nargs,
975                    &asof,
976                    &names,
977                    &kinds,
978                    &types,
979                    &los,
980                    &his,
981                    &keys,
982                    &d_name,
983                    &d_ty,
984                    &d_lo,
985                    &d_hi,
986                    &limit,
987                ],
988            )
989            .db()?;
990        rows.iter().map(cell_row).collect()
991    }
992
993    /// The constraint columns of the member and change queries ($6-$10).
994    fn columns(&self) -> [Vec<String>; 5] {
995        let col = |f: fn(&Constraint) -> &str| -> Vec<String> { self.args.iter().map(|a| f(a).to_string()).collect() };
996        [
997            col(|a| a.name.as_str()),
998            col(|a| a.kind.as_str()),
999            col(|a| a.ty.as_str()),
1000            col(|a| a.lo.as_str()),
1001            col(|a| a.hi.as_str()),
1002        ]
1003    }
1004
1005    /// Whether a matching cell has a stored version answering from after `asof`: from
1006    /// whichever side is smaller (both probed, up to 10,001), the function's receipts with an
1007    /// asof after `asof` (then each one's cell checked against the slice), or the slice's
1008    /// candidate cells (then each one's receipts by cell and asof).
1009    fn changed_after(&self, c: &mut Conn, asof: &str) -> Result<bool> {
1010        let (drive, candidates) = self.drive(c, true)?;
1011        let st = c.stmt(Q::ProbeRecent)?;
1012        let recent: i64 = c.client.query_one(&st, &[&self.fn_hash, &asof]).db()?.try_get(0).db()?;
1013        let qs = if recent <= candidates.unwrap_or(i64::MAX) {
1014            [Q::ChangedRecent; 3]
1015        } else {
1016            [Q::ChangedCandAll, Q::ChangedCandText, Q::ChangedCandNum]
1017        };
1018        let rows = self.query(c, asof, qs, drive)?;
1019        match rows.first() {
1020            Some(r) => r.try_get(0).db(),
1021            None => Ok(false),
1022        }
1023    }
1024
1025    /// The bound or ranged argument holding the fewest cells (probed, up to 10,001, when
1026    /// there are several, or when `count` asks), else none (every cell of the function); and
1027    /// the number of candidates when probed.
1028    fn drive(&self, c: &mut Conn, count: bool) -> Result<(Option<&Constraint>, Option<i64>)> {
1029        let mut probe = |a: Option<&Constraint>| -> Result<i64> {
1030            match a {
1031                None => {
1032                    let st = c.stmt(Q::ProbeCells)?;
1033                    c.client.query_one(&st, &[&self.fn_hash]).db()?.try_get(0).db()
1034                }
1035                Some(a) => {
1036                    let st = c.stmt(if a.ty == "number" { Q::SliceProbeNum } else { Q::SliceProbeText })?;
1037                    c.client.query_one(&st, &[&self.fn_hash, &a.name, &a.ty, &a.lo, &a.hi]).db()?.try_get(0).db()
1038                }
1039            }
1040        };
1041        let constrained: Vec<&Constraint> = self.args.iter().filter(|a| a.kind != Kind::Open).collect();
1042        Ok(match constrained.as_slice() {
1043            [] => (None, if count { Some(probe(None)?) } else { None }),
1044            [one] => (Some(*one), if count { Some(probe(Some(one))?) } else { None }),
1045            several => {
1046                let mut best: Option<(i64, &Constraint)> = None;
1047                for a in several {
1048                    let n = probe(Some(a))?;
1049                    if best.is_none_or(|(m, _)| n < m) {
1050                        best = Some((n, a));
1051                    }
1052                }
1053                (best.map(|(_, a)| a), best.map(|(n, _)| n))
1054            }
1055        })
1056    }
1057
1058    /// Runs one of a family of slice queries `qs` (all cells, a text range, a number range)
1059    /// with the slice's parameters and the candidates narrowed by `drive`.
1060    fn query(&self, c: &mut Conn, asof: &str, qs: [Q; 3], drive: Option<&Constraint>) -> Result<Vec<postgres::Row>> {
1061        let [names, kinds, types, los, his] = self.columns();
1062        let keys: Vec<String> = self.args.iter().filter(|a| a.kind != Kind::Value).map(|a| a.name.clone()).collect();
1063        let nargs = i32::try_from(self.args.len()).unwrap_or(i32::MAX);
1064        let (q, d_name, d_ty, d_lo, d_hi) = match drive {
1065            None => (qs[0], "", "", "", ""),
1066            Some(a) => {
1067                let q = if a.ty == "number" { qs[2] } else { qs[1] };
1068                (q, a.name.as_str(), a.ty.as_str(), a.lo.as_str(), a.hi.as_str())
1069            }
1070        };
1071        let st = c.stmt(q)?;
1072        c.client
1073            .query(
1074                &st,
1075                &[
1076                    &self.fn_hash,
1077                    &self.ns,
1078                    &self.fn_name,
1079                    &nargs,
1080                    &asof,
1081                    &names,
1082                    &kinds,
1083                    &types,
1084                    &los,
1085                    &his,
1086                    &keys,
1087                    &d_name,
1088                    &d_ty,
1089                    &d_lo,
1090                    &d_hi,
1091                ],
1092            )
1093            .db()
1094    }
1095
1096    /// The rows of one of the member queries `qs` (all cells, a text range, a number range),
1097    /// each made into a `T` (the cell id in column `at`, the key after it), in key order.
1098    fn rows<T>(
1099        &self,
1100        c: &mut Conn,
1101        asof: &str,
1102        qs: [Q; 3],
1103        at: usize,
1104        make: impl Fn(&postgres::Row, &str) -> Result<T>,
1105        cell_of: impl Fn(&T) -> &String,
1106    ) -> Result<Vec<T>> {
1107        let (drive, _) = self.drive(c, false)?;
1108        let rows = self.query(c, asof, qs, drive)?;
1109        let mut out: Vec<(Vec<String>, T)> = Vec::with_capacity(rows.len());
1110        for r in &rows {
1111            let cell_id: String = r.try_get(at).db()?;
1112            let key: Vec<String> = r.try_get(at + 1).db()?;
1113            out.push((key, make(r, &cell_id)?));
1114        }
1115        out.sort_by(|(a, ma), (b, mb)| cmp_keys(a, b).then_with(|| cell_of(ma).cmp(cell_of(mb))));
1116        Ok(out.into_iter().map(|(_, m)| m).collect())
1117    }
1118}