//! The pragmas are correctness, not tuning — and `foreign_keys` in particular //! is load-bearing: the fold turns a bad reference into a per-op rejection //! only because SQLite raises at statement time. With it off, the same op would //! APPLY, and the file would fill with dangling rows the other half refuses. //! //! The re-entrancy cases are here because this driver takes a SAVEPOINT //! rather than joining the outer transaction — see the note on //! `an_inner_failure_rolls_back_only_the_inner_savepoint`. use super::*; #[test] fn opens_with_the_pragmas_the_format_depends_on() { let db = Driver::open_in_memory().expect("opens"); // READ BACK, not assumed — the whole reason the assertions exist. assert_eq!( db.get("PRAGMA foreign_keys", &[]) .expect("reads") .and_then(|row| row.int("foreign_keys")), Some(1) ); assert_eq!( db.get("PRAGMA synchronous", &[]) .expect("reads") .and_then(|row| row.int("synchronous")), Some(1) // NORMAL ); assert_eq!( db.get("PRAGMA busy_timeout", &[]) .expect("reads") .and_then(|row| row.int("timeout")), // Thirty seconds. Five was falsified on 2026-09-23 — twice in an hour, // on two unrelated PRs, by `server.startNew` meeting a live server's // writer while `create` ran the ladder. See the comment in driver.rs. Some(30_000) ); } /// **`busy_timeout` is set before anything that can block, and it stays that /// way.** `journal_mode = WAL` needs an EXCLUSIVE lock on the file, so with the /// timeout still at SQLite's default of zero a second opener meeting a live /// connection fails on the spot with `database is locked` instead of waiting. /// That is what it did until 2026-09-12, and it is why /// `cotton-client`'s `bootstrap::mod_tests`'s two-thread single-flight test /// failed or passed on how long an unrelated open happened to take. /// /// The order is not observable from an open connection — both pragmas have /// been applied by the time anyone can ask — so this reads the source. It is in /// the same crate as the file it reads and it fails LOUDLY if either pragma /// stops being found, rather than going quiet the way a guard that reads /// another package's file by path does. #[test] fn the_busy_timeout_is_set_before_the_pragma_that_needs_an_exclusive_lock() { let source = include_str!("driver.rs"); let timeout = source .find(r#"pragma_update(None, "busy_timeout""#) .expect("driver.rs still sets busy_timeout — if this moved, this guard must move with it"); let journal = source .find(r#"pragma_update_and_check(None, "journal_mode""#) .expect("driver.rs still sets journal_mode — if this moved, this guard must move with it"); assert!( timeout < journal, "busy_timeout must be set BEFORE journal_mode: journal_mode takes an exclusive lock, and \ under the default zero timeout a second opener fails instantly rather than waiting" ); } #[test] fn fts5_is_compiled_in() { // rusqlite's bundled SQLite carries the module; without it every insert // into a searchable table dies in its fts_* trigger, search fails, and no // migration can rename a table (issue #15). let db = Driver::open_in_memory().expect("opens"); assert_eq!( db.get(FTS5_PROBE_SQL, &[]) .expect("reads") .and_then(|row| row.int("fts5")), Some(1) ); db.exec("CREATE VIRTUAL TABLE fts_probe USING fts5(body)") .expect("an FTS5 table creates"); } #[test] fn a_file_on_disk_opens_in_wal() { let dir = std::env::temp_dir().join(format!("cotton-store-driver-{}", std::process::id())); std::fs::create_dir_all(&dir).expect("temp dir"); let path = dir.join("wal.db"); let _ = std::fs::remove_file(&path); { let db = Driver::open(&path).expect("opens"); let mode = db .get("PRAGMA journal_mode", &[]) .expect("reads") .and_then(|row| row.text("journal_mode").map(str::to_string)); assert_eq!(mode.as_deref(), Some("wal")); } let _ = std::fs::remove_dir_all(&dir); } /// RULE (AUDIT E, a copy of the phone's files): every file opens with deleted content overwritten (`secure_delete` /// FAST, 2), so a message erased is not left readable in free pages. #[test] fn deleted_content_is_overwritten_where_it_lay() { let dir = tempfile::tempdir().expect("temp dir"); let db = Driver::open(&dir.path().join("erase.db")).expect("opens"); assert_eq!(db.get("PRAGMA secure_delete", &[]).expect("reads").and_then(|row| row.int("secure_delete")), Some(2)); } /// RULE (21 Nov 2026): a file's write-ahead log goes back to at most `WAL_KEPT_BYTES` once a checkpoint has folded it in, whichever checkpoint it was — SQLite's own included — and not only after a TRUNCATE one: a first pull grew `-wal` to tens of megabytes, and a phone whose TRUNCATE fold met a reader kept it at that size, counted in the app's Documents & Data. #[test] fn the_write_ahead_log_goes_back_to_its_limit_after_any_checkpoint() { let dir = tempfile::tempdir().expect("temp dir"); let path = dir.path().join("big.db"); let wal = dir.path().join("big.db-wal"); let db = Driver::open(&path).expect("opens"); assert_eq!(db.get("PRAGMA journal_size_limit", &[]).expect("reads").and_then(|row| row.int("journal_size_limit")), Some(WAL_KEPT_BYTES)); db.exec("CREATE TABLE t (id INTEGER PRIMARY KEY, body BLOB)").expect("creates"); // One transaction of about 24 MB, as a first pull's pages are: the log // holds all of it until the commit, whatever SQLite's own checkpoints do. db.transaction(|db| { for n in 0..6_000 { db.run("INSERT INTO t (id, body) VALUES (?, zeroblob(4000))", &[Value::Integer(n)])?; } Ok(()) }) .expect("a big write"); let grown = std::fs::metadata(&wal).map(|meta| meta.len()).unwrap_or(0); assert!(grown > 2 * WAL_KEPT_BYTES as u64, "the log grew to {grown}"); // A checkpoint that is not TRUNCATE (SQLite's own are PASSIVE), then the // next write, which starts the log over. db.get("PRAGMA wal_checkpoint(PASSIVE)", &[]).expect("a checkpoint"); db.run("INSERT INTO t (id, body) VALUES (?, zeroblob(10))", &[Value::Integer(-1)]).expect("the next write"); let kept = std::fs::metadata(&wal).map(|meta| meta.len()).unwrap_or(0); assert!(kept <= WAL_KEPT_BYTES as u64, "the log went back to {kept}, at most {WAL_KEPT_BYTES}"); } #[test] fn a_checkpoint_leaves_nothing_in_the_write_ahead_log() { // What a force-quit would otherwise leave for the next launch to recover, // paid on the way out instead. `TRUNCATE` is the mode that makes the file // zero bytes rather than merely re-usable, so "is there anything to // recover" is answerable by looking. let dir = std::env::temp_dir().join(format!("cotton-store-checkpoint-{}", std::process::id())); std::fs::create_dir_all(&dir).expect("temp dir"); let path = dir.join("checkpoint.db"); let _ = std::fs::remove_file(&path); let wal = path.with_file_name("checkpoint.db-wal"); { let db = Driver::open(&path).expect("opens"); db.exec("CREATE TABLE t (id TEXT PRIMARY KEY, n INTEGER)") .expect("creates"); for n in 0..200 { db.run( "INSERT INTO t (id, n) VALUES (?, ?)", &[Value::Text(format!("row-{n}")), Value::Integer(n)], ) .expect("inserts"); } assert!( std::fs::metadata(&wal).map(|meta| meta.len()).unwrap_or(0) > 0, "the writes are in the log to begin with" ); db.checkpoint_truncate().expect("a checkpoint"); assert_eq!( std::fs::metadata(&wal).map(|meta| meta.len()).unwrap_or(0), 0, "the log is empty: a force-quit after this leaves nothing to recover" ); // And the rows are still there, which is the half a truncation must // never cost. assert_eq!( db.get("SELECT COUNT(*) AS n FROM t", &[]) .expect("reads") .and_then(|row| row.int("n")), Some(200) ); } let _ = std::fs::remove_dir_all(&dir); } #[test] fn run_answers_how_many_rows_it_changed() { let db = Driver::open_in_memory().expect("opens"); db.exec("CREATE TABLE t (id TEXT PRIMARY KEY, n INTEGER)") .expect("creates"); assert_eq!( db.run( "INSERT INTO t (id, n) VALUES (?, ?)", &[Value::Text("a".into()), Value::Integer(1)] ) .expect("inserts"), 1 ); assert_eq!(db.run("UPDATE t SET n = 2", &[]).expect("updates"), 1); assert_eq!( db.run("DELETE FROM t WHERE id = 'nope'", &[]) .expect("deletes"), 0 ); } #[test] fn all_and_get_read_columns_in_declaration_order() { let db = Driver::open_in_memory().expect("opens"); db.exec("CREATE TABLE t (id TEXT, n INTEGER, r REAL, b BLOB)") .expect("creates"); db.exec("INSERT INTO t VALUES ('a', 1, 1.5, x'00ff'), ('b', NULL, NULL, NULL)") .expect("inserts"); let rows = db.all("SELECT * FROM t ORDER BY id", &[]).expect("reads"); assert_eq!(rows.len(), 2); assert_eq!( rows[0] .columns() .iter() .map(|(name, _)| name.as_str()) .collect::>(), ["id", "n", "r", "b"] ); assert_eq!(rows[0].text("id"), Some("a")); assert_eq!(rows[0].int("n"), Some(1)); assert_eq!(rows[0].real("r"), Some(1.5)); assert_eq!(rows[0].get("b"), Some(&Value::Blob(vec![0, 255]))); assert_eq!(rows[1].text("id"), Some("b")); assert_eq!(rows[1].int("n"), None); assert_eq!( db.get("SELECT * FROM t ORDER BY id", &[]) .expect("reads") .and_then(|row| row.text("id").map(str::to_string)), Some("a".to_string()) ); assert!(db .get("SELECT * FROM t WHERE id = 'nope'", &[]) .expect("reads") .is_none()); } #[test] fn a_transaction_commits_its_work() { let db = Driver::open_in_memory().expect("opens"); db.exec("CREATE TABLE t (id TEXT PRIMARY KEY)") .expect("creates"); db.transaction(|db| db.run("INSERT INTO t VALUES ('a')", &[])) .expect("commits"); assert_eq!(db.all("SELECT * FROM t", &[]).expect("reads").len(), 1); assert_eq!(db.transaction_depth(), 0); } #[test] fn a_failing_transaction_rolls_the_whole_thing_back() { let db = Driver::open_in_memory().expect("opens"); db.exec("CREATE TABLE t (id TEXT PRIMARY KEY)") .expect("creates"); let outcome: Result<()> = db.transaction(|db| { db.run("INSERT INTO t VALUES ('a')", &[])?; Err(StoreError::refused("deliberate")) }); assert!(outcome.is_err()); assert_eq!(db.all("SELECT * FROM t", &[]).expect("reads").len(), 0); assert_eq!(db.transaction_depth(), 0); } #[test] fn a_nested_transaction_joins_the_outer_one() { // The property the fold depends on: a fold called from inside writeLocal // must join the caller's transaction, never open a second. let db = Driver::open_in_memory().expect("opens"); db.exec("CREATE TABLE t (id TEXT PRIMARY KEY)") .expect("creates"); db.transaction(|db| { assert_eq!(db.transaction_depth(), 1); db.run("INSERT INTO t VALUES ('outer')", &[])?; db.transaction(|db| { assert_eq!(db.transaction_depth(), 2); db.run("INSERT INTO t VALUES ('inner')", &[]) })?; Ok(()) }) .expect("commits"); assert_eq!(db.all("SELECT * FROM t", &[]).expect("reads").len(), 2); } #[test] fn an_inner_failure_rolls_back_only_the_inner_savepoint() { // The one place this driver is DELIBERATELY stricter than betterSqlite.ts, // which re-enters by simply calling the closure: there, an inner failure // the caller catches leaves the inner writes applied. Spec R5 asks for // savepoints on the inner levels, which is also what the fold does by hand // for its per-op rollback — so the behaviour is the fold's, generalised. let db = Driver::open_in_memory().expect("opens"); db.exec("CREATE TABLE t (id TEXT PRIMARY KEY)") .expect("creates"); db.transaction(|db| { db.run("INSERT INTO t VALUES ('outer')", &[])?; let inner: Result<()> = db.transaction(|db| { db.run("INSERT INTO t VALUES ('inner')", &[])?; Err(StoreError::refused("deliberate")) }); assert!(inner.is_err()); db.run("INSERT INTO t VALUES ('after')", &[])?; Ok(()) }) .expect("commits"); let ids: Vec = db .all("SELECT id FROM t ORDER BY id", &[]) .expect("reads") .iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect(); assert_eq!(ids, ["after", "outer"]); } #[test] fn an_outer_failure_after_a_successful_inner_one_takes_everything() { let db = Driver::open_in_memory().expect("opens"); db.exec("CREATE TABLE t (id TEXT PRIMARY KEY)") .expect("creates"); let outcome: Result<()> = db.transaction(|db| { db.transaction(|db| db.run("INSERT INTO t VALUES ('inner')", &[]))?; Err(StoreError::refused("deliberate")) }); assert!(outcome.is_err()); assert_eq!(db.all("SELECT * FROM t", &[]).expect("reads").len(), 0); } #[test] fn a_bad_reference_is_refused_immediately_not_at_commit() { // The property the fold's per-op savepoint depends on. If enforcement ever // became deferred, a violation would escape the savepoint and surface from // the outermost commit — which is precisely the wedge. let db = Driver::open_in_memory().expect("opens"); db.exec("CREATE TABLE parent (id TEXT PRIMARY KEY)") .expect("creates"); db.exec("CREATE TABLE child (id TEXT PRIMARY KEY, parent_id TEXT REFERENCES parent(id))") .expect("creates"); let outcome: Result = db.transaction(|db| { db.transaction(|db| { db.run( "INSERT INTO child (id, parent_id) VALUES ('c1', 'no-such-parent')", &[], ) }) }); let error = outcome.expect_err("the reference is refused"); assert!( error.to_string().to_uppercase().contains("FOREIGN KEY"), "got {error}" ); } #[test] fn assert_foreign_keys_on_is_quiet_when_all_is_well_and_refuses_a_definite_off() { assert_eq!(assert_foreign_keys_on(Some(1.0)).expect("quiet"), None); let error = assert_foreign_keys_on(Some(0.0)).expect_err("refuses"); assert!( error.to_string().contains("foreign_keys is OFF"), "got {error}" ); // It says WHY it matters, not just that it is off. assert!( error.to_string().contains("wedging sync") || error.to_string().contains("dangling"), "got {error}" ); } #[test] fn assert_foreign_keys_on_reports_but_does_not_refuse_when_it_could_not_read() { // COULD NOT READ is not the same as OFF. Refusing 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. for unreadable in [None, Some(f64::NAN)] { let warning = assert_foreign_keys_on(unreadable) .expect("does not refuse") .expect("warns"); assert!( warning.to_lowercase().contains("could not read"), "{warning}" ); } } #[test] fn assert_fts5_compiled_refuses_a_definite_absence_and_names_the_fix() { assert_eq!(assert_fts5_compiled(Some(1.0)).expect("quiet"), None); let error = assert_fts5_compiled(Some(0.0)).expect_err("refuses"); let message = error.to_string(); assert!(message.contains("WITHOUT FTS5"), "got {message}"); // Where the build comes from IS the whole answer: there is no flag to // flip any more, so the message must send the reader at the SQLite the // connection actually got rather than at a manifest. assert!(message.contains("rusqlite's `bundled` feature"), "got {message}"); assert!(message.contains("crates/Cargo.toml"), "got {message}"); } #[test] fn assert_fts5_compiled_reports_but_does_not_refuse_when_it_could_not_read() { for unreadable in [None, Some(f64::NAN)] { let warning = assert_fts5_compiled(unreadable) .expect("does not refuse") .expect("warns"); assert!( warning.to_lowercase().contains("could not read"), "{warning}" ); } } #[test] fn a_savepoint_name_never_collides_with_the_folds_own() { // The fold issues `SAVEPOINT sp_` through `exec`, inside the caller's // transaction. A nested `transaction` must not shadow one, or its // `ROLLBACK TO` would unwind to the wrong place. let db = Driver::open_in_memory().expect("opens"); db.exec("CREATE TABLE t (id TEXT PRIMARY KEY)") .expect("creates"); db.transaction(|db| { db.exec("SAVEPOINT sp_1")?; db.run("INSERT INTO t VALUES ('fold')", &[])?; db.transaction(|db| db.run("INSERT INTO t VALUES ('nested')", &[]))?; db.exec("ROLLBACK TO sp_1")?; db.exec("RELEASE sp_1")?; Ok(()) }) .expect("commits"); // The fold's own rollback took BOTH rows, because both were written after // its savepoint — which is exactly what it means for the nested // transaction to have joined rather than shadowed. assert_eq!(db.all("SELECT * FROM t", &[]).expect("reads").len(), 0); } /// The SQLite compiled into every Cotton binary is 3.51.3 or later. /// /// 3.51.0 added a check to the unix VFS (`unixIsSharingShmNode`) that takes /// the process-wide VFS mutex while `unixLock` already holds the file's inode /// mutex; `unixClose` takes the same two in the opposite order. Two /// connections to one WAL file closing on two threads — what a server restart /// does to `registry.db` — deadlock with no holder in sight: the `swift` job of /// PR #1148's run 975 sat in exactly that for 25 minutes. 3.51.2 fixed it /// ("an obscure deadlock in the new broken-posix-lock detection logic"), and /// 3.51.3 fixed the WAL-reset corruption bug on top. `bundled` means the /// version comes from `libsqlite3-sys`, so a rusqlite downgrade is the only way /// back to the broken one, and this is what refuses it. #[test] fn the_bundled_sqlite_has_the_unix_vfs_deadlock_and_wal_reset_fixes() { assert!( rusqlite::version_number() >= 3_051_003, "bundled SQLite is {}, older than 3.51.3", rusqlite::version() ); } /// RULE: A write transaction holds the write lock from its BEGIN, so a transaction that reads first is never refused "database is locked" because another connection (litestream on a served file) committed between its read and its write. #[test] fn a_transaction_that_reads_first_still_writes_while_another_connection_wants_the_file() { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("life.db"); let db = Driver::open(&path).expect("opens"); db.exec("CREATE TABLE t (n INTEGER)").expect("a table"); // The other connection: litestream's stand-in, which does not wait. let other = rusqlite::Connection::open(&path).expect("a second connection"); other.pragma_update(None, "busy_timeout", 0).expect("no wait"); db.transaction(|db| { // The read every mint makes first. db.get("SELECT count(*) AS n FROM t", &[])?; // The other connection cannot commit under this transaction's snapshot… let refused = other.execute("INSERT INTO t VALUES (2)", []); assert!(refused.is_err(), "the write lock is held from BEGIN"); // …so this transaction's own write stands. db.run("INSERT INTO t VALUES (1)", &[])?; Ok(()) }) .expect("the write is not refused"); other.execute("INSERT INTO t VALUES (2)", []).expect("the other connection writes once the file is free"); assert_eq!(db.get("SELECT count(*) AS n FROM t", &[]).expect("reads").and_then(|row| row.int("n")), Some(2)); } /// RULE: A read-only handle's transaction takes no write lock: it begins deferred and reads beside a writer that holds the file. #[test] fn a_readers_transaction_takes_no_write_lock() { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("life.db"); let db = Driver::open(&path).expect("opens"); db.exec("CREATE TABLE t (n INTEGER)").expect("a table"); let reader = Driver::open_reader(&path).expect("a reader"); db.transaction(|db| { db.run("INSERT INTO t VALUES (1)", &[])?; let seen = reader.transaction(|reader| reader.get("SELECT count(*) AS n FROM t", &[]))?; assert_eq!(seen.and_then(|row| row.int("n")), Some(0), "the last committed snapshot"); Ok(()) }) .expect("both transactions run"); } /// RULE: a read transaction never asks for the file's write lock — it answers while another connection holds it; only a transaction that may write waits for it. #[test] fn a_read_transaction_answers_while_another_connection_holds_the_write_lock() { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("life.db"); let db = Driver::open(&path).expect("opens"); db.exec("CREATE TABLE t (n INTEGER); INSERT INTO t VALUES (7)").expect("seeds"); // The replicator beside the app, mid-checkpoint: another connection that // has the write lock and is in no hurry. let other = rusqlite::Connection::open(&path).expect("a second connection"); other.execute_batch("BEGIN IMMEDIATE; INSERT INTO t VALUES (8)").expect("takes the write lock"); // The wait is thirty seconds on a real handle; cut here so the one that // asks is told at once. db.connection().busy_timeout(std::time::Duration::from_millis(400)).expect("a short ceiling"); let before = (db.steps(), db.time_inside()); db.take_slowest(); let read = db.read_transaction(|db| Ok(db.get("SELECT COUNT(*) AS n FROM t", &[])?.and_then(|row| row.int("n")))); assert_eq!(read.expect("a read waits for nobody"), Some(1), "and it reads what is committed"); assert_eq!(db.take_slowest(), None, "nothing waited"); // The same body as a transaction that may write stands behind the other // connection — and the wait is NO STEPS, which is why a hold also says its // time inside SQLite and the statement that spent it. let steps = db.steps(); let write = db.transaction(|db| Ok(db.get("SELECT COUNT(*) AS n FROM t", &[])?.and_then(|row| row.int("n")))); assert!(write.is_err(), "a transaction that may write asks for the lock at BEGIN"); assert_eq!(db.steps(), steps, "waiting for a lock is not a step"); assert!(db.time_inside() - before.1 >= SLOW_STATEMENT, "but it is time inside SQLite"); let (took, sql) = db.take_slowest().expect("the statement that waited is named"); assert!(took >= SLOW_STATEMENT && sql == "BEGIN IMMEDIATE", "{took:?} {sql}"); assert!(before.0 <= steps); other.execute_batch("ROLLBACK").expect("lets go"); } /// RULE: Cached counts follow the SQLite snapshot, including local writes, another connection's commits and rollback; a page must never reuse an uncommitted total. #[test] fn cached_counts_follow_writes_and_rollback() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("counts.sqlite"); let db = Driver::open(&path).unwrap(); db.exec("CREATE TABLE counted (id INTEGER PRIMARY KEY)").unwrap(); let count = || db.cached_counts("counted", || { Ok(vec![db.get("SELECT count(*) AS n FROM counted", &[])?.unwrap().int("n").unwrap()]) }).unwrap()[0]; assert_eq!(count(), 0); assert_eq!(db.cached_counts("counted", || panic!("unchanged count must be reused")).unwrap(), vec![0]); db.run("INSERT INTO counted VALUES (1)", &[]).unwrap(); assert_eq!(count(), 1); let outcome: Result<()> = db.transaction(|db| { db.run("INSERT INTO counted VALUES (2)", &[])?; assert_eq!(count(), 2); Err(StoreError::refused("synthetic rollback")) }); assert!(outcome.is_err()); assert_eq!(count(), 1); let peer = Driver::open(&path).unwrap(); peer.run("INSERT INTO counted VALUES (3)", &[]).unwrap(); db.read_transaction(|_| { assert_eq!(count(), 2); Ok(()) }).unwrap(); db.read_transaction(|_| { assert_eq!(count(), 2); peer.run("INSERT INTO counted VALUES (4)", &[])?; assert_eq!(count(), 2, "the open read keeps its snapshot"); Ok(()) }).unwrap(); assert_eq!(count(), 3, "the next snapshot sees the peer's commit"); db.exec("DROP TABLE counted; CREATE TABLE counted (id INTEGER PRIMARY KEY)").unwrap(); assert_eq!(count(), 0, "local schema changes do not increment total_changes"); } /// RULE: once the serving process sets its page cache, every connection the driver opens keeps it, because SQLite's 2 MB default made the serving Mac's reads 2.5–3.5x slower beside its other connections (12 Oct 2026). #[test] fn a_serving_process_opens_every_connection_with_its_page_cache() { crate::driver::serve_with_page_cache(crate::driver::SERVING_PAGE_CACHE_KIB); let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("served.db"); let writer = Driver::open(&path).unwrap(); let reader = Driver::open_reader(&path).unwrap(); for (who, db) in [("writer", &writer), ("reader", &reader)] { let size = db.get("PRAGMA cache_size", &[]).unwrap().and_then(|row| row.int("cache_size")); assert_eq!(size, Some(-crate::driver::SERVING_PAGE_CACHE_KIB), "the {who}'s page cache"); } } /// RULE: Table-presence caching follows local and peer DDL and rollback, including reused schema versions, so a fold never overlooks the audience safety table or rescans the file for each record. #[test] fn table_presence_cache_follows_ddl_and_rollback() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("synthetic.db"); let db = Driver::open(&path).unwrap(); let peer = Driver::open(&path).unwrap(); assert!(!db.table_exists("synthetic_a").unwrap()); db.exec("CREATE TABLE synthetic_a (id TEXT)").unwrap(); assert!(db.table_exists("synthetic_a").unwrap()); db.exec("SAVEPOINT presence; CREATE TABLE synthetic_b (id TEXT)").unwrap(); assert!(db.table_exists("synthetic_b").unwrap()); db.exec("ROLLBACK TO presence; RELEASE presence; CREATE TABLE synthetic_c (id TEXT)").unwrap(); assert!(!db.table_exists("synthetic_b").unwrap()); assert!(db.table_exists("synthetic_c").unwrap()); peer.exec("DROP TABLE synthetic_a").unwrap(); assert!(!db.table_exists("synthetic_a").unwrap()); db.exec("BEGIN").unwrap(); assert!(!db.table_exists("synthetic_d").unwrap()); peer.exec("CREATE TABLE synthetic_d (id TEXT)").unwrap(); assert!(!db.table_exists("synthetic_d").unwrap()); db.exec("COMMIT").unwrap(); assert!(db.table_exists("synthetic_d").unwrap()); db.watch_statements(); for _ in 0..100 { assert!(db.table_exists("synthetic_d").unwrap()); } assert!(db.statements_seen().iter().all(|sql| !sql.contains("sqlite_schema") && !sql.contains("sqlite_master"))); } /// RULE: Bulk index deferral is scoped to its import, including nested calls /// and unwinding, so later ordinary writes keep their original index policy. #[test] fn bulk_index_deferral_restores_the_handles_policy() { let db = Driver::open_in_memory().unwrap(); assert!(!db.indexes_beside()); let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { db.with_index_beside(|| { assert!(db.indexes_beside()); db.with_index_beside(|| assert!(db.indexes_beside())); assert!(db.indexes_beside()); panic!("synthetic interrupted import"); }); })); assert!(result.is_err()); assert!(!db.indexes_beside()); let db = db.index_beside(); db.with_index_beside(|| assert!(db.indexes_beside())); assert!(db.indexes_beside()); } /// Every commit a handle makes is counted on its thread: a transaction's /// writes are one, each lone write its own, a savepoint none, and a rolled /// back transaction none. #[test] fn every_commit_is_counted_once_on_its_thread() { let db = Driver::open_in_memory().expect("opens"); db.exec("CREATE TABLE t (x)").expect("a table"); let before = Driver::thread_commits(); db.transaction(|db| { for x in 0..3 { db.run("INSERT INTO t VALUES (?)", &[rusqlite::types::Value::Integer(x)])?; } db.transaction(|db| db.run("INSERT INTO t VALUES (9)", &[]).map(|_| ())) }) .expect("one transaction"); assert_eq!(Driver::thread_commits() - before, 1, "one transaction, savepoint and all, is one commit"); for x in 0..3 { db.run("INSERT INTO t VALUES (?)", &[rusqlite::types::Value::Integer(x)]).expect("a lone write"); } assert_eq!(Driver::thread_commits() - before, 4, "each lone write is its own commit"); let _ = db.transaction(|db| { db.run("INSERT INTO t VALUES (7)", &[])?; Err::<(), _>(crate::StoreError::refused("invented")) }); assert_eq!(Driver::thread_commits() - before, 4, "a rolled back transaction commits nothing"); } /// RULE: a change stamp moves on this connection's own write and on another /// connection's commit, and two connections never share one: what a screen /// keeps by it is never older than the file. #[test] fn a_change_stamp_moves_on_every_write_from_any_connection() { let dir = tempfile::tempdir().expect("a folder"); let path = dir.path().join("stamp.sqlite"); let reader = Driver::open(&path).expect("opens"); let writer = Driver::open(&path).expect("opens"); writer.exec("CREATE TABLE t (id INTEGER PRIMARY KEY, name TEXT)").expect("made"); let first = reader.change_stamp().expect("a stamp"); assert_eq!(reader.change_stamp().expect("a stamp"), first, "nothing changed"); writer.run("INSERT INTO t (name) VALUES (?)", &[Value::Text("invented".into())]).expect("written"); let after_peer = reader.change_stamp().expect("a stamp"); assert_ne!(after_peer, first, "another connection's commit"); reader.run("UPDATE t SET name = ?", &[Value::Text("renamed".into())]).expect("written"); assert_ne!(reader.change_stamp().expect("a stamp"), after_peer, "this connection's own write"); assert_ne!(writer.change_stamp().expect("a stamp").0, reader.change_stamp().expect("a stamp").0, "each connection its own"); // A handle opened after another closed may sit at its address with the same counts: its stamp is never the // closed one's (Post keeps answers by it, 26 Nov 2026). let closed = writer.change_stamp().expect("a stamp"); drop(writer); let again = Driver::open(&path).expect("opens"); assert_ne!(again.change_stamp().expect("a stamp").0, closed.0, "a later handle never takes a closed one's stamp"); }