mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 15:26: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 {
|
pub fn dir(&self) -> &Path {
|
||||||
&self.dir
|
&self.dir
|
||||||
}
|
}
|
||||||
@@ -154,7 +171,7 @@ impl Graph {
|
|||||||
|
|
||||||
/// Creates a page. Its origin defaults to today's journal (pages are born in journals).
|
/// Creates a page. Its origin defaults to today's journal (pages are born in journals).
|
||||||
pub fn create_page(&self, new: NewPage) -> Result<Page> {
|
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)?;
|
let page = self.create_page_tx(new)?;
|
||||||
tx.commit()?;
|
tx.commit()?;
|
||||||
Ok(page)
|
Ok(page)
|
||||||
@@ -184,6 +201,16 @@ impl Graph {
|
|||||||
Ok(page)
|
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.
|
/// 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> {
|
pub fn ensure_page(&self, title: &str, origin: Option<NaiveDate>) -> Result<Page> {
|
||||||
if let Some(p) = self.page_by_title(title)? {
|
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.
|
/// Renames a page and rewrites `[[Old]]` / `#Old` in every referencing block.
|
||||||
pub fn rename_page(&self, id: PageId, new_title: &str) -> Result<Page> {
|
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
|
let mut page = self
|
||||||
.get_page(id)?
|
.get_page(id)?
|
||||||
.ok_or_else(|| Error::NotFound(id.to_string()))?;
|
.ok_or_else(|| Error::NotFound(id.to_string()))?;
|
||||||
@@ -277,7 +304,7 @@ impl Graph {
|
|||||||
|
|
||||||
/// Deletes a page and all its blocks.
|
/// Deletes a page and all its blocks.
|
||||||
pub fn delete_page(&self, id: PageId) -> Result<()> {
|
pub fn delete_page(&self, id: PageId) -> Result<()> {
|
||||||
let tx = self.conn.unchecked_transaction()?;
|
let tx = self.tx()?;
|
||||||
let ids: Vec<String> = {
|
let ids: Vec<String> = {
|
||||||
let mut st = self
|
let mut st = self
|
||||||
.conn
|
.conn
|
||||||
@@ -318,7 +345,7 @@ impl Graph {
|
|||||||
|
|
||||||
/// The journal page for `date`, created if missing.
|
/// The journal page for `date`, created if missing.
|
||||||
pub fn journal(&self, date: NaiveDate) -> Result<Page> {
|
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)?;
|
let p = self.ensure_journal_tx(date)?;
|
||||||
tx.commit()?;
|
tx.commit()?;
|
||||||
Ok(p)
|
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.
|
/// Journals in `[from, to]`, newest first.
|
||||||
pub fn journals_between(&self, from: NaiveDate, to: NaiveDate) -> Result<Vec<Page>> {
|
pub fn journals_between(&self, from: NaiveDate, to: NaiveDate) -> Result<Vec<Page>> {
|
||||||
let mut st = self.conn.prepare_cached(&format!(
|
let mut st = self.conn.prepare_cached(&format!(
|
||||||
@@ -476,7 +513,7 @@ impl Graph {
|
|||||||
|
|
||||||
/// Inserts a new block with `content` and indexes its refs.
|
/// Inserts a new block with `content` and indexes its refs.
|
||||||
pub fn insert_block(&self, page: PageId, at: Placement, content: &str) -> Result<Block> {
|
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 (parent_id, position) = self.resolve_placement(page, at)?;
|
||||||
let now = self.now_ms();
|
let now = self.now_ms();
|
||||||
let block = Block {
|
let block = Block {
|
||||||
@@ -498,7 +535,7 @@ impl Graph {
|
|||||||
/// Writes a fully specified block (importer). Pages referenced by it are created, born in
|
/// 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.
|
/// the block's journal when it lives in one. Does not record edit activity.
|
||||||
pub fn put_block(&self, block: &Block) -> Result<()> {
|
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.write_block(block, &self.tick())?;
|
||||||
self.ensure_ref_pages(block)?;
|
self.ensure_ref_pages(block)?;
|
||||||
tx.commit()?;
|
tx.commit()?;
|
||||||
@@ -506,7 +543,7 @@ impl Graph {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_block(&self, id: BlockId, content: &str) -> Result<Block> {
|
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
|
let mut b = self
|
||||||
.get_block(id)?
|
.get_block(id)?
|
||||||
.ok_or_else(|| Error::NotFound(id.to_string()))?;
|
.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> {
|
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
|
let mut b = self
|
||||||
.get_block(id)?
|
.get_block(id)?
|
||||||
.ok_or_else(|| Error::NotFound(id.to_string()))?;
|
.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.
|
/// 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> {
|
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
|
let mut b = self
|
||||||
.get_block(id)?
|
.get_block(id)?
|
||||||
.ok_or_else(|| Error::NotFound(id.to_string()))?;
|
.ok_or_else(|| Error::NotFound(id.to_string()))?;
|
||||||
@@ -575,7 +612,7 @@ impl Graph {
|
|||||||
|
|
||||||
/// Deletes a block and its subtree.
|
/// Deletes a block and its subtree.
|
||||||
pub fn delete_block(&self, id: BlockId) -> Result<()> {
|
pub fn delete_block(&self, id: BlockId) -> Result<()> {
|
||||||
let tx = self.conn.unchecked_transaction()?;
|
let tx = self.tx()?;
|
||||||
let b = self
|
let b = self
|
||||||
.get_block(id)?
|
.get_block(id)?
|
||||||
.ok_or_else(|| Error::NotFound(id.to_string()))?;
|
.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.
|
/// Returns whether it changed local state. Applied ops are re-logged locally.
|
||||||
pub fn apply_remote(&self, hlc: &str, op: &Op) -> Result<bool> {
|
pub fn apply_remote(&self, hlc: &str, op: &Op) -> Result<bool> {
|
||||||
self.clock.observe(hlc);
|
self.clock.observe(hlc);
|
||||||
let tx = self.conn.unchecked_transaction()?;
|
let tx = self.tx()?;
|
||||||
let newer = |table: &str, id: &str| -> Result<bool> {
|
let newer = |table: &str, id: &str| -> Result<bool> {
|
||||||
let local: Option<String> = self
|
let local: Option<String> = self
|
||||||
.conn
|
.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>(
|
fn entry<'a>(
|
||||||
days: &'a mut std::collections::BTreeMap<String, TimelineDay>,
|
days: &'a mut std::collections::BTreeMap<String, TimelineDay>,
|
||||||
d: &str,
|
d: &str,
|
||||||
|
|||||||
@@ -186,3 +186,42 @@ fn assets_are_deduplicated() {
|
|||||||
assert_eq!(a, b);
|
assert_eq!(a, b);
|
||||||
assert!(g.blobs().contains(&a.hash));
|
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>> {
|
pub fn journals(&self, before: Option<String>, limit: u32) -> Result<Vec<PageData>> {
|
||||||
let g = self.lock();
|
let g = self.lock();
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
let mut cursor = match before {
|
let cursor = match before {
|
||||||
None => {
|
None => {
|
||||||
let today = g.today_journal()?;
|
let today = g.today_journal()?;
|
||||||
let date = today.journal_date;
|
let date = today.journal_date;
|
||||||
@@ -135,14 +135,10 @@ impl SynapseGraph {
|
|||||||
}
|
}
|
||||||
Some(b) => Some(parse_date(&b)?),
|
Some(b) => Some(parse_date(&b)?),
|
||||||
};
|
};
|
||||||
while (out.len() as u32) < limit {
|
if (out.len() as u32) < limit {
|
||||||
let Some(d) = cursor else { break };
|
for page in g.journals_before(cursor, limit - out.len() as u32)? {
|
||||||
let Some(prev) = g.journal_neighbors(d)?.prev else {
|
out.push(page_view(&g, &page)?);
|
||||||
break;
|
}
|
||||||
};
|
|
||||||
let page = g.journal(prev)?;
|
|
||||||
out.push(page_view(&g, &page)?);
|
|
||||||
cursor = Some(prev);
|
|
||||||
}
|
}
|
||||||
Ok(out)
|
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
|
// One transaction for the whole write phase: much faster, and a failed import leaves the
|
||||||
// only needs a re-import (idempotent), so durability per commit is not required.
|
// graph untouched.
|
||||||
let _ = graph.conn().pragma_update(None, "synchronous", "OFF");
|
graph.transaction(|g| write_all(g, opts, &docs, &origin, &mut report, &mut progress))?;
|
||||||
let result = write_all(graph, opts, &docs, &origin, &mut report, &mut progress);
|
|
||||||
let _ = graph.conn().pragma_update(None, "synchronous", "NORMAL");
|
|
||||||
result?;
|
|
||||||
Ok(report)
|
Ok(report)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user