diff --git a/crates/synapse-core/src/store.rs b/crates/synapse-core/src/store.rs index ab9e133..726cfd8 100644 --- a/crates/synapse-core/src/store.rs +++ b/crates/synapse-core/src/store.rs @@ -78,6 +78,23 @@ impl Graph { }) } + /// Runs `f` atomically. Calls nest (SQLite savepoints), so callers such as importers can + /// group many graph operations into one transaction. + pub fn transaction(&self, f: impl FnOnce(&Graph) -> Result) -> Result { + let tx = self.tx()?; + let out = f(self)?; + tx.commit()?; + Ok(out) + } + + fn tx(&self) -> Result> { + self.conn.execute_batch("SAVEPOINT graph")?; + Ok(Tx { + conn: &self.conn, + done: false, + }) + } + pub fn dir(&self) -> &Path { &self.dir } @@ -154,7 +171,7 @@ impl Graph { /// Creates a page. Its origin defaults to today's journal (pages are born in journals). pub fn create_page(&self, new: NewPage) -> Result { - let tx = self.conn.unchecked_transaction()?; + let tx = self.tx()?; let page = self.create_page_tx(new)?; tx.commit()?; Ok(page) @@ -184,6 +201,16 @@ impl Graph { Ok(page) } + /// Writes a fully specified page as-is, keeping its timestamps (importers, restore). + pub fn put_page(&self, page: &Page) -> Result<()> { + let tx = self.tx()?; + if let Some(o) = page.origin_journal { + self.ensure_journal_tx(o)?; + } + self.write_page(page, &self.tick())?; + tx.commit() + } + /// Returns the page with this title, creating it (born in `origin`) if missing. pub fn ensure_page(&self, title: &str, origin: Option) -> Result { if let Some(p) = self.page_by_title(title)? { @@ -235,7 +262,7 @@ impl Graph { /// Renames a page and rewrites `[[Old]]` / `#Old` in every referencing block. pub fn rename_page(&self, id: PageId, new_title: &str) -> Result { - let tx = self.conn.unchecked_transaction()?; + let tx = self.tx()?; let mut page = self .get_page(id)? .ok_or_else(|| Error::NotFound(id.to_string()))?; @@ -277,7 +304,7 @@ impl Graph { /// Deletes a page and all its blocks. pub fn delete_page(&self, id: PageId) -> Result<()> { - let tx = self.conn.unchecked_transaction()?; + let tx = self.tx()?; let ids: Vec = { let mut st = self .conn @@ -318,7 +345,7 @@ impl Graph { /// The journal page for `date`, created if missing. pub fn journal(&self, date: NaiveDate) -> Result { - let tx = self.conn.unchecked_transaction()?; + let tx = self.tx()?; let p = self.ensure_journal_tx(date)?; tx.commit()?; Ok(p) @@ -369,6 +396,16 @@ impl Graph { }) } + /// Up to `limit` journals strictly before `before` (or the newest ones), newest first. + pub fn journals_before(&self, before: Option, limit: u32) -> Result> { + let mut st = self.conn.prepare_cached(&format!( + "SELECT {PAGE_COLS} FROM pages WHERE journal_date IS NOT NULL AND (?1 IS NULL OR journal_date < ?1) + ORDER BY journal_date DESC LIMIT ?2" + ))?; + let rows = st.query_map(params![before.map(journal_title), limit], page_row)?; + Ok(rows.collect::>()?) + } + /// Journals in `[from, to]`, newest first. pub fn journals_between(&self, from: NaiveDate, to: NaiveDate) -> Result> { let mut st = self.conn.prepare_cached(&format!( @@ -476,7 +513,7 @@ impl Graph { /// Inserts a new block with `content` and indexes its refs. pub fn insert_block(&self, page: PageId, at: Placement, content: &str) -> Result { - let tx = self.conn.unchecked_transaction()?; + let tx = self.tx()?; let (parent_id, position) = self.resolve_placement(page, at)?; let now = self.now_ms(); let block = Block { @@ -498,7 +535,7 @@ impl Graph { /// Writes a fully specified block (importer). Pages referenced by it are created, born in /// the block's journal when it lives in one. Does not record edit activity. pub fn put_block(&self, block: &Block) -> Result<()> { - let tx = self.conn.unchecked_transaction()?; + let tx = self.tx()?; self.write_block(block, &self.tick())?; self.ensure_ref_pages(block)?; tx.commit()?; @@ -506,7 +543,7 @@ impl Graph { } pub fn update_block(&self, id: BlockId, content: &str) -> Result { - let tx = self.conn.unchecked_transaction()?; + let tx = self.tx()?; let mut b = self .get_block(id)? .ok_or_else(|| Error::NotFound(id.to_string()))?; @@ -520,7 +557,7 @@ impl Graph { } pub fn set_block_properties(&self, id: BlockId, properties: Properties) -> Result { - let tx = self.conn.unchecked_transaction()?; + let tx = self.tx()?; let mut b = self .get_block(id)? .ok_or_else(|| Error::NotFound(id.to_string()))?; @@ -541,7 +578,7 @@ impl Graph { /// Moves a block (with its subtree) to a new place, possibly on another page. pub fn move_block(&self, id: BlockId, page: PageId, at: Placement) -> Result { - let tx = self.conn.unchecked_transaction()?; + let tx = self.tx()?; let mut b = self .get_block(id)? .ok_or_else(|| Error::NotFound(id.to_string()))?; @@ -575,7 +612,7 @@ impl Graph { /// Deletes a block and its subtree. pub fn delete_block(&self, id: BlockId) -> Result<()> { - let tx = self.conn.unchecked_transaction()?; + let tx = self.tx()?; let b = self .get_block(id)? .ok_or_else(|| Error::NotFound(id.to_string()))?; @@ -891,7 +928,7 @@ impl Graph { /// Returns whether it changed local state. Applied ops are re-logged locally. pub fn apply_remote(&self, hlc: &str, op: &Op) -> Result { self.clock.observe(hlc); - let tx = self.conn.unchecked_transaction()?; + let tx = self.tx()?; let newer = |table: &str, id: &str| -> Result { let local: Option = self .conn @@ -1130,6 +1167,28 @@ impl Graph { } } +/// Savepoint guard: rolled back on drop unless committed. +struct Tx<'a> { + conn: &'a Connection, + done: bool, +} + +impl Tx<'_> { + fn commit(mut self) -> Result<()> { + self.conn.execute_batch("RELEASE graph")?; + self.done = true; + Ok(()) + } +} + +impl Drop for Tx<'_> { + fn drop(&mut self) { + if !self.done { + let _ = self.conn.execute_batch("ROLLBACK TO graph; RELEASE graph"); + } + } +} + fn entry<'a>( days: &'a mut std::collections::BTreeMap, d: &str, diff --git a/crates/synapse-core/tests/graph.rs b/crates/synapse-core/tests/graph.rs index c853c99..5d896ef 100644 --- a/crates/synapse-core/tests/graph.rs +++ b/crates/synapse-core/tests/graph.rs @@ -186,3 +186,42 @@ fn assets_are_deduplicated() { assert_eq!(a, b); assert!(g.blobs().contains(&a.hash)); } + +#[test] +fn transactions_nest_and_roll_back() { + let (_d, g) = graph(); + let r: synapse_core::Result<()> = g.transaction(|g| { + g.create_page(NewPage::titled("Kept?"))?; + Err(synapse_core::Error::Invalid("abort".into())) + }); + assert!(r.is_err()); + assert!(g.page_by_title("Kept?").unwrap().is_none()); + g.transaction(|g| { + let p = g.create_page(NewPage::titled("Outer"))?; + g.insert_block(p.id, Placement::LastChildOf(None), "inner tx")?; + Ok(()) + }) + .unwrap(); + assert!(g.page_by_title("Outer").unwrap().is_some()); +} + +#[test] +fn journals_before_pages_backwards() { + let (_d, g) = graph(); + for d in [1, 3, 7] { + g.journal(day(2026, 10, d)).unwrap(); + } + let titles = |v: Vec| { + v.into_iter() + .map(|p| p.journal_date.unwrap()) + .collect::>() + }; + assert_eq!( + titles(g.journals_before(None, 2).unwrap()), + vec![day(2026, 10, 7), day(2026, 10, 3)] + ); + assert_eq!( + titles(g.journals_before(Some(day(2026, 10, 3)), 5).unwrap()), + vec![day(2026, 10, 1)] + ); +} diff --git a/crates/synapse-ffi/src/api/graph.rs b/crates/synapse-ffi/src/api/graph.rs index 92499eb..9a5dd2f 100644 --- a/crates/synapse-ffi/src/api/graph.rs +++ b/crates/synapse-ffi/src/api/graph.rs @@ -126,7 +126,7 @@ impl SynapseGraph { pub fn journals(&self, before: Option, limit: u32) -> Result> { let g = self.lock(); let mut out = Vec::new(); - let mut cursor = match before { + let cursor = match before { None => { let today = g.today_journal()?; let date = today.journal_date; @@ -135,14 +135,10 @@ impl SynapseGraph { } Some(b) => Some(parse_date(&b)?), }; - while (out.len() as u32) < limit { - let Some(d) = cursor else { break }; - let Some(prev) = g.journal_neighbors(d)?.prev else { - break; - }; - let page = g.journal(prev)?; - out.push(page_view(&g, &page)?); - cursor = Some(prev); + if (out.len() as u32) < limit { + for page in g.journals_before(cursor, limit - out.len() as u32)? { + out.push(page_view(&g, &page)?); + } } Ok(out) } diff --git a/crates/synapse-import/src/lib.rs b/crates/synapse-import/src/lib.rs index 17f793c..7fb6ad1 100644 --- a/crates/synapse-import/src/lib.rs +++ b/crates/synapse-import/src/lib.rs @@ -182,12 +182,9 @@ pub fn import_logseq( } } - // Every core write commits on its own; without fsyncs that is cheap. A crash mid-import - // only needs a re-import (idempotent), so durability per commit is not required. - let _ = graph.conn().pragma_update(None, "synchronous", "OFF"); - let result = write_all(graph, opts, &docs, &origin, &mut report, &mut progress); - let _ = graph.conn().pragma_update(None, "synchronous", "NORMAL"); - result?; + // One transaction for the whole write phase: much faster, and a failed import leaves the + // graph untouched. + graph.transaction(|g| write_all(g, opts, &docs, &origin, &mut report, &mut progress))?; Ok(report) }