kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
//! The reference SQLite store (ADR 0017 §2): Kovlet's bookkeeping tables in a
//! SQLite file, either its own or the app's.
//!
//! - [`SqliteStore::open`]: its own file, with the built-in row store, so an
//!   app with no database can read rows back (`space.table("todos").all()`).
//! - [`SqliteStore::shared`]: the app's own connection. The bookkeeping
//!   tables live next to the app's tables, and the core runs the app's
//!   `apply` and its own `commit` in **one transaction**.
//!   [`SqliteStore::shared_batch`] is the same with one `apply` call per
//!   [`ChangeBatch`] instead of per [`Change`].
//! - [`SqliteStore::lending`]: for an app whose database type owns its
//!   connection (and keeps derived state on write). The app lends its
//!   connection for one transaction at a time, e.g. `|f| db.with_tx(f)`, so
//!   app rows, derived state and Kovlet's bookkeeping commit together.
//! - Record mode: inside its own transaction, the app writes its rows and
//!   calls `space.record(&tx, table, id, fields)`, which queues the write in
//!   the same transaction (Workplane's pattern).

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, Mutex};

use rusqlite::{params, Connection, OptionalExtension};

use super::builtin::{apply_row_change, ReadStore, Row};
use super::{
    Change, ChangeBatch, DataStore, Origin, PendingMutation, RowClocks, RowRef, SpaceState, StateWrite, SyncStore,
    TransactionalStore, TxView, Upload,
};
use crate::error::{Error, Result};
use crate::protocol::{FileState, JsonMap, Mutation};

