Skip to main content

kovlet/store/
sqlite.rs

1//! The reference SQLite store (ADR 0017 §2): Kovlet's bookkeeping tables in a
2//! SQLite file, either its own or the app's.
3//!
4//! - [`SqliteStore::open`]: its own file, with the built-in row store, so an
5//!   app with no database can read rows back (`space.table("todos").all()`).
6//! - [`SqliteStore::shared`]: the app's own connection. The bookkeeping
7//!   tables live next to the app's tables, and the core runs the app's
8//!   `apply` and its own `commit` in **one transaction**.
9//!   [`SqliteStore::shared_batch`] is the same with one `apply` call per
10//!   [`ChangeBatch`] instead of per [`Change`].
11//! - [`SqliteStore::lending`]: for an app whose database type owns its
12//!   connection (and keeps derived state on write). The app lends its
13//!   connection for one transaction at a time, e.g. `|f| db.with_tx(f)`, so
14//!   app rows, derived state and Kovlet's bookkeeping commit together.
15//! - Record mode: inside its own transaction, the app writes its rows and
16//!   calls `space.record(&tx, table, id, fields)`, which queues the write in
17//!   the same transaction (Workplane's pattern).
18
19use std::collections::{BTreeMap, HashMap, HashSet};
20use std::path::Path;
21use std::sync::{Arc, Mutex};
22
23use rusqlite::{params, Connection, OptionalExtension};
24
25use super::builtin::{apply_row_change, ReadStore, Row};
26use super::{
27    Change, ChangeBatch, DataStore, Origin, PendingMutation, RowClocks, RowRef, SpaceState, StateWrite, SyncStore,
28    TransactionalStore, TxView, Upload,
29};
30use crate::error::{Error, Result};
31use crate::protocol::{FileState, JsonMap, Mutation};
32
33/// The bookkeeping schema (ADR 0017 §2), plus `trashed` on the `_deleted` row.
34pub const SCHEMA: &str = "
35CREATE TABLE IF NOT EXISTS kovlet_spaces (space_id TEXT PRIMARY KEY, cursor INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL);
36CREATE TABLE IF NOT EXISTS kovlet_clocks (space_id TEXT, tbl TEXT, id TEXT, field TEXT, hlc TEXT NOT NULL, trashed INTEGER,
37                            PRIMARY KEY (space_id, tbl, id, field)) WITHOUT ROWID;
38CREATE TABLE IF NOT EXISTS kovlet_outbox (space_id TEXT, n INTEGER, mutation_id TEXT NOT NULL UNIQUE, body TEXT NOT NULL,
39                            blob TEXT, held TEXT, PRIMARY KEY (space_id, n));
40CREATE TABLE IF NOT EXISTS kovlet_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
41CREATE TABLE IF NOT EXISTS kovlet_queue (space_id TEXT, n INTEGER, mutation_id TEXT NOT NULL UNIQUE, body TEXT NOT NULL,
42                            PRIMARY KEY (space_id, n));
43";
44
45/// Columns added after [`SCHEMA`] first shipped, added in place to older databases.
46fn migrate(conn: &Connection) -> Result<()> {
47    let has_batch = conn.prepare("SELECT 1 FROM pragma_table_info('kovlet_outbox') WHERE name = 'batch'")?.exists([])?;
48    if !has_batch {
49        // The atomic batch an outbox entry belongs to (BORG-147).
50        conn.execute_batch("ALTER TABLE kovlet_outbox ADD COLUMN batch TEXT")?;
51    }
52    Ok(())
53}
54
55/// The built-in row store's tables (own-file mode only).
56const BUILTIN_SCHEMA: &str = "
57CREATE TABLE IF NOT EXISTS kovlet_rows (space_id TEXT, tbl TEXT, id TEXT, fields TEXT NOT NULL, trashed INTEGER NOT NULL DEFAULT 0,
58                            PRIMARY KEY (space_id, tbl, id)) WITHOUT ROWID;
59CREATE TABLE IF NOT EXISTS kovlet_files (space_id TEXT, id TEXT, state TEXT NOT NULL, PRIMARY KEY (space_id, id)) WITHOUT ROWID;
60";
61
62/// Writes one change into the app's own tables, inside the core's transaction.
63pub type ApplyFn = dyn Fn(&Connection, &ChangeBatch, &Change) -> Result<()> + Send + Sync;
64
65/// Writes a whole batch into the app's own tables, inside the core's transaction.
66pub type ApplyBatchFn = dyn Fn(&Connection, &ChangeBatch) -> Result<()> + Send + Sync;
67
68/// Lends the app's connection for one transaction: begin a transaction, call
69/// `f` with it, commit if `f` returns `Ok`, roll back otherwise, and return
70/// `f`'s result. See [`SqliteStore::lending`].
71pub type LendFn = dyn Fn(&mut dyn FnMut(&Connection) -> Result<()>) -> Result<()> + Send + Sync;
72
73enum Data {
74    /// Own file: rows go to `kovlet_rows` / `kovlet_files`.
75    Builtin { snapshot_files: Mutex<HashMap<String, HashSet<String>>> },
76    /// The app's database: rows go through the app's function, per change.
77    App(Box<ApplyFn>),
78    /// The app's database: rows go through the app's function, per batch.
79    AppBatch(Box<ApplyBatchFn>),
80}
81
82enum Conn {
83    /// A connection Kovlet can lock.
84    Shared(Arc<Mutex<Connection>>),
85    /// The app's connection, lent for one transaction at a time.
86    Lent(Box<LendFn>),
87}
88
89/// See the module docs.
90pub struct SqliteStore {
91    conn: Conn,
92    data: Data,
93}
94
95impl SqliteStore {
96    /// Opens (or creates) a store in its own file, with the built-in row store.
97    pub fn open(path: impl AsRef<Path>) -> Result<SqliteStore> {
98        let conn = Connection::open(path)?;
99        conn.pragma_update(None, "journal_mode", "WAL")?;
100        conn.pragma_update(None, "synchronous", "NORMAL")?;
101        SqliteStore::builtin(conn)
102    }
103
104    /// An in-memory SQLite store with the built-in row store (tests).
105    pub fn in_memory() -> Result<SqliteStore> {
106        SqliteStore::builtin(Connection::open_in_memory()?)
107    }
108
109    fn builtin(conn: Connection) -> Result<SqliteStore> {
110        conn.execute_batch(SCHEMA)?;
111        migrate(&conn)?;
112        conn.execute_batch(BUILTIN_SCHEMA)?;
113        Ok(SqliteStore {
114            conn: Conn::Shared(Arc::new(Mutex::new(conn))),
115            data: Data::Builtin { snapshot_files: Mutex::new(HashMap::new()) },
116        })
117    }
118
119    /// Shares the app's connection: Kovlet's tables go into the app's
120    /// database, and `apply` writes the app's rows in the same transaction as
121    /// Kovlet's bookkeeping.
122    ///
123    /// ```no_run
124    /// # use std::sync::{Arc, Mutex};
125    /// # use kovlet::store::{Change, sqlite::SqliteStore};
126    /// let db = Arc::new(Mutex::new(rusqlite::Connection::open("app.db").unwrap()));
127    /// let store = SqliteStore::shared(db.clone(), |tx, _batch, change| {
128    ///     if let Change::Upsert { id, fields, .. } = change {
129    ///         tx.execute("INSERT INTO items (id, text) VALUES (?1, ?2)
130    ///                     ON CONFLICT(id) DO UPDATE SET text = coalesce(?2, text)",
131    ///                    (id, fields.get("text").and_then(|v| v.as_str())))?;
132    ///     }
133    ///     Ok(())
134    /// }).unwrap();
135    /// ```
136    pub fn shared(
137        conn: Arc<Mutex<Connection>>,
138        apply: impl Fn(&Connection, &ChangeBatch, &Change) -> Result<()> + Send + Sync + 'static,
139    ) -> Result<SqliteStore> {
140        SqliteStore::with(Conn::Shared(conn), Data::App(Box::new(apply)))
141    }
142
143    /// Like [`SqliteStore::shared`], but `apply` gets the whole batch: one
144    /// call per [`ChangeBatch`], inside the transaction that also commits
145    /// Kovlet's bookkeeping. Use it to save a batch in one go, or to finish a
146    /// snapshot when `batch.complete` is set.
147    ///
148    /// ```no_run
149    /// # use std::sync::{Arc, Mutex};
150    /// # use kovlet::store::{Change, sqlite::SqliteStore};
151    /// let db = Arc::new(Mutex::new(rusqlite::Connection::open("app.db").unwrap()));
152    /// let store = SqliteStore::shared_batch(db.clone(), |tx, batch| {
153    ///     for change in &batch.changes {
154    ///         if let (Some("items"), Some(id)) = (change.table(), change.id()) {
155    ///             // write `change` into `items` row `id`
156    ///         }
157    ///     }
158    ///     Ok(())
159    /// }).unwrap();
160    /// ```
161    pub fn shared_batch(
162        conn: Arc<Mutex<Connection>>,
163        apply: impl Fn(&Connection, &ChangeBatch) -> Result<()> + Send + Sync + 'static,
164    ) -> Result<SqliteStore> {
165        SqliteStore::with(Conn::Shared(conn), Data::AppBatch(Box::new(apply)))
166    }
167
168    /// For an app whose database type owns its connection: Kovlet never holds
169    /// the connection, it borrows it for one transaction at a time through
170    /// `lend`. `lend(f)` must begin a transaction on the app's connection, run
171    /// `f` with it, and commit if `f` returns `Ok` (roll back otherwise). Any
172    /// derived state the app keeps on write (indexes, totals, history) then
173    /// commits in the same transaction as the rows and Kovlet's bookkeeping.
174    ///
175    /// `apply` is called once per batch, inside that transaction. Record mode
176    /// works as with [`SqliteStore::shared`]: inside the app's own
177    /// transaction, `space.record(&tx, …)` queues the write in it.
178    ///
179    /// `lend` runs on Kovlet's threads and must not be called re-entrantly:
180    /// don't call `space.write(…)` from inside your own transaction (use
181    /// `space.record` there).
182    ///
183    /// ```no_run
184    /// # use kovlet::sqlite::{rusqlite::Connection, SqliteStore};
185    /// # struct Db; impl Db { fn with_tx<T>(&self, f: impl FnOnce(&Connection) -> kovlet::Result<T>) -> kovlet::Result<T> { unimplemented!() } }
186    /// # let db = std::sync::Arc::new(Db);
187    /// let lender = db.clone();
188    /// let store = SqliteStore::lending(move |f| lender.with_tx(|tx| f(tx)), |tx, batch| {
189    ///     // write `batch.changes` into the app's tables through `tx`
190    ///     Ok(())
191    /// }).unwrap();
192    /// ```
193    pub fn lending(
194        lend: impl Fn(&mut dyn FnMut(&Connection) -> Result<()>) -> Result<()> + Send + Sync + 'static,
195        apply: impl Fn(&Connection, &ChangeBatch) -> Result<()> + Send + Sync + 'static,
196    ) -> Result<SqliteStore> {
197        SqliteStore::with(Conn::Lent(Box::new(lend)), Data::AppBatch(Box::new(apply)))
198    }
199
200    fn with(conn: Conn, data: Data) -> Result<SqliteStore> {
201        let store = SqliteStore { conn, data };
202        store.with_conn(|c| {
203            c.execute_batch(SCHEMA)?;
204            migrate(c)
205        })?;
206        Ok(store)
207    }
208
209    /// The shared connection; `None` for a [`SqliteStore::lending`] store.
210    pub fn connection(&self) -> Option<Arc<Mutex<Connection>>> {
211        match &self.conn {
212            Conn::Shared(c) => Some(c.clone()),
213            Conn::Lent(_) => None,
214        }
215    }
216
217    /// Runs `f` on the connection: under the store's lock, or inside one
218    /// transaction the app lends.
219    fn with_conn<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
220        match &self.conn {
221            Conn::Shared(c) => f(&c.lock().unwrap_or_else(|e| e.into_inner())),
222            Conn::Lent(lend) => {
223                let mut f = Some(f);
224                let mut out = None;
225                lend(&mut |c| {
226                    let f = f.take().ok_or_else(|| Error::config("SqliteStore::lending: lend called f twice"))?;
227                    out = Some(f(c)?);
228                    Ok(())
229                })?;
230                out.ok_or_else(|| Error::config("SqliteStore::lending: lend returned without calling f"))
231            }
232        }
233    }
234
235    fn apply_in(&self, conn: &Connection, batch: &ChangeBatch) -> Result<()> {
236        match &self.data {
237            Data::App(f) => {
238                for c in &batch.changes {
239                    f(conn, batch, c)?;
240                }
241                Ok(())
242            }
243            Data::AppBatch(f) => f(conn, batch),
244            Data::Builtin { snapshot_files } => builtin_apply(conn, batch, snapshot_files),
245        }
246    }
247}
248
249fn builtin_apply(
250    conn: &Connection,
251    batch: &ChangeBatch,
252    snapshot_files: &Mutex<HashMap<String, HashSet<String>>>,
253) -> Result<()> {
254    let space = &batch.space_id;
255    for c in &batch.changes {
256        match c {
257            Change::File { file } => {
258                conn.execute(
259                    "INSERT INTO kovlet_files (space_id, id, state) VALUES (?1, ?2, ?3)
260                     ON CONFLICT(space_id, id) DO UPDATE SET state = excluded.state",
261                    params![space, file.id, serde_json::to_string(file)?],
262                )?;
263            }
264            Change::Schema { table, schema: None } => {
265                conn.execute("DELETE FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2", params![space, table])?;
266            }
267            Change::Schema { .. } => {}
268            Change::Purge { table, id } => {
269                conn.execute(
270                    "DELETE FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
271                    params![space, table, id],
272                )?;
273            }
274            Change::Upsert { table, id, .. } | Change::Delete { table, id } | Change::Restore { table, id } => {
275                let cur = read_row(conn, space, table, id)?;
276                let mut tables: BTreeMap<String, BTreeMap<String, Row>> = BTreeMap::new();
277                if let Some(r) = cur {
278                    tables.entry(table.clone()).or_default().insert(id.clone(), r);
279                }
280                apply_row_change(&mut tables, c);
281                if let Some(r) = tables.get(table).and_then(|t| t.get(id)) {
282                    conn.execute(
283                        "INSERT INTO kovlet_rows (space_id, tbl, id, fields, trashed) VALUES (?1, ?2, ?3, ?4, ?5)
284                         ON CONFLICT(space_id, tbl, id) DO UPDATE SET fields = excluded.fields, trashed = excluded.trashed",
285                        params![space, table, id, serde_json::to_string(&r.fields)?, r.trashed],
286                    )?;
287                }
288            }
289        }
290    }
291    if batch.origin == Origin::Snapshot {
292        let mut snaps = snapshot_files.lock().unwrap();
293        let seen = snaps.entry(space.clone()).or_default();
294        for c in &batch.changes {
295            if let Change::File { file } = c {
296                seen.insert(file.id.clone());
297            }
298        }
299        if batch.complete {
300            let seen = snaps.remove(space).unwrap_or_default();
301            let mut stmt = conn.prepare("SELECT id FROM kovlet_files WHERE space_id = ?1")?;
302            let ids: Vec<String> = stmt.query_map([space], |r| r.get(0))?.collect::<Result<_, _>>()?;
303            for id in ids {
304                if !seen.contains(&id) {
305                    conn.execute("DELETE FROM kovlet_files WHERE space_id = ?1 AND id = ?2", params![space, id])?;
306                }
307            }
308        }
309    }
310    Ok(())
311}
312
313fn read_row(conn: &Connection, space: &str, table: &str, id: &str) -> Result<Option<Row>> {
314    let r: Option<(String, bool)> = conn
315        .query_row(
316            "SELECT fields, trashed FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
317            params![space, table, id],
318            |r| Ok((r.get(0)?, r.get(1)?)),
319        )
320        .optional()?;
321    match r {
322        None => Ok(None),
323        Some((f, trashed)) => {
324            Ok(Some(Row { id: id.to_string(), fields: serde_json::from_str::<JsonMap>(&f)?, trashed }))
325        }
326    }
327}
328
329// ---------------------------------------------------------------- bookkeeping SQL
330
331fn load(conn: &Connection, space: &str) -> Result<SpaceState> {
332    let r: Option<(i64, String)> = conn
333        .query_row("SELECT cursor, state FROM kovlet_spaces WHERE space_id = ?1", [space], |r| {
334            Ok((r.get(0)?, r.get(1)?))
335        })
336        .optional()?;
337    Ok(match r {
338        None => SpaceState::default(),
339        Some((cursor, state)) => SpaceState { cursor, schemas: serde_json::from_str(&state).unwrap_or_default() },
340    })
341}
342
343fn clocks(conn: &Connection, space: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>> {
344    let mut out: BTreeMap<String, RowClocks> = BTreeMap::new();
345    let mut stmt = conn
346        .prepare_cached("SELECT field, hlc, trashed FROM kovlet_clocks WHERE space_id = ?1 AND tbl = ?2 AND id = ?3")?;
347    for id in ids {
348        let rows = stmt.query_map(params![space, table, id], |r| {
349            Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option<bool>>(2)?))
350        })?;
351        for row in rows {
352            let (field, hlc, trashed) = row?;
353            let rc = out.entry(id.clone()).or_default();
354            if field == "_deleted" {
355                rc.deleted = Some(hlc);
356                rc.trashed = trashed;
357            } else {
358                rc.fields.insert(field, hlc);
359            }
360        }
361    }
362    Ok(out)
363}
364
365fn row_ids(conn: &Connection, space: &str) -> Result<Vec<RowRef>> {
366    let mut stmt = conn.prepare("SELECT DISTINCT tbl, id FROM kovlet_clocks WHERE space_id = ?1")?;
367    let v = stmt.query_map([space], |r| Ok(RowRef { table: r.get(0)?, id: r.get(1)? }))?.collect::<Result<_, _>>()?;
368    Ok(v)
369}
370
371fn outbox(conn: &Connection, space: &str, limit: usize) -> Result<Vec<PendingMutation>> {
372    let mut stmt = conn
373        .prepare_cached("SELECT body, blob, held, batch FROM kovlet_outbox WHERE space_id = ?1 ORDER BY n LIMIT ?2")?;
374    let rows = stmt.query_map(params![space, limit.min(i64::MAX as usize) as i64], |r| {
375        Ok((
376            r.get::<_, String>(0)?,
377            r.get::<_, Option<String>>(1)?,
378            r.get::<_, Option<String>>(2)?,
379            r.get::<_, Option<String>>(3)?,
380        ))
381    })?;
382    let mut out = Vec::new();
383    for row in rows {
384        let (body, blob, held, batch) = row?;
385        let mutation: Mutation = serde_json::from_str(&body)?;
386        let upload: Option<Upload> = blob.as_deref().map(serde_json::from_str).transpose()?;
387        out.push(PendingMutation { mutation, upload, held, batch });
388    }
389    Ok(out)
390}
391
392fn commit(conn: &Connection, space: &str, w: &StateWrite) -> Result<()> {
393    for (r, rc) in &w.clocks {
394        conn.execute(
395            "DELETE FROM kovlet_clocks WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
396            params![space, r.table, r.id],
397        )?;
398        let mut ins = conn.prepare_cached(
399            "INSERT INTO kovlet_clocks (space_id, tbl, id, field, hlc, trashed) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
400        )?;
401        for (f, h) in &rc.fields {
402            ins.execute(params![space, r.table, r.id, f, h, Option::<bool>::None])?;
403        }
404        if let Some(d) = &rc.deleted {
405            ins.execute(params![space, r.table, r.id, "_deleted", d, rc.trashed])?;
406        }
407    }
408    for r in &w.purge {
409        conn.execute(
410            "DELETE FROM kovlet_clocks WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
411            params![space, r.table, r.id],
412        )?;
413    }
414    for id in &w.outbox_remove {
415        conn.execute("DELETE FROM kovlet_outbox WHERE space_id = ?1 AND mutation_id = ?2", params![space, id])?;
416    }
417    for p in &w.outbox_update {
418        conn.execute(
419            "UPDATE kovlet_outbox SET body = ?3, blob = ?4, held = ?5, batch = ?6 WHERE space_id = ?1 AND mutation_id = ?2",
420            params![
421                space,
422                p.mutation.mutation_id,
423                serde_json::to_string(&p.mutation)?,
424                p.upload.as_ref().map(serde_json::to_string).transpose()?,
425                p.held,
426                p.batch
427            ],
428        )?;
429    }
430    if !w.outbox_add.is_empty() {
431        let mut n: i64 =
432            conn.query_row("SELECT coalesce(max(n), 0) FROM kovlet_outbox WHERE space_id = ?1", [space], |r| r.get(0))?;
433        for p in &w.outbox_add {
434            n += 1;
435            conn.execute(
436                "INSERT OR IGNORE INTO kovlet_outbox (space_id, n, mutation_id, body, blob, held, batch) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
437                params![
438                    space,
439                    n,
440                    p.mutation.mutation_id,
441                    serde_json::to_string(&p.mutation)?,
442                    p.upload.as_ref().map(serde_json::to_string).transpose()?,
443                    p.held,
444                    p.batch
445                ],
446            )?;
447        }
448    }
449    if w.cursor.is_some() || w.schemas.is_some() {
450        let cur = load(conn, space)?;
451        let cursor = w.cursor.unwrap_or(cur.cursor);
452        let schemas = w.schemas.as_ref().unwrap_or(&cur.schemas);
453        conn.execute(
454            "INSERT INTO kovlet_spaces (space_id, cursor, state) VALUES (?1, ?2, ?3)
455             ON CONFLICT(space_id) DO UPDATE SET cursor = excluded.cursor, state = excluded.state",
456            params![space, cursor, serde_json::to_string(schemas)?],
457        )?;
458    }
459    for (k, v) in &w.meta {
460        meta_set(conn, k, v)?;
461    }
462    Ok(())
463}
464
465fn meta_set(conn: &Connection, key: &str, value: &str) -> Result<()> {
466    conn.execute(
467        "INSERT INTO kovlet_meta (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
468        params![key, value],
469    )?;
470    Ok(())
471}
472
473/// Runs `f` in a transaction on a connection that may already be inside one
474/// (record mode): a savepoint then.
475fn in_tx<T>(conn: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
476    let nested = !conn.is_autocommit();
477    conn.execute_batch(if nested { "SAVEPOINT kovlet" } else { "BEGIN IMMEDIATE" })?;
478    match f(conn) {
479        Ok(v) => {
480            conn.execute_batch(if nested { "RELEASE kovlet" } else { "COMMIT" })?;
481            Ok(v)
482        }
483        Err(e) => {
484            let _ = conn.execute_batch(if nested { "ROLLBACK TO kovlet; RELEASE kovlet" } else { "ROLLBACK" });
485            Err(e)
486        }
487    }
488}
489
490impl SyncStore for SqliteStore {
491    fn load(&self, space_id: &str) -> Result<SpaceState> {
492        self.with_conn(|c| load(c, space_id))
493    }
494    fn clocks(&self, space_id: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>> {
495        self.with_conn(|c| clocks(c, space_id, table, ids))
496    }
497    fn row_ids(&self, space_id: &str) -> Result<Vec<RowRef>> {
498        self.with_conn(|c| row_ids(c, space_id))
499    }
500    fn outbox(&self, space_id: &str, limit: usize) -> Result<Vec<PendingMutation>> {
501        self.with_conn(|c| outbox(c, space_id, limit))
502    }
503    fn commit(&self, space_id: &str, write: &StateWrite) -> Result<()> {
504        self.with_conn(|conn| in_tx(conn, |c| commit(c, space_id, write)))
505    }
506    fn forget_space(&self, space_id: &str) -> Result<()> {
507        self.with_conn(|conn| {
508            in_tx(conn, |c| {
509                for t in ["kovlet_spaces", "kovlet_clocks", "kovlet_outbox", "kovlet_queue"] {
510                    c.execute(&format!("DELETE FROM {t} WHERE space_id = ?1"), [space_id])?;
511                }
512                Ok(())
513            })
514        })?;
515        if let Data::Builtin { snapshot_files } = &self.data {
516            snapshot_files.lock().unwrap().remove(space_id);
517        }
518        Ok(())
519    }
520    fn meta_get(&self, key: &str) -> Result<Option<String>> {
521        self.with_conn(|c| {
522            Ok(c.query_row("SELECT value FROM kovlet_meta WHERE key = ?1", [key], |r| r.get(0)).optional()?)
523        })
524    }
525    fn meta_set(&self, key: &str, value: &str) -> Result<()> {
526        self.with_conn(|c| meta_set(c, key, value))
527    }
528    fn queue_add(&self, space_id: &str, entries: &[Mutation]) -> Result<()> {
529        self.with_conn(|conn| {
530            in_tx(conn, |c| {
531                let mut n: i64 =
532                    c.query_row("SELECT coalesce(max(n), 0) FROM kovlet_queue WHERE space_id = ?1", [space_id], |r| {
533                        r.get(0)
534                    })?;
535                let mut ins = c.prepare_cached(
536                    "INSERT OR IGNORE INTO kovlet_queue (space_id, n, mutation_id, body) VALUES (?1, ?2, ?3, ?4)",
537                )?;
538                for m in entries {
539                    n += 1;
540                    ins.execute(params![space_id, n, m.mutation_id, serde_json::to_string(m)?])?;
541                }
542                Ok(())
543            })
544        })
545    }
546    fn queued(&self, space_id: &str, limit: usize) -> Result<Vec<Mutation>> {
547        self.with_conn(|conn| {
548            let mut stmt =
549                conn.prepare_cached("SELECT body FROM kovlet_queue WHERE space_id = ?1 ORDER BY n LIMIT ?2")?;
550            let rows =
551                stmt.query_map(params![space_id, limit.min(i64::MAX as usize) as i64], |r| r.get::<_, String>(0))?;
552            let mut out = Vec::new();
553            for body in rows {
554                out.push(serde_json::from_str(&body?)?);
555            }
556            Ok(out)
557        })
558    }
559    fn queue_remove(&self, space_id: &str, mutation_ids: &[String]) -> Result<()> {
560        self.with_conn(|conn| {
561            in_tx(conn, |c| {
562                let mut del = c.prepare_cached("DELETE FROM kovlet_queue WHERE space_id = ?1 AND mutation_id = ?2")?;
563                for id in mutation_ids {
564                    del.execute(params![space_id, id])?;
565                }
566                Ok(())
567            })
568        })
569    }
570    fn transactional(&self) -> Option<&dyn TransactionalStore> {
571        Some(self)
572    }
573}
574
575struct View<'a> {
576    store: &'a SqliteStore,
577    conn: &'a Connection,
578}
579
580impl TxView for View<'_> {
581    fn clocks(&self, space_id: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>> {
582        clocks(self.conn, space_id, table, ids)
583    }
584    fn row_ids(&self, space_id: &str) -> Result<Vec<RowRef>> {
585        row_ids(self.conn, space_id)
586    }
587    fn apply(&self, batch: &ChangeBatch) -> Result<()> {
588        self.store.apply_in(self.conn, batch)
589    }
590    fn commit(&self, space_id: &str, write: &StateWrite) -> Result<()> {
591        commit(self.conn, space_id, write)
592    }
593    fn meta_set(&self, key: &str, value: &str) -> Result<()> {
594        meta_set(self.conn, key, value)
595    }
596}
597
598impl TransactionalStore for SqliteStore {
599    fn transaction(&self, f: &mut dyn FnMut(&dyn TxView) -> Result<()>) -> Result<()> {
600        self.with_conn(|conn| in_tx(conn, |c| f(&View { store: self, conn: c })))
601    }
602}
603
604impl SqliteStore {
605    /// Record mode: runs `f` on the given connection (the app's open
606    /// transaction), without taking the store's lock or lending a connection.
607    pub(crate) fn transaction_on(&self, conn: &Connection, f: &mut dyn FnMut(&dyn TxView) -> Result<()>) -> Result<()> {
608        in_tx(conn, |c| f(&View { store: self, conn: c }))
609    }
610}
611
612impl DataStore for SqliteStore {
613    fn apply(&self, batch: &ChangeBatch) -> Result<()> {
614        self.with_conn(|conn| in_tx(conn, |c| self.apply_in(c, batch)))
615    }
616}
617
618impl ReadStore for SqliteStore {
619    fn rows(&self, space_id: &str, table: &str) -> Result<Vec<Row>> {
620        if !matches!(self.data, Data::Builtin { .. }) {
621            return Err(Error::config("a shared SqliteStore has no built-in rows: read the app's own tables"));
622        }
623        self.with_conn(|conn| {
624            let mut stmt = conn.prepare(
625                "SELECT id, fields FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2 AND trashed = 0 ORDER BY id",
626            )?;
627            let rows =
628                stmt.query_map(params![space_id, table], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
629            let mut out = Vec::new();
630            for row in rows {
631                let (id, f) = row?;
632                out.push(Row { id, fields: serde_json::from_str(&f)?, trashed: false });
633            }
634            Ok(out)
635        })
636    }
637
638    fn get(&self, space_id: &str, table: &str, id: &str) -> Result<Option<Row>> {
639        self.with_conn(|c| read_row(c, space_id, table, id))
640    }
641
642    fn files(&self, space_id: &str) -> Result<Vec<FileState>> {
643        self.with_conn(|conn| {
644            let mut stmt = conn.prepare("SELECT state FROM kovlet_files WHERE space_id = ?1 ORDER BY id")?;
645            let rows = stmt.query_map([space_id], |r| r.get::<_, String>(0))?;
646            let mut out = Vec::new();
647            for s in rows {
648                let f: FileState = serde_json::from_str(&s?)?;
649                if !f.deleted {
650                    out.push(f);
651                }
652            }
653            Ok(out)
654        })
655    }
656}