//! Bounded primary-key seeks for consumers of every receipt in one table. use crate::{ driver::{Driver, Row}, error::Result, }; use rusqlite::types::Value; pub const PAGE_SIZE: i64 = 64; pub const FIRST_PAGE: &str = "SELECT * FROM _writes WHERE tbl = ?1 ORDER BY row_id, hlc LIMIT ?2"; pub const NEXT_PAGE: &str = "SELECT * FROM _writes WHERE tbl = ?1 AND (row_id, hlc) > (?2, ?3) ORDER BY row_id, hlc LIMIT ?4"; pub struct TablePages { table: String, cursor: Option<(String, String)>, done: bool, } impl TablePages { pub fn new(table: &str) -> Self { Self { table: table.into(), cursor: None, done: false, } } pub fn next(&mut self, db: &Driver) -> Result>> { if self.done { return Ok(None); } let rows = if let Some((row, hlc)) = &self.cursor { db.all( NEXT_PAGE, &[ self.table.clone().into(), row.clone().into(), hlc.clone().into(), PAGE_SIZE.into(), ], )? } else { db.all( FIRST_PAGE, &[Value::Text(self.table.clone()), PAGE_SIZE.into()], )? }; if let Some(last) = rows.last() { self.cursor = Some(( last.text("row_id").unwrap().into(), last.text("hlc").unwrap().into(), )); } self.done = rows.len() < PAGE_SIZE as usize; Ok(Some(rows)) } } #[cfg(test)] mod tests { use super::*; /// RULE: Receipt consumers seek at most 64 rows per read; repeated row ids, empty stamps and NULL bytes must survive page boundaries without a whole-table sort holding the writer. #[test] fn million_receipts_table_consumers_seek_bounded_pages() { let dir = tempfile::tempdir().unwrap(); let db = Driver::open(dir.path().join("synthetic.db")).unwrap(); crate::fixtures::build_at_version(&db, crate::migrate::SCHEMA_VERSION); db.exec("WITH RECURSIVE n(x) AS (VALUES(0) UNION ALL SELECT x+1 FROM n WHERE x<999999) INSERT INTO _writes(tbl,row_id,hlc) SELECT 'cotton_todos',printf('%08d',x/130),CASE WHEN x%130=0 THEN '' ELSE printf('%08d',x) END FROM n").unwrap(); db.exec("INSERT INTO _cursors(author_device_id,hlc_seen,updated_at) SELECT printf('%08d',rowid),'seen','now' FROM _writes WHERE rowid<=1000").unwrap(); db.exec("INSERT INTO _tombstones(tbl,row_id,hlc,op_id,author,actor,bytes) SELECT tbl,row_id,max(hlc),row_id,'a','a',X'7B7D' FROM _writes GROUP BY tbl,row_id").unwrap(); for (sql, params, index) in [ ( FIRST_PAGE, vec!["cotton_todos".to_string().into(), PAGE_SIZE.into()], "sqlite_autoindex__writes_2", ), ( NEXT_PAGE, vec![ "cotton_todos".to_string().into(), "00000000".to_string().into(), "".to_string().into(), PAGE_SIZE.into(), ], "sqlite_autoindex__writes_2", ), ( crate::keep::KEEP_WRITES_PAGE, vec!["cotton_todos".to_string().into(), "".to_string().into()], "sqlite_autoindex__writes_2", ), ( crate::keep::KEEP_TOMBSTONES_PAGE, vec!["cotton_todos".to_string().into(), "".to_string().into()], "sqlite_autoindex__tombstones_1", ), ( crate::cursors::FIRST_CURSORS_PAGE, vec!["".to_string().into()], "sqlite_autoindex__cursors_1", ), ( crate::cursors::CURSORS_PAGE, vec!["00000064".to_string().into()], "sqlite_autoindex__cursors_1", ), ] { let plan = db .all(&format!("EXPLAIN QUERY PLAN {sql}"), ¶ms) .unwrap(); assert!( plan.iter().any(|r| r .text("detail") .is_some_and(|s| s.contains("SEARCH") && s.contains(index))), "{plan:?}" ); assert!( !plan.iter().any(|r| r .text("detail") .is_some_and(|s| s.contains("SCAN") || s.contains("TEMP B-TREE"))), "{plan:?}" ); assert!(db.all(sql, ¶ms).unwrap().len() <= PAGE_SIZE as usize); } let mut pages = TablePages::new("cotton_todos"); let mut total = 0; while let Some(rows) = pages.next(&db).unwrap() { assert!(rows.len() <= PAGE_SIZE as usize); total += rows.len(); } assert_eq!(total, 1_000_000); assert_eq!(crate::cursors::read_cursors(&db).unwrap().len(), 1000); assert!(TablePages::new("absent") .next(&db) .unwrap() .unwrap() .is_empty()); } }