/// The bookkeeping schema (ADR 0017 §2), plus `trashed` on the `_deleted` row.
pub const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS kovlet_spaces (space_id TEXT PRIMARY KEY, cursor INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS kovlet_clocks (space_id TEXT, tbl TEXT, id TEXT, field TEXT, hlc TEXT NOT NULL, trashed INTEGER,
                            PRIMARY KEY (space_id, tbl, id, field)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS kovlet_outbox (space_id TEXT, n INTEGER, mutation_id TEXT NOT NULL UNIQUE, body TEXT NOT NULL,
                            blob TEXT, held TEXT, PRIMARY KEY (space_id, n));
CREATE TABLE IF NOT EXISTS kovlet_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS kovlet_queue (space_id TEXT, n INTEGER, mutation_id TEXT NOT NULL UNIQUE, body TEXT NOT NULL,
                            PRIMARY KEY (space_id, n));
";

/// Columns added after [`SCHEMA`] first shipped, added in place to older databases.
fn migrate(conn: &Connection) -> Result<()> {
    let has_batch = conn.prepare("SELECT 1 FROM pragma_table_info('kovlet_outbox') WHERE name = 'batch'")?.exists([])?;
    if !has_batch {
        // The atomic batch an outbox entry belongs to (BORG-147).
        conn.execute_batch("ALTER TABLE kovlet_outbox ADD COLUMN batch TEXT")?;
    }
    Ok(())
}

/// The built-in row store's tables (own-file mode only).
const BUILTIN_SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS kovlet_rows (space_id TEXT, tbl TEXT, id TEXT, fields TEXT NOT NULL, trashed INTEGER NOT NULL DEFAULT 0,
                            PRIMARY KEY (space_id, tbl, id)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS kovlet_files (space_id TEXT, id TEXT, state TEXT NOT NULL, PRIMARY KEY (space_id, id)) WITHOUT ROWID;
";

/// Writes one change into the app's own tables, inside the core's transaction.
pub type ApplyFn = dyn Fn(&Connection, &ChangeBatch, &Change) -> Result<()> + Send + Sync;

/// Writes a whole batch into the app's own tables, inside the core's transaction.
pub type ApplyBatchFn = dyn Fn(&Connection, &ChangeBatch) -> Result<()> + Send + Sync;

/// Lends the app's connection for one transaction: begin a transaction, call
/// `f` with it, commit if `f` returns `Ok`, roll back otherwise, and return
/// `f`'s result. See [`SqliteStore::lending`].
pub type LendFn = dyn Fn(&mut dyn FnMut(&Connection) -> Result<()>) -> Result<()> + Send + Sync;

enum Data {
    /// Own file: rows go to `kovlet_rows` / `kovlet_files`.
    Builtin { snapshot_files: Mutex<HashMap<String, HashSet<String>>> },
    /// The app's database: rows go through the app's function, per change.
    App(Box<ApplyFn>),
    /// The app's database: rows go through the app's function, per batch.
    AppBatch(Box<ApplyBatchFn>),
}

enum Conn {
    /// A connection Kovlet can lock.
    Shared(Arc<Mutex<Connection>>),
    /// The app's connection, lent for one transaction at a time.
    Lent(Box<LendFn>),
}

/// See the module docs.
pub struct SqliteStore {
    conn: Conn,
    data: Data,
}

impl SqliteStore {
    /// Opens (or creates) a store in its own file, with the built-in row store.
    pub fn open(path: impl AsRef<Path>) -> Result<SqliteStore> {
        let conn = Connection::open(path)?;
        conn.pragma_update(None, "journal_mode", "WAL")?;
        conn.pragma_update(None, "synchronous", "NORMAL")?;
        SqliteStore::builtin(conn)
    }

    /// An in-memory SQLite store with the built-in row store (tests).
    pub fn in_memory() -> Result<SqliteStore> {
        SqliteStore::builtin(Connection::open_in_memory()?)
    }

    fn builtin(conn: Connection) -> Result<SqliteStore> {
        conn.execute_batch(SCHEMA)?;
        migrate(&conn)?;
        conn.execute_batch(BUILTIN_SCHEMA)?;
        Ok(SqliteStore {
            conn: Conn::Shared(Arc::new(Mutex::new(conn))),
            data: Data::Builtin { snapshot_files: Mutex::new(HashMap::new()) },
        })
    }

    /// Shares the app's connection: Kovlet's tables go into the app's
    /// database, and `apply` writes the app's rows in the same transaction as
    /// Kovlet's bookkeeping.
    ///
    /// ```no_run
    /// # use std::sync::{Arc, Mutex};
    /// # use kovlet::store::{Change, sqlite::SqliteStore};
    /// let db = Arc::new(Mutex::new(rusqlite::Connection::open("app.db").unwrap()));
    /// let store = SqliteStore::shared(db.clone(), |tx, _batch, change| {
    ///     if let Change::Upsert { id, fields, .. } = change {
    ///         tx.execute("INSERT INTO items (id, text) VALUES (?1, ?2)
    ///                     ON CONFLICT(id) DO UPDATE SET text = coalesce(?2, text)",
    ///                    (id, fields.get("text").and_then(|v| v.as_str())))?;
    ///     }
    ///     Ok(())
    /// }).unwrap();
    /// ```
    pub fn shared(
        conn: Arc<Mutex<Connection>>,
        apply: impl Fn(&Connection, &ChangeBatch, &Change) -> Result<()> + Send + Sync + 'static,
    ) -> Result<SqliteStore> {
        SqliteStore::with(Conn::Shared(conn), Data::App(Box::new(apply)))
    }

    /// Like [`SqliteStore::shared`], but `apply` gets the whole batch: one
    /// call per [`ChangeBatch`], inside the transaction that also commits
    /// Kovlet's bookkeeping. Use it to save a batch in one go, or to finish a
    /// snapshot when `batch.complete` is set.
    ///
    /// ```no_run
    /// # use std::sync::{Arc, Mutex};
    /// # use kovlet::store::{Change, sqlite::SqliteStore};
    /// let db = Arc::new(Mutex::new(rusqlite::Connection::open("app.db").unwrap()));
    /// let store = SqliteStore::shared_batch(db.clone(), |tx, batch| {
    ///     for change in &batch.changes {
    ///         if let (Some("items"), Some(id)) = (change.table(), change.id()) {
    ///             // write `change` into `items` row `id`
    ///         }
    ///     }
    ///     Ok(())
    /// }).unwrap();
    /// ```
    pub fn shared_batch(
        conn: Arc<Mutex<Connection>>,
        apply: impl Fn(&Connection, &ChangeBatch) -> Result<()> + Send + Sync + 'static,
    ) -> Result<SqliteStore> {
        SqliteStore::with(Conn::Shared(conn), Data::AppBatch(Box::new(apply)))
    }

    /// For an app whose database type owns its connection: Kovlet never holds
    /// the connection, it borrows it for one transaction at a time through
    /// `lend`. `lend(f)` must begin a transaction on the app's connection, run
    /// `f` with it, and commit if `f` returns `Ok` (roll back otherwise). Any
    /// derived state the app keeps on write (indexes, totals, history) then
    /// commits in the same transaction as the rows and Kovlet's bookkeeping.
    ///
    /// `apply` is called once per batch, inside that transaction. Record mode
    /// works as with [`SqliteStore::shared`]: inside the app's own
    /// transaction, `space.record(&tx, …)` queues the write in it.
    ///
    /// `lend` runs on Kovlet's threads and must not be called re-entrantly:
    /// don't call `space.write(…)` from inside your own transaction (use
    /// `space.record` there).
    ///
    /// ```no_run
    /// # use kovlet::sqlite::{rusqlite::Connection, SqliteStore};
    /// # struct Db; impl Db { fn with_tx<T>(&self, f: impl FnOnce(&Connection) -> kovlet::Result<T>) -> kovlet::Result<T> { unimplemented!() } }
    /// # let db = std::sync::Arc::new(Db);
    /// let lender = db.clone();
    /// let store = SqliteStore::lending(move |f| lender.with_tx(|tx| f(tx)), |tx, batch| {
    ///     // write `batch.changes` into the app's tables through `tx`
    ///     Ok(())
    /// }).unwrap();
    /// ```
    pub fn lending(
        lend: impl Fn(&mut dyn FnMut(&Connection) -> Result<()>) -> Result<()> + Send + Sync + 'static,
        apply: impl Fn(&Connection, &ChangeBatch) -> Result<()> + Send + Sync + 'static,
    ) -> Result<SqliteStore> {
        SqliteStore::with(Conn::Lent(Box::new(lend)), Data::AppBatch(Box::new(apply)))
    }

    fn with(conn: Conn, data: Data) -> Result<SqliteStore> {
        let store = SqliteStore { conn, data };
        store.with_conn(|c| {
            c.execute_batch(SCHEMA)?;
            migrate(c)
        })?;
        Ok(store)
    }

    /// The shared connection; `None` for a [`SqliteStore::lending`] store.
    pub fn connection(&self) -> Option<Arc<Mutex<Connection>>> {
        match &self.conn {
            Conn::Shared(c) => Some(c.clone()),
            Conn::Lent(_) => None,
        }
    }

    /// Runs `f` on the connection: under the store's lock, or inside one
    /// transaction the app lends.
    fn with_conn<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
        match &self.conn {
            Conn::Shared(c) => f(&c.lock().unwrap_or_else(|e| e.into_inner())),
            Conn::Lent(lend) => {
                let mut f = Some(f);
                let mut out = None;
                lend(&mut |c| {
                    let f = f.take().ok_or_else(|| Error::config("SqliteStore::lending: lend called f twice"))?;
                    out = Some(f(c)?);
                    Ok(())
                })?;
                out.ok_or_else(|| Error::config("SqliteStore::lending: lend returned without calling f"))
            }
        }
    }

    fn apply_in(&self, conn: &Connection, batch: &ChangeBatch) -> Result<()> {
        match &self.data {
            Data::App(f) => {
                for c in &batch.changes {
                    f(conn, batch, c)?;
                }
                Ok(())
            }
            Data::AppBatch(f) => f(conn, batch),
            Data::Builtin { snapshot_files } => builtin_apply(conn, batch, snapshot_files),
        }
    }
}

fn builtin_apply(
    conn: &Connection,
    batch: &ChangeBatch,
    snapshot_files: &Mutex<HashMap<String, HashSet<String>>>,
) -> Result<()> {
    let space = &batch.space_id;
    for c in &batch.changes {
        match c {
            Change::File { file } => {
                conn.execute(
                    "INSERT INTO kovlet_files (space_id, id, state) VALUES (?1, ?2, ?3)
                     ON CONFLICT(space_id, id) DO UPDATE SET state = excluded.state",
                    params![space, file.id, serde_json::to_string(file)?],
                )?;
            }
            Change::Schema { table, schema: None } => {
                conn.execute("DELETE FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2", params![space, table])?;
            }
            Change::Schema { .. } => {}
            Change::Purge { table, id } => {
                conn.execute(
                    "DELETE FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
                    params![space, table, id],
                )?;
            }
            Change::Upsert { table, id, .. } | Change::Delete { table, id } | Change::Restore { table, id } => {
                let cur = read_row(conn, space, table, id)?;
                let mut tables: BTreeMap<String, BTreeMap<String, Row>> = BTreeMap::new();
                if let Some(r) = cur {
                    tables.entry(table.clone()).or_default().insert(id.clone(), r);
                }
                apply_row_change(&mut tables, c);
                if let Some(r) = tables.get(table).and_then(|t| t.get(id)) {
                    conn.execute(
                        "INSERT INTO kovlet_rows (space_id, tbl, id, fields, trashed) VALUES (?1, ?2, ?3, ?4, ?5)
                         ON CONFLICT(space_id, tbl, id) DO UPDATE SET fields = excluded.fields, trashed = excluded.trashed",
                        params![space, table, id, serde_json::to_string(&r.fields)?, r.trashed],
                    )?;
                }
            }
        }
    }
    if batch.origin == Origin::Snapshot {
        let mut snaps = snapshot_files.lock().unwrap();
        let seen = snaps.entry(space.clone()).or_default();
        for c in &batch.changes {
            if let Change::File { file } = c {
                seen.insert(file.id.clone());
            }
        }
        if batch.complete {
            let seen = snaps.remove(space).unwrap_or_default();
            let mut stmt = conn.prepare("SELECT id FROM kovlet_files WHERE space_id = ?1")?;
            let ids: Vec<String> = stmt.query_map([space], |r| r.get(0))?.collect::<Result<_, _>>()?;
            for id in ids {
                if !seen.contains(&id) {
                    conn.execute("DELETE FROM kovlet_files WHERE space_id = ?1 AND id = ?2", params![space, id])?;
                }
            }
        }
    }
    Ok(())
}

fn read_row(conn: &Connection, space: &str, table: &str, id: &str) -> Result<Option<Row>> {
    let r: Option<(String, bool)> = conn
        .query_row(
            "SELECT fields, trashed FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
            params![space, table, id],
            |r| Ok((r.get(0)?, r.get(1)?)),
        )
        .optional()?;
    match r {
        None => Ok(None),
        Some((f, trashed)) => {
            Ok(Some(Row { id: id.to_string(), fields: serde_json::from_str::<JsonMap>(&f)?, trashed }))
        }
    }
}

// ---------------------------------------------------------------- bookkeeping SQL

fn load(conn: &Connection, space: &str) -> Result<SpaceState> {
    let r: Option<(i64, String)> = conn
        .query_row("SELECT cursor, state FROM kovlet_spaces WHERE space_id = ?1", [space], |r| {
            Ok((r.get(0)?, r.get(1)?))
        })
        .optional()?;
    Ok(match r {
        None => SpaceState::default(),
        Some((cursor, state)) => SpaceState { cursor, schemas: serde_json::from_str(&state).unwrap_or_default() },
    })
}

fn clocks(conn: &Connection, space: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>> {
    let mut out: BTreeMap<String, RowClocks> = BTreeMap::new();
    let mut stmt = conn
        .prepare_cached("SELECT field, hlc, trashed FROM kovlet_clocks WHERE space_id = ?1 AND tbl = ?2 AND id = ?3")?;
    for id in ids {
        let rows = stmt.query_map(params![space, table, id], |r| {
            Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option<bool>>(2)?))
        })?;
        for row in rows {
            let (field, hlc, trashed) = row?;
            let rc = out.entry(id.clone()).or_default();
            if field == "_deleted" {
                rc.deleted = Some(hlc);
                rc.trashed = trashed;
            } else {
                rc.fields.insert(field, hlc);
            }
        }
    }
    Ok(out)
}

fn row_ids(conn: &Connection, space: &str) -> Result<Vec<RowRef>> {
    let mut stmt = conn.prepare("SELECT DISTINCT tbl, id FROM kovlet_clocks WHERE space_id = ?1")?;
    let v = stmt.query_map([space], |r| Ok(RowRef { table: r.get(0)?, id: r.get(1)? }))?.collect::<Result<_, _>>()?;
    Ok(v)
}

fn outbox(conn: &Connection, space: &str, limit: usize) -> Result<Vec<PendingMutation>> {
    let mut stmt = conn
        .prepare_cached("SELECT body, blob, held, batch FROM kovlet_outbox WHERE space_id = ?1 ORDER BY n LIMIT ?2")?;
    let rows = stmt.query_map(params![space, limit.min(i64::MAX as usize) as i64], |r| {
        Ok((
            r.get::<_, String>(0)?,
            r.get::<_, Option<String>>(1)?,
            r.get::<_, Option<String>>(2)?,
            r.get::<_, Option<String>>(3)?,
        ))
    })?;
    let mut out = Vec::new();
    for row in rows {
        let (body, blob, held, batch) = row?;
        let mutation: Mutation = serde_json::from_str(&body)?;
        let upload: Option<Upload> = blob.as_deref().map(serde_json::from_str).transpose()?;
        out.push(PendingMutation { mutation, upload, held, batch });
    }
    Ok(out)
}

fn commit(conn: &Connection, space: &str, w: &StateWrite) -> Result<()> {
    for (r, rc) in &w.clocks {
        conn.execute(
            "DELETE FROM kovlet_clocks WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
            params![space, r.table, r.id],
        )?;
        let mut ins = conn.prepare_cached(
            "INSERT INTO kovlet_clocks (space_id, tbl, id, field, hlc, trashed) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
        )?;
        for (f, h) in &rc.fields {
            ins.execute(params![space, r.table, r.id, f, h, Option::<bool>::None])?;
        }
        if let Some(d) = &rc.deleted {
            ins.execute(params![space, r.table, r.id, "_deleted", d, rc.trashed])?;
        }
    }
    for r in &w.purge {
        conn.execute(
            "DELETE FROM kovlet_clocks WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
            params![space, r.table, r.id],
        )?;
    }
    for id in &w.outbox_remove {
        conn.execute("DELETE FROM kovlet_outbox WHERE space_id = ?1 AND mutation_id = ?2", params![space, id])?;
    }
    for p in &w.outbox_update {
        conn.execute(
            "UPDATE kovlet_outbox SET body = ?3, blob = ?4, held = ?5, batch = ?6 WHERE space_id = ?1 AND mutation_id = ?2",
            params![
                space,
                p.mutation.mutation_id,
                serde_json::to_string(&p.mutation)?,
                p.upload.as_ref().map(serde_json::to_string).transpose()?,
                p.held,
                p.batch
            ],
        )?;
    }
    if !w.outbox_add.is_empty() {
        let mut n: i64 =
            conn.query_row("SELECT coalesce(max(n), 0) FROM kovlet_outbox WHERE space_id = ?1", [space], |r| r.get(0))?;
        for p in &w.outbox_add {
            n += 1;
            conn.execute(
                "INSERT OR IGNORE INTO kovlet_outbox (space_id, n, mutation_id, body, blob, held, batch) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                params![
                    space,
                    n,
                    p.mutation.mutation_id,
                    serde_json::to_string(&p.mutation)?,
                    p.upload.as_ref().map(serde_json::to_string).transpose()?,
                    p.held,
                    p.batch
                ],
            )?;
        }
    }
    if w.cursor.is_some() || w.schemas.is_some() {
        let cur = load(conn, space)?;
        let cursor = w.cursor.unwrap_or(cur.cursor);
        let schemas = w.schemas.as_ref().unwrap_or(&cur.schemas);
        conn.execute(
            "INSERT INTO kovlet_spaces (space_id, cursor, state) VALUES (?1, ?2, ?3)
             ON CONFLICT(space_id) DO UPDATE SET cursor = excluded.cursor, state = excluded.state",
            params![space, cursor, serde_json::to_string(schemas)?],
        )?;
    }
    for (k, v) in &w.meta {
        meta_set(conn, k, v)?;
    }
    Ok(())
}

