//! The one seam between this crate and SQLite (spec R5). //! //! The surface is deliberately the TypeScript one — `exec`, `run`, `all`, //! `get`, `transaction` — and deliberately synchronous: SQLite is a //! single-writer engine, every operation here is local, and an async surface //! would make `transaction` unable to guarantee that a fold is atomic. //! //! `transaction` is RE-ENTRANT. The fold runs a savepoint per op inside the //! caller's transaction, so an inner call must JOIN the outer one rather than //! open a second. use std::cell::{Cell, RefCell}; use rusqlite::types::{Value, ValueRef}; use rusqlite::{Connection, OpenFlags}; use crate::error::{Result, StoreError}; /// How both halves ask SQLite whether FTS5 was compiled in. pub const FTS5_PROBE_SQL: &str = "SELECT sqlite_compileoption_used('ENABLE_FTS5') AS fts5"; /// One row, in the column order the statement declared. /// /// An ordered list rather than a map because `dump` compares rows column by /// column in DECLARATION order, and because a `_meta` read wants the same /// shape as a `PRAGMA table_info` walk. #[derive(Debug, Clone, PartialEq, Default)] pub struct Row { columns: Vec<(String, Value)>, } impl Row { pub fn new(columns: Vec<(String, Value)>) -> Self { Row { columns } } pub fn columns(&self) -> &[(String, Value)] { &self.columns } pub fn len(&self) -> usize { self.columns.len() } pub fn is_empty(&self) -> bool { self.columns.is_empty() } pub fn get(&self, name: &str) -> Option<&Value> { self.columns .iter() .find(|(column, _)| column == name) .map(|(_, value)| value) } /// The column as TEXT, `None` when absent or NULL. pub fn text(&self, name: &str) -> Option<&str> { match self.get(name) { Some(Value::Text(text)) => Some(text.as_str()), _ => None, } } /// The column as an integer, `None` when absent, NULL or not a number. pub fn int(&self, name: &str) -> Option { match self.get(name) { Some(Value::Integer(value)) => Some(*value), Some(Value::Real(value)) => Some(*value as i64), _ => None, } } /// The column as a float, `None` when absent, NULL or not a number. pub fn real(&self, name: &str) -> Option { match self.get(name) { Some(Value::Integer(value)) => Some(*value as f64), Some(Value::Real(value)) => Some(*value), _ => None, } } } /// WATCHED TABLES (CORE 5, L5): the tables a kept answer depends on, each with whether an UPDATE of one of its rows /// counts (false: only a row added or taken away does, for a table whose rows' links never change once written). /// Every handle's update hook counts a change to one of them in [`watched_changes`], in this process, whichever handle /// wrote it (a sync's fold on the writer, a screen's write): a reader's kept answer is good while that count stands, /// however many other writes (a playback position saved every few seconds) go by. static WATCHED_TABLES: std::sync::RwLock> = std::sync::RwLock::new(Vec::new()); static WATCHED_CHANGES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// Every commit any handle of this process made: a change of `data_version` with this unmoved is another process's. static PROCESS_COMMITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); /// Watch `table` (its stored name): see [`WATCHED_TABLES`]. Idempotent. pub fn watch_table(table: &str, updates_count: bool) { let mut watched = WATCHED_TABLES.write().unwrap_or_else(std::sync::PoisonError::into_inner); if !watched.iter().any(|(name, _)| name == table) { watched.push((table.to_string(), updates_count)); WATCHED_CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst); } } /// How many changes to a watched table this process has made ([`watch_table`]). pub fn watched_changes() -> u64 { WATCHED_CHANGES.load(std::sync::atomic::Ordering::SeqCst) } /// How many commits this process has made, on any handle. pub fn process_commits() -> u64 { PROCESS_COMMITS.load(std::sync::atomic::Ordering::SeqCst) } fn watched_row_changed(action: rusqlite::hooks::Action, table: &str) { let watched = WATCHED_TABLES.read().unwrap_or_else(std::sync::PoisonError::into_inner); if watched.iter().any(|(name, updates)| name == table && (*updates || action != rusqlite::hooks::Action::SQLITE_UPDATE)) { WATCHED_CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst); } } thread_local! { /// [`Driver::thread_steps`]. static THREAD_STEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; /// [`Driver::thread_commits`]. static THREAD_COMMITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// What a checkpoint did with the write-ahead log. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Folded { /// Every frame is in the file and the log is empty. Truncated, /// A reader or a writer held the log: what could be folded was, the log /// stays, and nothing is wrong. Busy, } /// How many prepared statements a handle keeps ([`Driver::all`], [`Driver::run`]). const STATEMENT_CACHE: usize = 256; /// The most of its write-ahead log a file keeps once a checkpoint has folded /// it in (`PRAGMA journal_size_limit`): 8 MB, about two of SQLite's own /// checkpoints' worth, so a log in steady use is not cut and grown again. pub const WAL_KEPT_BYTES: i64 = 8 * 1024 * 1024; /// An open Cotton database. pub struct Driver { conn: Connection, // Dropped AFTER SQLite closes, including a connection left on a blocking worker. _folder_lock: Option>, device_scope: Cell>, /// How deep the caller is inside `transaction`. `Cell` rather than a `&mut` /// receiver because every other method takes `&self` — the fold, the /// migrator and the outbox all hold one shared handle. depth: Cell, /// Whether the outermost `transaction` open now may write (`BEGIN IMMEDIATE`): what it reads may roll back, so an /// answer worked out inside it is never kept past it ([`Self::in_write_transaction`]). writing: Cell, /// Names savepoints so a nested `transaction` cannot collide with the /// fold's own `SAVEPOINT` statements, which it issues through `exec`. savepoint_seq: Cell, /// THE JUDGE this file is written by, when the process that holds it has /// one (slice 1): the serving Mac's relay reading, set by the server's /// file store at open, or — on a replica — the same process clock fed by /// its server's answers. `None` on every other handle — a test's, a server /// with no relay — whose writers stamp by the wall clock /// ([`crate::mint::clock::writer_clock`]). judge: Option>, /// How this handle's file is held, for its judge's release pass: the /// serving Mac's file ([`Driver::judged_by`]) or a replica's /// ([`Driver::replica_judged_by`]), which queues what it releases. held: crate::mint::Held, /// A replica's own op ids, for the writes an ANSWER makes it mint — the /// re-date of a `future` refusal and the release pass an answer's judge /// time starts ([`crate::exchange::fold_answer`]). This crate mints no op /// ids of its own (R7); the replica's shell hands its source over with /// the judge. replica_ids: RefCell>>, /// The release pass has run on this handle with judge time, no mint has /// held since, and no transaction or savepoint has rolled back since — so /// the next judged write or answer need not scan for held receipts again /// ([`crate::mint::clock::writer_clock`]). Every rollback below clears it. released: Cell, /// THE DEVICE KEY this handle's receipts are signed with (keys slice KS1), /// given by the process that holds the key as it opens a file. `None` on a /// handle with no device behind it — a test's, a server that is not a /// device — whose receipts are minted unsigned. signer: crate::signed::SignerSlot, /// Serving startup may fold required rows before accepting requests. /// Those folds invalidate the index without rebuilding a whole database. derive_ready: Option>, index_beside: Cell, /// Every statement this handle has run since [`Driver::watch_statements`], /// for a guard that counts what a path asks of the file. `None` — the /// ordinary handle — keeps nothing. watched: RefCell>>, /// SQLite's own count of the work this handle's statements did /// ([`Driver::steps`]). steps: Cell, /// The same count by statement text, kept only while watched. steps_by: RefCell>, /// Elapsed time by statement, only while the handle is watched. times_by: RefCell>, /// The wall time this handle has spent inside its statements /// ([`Driver::time_inside`]). inside: Cell, /// The slowest statement since [`Driver::take_slowest`], when one was slow /// enough to be worth its words. slowest: RefCell>, /// Small derived totals only, owned by this connection and invalidated /// by SQLite's local change counter and other connections' data version. counts: RefCell, /// Table names in this connection's current schema snapshot. tables: RefCell)>>, /// The package tables this file's definitions declare, as the fold sees /// them, under the stamp they were read at /// ([`crate::schema::package_shape::spec_on`]). package_specs: RefCell)>>, /// Package specs read one table at a time ([`Driver::keep_package_spec`]), at a stamp. package_spec_one: RefCell>)>>, /// What a batch of rows reads once rather than once a row /// ([`Driver::in_batch`]): `None` outside one. batch: RefCell>, /// This handle's number in the process, never given twice /// ([`Driver::file_key`]). handle: u64, } /// The facts a batch has read, by key, each kept until a write could change /// it ([`Driver::batch_fact`]). #[derive(Default)] struct BatchFacts { facts: std::collections::BTreeMap>, } /// The tables a batch fact is read from: a write naming one of them, any /// change of the schema, and any rollback forget every fact the batch read. const BATCH_SOURCES: [&str; 6] = [ "cotton_audiences", "cotton_table_definitions", "cotton_tool_definitions", "cotton_devices", "cotton_authors", "_meta", ]; /// The next [`Driver::handle`] number. static NEXT_HANDLE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); #[derive(Default)] struct CountCache { stamp: Option<(u64, i64, i64)>, values: std::collections::BTreeMap>, } /// How long a statement takes before a slow hold names it /// ([`Driver::take_slowest`]). /// THE PAGE CACHE EVERY CONNECTION THIS PROCESS OPENS KEEPS, in KiB; `0` is /// SQLite's own default (2 MB). Set once by the process that SERVES a file /// ([`serve_with_page_cache`]); a phone never sets it and keeps the default. /// /// **Measured on the serving Mac, 12 Oct 2026**, the email list's count over /// the 4.5 GB personal file, three connections open in one process: with the /// default 2 MB, every connection but the one that scanned last took 160 ms /// against 44–60 ms (2.5–3.5x) — and the server keeps its writer open beside /// the window's read connections on the same file. 4/8/16 MB kept the /// penalty, 32 MB halved it, 64 MB and up removed it: 35–37 ms on every /// connection, 1.8x faster than a lone default connection too. SQLite fills /// the cache only as pages are read, so the size is a ceiling, not an /// allocation. static PAGE_CACHE_KIB: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(0); /// The serving Mac's page cache per connection: twice the measured knee. pub const SERVING_PAGE_CACHE_KIB: i64 = 128 * 1024; /// Every connection this process opens from now on keeps a page cache of up to /// `kib` KiB. The serving process calls it once, before it opens a file. pub fn serve_with_page_cache(kib: i64) { PAGE_CACHE_KIB.store(kib, std::sync::atomic::Ordering::Relaxed); } thread_local! { static OPENED_ON_THIS_THREAD: Cell = const { Cell::new(0) }; } /// How many connections this thread has wrapped ([`Driver::from_connection`]). /// What a guard counts to prove a hot path opens no file: every open runs the /// open-time batch, and a status poll that opened one per database per call /// held the serving Mac at 1,000% CPU on build 158 (20 Oct 2026). pub fn connections_opened_on_this_thread() -> u64 { OPENED_ON_THIS_THREAD.with(Cell::get) } pub const SLOW_STATEMENT: std::time::Duration = std::time::Duration::from_millis(250); /// How much of a slow statement's text a slow hold's line carries. pub const SLOW_STATEMENT_WORDS: usize = 160; impl Driver { /// Open (or create) a file and assert the pragmas the format depends on. pub fn open(path: impl AsRef) -> Result { let folder_lock = crate::process_lock::for_store(path.as_ref()).map_err(StoreError::refused)?; let conn = Connection::open_with_flags( path, OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE | OpenFlags::SQLITE_OPEN_URI | OpenFlags::SQLITE_OPEN_NO_MUTEX, )?; let mut driver = Driver::from_connection(conn, true)?; driver._folder_lock = folder_lock; Ok(driver) } /// Open an EXISTING file read-only, beside the writer that already holds it. /// /// The reader half of WAL's one-writer-many-readers: a connection that can /// never write (`SQLITE_OPEN_READ_ONLY` and `query_only`, so even a TEMP /// table is refused) and therefore never takes the write lock, and whose /// every transaction reads the last COMMITTED snapshot while the writer /// keeps going. A device's screens read here so a list never queues behind /// a sync fold holding the writer. /// /// The file must already be in WAL mode — the writer's open puts it there, /// and a read-only connection cannot. A file in any other mode is REFUSED /// rather than read: under a rollback journal a reader blocks the writer /// and the writer blocks the reader, which is the very wait this connection /// exists to remove, so opening one anyway would be a silent regression. pub fn open_reader(path: impl AsRef) -> Result { let folder_lock = crate::process_lock::for_store(path.as_ref()).map_err(StoreError::refused)?; let mut driver = Driver::reader(path)?; driver._folder_lock = folder_lock; Ok(driver) } /// A reader from ANOTHER process, beside the app that holds the folder. /// /// [`Driver::open_reader`] claims the folder's process lease, so a second /// process is refused while the app runs — which is right for anything /// that may write, and wrong for a read-only export beside the serving /// app, which met "Another CottonDB has this folder open" (19 Oct 2026). This connection takes no lease and so never contends for /// the folder. It is safe without one because it cannot write: read-only /// flags and `query_only`, on an EXISTING file in WAL mode, reading the /// holder's last committed snapshot while the holder keeps writing. pub fn open_snapshot_reader(path: impl AsRef) -> Result { Driver::reader(path) } fn reader(path: impl AsRef) -> Result { let conn = Connection::open_with_flags( path, OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_URI | OpenFlags::SQLITE_OPEN_NO_MUTEX, )?; conn.pragma_update(None, "query_only", true)?; let driver = Driver::from_connection(conn, false)?; let mode = driver .get("PRAGMA journal_mode", &[])? .and_then(|row| row.text("journal_mode").map(str::to_ascii_lowercase)); if mode.as_deref() != Some("wal") { return Err(StoreError::refused(format!( "a read connection needs the file in WAL mode, and it is in {} — a reader on any \ other journal would block the writer and be blocked by it", mode.as_deref().unwrap_or("no readable mode") ))); } Ok(driver) } /// An in-memory file. WAL is skipped — there is no journal to write. pub fn open_in_memory() -> Result { Driver::from_connection(Connection::open_in_memory()?, false) } /// Wrap an already-open connection, setting and then READING BACK the /// pragmas. The set alone is not enough: `PRAGMA foreign_keys` is /// per-connection and silently ignored inside a transaction, so a handle /// that merely issued it can still be running with enforcement off. pub fn from_connection(conn: Connection, wal: bool) -> Result { OPENED_ON_THIS_THREAD.with(|opened| opened.set(opened.get() + 1)); // MAIL PREDICATE phase 2 (rule 5): the one normaliser of a mail's address, as SQL, on every connection a mail // cut is read on (SQLite's own lower folds A to Z only). register_mail_functions(&conn)?; let mut driver = Driver { _folder_lock: None, conn, device_scope: Cell::new(None), depth: Cell::new(0), writing: Cell::new(false), savepoint_seq: Cell::new(0), judge: None, held: crate::mint::Held::Served, replica_ids: RefCell::new(None), released: Cell::new(false), signer: crate::signed::SignerSlot::default(), derive_ready: None, index_beside: Cell::new(false), watched: RefCell::new(None), steps: Cell::new(0), steps_by: RefCell::new(std::collections::BTreeMap::new()), times_by: RefCell::new(std::collections::BTreeMap::new()), inside: Cell::new(std::time::Duration::ZERO), slowest: RefCell::new(None), counts: RefCell::new(CountCache::default()), tables: RefCell::new(None), package_specs: RefCell::new(None), batch: RefCell::new(None), package_spec_one: RefCell::new(None), handle: NEXT_HANDLE.fetch_add(1, std::sync::atomic::Ordering::Relaxed), }; // Correctness, not tuning: WAL so a reader never blocks the writer, // `foreign_keys` because the schema's cascades are load-bearing, and // `busy_timeout` so a concurrent writer waits instead of throwing // SQLITE_BUSY at the caller. `synchronous = NORMAL` is the spec's // choice: with WAL it survives an app crash, and the durability it // trades away is covered by the op log. // // **`busy_timeout` IS FIRST, AND THAT ORDER IS THE POINT.** It is the // only pragma here that changes how the OTHERS behave, and the one // below it — `journal_mode = WAL` — is the single statement in this // function that needs an EXCLUSIVE lock on the file. Set last, as it // was until 2026-09-12, that statement ran under SQLite's default busy // timeout of ZERO: a second opener meeting a live connection did not // wait a millisecond, it failed on the spot with `database is locked`. // A phone opening its replica while the sync loop held it got an error // instead of a wait, and `bootstrap::mod_tests`'s two-thread // single-flight test failed whenever the first thread was still holding // its handle — which is a race on how long an unrelated open takes in // WALL TIME, the one thing a test may never depend on. // // With the timeout set first the wait is "until the holder lets go", // and the seconds are a CEILING that only fires when something is // genuinely wedged. // // THIRTY SECONDS, NOT FIVE, AND THE FIVE WERE FALSIFIED RATHER THAN // OUTGROWN. The sentence above promised a ceiling nothing reaches // unless it is stuck; on 2026-09-23 it fired twice in an hour on two // unrelated PRs, in two different `cotton-ffi` tunnel tests, at the // same line: `server.startNew` against a data directory a live server // already holds, answering `database_not_made: sqlite: database is // locked`. Nothing was wedged. `create` runs the WHOLE ladder — one // commit a rung, and the ladder grows with every schema change — while // the server beside it writes, so what the holder needs is a function // of how many rungs there are and how fast the machine is, and five // seconds stopped covering both the day the CI host began running four // jobs at once. // // A LONGER WAIT IS STRICTLY BETTER THAN A SPURIOUS ERROR, which is the // whole argument. This number does not make anything faster and it // does not paper over a deadlock: SQLite breaks a real one by returning // SQLITE_BUSY at the ceiling either way, and a person on a slow phone // meeting their own first-run `create` would rather wait than be told // their database could not be made. What it is NOT is a fix to whatever // holds the write lock across a ladder — that is `cotton_store::create` // and the server's own writer, and it is worth doing on its own. driver.conn.pragma_update(None, "busy_timeout", 30_000)?; // EVERY STATEMENT IS PREPARED ONCE A HANDLE and kept: a fold asks some // twenty-five statements per row, and preparing each afresh against a // schema of a few hundred tables was a share of every row's cost (a // fresh copy's 3,727 shell lines, copy-installer-store, 8 Nov 2026). // SQLite prepares a kept statement again itself after a schema change. driver.conn.set_prepared_statement_cache_capacity(STATEMENT_CACHE); // Tuning, and only where the process serves (`PAGE_CACHE_KIB`). let page_cache = PAGE_CACHE_KIB.load(std::sync::atomic::Ordering::Relaxed); if page_cache > 0 { driver.conn.pragma_update(None, "cache_size", -page_cache)?; } if wal { // `journal_mode` answers with the mode it settled on, so it has to // be run as a query rather than an exec. driver .conn .pragma_update_and_check(None, "journal_mode", "WAL", |_| Ok(()))?; // THE LOG SHRINKS BACK AFTER EVERY CHECKPOINT, not only after a // TRUNCATE one. SQLite's own checkpoints (every 1,000 pages) fold // the log in but leave `-wal` at the largest it ever grew: a first // pull or a kit's fill wrote hundreds of megabytes into it, and a // phone whose TRUNCATE fold met a reader (`fold_wal` answers Busy // and waits for no one) kept that file for as long as readers kept // meeting it — counted in the app's Documents & Data. With a limit, // the log is cut to it each time it starts over. driver.conn.pragma_update_and_check(None, "journal_size_limit", WAL_KEPT_BYTES, |_| Ok(()))?; } driver.conn.pragma_update(None, "synchronous", "NORMAL")?; // AUDIT E (a copy of the phone's files): what is deleted (a chat's timer, Blocked's sweep, a row binned for // good) is overwritten in the pages it lay in wherever that costs no extra writes, not left readable in free // pages for whoever copies the file. driver.conn.pragma_update(None, "secure_delete", "FAST")?; driver.conn.pragma_update(None, "foreign_keys", "ON")?; // Every commit this handle makes — a transaction's or a lone // statement's autocommit — counted on the thread that made it // (`Driver::thread_commits`). Never vetoes one. driver.conn.commit_hook(Some(|| { THREAD_COMMITS.with(|counted| counted.set(counted.get() + 1)); PROCESS_COMMITS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); false }))?; // A row of a watched table added, changed or taken away (`watch_table`), counted before its commit: a write // that rolls back is counted too, which only costs a kept answer. driver.conn.update_hook(Some(|action, _db: &str, table: &str, _rowid| watched_row_changed(action, table)))?; if let Some(warning) = assert_foreign_keys_on(driver.pragma_number("PRAGMA foreign_keys")?)? { driver.warnings_out(&warning); } if let Some(warning) = assert_fts5_compiled(driver.pragma_number(FTS5_PROBE_SQL)?)? { driver.warnings_out(&warning); } Ok(driver) } /// Fold the write-ahead log back into the file and truncate it to nothing. /// /// **What a force-quit costs, paid while the app is still alive.** With /// WAL and `synchronous = NORMAL` the recent writes live in `-wal` until /// SQLite folds them in; `cotton_close` runs from a Swift `deinit` and a /// SIGKILL runs no `deinit`, so the launch after a force-quit is the one /// that pays the recovery — on a `-wal` that has been growing since the /// last checkpoint, on the main thread's one-call-at-a-time boundary, in /// front of the person who is looking at the splash. Called on the way OUT /// (`sync.background`) there is nothing left to recover on the way in. /// /// Cheap and safe: a checkpoint writes no rows of its own, and a reader /// holding the file simply leaves the log where it is — the answer is /// [`Folded::Busy`], which is not an error. pub fn checkpoint_truncate(&self) -> Result { let row = self.get("PRAGMA wal_checkpoint(TRUNCATE)", &[])?; Ok(match row.and_then(|row| row.int("busy")) { Some(0) | None => Folded::Truncated, Some(_) => Folded::Busy, }) } /// [`Self::checkpoint_truncate`] WITHOUT WAITING for anybody. /// /// A TRUNCATE checkpoint waits — up to `busy_timeout`, thirty seconds — /// for every reader to reach the newest snapshot, and a sync pass that /// folds after itself does it with the file in its hands: a screen's read /// would be thirty seconds of every write queued behind it. Here the wait /// is none, a reader in the way answers [`Folded::Busy`], and the log is /// folded by the next pass instead. pub fn checkpoint_truncate_unwaited(&self) -> Result { let waits = self .get("PRAGMA busy_timeout", &[])? .and_then(|row| row.int("timeout")) .unwrap_or(0); self.conn.busy_timeout(std::time::Duration::ZERO)?; let folded = self.checkpoint_truncate(); self.conn .busy_timeout(std::time::Duration::from_millis(u64::try_from(waits).unwrap_or(0)))?; folded } /// The raw handle, for a caller that needs `rusqlite` itself rather than /// this crate's narrowed surface — today `cotton-client`'s importer, which /// attaches a read-only snapshot and streams rows out of it. pub fn connection(&self) -> &Connection { &self.conn } /// The raw handle to change: from rusqlite 0.41 a handler or hook /// (`progress_handler`, `commit_hook`) is set through `&mut Connection`, /// so only the one holding the connection outright can set it. pub fn connection_mut(&mut self) -> &mut Connection { &mut self.conn } /// What a process-wide cache of something read from this file is kept /// under: the file's path, which every handle on it shares — or, for a /// database in memory, which no other handle can open, this handle's own /// number, never given twice in the process. A cache keyed by path alone /// has no key for a file in memory and reads it again on every call. pub fn file_key(&self) -> String { match self.conn.path().filter(|path| !path.is_empty()) { Some(path) => path.to_string(), None => format!("memory:{}", self.handle), } } /// Bind the local device's persisted admission before bootstrapping a /// replica. It is independent of the serving Mac's identity in a snapshot. pub fn set_device_scope(&self, scope: crate::device_scope::DeviceScope) { self.device_scope.set(Some(scope)); } pub fn device_scope(&self) -> Option { self.device_scope.get() } /// How deep the caller is inside `transaction` — 0 outside one. /// This handle, written and served by `judge` (slice 1). Only the serving /// Mac's file store calls it, as it opens a file. #[must_use] pub fn judged_by(mut self, judge: std::sync::Arc) -> Driver { self.judge = Some(judge); self.held = crate::mint::Held::Served; self } /// This REPLICA's handle, written by `judge` (slice 1, the replica's /// half): its writers mint by the process's judge time, its release pass /// queues what it releases, and every exchange answer folded into it is a /// reading. `ids` mints the op ids an answer makes it write. Only the /// replica's open calls it. #[must_use] pub fn replica_judged_by( mut self, judge: std::sync::Arc, ids: Box, ) -> Driver { self.judge = Some(judge); self.held = crate::mint::Held::Replica; self.replica_ids = RefCell::new(Some(ids)); self } /// This handle, its receipts signed by `signer`'s device key. #[must_use] pub fn signed_by(mut self, signer: std::sync::Arc) -> Driver { self.signer = crate::signed::SignerSlot::filled(signer); self } /// This handle, signing with whatever key `slot` holds — now or once the /// process that opened it learns its device key. #[must_use] pub fn sharing_signer(mut self, slot: crate::signed::SignerSlot) -> Driver { self.signer = slot; self } /// Defer derived work until the serving listener is ready. Folds still /// commit their records, marking the index stale for refusing readers. #[must_use] pub fn derive_after(mut self, ready: std::sync::Arc) -> Driver { self.derive_ready = Some(ready); self } /// A STALE INDEX IS REBUILT BESIDE THE FOLDS, NEVER IN ONE. On a device a /// fold runs inside the sync pass with the copy's mutex held, and a /// whole rebuild there held both for minutes (the 304 phone, 20 Oct /// 2026). A fold on this handle that meets a stale index leaves the rows /// it changed for the background rebuild to patch when it swaps its /// index in (`cotton_tools::derive::ensure_file_current`). #[must_use] pub fn index_beside(self) -> Driver { self.index_beside.set(true); self } /// Defer stale-index work during a bulk import, restoring the handle's /// ordinary policy on return or unwind. The caller rebuilds once after /// its last fold; readers continue to refuse a stale index meanwhile. pub fn with_index_beside(&self, write: impl FnOnce() -> T) -> T { struct Restore<'a>(&'a Cell, bool); impl Drop for Restore<'_> { fn drop(&mut self) { self.0.set(self.1); } } let _restore = Restore(&self.index_beside, self.index_beside.replace(true)); write() } /// Whether this handle leaves a stale index to the background /// ([`Driver::index_beside`]). pub fn indexes_beside(&self) -> bool { self.index_beside.get() } pub(crate) fn derivation_ready(&self) -> bool { self.derive_ready.as_ref().is_none_or(|ready| ready.load(std::sync::atomic::Ordering::Acquire)) } /// The device key this handle signs with, if any. pub fn signer(&self) -> Option<&std::sync::Arc> { self.signer.get() } /// The slot this handle reads its signer from, for a handle opened beside it. pub fn signer_slot(&self) -> crate::signed::SignerSlot { self.signer.clone() } /// The judge this handle is written and served by, if any. pub fn judge(&self) -> Option<&std::sync::Arc> { self.judge.as_ref() } /// The judge of a REPLICA's handle ([`Driver::replica_judged_by`]); `None` /// on the serving Mac's file and on an unjudged handle. pub fn replica_judge(&self) -> Option<&std::sync::Arc> { self.judge.as_ref().filter(|_| self.held == crate::mint::Held::Replica) } /// How a judged handle's file is held — what its release pass does with /// what it releases. pub(crate) fn judged_held(&self) -> crate::mint::Held { self.held } /// Run `work` with this replica's op-id source; `None` on a handle that /// was handed none ([`Driver::replica_judged_by`]). pub(crate) fn with_replica_ids(&self, work: impl FnOnce(&mut dyn crate::outbox::IdSource) -> T) -> Option { let mut ids = self.replica_ids.borrow_mut(); let ids = ids.as_mut()?; Some(work(ids.as_mut())) } pub(crate) fn released(&self) -> bool { self.released.get() } pub(crate) fn set_released(&self, released: bool) { self.released.set(released); } pub fn transaction_depth(&self) -> u32 { self.depth.get() } /// Inside a transaction that may write and may yet roll back: `total_changes` never goes down, so a change stamp /// read in here can equal one read after the rollback, and an answer kept by it would outlive the rows it read. /// A cache keyed by [`Self::change_stamp`] keeps nothing worked out in here. A raw `BEGIN` sent through `exec` /// (outside `transaction`) is counted too, by SQLite's own autocommit flag, unless it is a read transaction. pub fn in_write_transaction(&self) -> bool { self.writing.get() || (self.depth.get() == 0 && !self.conn.is_autocommit()) } /// Start keeping the text of every statement this handle runs, from /// nothing. For a guard on WHAT A PATH ASKS OF THE FILE — how many /// statements, and of which kind — which a result cannot show: a scan and /// a point read answer the same rows. pub fn watch_statements(&self) { *self.watched.borrow_mut() = Some(Vec::new()); self.steps_by.borrow_mut().clear(); self.times_by.borrow_mut().clear(); } /// The statements run since [`Driver::watch_statements`], in order; none /// on a handle that is not watched. pub fn statements_seen(&self) -> Vec { self.watched.borrow().clone().unwrap_or_default() } /// HOW MUCH THIS HANDLE HAS ASKED OF THE FILE since it was opened: the /// virtual-machine steps of every statement it ran, by SQLite's own count /// (`SQLITE_STMTSTATUS_VM_STEP`). A row visited is a handful of steps /// whether an index found it or a scan passed over it, so the difference /// across a piece of work is what that work read — which neither the /// number of statements nor their results can show. Always counted: it is /// one counter read per statement. pub fn steps(&self) -> u64 { self.steps.get() } /// [`Driver::steps`] for EVERY handle this thread has stepped, since the /// thread began — the difference across a call is what it read, whichever /// file answered it (a phone's replica, a Mac's served file). The Debug /// group's slow reads (`shell::diagnostics`) take it around each `read.*`. pub fn thread_steps() -> u64 { THREAD_STEPS.with(std::cell::Cell::get) } /// HOW MANY COMMITS every handle this thread opened has made, since the /// thread began — a transaction's COMMIT and each lone write's autocommit /// alike, by SQLite's own commit hook. Each is a durable write the disk /// waits for on a file not in WAL, and a WAL frame set on one that is, so /// the difference across a piece of work says whether it wrote in one /// transaction or in many. pub fn thread_commits() -> u64 { THREAD_COMMITS.with(std::cell::Cell::get) } /// [`Driver::steps`] by statement text, since [`Driver::watch_statements`], /// most first — which statement of a path did the reading. pub fn steps_by_statement(&self) -> Vec<(u64, String)> { let mut by: Vec<(u64, String)> = self.steps_by.borrow().iter().map(|(sql, steps)| (*steps, sql.clone())).collect(); by.sort_by(|a, b| b.cmp(a)); by } /// Elapsed statement times since watching began, slowest first. Together /// with VM steps this distinguishes query work from lock and disk waits. pub fn times_by_statement(&self) -> Vec<(std::time::Duration, String)> { let mut by: Vec<_> = self.times_by.borrow().iter().map(|(sql, took)| (*took, sql.clone())).collect(); by.sort_by(|a, b| b.cmp(a)); by } fn stepped(&self, sql: &str, statement: &rusqlite::Statement<'_>) { // A cached statement keeps its counter between uses: read and reset. let steps = u64::try_from(statement.reset_status(rusqlite::StatementStatus::VmStep)).unwrap_or(0); self.steps.set(self.steps.get() + steps); THREAD_STEPS.with(|counted| counted.set(counted.get() + steps)); if self.watched.borrow().is_some() { *self.steps_by.borrow_mut().entry(sql.to_string()).or_default() += steps; } } /// Run `body` as one batch: the facts it asks through /// [`Driver::batch_fact`] are read once, and read again only after a write /// that could change them. A batch inside a batch is the outer one. pub fn in_batch(&self, body: impl FnOnce() -> T) -> T { let outer = self.batch.borrow().is_some(); if !outer { *self.batch.borrow_mut() = Some(BatchFacts::default()); } struct Leave<'a>(&'a Driver, bool); impl Drop for Leave<'_> { fn drop(&mut self) { if !self.1 { *self.0.batch.borrow_mut() = None; } } } let _leave = Leave(self, outer); body() } /// Is this handle inside [`Driver::in_batch`]? pub fn batching(&self) -> bool { self.batch.borrow().is_some() } /// The fact `key`, read by `read` once a batch; outside a batch, read /// every time. `key` names every input of `read` (its table, its actor). /// Only facts read from [`BATCH_SOURCES`] belong here. pub(crate) fn batch_fact(&self, key: &str, read: impl FnOnce() -> Result) -> Result { if let Some(batch) = self.batch.borrow().as_ref() { if let Some(kept) = batch.facts.get(key).and_then(|fact| fact.downcast_ref::()) { return Ok(kept.clone()); } } else { return read(); } let fact = read()?; if let Some(batch) = self.batch.borrow_mut().as_mut() { batch.facts.insert(key.to_string(), Box::new(fact.clone())); } Ok(fact) } fn forget_batch_facts(&self) { if let Some(batch) = self.batch.borrow_mut().as_mut() { batch.facts.clear(); } } /// A statement a batch runs: one that writes a fact's source or changes /// the schema forgets every fact the batch read. fn batch_write(&self, sql: &str) { if self.batch.borrow().as_ref().is_none_or(|batch| batch.facts.is_empty()) { return; } if sql.contains(';') { let upper = sql.to_ascii_uppercase(); if ["CREATE ", "ALTER ", "DROP "].iter().any(|word| upper.contains(word)) || BATCH_SOURCES.iter().any(|source| sql.contains(source)) { self.forget_batch_facts(); } return; } let head = sql.trim_start(); let starts = |word: &str| head.get(..word.len()).is_some_and(|start| start.eq_ignore_ascii_case(word)); if starts("SELECT") || starts("SAVEPOINT") || starts("RELEASE") || (starts("PRAGMA") && !head.contains('=')) { return; } if starts("CREATE") || starts("ALTER") || starts("DROP") || BATCH_SOURCES.iter().any(|source| sql.contains(source)) { self.forget_batch_facts(); } } fn seen(&self, sql: &str) { if let Some(seen) = self.watched.borrow_mut().as_mut() { seen.push(sql.to_string()); } } /// HOW LONG THIS HANDLE HAS SPENT INSIDE SQLITE since it was opened, by the /// wall clock: the steps, and every wait a statement makes that is no step /// at all — for another connection's lock (`busy_timeout`), for the disk. /// [`Driver::steps`] cannot see those: a `BEGIN IMMEDIATE` that waits /// sixteen seconds for the write lock is no steps. Raw /// [`Driver::connection`] statements are not counted. pub fn time_inside(&self) -> std::time::Duration { self.inside.get() } /// The slowest statement since this was last asked, and how long it took — /// kept only for one of [`SLOW_STATEMENT`] or more, in its first /// [`SLOW_STATEMENT_WORDS`] characters on one line. pub fn take_slowest(&self) -> Option<(std::time::Duration, String)> { self.slowest.borrow_mut().take() } fn timed(&self, sql: &str, began: std::time::Instant) { let took = began.elapsed(); self.inside.set(self.inside.get() + took); if self.watched.borrow().is_some() { *self.times_by.borrow_mut().entry(sql.to_string()).or_default() += took; } if took < SLOW_STATEMENT { return; } let mut slowest = self.slowest.borrow_mut(); if slowest.as_ref().is_none_or(|(longest, _)| took > *longest) { let words: String = sql.split_whitespace().collect::>().join(" "); *slowest = Some((took, words.chars().take(SLOW_STATEMENT_WORDS).collect())); } } /// Run one or more statements with no parameters and no result. pub fn exec(&self, sql: &str) -> Result<()> { // total_changes does not go backwards on rollback. A count computed // after an uncommitted write must not survive its rollback, including // a savepoint rollback or an unwind through TxGuard. if sql.to_ascii_uppercase().contains("ROLLBACK") { *self.counts.borrow_mut() = CountCache::default(); *self.tables.borrow_mut() = None; self.forget_batch_facts(); } self.batch_write(sql); self.seen(sql); let began = std::time::Instant::now(); let ran = self.conn.execute_batch(sql); self.timed(sql, began); Ok(ran?) } /// Run one statement, answering how many rows it changed. pub fn run(&self, sql: &str, params: &[Value]) -> Result { self.batch_write(sql); self.seen(sql); let began = std::time::Instant::now(); let mut statement = self.conn.prepare_cached(sql)?; let changes = statement.execute(rusqlite::params_from_iter(params.iter())); self.stepped(sql, &statement); self.timed(sql, began); Ok(changes?) } /// What changes whenever anything this connection can read has changed: /// this connection (its serial, never reused), its own writes (`total_changes`), any /// other connection's commit (`data_version`) and the schema. A screen /// keeps what it read by this stamp, as [`Self::cached_counts`] does; a /// stamp from another connection never equals this one's. pub fn change_stamp(&self) -> Result<(usize, u64, i64, i64)> { if !self.conn.is_autocommit() { self.get("SELECT rootpage FROM sqlite_schema LIMIT 1", &[])?; } let version = self.get("PRAGMA data_version", &[])?.and_then(|row| row.int("data_version")) .ok_or_else(|| StoreError::refused("SQLite did not answer its data version"))?; let schema = self.get("PRAGMA schema_version", &[])?.and_then(|row| row.int("schema_version")) .ok_or_else(|| StoreError::refused("SQLite did not answer its schema version"))?; // The handle's own serial, never reused, rather than its address: a handle opened after another closed can // sit at the same address with the same counts, and would read the closed one's kept answers. Ok((self.handle as usize, self.conn.total_changes(), version, schema)) } /// Reuse small totals while this connection's snapshot is unchanged. /// Keys must include every input to the count (workspace and filters). /// The closure is a read and returns only counts, never record payloads. pub fn cached_counts(&self, key: &str, read: impl FnOnce() -> Result>) -> Result> { // A cache hit must establish the deferred transaction's snapshot too. // PRAGMA data_version alone does not: without this read a peer could // commit between a cached total and the page that total describes. if !self.conn.is_autocommit() { self.get("SELECT rootpage FROM sqlite_schema LIMIT 1", &[])?; } // Read data_version through SQLite inside the caller's transaction: // a WAL reader keeps its old snapshot until that transaction ends. let version = self.get("PRAGMA data_version", &[])?.and_then(|row| row.int("data_version")) .ok_or_else(|| StoreError::refused("SQLite did not answer its data version"))?; // A local DROP/CREATE changes schema_version but not total_changes. let schema = self.get("PRAGMA schema_version", &[])?.and_then(|row| row.int("schema_version")) .ok_or_else(|| StoreError::refused("SQLite did not answer its schema version"))?; let stamp = (self.conn.total_changes(), version, schema); { let mut cache = self.counts.borrow_mut(); if cache.stamp != Some(stamp) { cache.values.clear(); cache.stamp = Some(stamp); } if let Some(value) = cache.values.get(key) { return Ok(value.clone()); } } let value = read()?; let mut cache = self.counts.borrow_mut(); // Arbitrarily many user filters must never grow a connection forever. if cache.values.len() >= 128 { cache.values.clear(); } cache.values.insert(key.to_string(), value.clone()); Ok(value) } /// Table presence in the same SQLite snapshot as the caller's reads. /// Schema-version checks are constant work; the schema is read once per /// DDL change, rather than once per folded record (notably audience checks). pub fn table_exists(&self, table: &str) -> Result { if self.batching() { return self.batch_fact(&format!("table_exists {table}"), || self.read_table_exists(table)); } self.read_table_exists(table) } fn read_table_exists(&self, table: &str) -> Result { if !self.conn.is_autocommit() { self.get("SELECT rootpage FROM sqlite_schema LIMIT 1", &[])?; } let version = self.get("PRAGMA schema_version", &[])?.and_then(|row| row.int("schema_version")) .ok_or_else(|| StoreError::refused("SQLite did not answer its schema version"))?; if let Some((at, tables)) = self.tables.borrow().as_ref() { if *at == version { return Ok(tables.contains(table)); } } let tables: std::collections::BTreeSet = self.all( "SELECT name FROM sqlite_schema WHERE type = 'table'", &[])? .iter().filter_map(|row| row.text("name").map(str::to_string)).collect(); let exists = tables.contains(table); *self.tables.borrow_mut() = Some((version, tables)); Ok(exists) } /// The package spec of `table` read at `stamp`, when this handle holds /// one: `Some(None)` is "read at this stamp, and not a package table". pub(crate) fn package_specs_cached(&self, stamp: &str, table: &str) -> Option> { if let Some((at, specs)) = self.package_specs.borrow().as_ref() { if at == stamp { return Some(specs.get(table).copied()); } } let one = self.package_spec_one.borrow(); let (at, specs) = one.as_ref()?; if at != stamp { return None; } specs.get(table).copied() } /// Keep the package spec of `table` alone, read at `stamp`. pub(crate) fn keep_package_spec(&self, stamp: String, table: &str, spec: Option<&'static crate::schema::decl::TableSpec>) { let mut one = self.package_spec_one.borrow_mut(); if one.as_ref().is_none_or(|(at, _)| *at != stamp) { *one = Some((stamp, std::collections::BTreeMap::new())); } if let Some((_, specs)) = one.as_mut() { specs.insert(table.to_owned(), spec); } } /// The names of the package specs read at `stamp`, when they are kept. pub(crate) fn package_names_cached(&self, stamp: &str) -> Option> { let cache = self.package_specs.borrow(); let (at, specs) = cache.as_ref()?; (at == stamp).then(|| specs.keys().cloned().collect()) } /// Keep the package specs read at `stamp`. pub(crate) fn keep_package_specs(&self, stamp: String, specs: std::collections::BTreeMap) { *self.package_specs.borrow_mut() = Some((stamp, specs)); } /// Every row the statement produces, in order. pub fn all(&self, sql: &str, params: &[Value]) -> Result> { self.seen(sql); let began = std::time::Instant::now(); let mut statement = self.conn.prepare_cached(sql)?; let out = (|| { let mut rows = statement.query(rusqlite::params_from_iter(params.iter()))?; let mut out = Vec::new(); // A kept statement learns a DDL change only when it steps, so its // columns are read from the first row, never before it. let mut names: Option> = None; while let Some(row) = rows.next()? { let names = names.get_or_insert_with(|| { row.as_ref().column_names().map(str::to_string).collect() }); let mut columns = Vec::with_capacity(names.len()); for (index, name) in names.iter().enumerate() { columns.push((name.clone(), owned(row.get_ref(index)?))); } out.push(Row::new(columns)); } Ok(out) })(); self.stepped(sql, &statement); self.timed(sql, began); out } /// Every row the statement produces, in order, each its values by /// position: no column name is copied per row (a whole list's cut). pub fn all_values(&self, sql: &str, params: &[Value]) -> Result>> { self.seen(sql); let began = std::time::Instant::now(); let mut statement = self.conn.prepare_cached(sql)?; let out = (|| { let mut rows = statement.query(rusqlite::params_from_iter(params.iter()))?; let mut out = Vec::new(); while let Some(row) = rows.next()? { // Read after the step, as in `all`: a DDL change re-prepares. let width = row.as_ref().column_count(); let mut values = Vec::with_capacity(width); for index in 0..width { values.push(owned(row.get_ref(index)?)); } out.push(values); } Ok(out) })(); self.stepped(sql, &statement); self.timed(sql, began); out } /// The first row, or `None`. pub fn get(&self, sql: &str, params: &[Value]) -> Result> { Ok(self.all(sql, params)?.into_iter().next()) } /// Runs `f` inside a transaction, rolling back if it fails. Re-entrant: /// the outermost call owns BEGIN/COMMIT and every inner one takes a /// SAVEPOINT, so an inner failure the caller catches unwinds only the /// inner work. /// /// A PANIC inside `f` rolls back too, through [`TxGuard`]. Without that the /// unwind skips every line after the call and leaves the connection inside /// an open BEGIN with `depth` still set: the next `transaction` on the same /// handle takes a SAVEPOINT inside a transaction nobody will ever commit, /// and a caller that catches the panic — a test harness, a task the runtime /// unwinds — then writes into it. `Result` is the language here; the guard /// is for the one exit a `Result` cannot describe. pub fn transaction(&self, f: impl FnOnce(&Driver) -> Result) -> Result { self.transaction_begun(false, f) } /// [`Driver::transaction`] for a READ: one consistent snapshot that NEVER /// ASKS FOR THE WRITE LOCK. /// /// `BEGIN IMMEDIATE` waits — up to `busy_timeout`, thirty seconds — for /// whichever other connection has the file's write lock, and on a served /// file there is one: the replicator beside the app. A read that began /// that way stood behind a writer it had nothing to do with, holding the /// file's own mutex, so every route and every screen stood behind the /// read. A WAL reader waits for nobody. A body that turns out to write /// takes the lock at its first write, as any deferred transaction does — /// and every caller of this refuses and rolls back a read that wrote. pub fn read_transaction(&self, f: impl FnOnce(&Driver) -> Result) -> Result { self.transaction_begun(true, f) } fn transaction_begun(&self, reading: bool, f: impl FnOnce(&Driver) -> Result) -> Result { if self.depth.get() == 0 { // THE WRITE LOCK IS TAKEN AT `BEGIN`, where `busy_timeout` is // honoured. A deferred `BEGIN` takes it at the first write, and a // transaction that READ first — every mint reads `_meta` — then // finds its snapshot stale if another connection committed in // between: SQLite answers that at once with "database is locked" // (SQLITE_BUSY_SNAPSHOT), whatever the timeout, and the write is // lost. The other connection is real on a served file — litestream // commits its own sequence row there every checkpoint. A read-only // handle ([`Driver::open_reader`]) can take no write lock and keeps // the deferred `BEGIN`: its transaction is one consistent snapshot. let read_only = reading || self.conn.is_readonly(rusqlite::MAIN_DB).unwrap_or(false); self.exec(if read_only { "BEGIN" } else { "BEGIN IMMEDIATE" })?; self.depth.set(1); self.writing.set(!read_only); let mut guard = TxGuard { driver: self, mark: None, depth_before: 0, armed: true, }; let outcome = f(self); guard.armed = false; drop(guard); self.depth.set(0); self.writing.set(false); match outcome { Ok(value) => { if let Err(error) = self.exec("COMMIT") { self.released.set(false); return Err(error); } Ok(value) } Err(error) => { // A failed ROLLBACK must not hide the reason the caller // actually failed — the original error is the useful one. let _ = self.exec("ROLLBACK"); self.released.set(false); Err(error) } } } else { let seq = self.savepoint_seq.get() + 1; self.savepoint_seq.set(seq); let mark = format!("cotton_tx_{seq}"); self.exec(&format!("SAVEPOINT {mark}"))?; let depth_before = self.depth.get(); self.depth.set(depth_before + 1); let mut guard = TxGuard { driver: self, mark: Some(mark.clone()), depth_before, armed: true, }; let outcome = f(self); guard.armed = false; drop(guard); self.depth.set(self.depth.get() - 1); match outcome { Ok(value) => { self.exec(&format!("RELEASE {mark}"))?; Ok(value) } Err(error) => { let _ = self.exec(&format!("ROLLBACK TO {mark}")); let _ = self.exec(&format!("RELEASE {mark}")); self.released.set(false); Err(error) } } } } /// A one-column, one-row numeric read — how both assertions get their /// value. `None` when the statement gave back nothing readable as a /// number, which is the "could not tell" arm of the tri-state. fn pragma_number(&self, sql: &str) -> Result> { let row = self.get(sql, &[])?; Ok(row.and_then(|row| match row.columns().first() { Some((_, Value::Integer(value))) => Some(*value as f64), Some((_, Value::Real(value))) => Some(*value), Some((_, Value::Text(text))) => text.parse::().ok(), _ => None, })) } /// Where a warning that is not fatal goes. /// /// The TypeScript hands the string back to its caller rather than logging, /// because the package cannot know whether it is on a phone, on the host /// or in a test. This crate is the same: the assertions RETURN the string /// and `open` — which has no caller to hand it to — writes it to stderr, /// the one channel a library may use without choosing anyone's transport. fn warnings_out(&self, warning: &str) { eprintln!("{warning}"); } } /// Undoes a transaction an UNWIND left open. /// /// Armed for the length of the caller's closure and disarmed the moment it /// returns, so the ordinary `Ok`/`Err` arms below are untouched: this fires /// only on a panic, which is the one exit that skips them. It puts the depth /// back before it speaks to SQLite, so a `Drop` running inside a wider unwind /// leaves the handle usable rather than merely rolled back. struct TxGuard<'a> { driver: &'a Driver, /// `None` for the outermost BEGIN/COMMIT; the savepoint's name otherwise. mark: Option, depth_before: u32, armed: bool, } impl Drop for TxGuard<'_> { fn drop(&mut self) { if !self.armed { return; } self.driver.depth.set(self.depth_before); self.driver.released.set(false); match &self.mark { None => { let _ = self.driver.exec("ROLLBACK"); } Some(mark) => { let _ = self.driver.exec(&format!("ROLLBACK TO {mark}")); let _ = self.driver.exec(&format!("RELEASE {mark}")); } } } } fn owned(value: ValueRef<'_>) -> Value { match value { ValueRef::Null => Value::Null, ValueRef::Integer(int) => Value::Integer(int), ValueRef::Real(real) => Value::Real(real), ValueRef::Text(text) => Value::Text(String::from_utf8_lossy(text).into_owned()), ValueRef::Blob(blob) => Value::Blob(blob.to_vec()), } } /// Both halves call this with whatever `PRAGMA foreign_keys` read back at open. /// /// ASSERTED, not assumed. The pragma is per-CONNECTION and is silently ignored /// inside a transaction, so a driver that merely SET it can still be running /// with enforcement off. The fold depends on immediate foreign-key enforcement /// to turn a bad reference into a per-op rejection instead of a wedge. /// /// Refuses when it is definitely OFF. Answers a warning STRING — never logs /// one — when it could not tell, and `None` when all is well. pub fn assert_foreign_keys_on(value: Option) -> Result> { match value { Some(1.0) => Ok(None), // COULD NOT READ is not the same as OFF, and must not be treated as // it. Throwing here would stop the app OPENING ITS DATABASE over a // diagnostic; a guard whose failure mode is worse than the thing it // guards is not a guard. None => Ok(Some( "cotton-store: could not read PRAGMA foreign_keys back on this connection — \ continuing, because failing to open the file would be worse than not knowing. \ If foreign keys really are off, the fold will apply rows with dangling references \ that the other half rejects." .to_string(), )), Some(nan) if nan.is_nan() => Ok(Some( "cotton-store: could not read PRAGMA foreign_keys back on this connection — \ continuing, because failing to open the file would be worse than not knowing. \ If foreign keys really are off, the fold will apply rows with dangling references \ that the other half rejects." .to_string(), )), Some(_) => Err(StoreError::refused( "cotton-store: PRAGMA foreign_keys is OFF on this connection. The fold relies on \ immediate foreign-key enforcement to reject a bad reference instead of wedging sync; \ with it off this file would accumulate dangling rows the other half refuses.", )), } } /// Both halves call this with whatever `FTS5_PROBE_SQL` read back at open. /// /// The file's search index is FTS5, and it is not optional: every searchable /// table carries insert/delete/update triggers into its `fts_*` table, so a /// SQLite built without the module cannot INSERT into cotton_todos at all — /// and cannot run a migration that renames a table, because `ALTER TABLE` /// re-validates every trigger. That is what held the owner's phone on the /// splash screen for two TestFlight builds (2026-08-25, #15). pub fn assert_fts5_compiled(value: Option) -> Result> { const UNREADABLE: &str = "cotton-store: could not read sqlite_compileoption_used('ENABLE_FTS5') back on this \ connection — continuing, because failing to open the file would be worse than not \ knowing. If FTS5 really is missing, every write to a searchable table and every search \ will fail."; match value { Some(1.0) => Ok(None), None => Ok(Some(UNREADABLE.to_string())), Some(nan) if nan.is_nan() => Ok(Some(UNREADABLE.to_string())), Some(_) => Err(StoreError::refused( "cotton-store: this SQLite was built WITHOUT FTS5, and the file's search index needs \ it — every insert into a searchable table fails in its fts_* trigger, search fails, \ and no migration can rename a table. Every build of this crate compiles its OWN \ SQLite from rusqlite's `bundled` feature (`crates/Cargo.toml`), which turns FTS5 \ on, and the phone and the server link the same amalgamation — so a connection \ reaching this line is running against some other SQLite. Find out whose, rather \ than switching a flag. See issue #15.", )), } } #[cfg(test)] #[path = "driver_tests.rs"] mod tests; /// The mail cuts' SQL functions (cotton-rules mail/cuts.rs, MAIL PREDICATE phase 2): `cotton_mail_key` is /// `normalise_key` and `cotton_mail_time` is `normalise_time`. On every connection a [`Driver`] opens, and the tests'. pub fn register_mail_functions(conn: &rusqlite::Connection) -> rusqlite::Result<()> { use cotton_rules::mail::predicate::cuts; let flags = rusqlite::functions::FunctionFlags::SQLITE_UTF8 | rusqlite::functions::FunctionFlags::SQLITE_DETERMINISTIC; conn.create_scalar_function(cuts::KEY_FUNCTION, 1, flags, |ctx| Ok(ctx.get::>(0)?.map(|key| cuts::normalise_key(&key))))?; conn.create_scalar_function(cuts::TIME_FUNCTION, 1, flags, |ctx| Ok(ctx.get::>(0)?.and_then(|time| cuts::normalise_time(&time)))) }