Skip to main content

khive_storage/
sql.rs

1//! SQL access capability traits.
2
3use std::any::Any;
4use std::future::Future;
5use std::pin::Pin;
6
7use async_trait::async_trait;
8
9use crate::types::{PageRequest, SqlRow, SqlStatement, SqlValue, StorageResult};
10use crate::StorageError;
11
12/// A boxed future, borrowing from the `&mut dyn SqlWriter` an
13/// [`AtomicUnitOp`] is called with (see [`SqlAccess::atomic_unit`]).
14pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
15
16/// A caller-supplied unit of work to run as ONE atomic operation via
17/// [`SqlAccess::atomic_unit`] (ADR-067 Component A, Fork C slice 2).
18///
19/// `op` receives a live `&mut dyn SqlWriter` already inside an open write
20/// transaction — it may issue DML and synchronous read assertions (no bare `BEGIN`/`COMMIT`/
21/// `ROLLBACK`; the caller-visible transaction boundary is owned entirely by
22/// `atomic_unit`, exactly like the existing `execute_batch` contract) — and
23/// returns its result type-erased via `Box<dyn Any + Send>` so this trait
24/// method stays object-safe (no method-level generics on a trait used as
25/// `dyn SqlAccess`). Callers downcast the returned box back to their own
26/// concrete outcome type.
27pub type AtomicUnitOp = Box<
28    dyn for<'w> FnOnce(&'w mut dyn SqlWriter) -> BoxFuture<'w, StorageResult<Box<dyn Any + Send>>>
29        + Send,
30>;
31
32/// Closed set of parameter-free maintenance statements executed outside the
33/// writer's per-request transaction wrapper.
34///
35/// Every variant renders a static SQL literal. Commands that require a caller
36/// value, such as a destination path, need a separate parameter-bound primitive;
37/// this set deliberately has no raw SQL variant or string conversion.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum TopLevelMaintenance {
40    /// Reclaim unused database pages with `VACUUM`.
41    Vacuum,
42    /// Checkpoint the write-ahead log and truncate it to zero bytes.
43    WalCheckpointTruncate,
44}
45
46impl TopLevelMaintenance {
47    /// Render the reviewed, parameter-free SQL literal for this operation.
48    pub const fn as_sql(self) -> &'static str {
49        match self {
50            Self::Vacuum => "VACUUM;",
51            Self::WalCheckpointTruncate => "PRAGMA wal_checkpoint(TRUNCATE);",
52        }
53    }
54}
55
56/// Owned state for consuming one SQL result in statement order.
57///
58/// A consumer must do bounded synchronous work and must not reenter SQL or wait
59/// for another operation on the same connection. Only private output should be
60/// accumulated: a failed query does not return the consumer, but cannot undo
61/// external side effects performed by it. Cancellation cannot preempt a blocked
62/// consumer; an interrupt hard-cap timeout may leave the worker owning it until
63/// that worker exits.
64pub trait SqlRowConsumer: Send + 'static {
65    /// Consume one owned row, which may be dropped before the next row is read.
66    fn push_row(&mut self, row: SqlRow) -> StorageResult<()>;
67
68    /// Recover the concrete accumulator after a successful query.
69    /// A failed downcast must be handled as a storage error by the caller.
70    fn into_any(self: Box<Self>) -> Box<dyn Any + Send>;
71}
72
73/// Read-capable SQL connection.
74#[async_trait]
75pub trait SqlReader: Send + 'static {
76    /// Execute `statement` and return the first row, or `None` if the result set is empty.
77    /// Implementations must not convert later matching rows into owned values.
78    /// Implementations may stop stepping the statement early, so statements with
79    /// side effects (e.g. DML with `RETURNING`) must not be issued through this
80    /// method; use [`SqlWriter::execute`] or [`SqlWriter::execute_batch`] for writes.
81    async fn query_row(&mut self, statement: SqlStatement) -> StorageResult<Option<SqlRow>>;
82    /// Execute `statement` and return all rows.
83    ///
84    /// This compatibility primitive has no result-size bound. Callers that do
85    /// not already constrain their SQL should use [`Self::query_page`].
86    async fn query_all(&mut self, statement: SqlStatement) -> StorageResult<Vec<SqlRow>>;
87    /// Consume one read-only statement without collecting all owned rows.
88    ///
89    /// Returns the same owned consumer only after successful completion. Driver,
90    /// consumer and cancellation errors expose no partially accumulated consumer.
91    /// The database engine may still buffer or sort rows for its query plan.
92    /// Transaction-control statements and writes are not accepted through this
93    /// method; an already-open read transaction remains owned by the reader.
94    ///
95    /// Unsupported backends fail explicitly instead of calling `query_all`.
96    /// On cancellation a backend may detach an interrupt-resistant worker after
97    /// its hard cap; that worker keeps its consumer and admission until it exits.
98    async fn query_consume(
99        &mut self,
100        _statement: SqlStatement,
101        _consumer: Box<dyn SqlRowConsumer>,
102    ) -> StorageResult<Box<dyn SqlRowConsumer>> {
103        Err(StorageError::Unsupported {
104            capability: crate::StorageCapability::Sql,
105            operation: "query_consume".into(),
106            message: "this reader does not support row consumption".into(),
107        })
108    }
109
110    /// Execute `statement` and return only the requested offset page.
111    ///
112    /// The default preserves source compatibility for alternate backends by
113    /// slicing [`Self::query_all`]. Backends should override this method when
114    /// they can stop row conversion at `page.limit`; khive-db's SQLite bridge
115    /// does so. On that path, materialization is bounded by the caller-supplied
116    /// `page.limit`, and callers own choosing a sane limit; the database engine
117    /// may still do work for the query plan and offset.
118    ///
119    /// Like [`Self::query_all`], the default has no result-size bound: it
120    /// materializes every matching row before slicing. Callers issuing
121    /// unconstrained SQL must not rely on the default to keep memory
122    /// proportional to `page.limit` — that bound holds only on backends that
123    /// override this method.
124    ///
125    /// Implementations may stop stepping the statement early, so statements with
126    /// side effects (e.g. DML with `RETURNING`) must not be issued through this
127    /// method; use [`SqlWriter::execute`] or [`SqlWriter::execute_batch`] for writes.
128    async fn query_page(
129        &mut self,
130        statement: SqlStatement,
131        page: PageRequest,
132    ) -> StorageResult<Vec<SqlRow>> {
133        let rows = self.query_all(statement).await?;
134        let offset = usize::try_from(page.offset).unwrap_or(usize::MAX);
135        let limit = usize::try_from(page.limit).unwrap_or(usize::MAX);
136        Ok(rows.into_iter().skip(offset).take(limit).collect())
137    }
138    /// Execute `statement` and return the first column of the first row as a scalar.
139    async fn query_scalar(&mut self, statement: SqlStatement) -> StorageResult<Option<SqlValue>>;
140    /// Execute a count statement and return its nonnegative integer scalar as `u64`.
141    ///
142    /// The default passes `statement` unchanged to [`Self::query_scalar`] exactly
143    /// once. It does not parse SQL or verify that the statement uses `COUNT`.
144    /// A negative integer, missing row, NULL, or non-integer scalar returns
145    /// [`StorageError::Internal`]; backend errors pass through unchanged.
146    async fn count(&mut self, statement: SqlStatement) -> StorageResult<u64> {
147        match self.query_scalar(statement).await? {
148            Some(SqlValue::Integer(value)) if value >= 0 => Ok(value as u64),
149            _ => Err(StorageError::Internal(
150                "SQL count expected a nonnegative integer scalar".into(),
151            )),
152        }
153    }
154    /// Run `EXPLAIN QUERY PLAN` for `statement` and return the plan rows.
155    async fn explain(&mut self, statement: SqlStatement) -> StorageResult<Vec<SqlRow>>;
156}
157
158/// Write-capable SQL connection (extends `SqlReader`).
159#[async_trait]
160pub trait SqlWriter: SqlReader + Send + 'static {
161    /// Execute a single DML statement and return the number of rows affected.
162    ///
163    /// Transaction-control rejection is an `execute_batch` contract; this
164    /// primitive remains available to internal transaction owners such as
165    /// `atomic_unit` for their `BEGIN`/`COMMIT`/`ROLLBACK` calls.
166    async fn execute(&mut self, statement: SqlStatement) -> StorageResult<u64>;
167    /// Execute multiple DML statements and return the total rows affected.
168    async fn execute_batch(&mut self, statements: Vec<SqlStatement>) -> StorageResult<u64>;
169    /// Execute a raw SQL script (no parameters; used for migrations).
170    ///
171    /// This script boundary is internal/migration-only and deliberately does
172    /// not inherit `execute_batch`'s transaction-control rejection.
173    async fn execute_script(&mut self, script: String) -> StorageResult<()>;
174
175    /// Execute one closed-set maintenance operation that MUST run outside any
176    /// open transaction (ADR-067 Component A, Fork C slice 2). `VACUUM`, for
177    /// example, is rejected by SQLite inside `BEGIN`/`COMMIT`.
178    ///
179    /// Default implementation delegates to [`Self::execute_script`]: every
180    /// writer implementation in this codebase except khive-db's
181    /// write-queue-routed `SqliteWriter` already runs `execute_script`
182    /// transaction-free (a plain connection call, or already inside a
183    /// caller-managed transaction where a top-level statement would be
184    /// invalid regardless of which method is called). `SqliteWriter`
185    /// overrides this to route around its writer task's per-request `BEGIN
186    /// IMMEDIATE` specifically for this call, while still serializing
187    /// through the single writer owner.
188    ///
189    /// SQL is rendered only from [`TopLevelMaintenance`]'s static literals;
190    /// this API does not accept caller-supplied or formatted SQL. It is an
191    /// internal maintenance boundary, not an `execute_batch` transaction-control
192    /// guard. The separate migration-only [`Self::execute_script`] is unchanged.
193    ///
194    /// ```no_run
195    /// use khive_storage::{SqlWriter, StorageResult, TopLevelMaintenance};
196    ///
197    /// async fn maintain(writer: &mut dyn SqlWriter) -> StorageResult<()> {
198    ///     writer.execute_script_top_level(TopLevelMaintenance::Vacuum).await?;
199    ///     writer.execute_script_top_level(TopLevelMaintenance::WalCheckpointTruncate).await
200    /// }
201    /// ```
202    ///
203    /// A runtime string cannot cross this boundary, even if its current contents
204    /// happen to be a supported maintenance statement:
205    ///
206    /// ```compile_fail,E0308
207    /// use khive_storage::{SqlWriter, StorageResult};
208    ///
209    /// async fn reject_script(writer: &mut dyn SqlWriter, script: String) -> StorageResult<()> {
210    ///     writer.execute_script_top_level(script).await
211    /// }
212    /// ```
213    async fn execute_script_top_level(
214        &mut self,
215        maintenance: TopLevelMaintenance,
216    ) -> StorageResult<()> {
217        self.execute_script(maintenance.as_sql().to_owned()).await
218    }
219}
220
221/// Base SQL access capability.
222#[async_trait]
223pub trait SqlAccess: Send + Sync + 'static {
224    /// Canonical filesystem identity for this SQL database, when file-backed.
225    ///
226    /// Cross-resource operations use this only to derive advisory coordination
227    /// files outside SQLite. Only genuinely pathless, process-private
228    /// implementations may return `None`; every file-backed implementation
229    /// must expose its canonical path so cross-process exclusion cannot
230    /// silently degrade. The method performs no I/O.
231    fn database_path(&self) -> Option<std::path::PathBuf> {
232        None
233    }
234
235    /// Acquire a read-only connection from the pool.
236    async fn reader(&self) -> StorageResult<Box<dyn SqlReader>>;
237    /// Acquire a read-write connection from the pool.
238    async fn writer(&self) -> StorageResult<Box<dyn SqlWriter>>;
239
240    /// Run `op` as ONE atomic unit of work (ADR-067 Component A, Fork C
241    /// slice 2).
242    ///
243    /// Where a single-writer task is active (file-backed pool,
244    /// `KHIVE_WRITE_QUEUE=1`), `op` runs inside that task's one write
245    /// transaction for this request — no separate connection is opened, so
246    /// this call cannot compete with the writer task for SQLite's write
247    /// lock. For an in-memory pool, one pool connection guard is retained
248    /// throughout the transaction. Where no writer task applies to a
249    /// file-backed pool, `op` runs under a manual
250    /// `BEGIN IMMEDIATE`/`COMMIT`/`ROLLBACK` on a writer handle exactly like
251    /// calling [`Self::writer`] and driving the statements by hand — the
252    /// pre-ADR-067 behavior, preserved byte-for-byte on this path.
253    ///
254    /// **The atomic-unit suspend-free invariant (normative for every
255    /// caller):** `op`'s future must complete on its **first poll** — it may
256    /// issue only synchronous DML against the `&mut dyn SqlWriter` it is
257    /// handed and must never reach a real suspension point (no embedding
258    /// computation, no ANN warming, no service or channel `await`, no
259    /// network round-trip). Synchronous external work is forbidden too: no
260    /// filesystem/process/network I/O, sleeps, blocking waits, or unbounded CPU
261    /// may run between the transaction owner's `BEGIN IMMEDIATE` and
262    /// `COMMIT`. First-poll enforcement alone cannot detect those operations;
263    /// ADR-091's write-transaction audit table is the review-time guard, and a
264    /// new owner or caller must update that table before merge. On the
265    /// single-writer and in-memory paths this is enforced at runtime: the backend drives
266    /// `op` through a single-poll driver and
267    /// returns a typed error the instant the future is `Pending`, so a
268    /// violation fails loudly rather than corrupting state. On the file-backed
269    /// flag-off path (no writer task active) a suspending `op` would currently
270    /// *succeed* — that path drives `op` as an ordinary `.await` under a
271    /// manual transaction — so the invariant is a correctness contract this
272    /// trait asks every caller to uphold, not something the type system or
273    /// every code path enforces. Callers must not rely on the flag-off
274    /// path's tolerance; behavior must be identical (synchronous DML only)
275    /// regardless of whether the single-writer flag is on.
276    async fn atomic_unit(&self, op: AtomicUnitOp) -> StorageResult<Box<dyn Any + Send>>;
277}