fn meta_set(conn: &Connection, key: &str, value: &str) -> Result<()> {
    conn.execute(
        "INSERT INTO kovlet_meta (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
        params![key, value],
    )?;
    Ok(())
}

/// Runs `f` in a transaction on a connection that may already be inside one
/// (record mode): a savepoint then.
fn in_tx<T>(conn: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
    let nested = !conn.is_autocommit();
    conn.execute_batch(if nested { "SAVEPOINT kovlet" } else { "BEGIN IMMEDIATE" })?;
    match f(conn) {
        Ok(v) => {
            conn.execute_batch(if nested { "RELEASE kovlet" } else { "COMMIT" })?;
            Ok(v)
        }
        Err(e) => {
            let _ = conn.execute_batch(if nested { "ROLLBACK TO kovlet; RELEASE kovlet" } else { "ROLLBACK" });
            Err(e)
        }
    }
}

impl SyncStore for SqliteStore {
    fn load(&self, space_id: &str) -> Result<SpaceState> {
        self.with_conn(|c| load(c, space_id))
    }
    fn clocks(&self, space_id: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>> {
        self.with_conn(|c| clocks(c, space_id, table, ids))
    }
    fn row_ids(&self, space_id: &str) -> Result<Vec<RowRef>> {
        self.with_conn(|c| row_ids(c, space_id))
    }
    fn outbox(&self, space_id: &str, limit: usize) -> Result<Vec<PendingMutation>> {
        self.with_conn(|c| outbox(c, space_id, limit))
    }
    fn commit(&self, space_id: &str, write: &StateWrite) -> Result<()> {
        self.with_conn(|conn| in_tx(conn, |c| commit(c, space_id, write)))
    }
    fn forget_space(&self, space_id: &str) -> Result<()> {
        self.with_conn(|conn| {
            in_tx(conn, |c| {
                for t in ["kovlet_spaces", "kovlet_clocks", "kovlet_outbox", "kovlet_queue"] {
                    c.execute(&format!("DELETE FROM {t} WHERE space_id = ?1"), [space_id])?;
                }
                Ok(())
            })
        })?;
        if let Data::Builtin { snapshot_files } = &self.data {
            snapshot_files.lock().unwrap().remove(space_id);
        }
        Ok(())
    }
    fn meta_get(&self, key: &str) -> Result<Option<String>> {
        self.with_conn(|c| {
            Ok(c.query_row("SELECT value FROM kovlet_meta WHERE key = ?1", [key], |r| r.get(0)).optional()?)
        })
    }
    fn meta_set(&self, key: &str, value: &str) -> Result<()> {
        self.with_conn(|c| meta_set(c, key, value))
    }
    fn queue_add(&self, space_id: &str, entries: &[Mutation]) -> Result<()> {
        self.with_conn(|conn| {
            in_tx(conn, |c| {
                let mut n: i64 =
                    c.query_row("SELECT coalesce(max(n), 0) FROM kovlet_queue WHERE space_id = ?1", [space_id], |r| {
                        r.get(0)
                    })?;
                let mut ins = c.prepare_cached(
                    "INSERT OR IGNORE INTO kovlet_queue (space_id, n, mutation_id, body) VALUES (?1, ?2, ?3, ?4)",
                )?;
                for m in entries {
                    n += 1;
                    ins.execute(params![space_id, n, m.mutation_id, serde_json::to_string(m)?])?;
                }
                Ok(())
            })
        })
    }
    fn queued(&self, space_id: &str, limit: usize) -> Result<Vec<Mutation>> {
        self.with_conn(|conn| {
            let mut stmt =
                conn.prepare_cached("SELECT body FROM kovlet_queue WHERE space_id = ?1 ORDER BY n LIMIT ?2")?;
            let rows =
                stmt.query_map(params![space_id, limit.min(i64::MAX as usize) as i64], |r| r.get::<_, String>(0))?;
            let mut out = Vec::new();
            for body in rows {
                out.push(serde_json::from_str(&body?)?);
            }
            Ok(out)
        })
    }
    fn queue_remove(&self, space_id: &str, mutation_ids: &[String]) -> Result<()> {
        self.with_conn(|conn| {
            in_tx(conn, |c| {
                let mut del = c.prepare_cached("DELETE FROM kovlet_queue WHERE space_id = ?1 AND mutation_id = ?2")?;
                for id in mutation_ids {
                    del.execute(params![space_id, id])?;
                }
                Ok(())
            })
        })
    }
    fn transactional(&self) -> Option<&dyn TransactionalStore> {
        Some(self)
    }
}

struct View<'a> {
    store: &'a SqliteStore,
    conn: &'a Connection,
}

