mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 07:16:17 +00:00
feat(core): nestable transactions, put_page and journals_before
Importer runs its write phase in one transaction (replaces the synchronous=OFF workaround); the FFI journals feed uses journals_before instead of walking back one day per query. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
537d70bb55
commit
30d58a0166
4 files changed
+117
-26
No files matched your search
@@ -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<T>(&self, f: impl FnOnce(&Graph) -> Result<T>) -> Result<T> {
|
||||
let tx = self.tx()?;
|
||||
let out = f(self)?;
|
||||
tx.commit()?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn tx(&self) -> Result<Tx<'_>> {
|
||||
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<Page> {
|
||||
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<NaiveDate>) -> Result<Page> {
|
||||
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<Page> {
|
||||
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<String> = {
|
||||
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<Page> {
|
||||
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<NaiveDate>, limit: u32) -> Result<Vec<Page>> {
|
||||
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::<std::result::Result<_, _>>()?)
|
||||
}
|
||||
|
||||
/// Journals in `[from, to]`, newest first.
|
||||
pub fn journals_between(&self, from: NaiveDate, to: NaiveDate) -> Result<Vec<Page>> {
|
||||
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<Block> {
|
||||
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<Block> {
|
||||
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<Block> {
|
||||
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<Block> {
|
||||
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<bool> {
|
||||
self.clock.observe(hlc);
|
||||
let tx = self.conn.unchecked_transaction()?;
|
||||
let tx = self.tx()?;
|
||||
let newer = |table: &str, id: &str| -> Result<bool> {
|
||||
let local: Option<String> = 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<String, TimelineDay>,
|
||||
d: &str,
|
||||
|
||||
@@ -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<synapse_core::Page>| {
|
||||
v.into_iter()
|
||||
.map(|p| p.journal_date.unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
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)]
|
||||
);
|
||||
}
|
||||
@@ -126,7 +126,7 @@ impl SynapseGraph {
|
||||
pub fn journals(&self, before: Option<String>, limit: u32) -> Result<Vec<PageData>> {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user