impl TxView for View<'_> {
    fn clocks(&self, space_id: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>> {
        clocks(self.conn, space_id, table, ids)
    }
    fn row_ids(&self, space_id: &str) -> Result<Vec<RowRef>> {
        row_ids(self.conn, space_id)
    }
    fn apply(&self, batch: &ChangeBatch) -> Result<()> {
        self.store.apply_in(self.conn, batch)
    }
    fn commit(&self, space_id: &str, write: &StateWrite) -> Result<()> {
        commit(self.conn, space_id, write)
    }
    fn meta_set(&self, key: &str, value: &str) -> Result<()> {
        meta_set(self.conn, key, value)
    }
}

impl TransactionalStore for SqliteStore {
    fn transaction(&self, f: &mut dyn FnMut(&dyn TxView) -> Result<()>) -> Result<()> {
        self.with_conn(|conn| in_tx(conn, |c| f(&View { store: self, conn: c })))
    }
}

impl SqliteStore {
    /// Record mode: runs `f` on the given connection (the app's open
    /// transaction), without taking the store's lock or lending a connection.
    pub(crate) fn transaction_on(&self, conn: &Connection, f: &mut dyn FnMut(&dyn TxView) -> Result<()>) -> Result<()> {
        in_tx(conn, |c| f(&View { store: self, conn: c }))
    }
}

impl DataStore for SqliteStore {
    fn apply(&self, batch: &ChangeBatch) -> Result<()> {
        self.with_conn(|conn| in_tx(conn, |c| self.apply_in(c, batch)))
    }
}

impl ReadStore for SqliteStore {
    fn rows(&self, space_id: &str, table: &str) -> Result<Vec<Row>> {
        if !matches!(self.data, Data::Builtin { .. }) {
            return Err(Error::config("a shared SqliteStore has no built-in rows: read the app's own tables"));
        }
        self.with_conn(|conn| {
            let mut stmt = conn.prepare(
                "SELECT id, fields FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2 AND trashed = 0 ORDER BY id",
            )?;
            let rows =
                stmt.query_map(params![space_id, table], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
            let mut out = Vec::new();
            for row in rows {
                let (id, f) = row?;
                out.push(Row { id, fields: serde_json::from_str(&f)?, trashed: false });
            }
            Ok(out)
        })
    }

    fn get(&self, space_id: &str, table: &str, id: &str) -> Result<Option<Row>> {
        self.with_conn(|c| read_row(c, space_id, table, id))
    }

    fn files(&self, space_id: &str) -> Result<Vec<FileState>> {
        self.with_conn(|conn| {
            let mut stmt = conn.prepare("SELECT state FROM kovlet_files WHERE space_id = ?1 ORDER BY id")?;
            let rows = stmt.query_map([space_id], |r| r.get::<_, String>(0))?;
            let mut out = Vec::new();
            for s in rows {
                let f: FileState = serde_json::from_str(&s?)?;
                if !f.deleted {
                    out.push(f);
                }
            }
            Ok(out)
        })
    }
}