mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 23:36:20 +00:00
Merge branch 'refs/heads/claude/import-96e10a' into feat/integration
This commit is contained in:
commit
6a4a76670b
5 files changed
+500
-67
No files matched your search
@@ -29,7 +29,13 @@ fn main() {
|
|||||||
let report = import_logseq(src, &graph, &opts, |p| {
|
let report = import_logseq(src, &graph, &opts, |p| {
|
||||||
let step = (p.done * 20).checked_div(p.total).unwrap_or(0);
|
let step = (p.done * 20).checked_div(p.total).unwrap_or(0);
|
||||||
if last != (Some(p.phase), step) {
|
if last != (Some(p.phase), step) {
|
||||||
eprintln!("{:?}: {}/{}", p.phase, p.done, p.total);
|
eprintln!(
|
||||||
|
"[{:.1?}] {:?}: {}/{}",
|
||||||
|
started.elapsed(),
|
||||||
|
p.phase,
|
||||||
|
p.done,
|
||||||
|
p.total
|
||||||
|
);
|
||||||
last = (Some(p.phase), step);
|
last = (Some(p.phase), step);
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ mod config;
|
|||||||
mod names;
|
mod names;
|
||||||
mod outline;
|
mod outline;
|
||||||
mod rewrite;
|
mod rewrite;
|
||||||
|
mod track;
|
||||||
|
|
||||||
use chrono::{Local, NaiveDate, TimeZone};
|
use chrono::{Local, NaiveDate, TimeZone};
|
||||||
use config::Config;
|
use config::Config;
|
||||||
@@ -25,6 +26,7 @@ use uuid::Uuid;
|
|||||||
pub use config::DateFormat;
|
pub use config::DateFormat;
|
||||||
|
|
||||||
/// Namespace for deterministic block ids of blocks without a Logseq `id::`.
|
/// Namespace for deterministic block ids of blocks without a Logseq `id::`.
|
||||||
|
/// Namespace of fallback ids (kept for id stability across versions).
|
||||||
const BLOCK_NS: Uuid = Uuid::from_u128(0x2b6d_41c9_0e87_4f3a_9d15_c7a8_e340_5b12);
|
const BLOCK_NS: Uuid = Uuid::from_u128(0x2b6d_41c9_0e87_4f3a_9d15_c7a8_e340_5b12);
|
||||||
const CHUNK: usize = 256;
|
const CHUNK: usize = 256;
|
||||||
|
|
||||||
@@ -184,6 +186,7 @@ pub fn import_logseq(
|
|||||||
|
|
||||||
// One transaction for the whole write phase: much faster, and a failed import leaves the
|
// One transaction for the whole write phase: much faster, and a failed import leaves the
|
||||||
// graph untouched.
|
// graph untouched.
|
||||||
|
track::init(graph)?;
|
||||||
graph.transaction(|g| write_all(g, opts, &docs, &origin, &mut report, &mut progress))?;
|
graph.transaction(|g| write_all(g, opts, &docs, &origin, &mut report, &mut progress))?;
|
||||||
Ok(report)
|
Ok(report)
|
||||||
}
|
}
|
||||||
@@ -213,7 +216,8 @@ fn write_all(
|
|||||||
total: order.len(),
|
total: order.len(),
|
||||||
});
|
});
|
||||||
let d = &docs[i];
|
let d = &docs[i];
|
||||||
match ensure_page(graph, d, origin.get(&d.key).copied()) {
|
let o = origin.get(&d.key).copied();
|
||||||
|
match graph.transaction(|g| ensure_page(g, d, o)) {
|
||||||
Ok(r) => {
|
Ok(r) => {
|
||||||
ids.insert(i, r);
|
ids.insert(i, r);
|
||||||
}
|
}
|
||||||
@@ -237,7 +241,8 @@ fn write_all(
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let d = &docs[i];
|
let d = &docs[i];
|
||||||
match write_doc(graph, d, pid, existed, opts, report) {
|
// A failing document rolls back as a whole and becomes a warning.
|
||||||
|
match graph.transaction(|g| write_doc(g, d, pid, existed, opts, report)) {
|
||||||
Ok(()) => {}
|
Ok(()) => {}
|
||||||
Err(e) => report.warnings.push(format!("{}: {e}", d.rel)),
|
Err(e) => report.warnings.push(format!("{}: {e}", d.rel)),
|
||||||
}
|
}
|
||||||
@@ -452,13 +457,19 @@ fn dedupe(mut docs: Vec<Doc>, warnings: &mut Vec<String>) -> Vec<Doc> {
|
|||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Finds or creates the page row. Returns `(id, already existed)`.
|
/// Finds or creates the page row. Returns `(id, already existed)`. A page previously imported
|
||||||
|
/// from the same file is found by source path, so renames made in Synapse are respected.
|
||||||
fn ensure_page(g: &Graph, d: &Doc, origin: Option<NaiveDate>) -> Result<(PageId, bool)> {
|
fn ensure_page(g: &Graph, d: &Doc, origin: Option<NaiveDate>) -> Result<(PageId, bool)> {
|
||||||
if let Some(date) = d.journal {
|
if let Some(date) = d.journal {
|
||||||
let existed = g.get_page(synapse_core::store::journal_id(date))?.is_some();
|
let existed = g.get_page(synapse_core::store::journal_id(date))?.is_some();
|
||||||
let p = g.journal(date)?;
|
let p = g.journal(date)?;
|
||||||
return Ok((p.id, existed));
|
return Ok((p.id, existed));
|
||||||
}
|
}
|
||||||
|
if let Some(id) = track::page_of(g, &d.rel)?
|
||||||
|
&& g.get_page(id)?.is_some()
|
||||||
|
{
|
||||||
|
return Ok((id, true));
|
||||||
|
}
|
||||||
if let Some(p) = g.page_by_title(&d.title)? {
|
if let Some(p) = g.page_by_title(&d.title)? {
|
||||||
if title_key(&p.title) != d.key {
|
if title_key(&p.title) != d.key {
|
||||||
return Err(synapse_core::Error::Conflict(format!(
|
return Err(synapse_core::Error::Conflict(format!(
|
||||||
@@ -487,94 +498,232 @@ fn write_doc(
|
|||||||
report: &mut Report,
|
report: &mut Report,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let existing = if existed { g.page_tree(pid)? } else { vec![] };
|
let existing = if existed { g.page_tree(pid)? } else { vec![] };
|
||||||
|
let tracked = track::blocks_of(g, pid)?;
|
||||||
|
let first_import = tracked.is_empty();
|
||||||
if existed && opts.existing == ExistingPages::Skip && !existing.is_empty() {
|
if existed && opts.existing == ExistingPages::Skip && !existing.is_empty() {
|
||||||
report.unchanged += 1;
|
report.unchanged += 1;
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
let old: HashMap<Uuid, &Block> = existing.iter().map(|(_, b)| (b.id, b)).collect();
|
||||||
|
|
||||||
// Final ids: Logseq `id::` when free, else deterministic.
|
// Final ids: Logseq `id::` when free; otherwise derived from (source file, parent id,
|
||||||
|
// content, duplicate index) so edits elsewhere in the file never shift them.
|
||||||
let mut ids: Vec<Uuid> = Vec::with_capacity(d.blocks.len());
|
let mut ids: Vec<Uuid> = Vec::with_capacity(d.blocks.len());
|
||||||
let mut used: HashSet<Uuid> = HashSet::new();
|
let mut used: HashSet<Uuid> = HashSet::new();
|
||||||
for (i, b) in d.blocks.iter().enumerate() {
|
let mut dups: HashMap<(Option<Uuid>, String), usize> = HashMap::new();
|
||||||
let fallback = || Uuid::new_v5(&BLOCK_NS, format!("{}\0{i}", d.key).as_bytes());
|
for b in &d.blocks {
|
||||||
|
let parent = b.parent.map(|p| ids[p]);
|
||||||
|
let fallback = |dups: &mut HashMap<(Option<Uuid>, String), usize>| {
|
||||||
|
let h = track::id_hash(&b.content, &b.properties);
|
||||||
|
let n = dups.entry((parent, h.clone())).or_default();
|
||||||
|
let name = format!("{}\0{parent:?}\0{h}\0{n}", d.rel);
|
||||||
|
*n += 1;
|
||||||
|
Uuid::new_v5(&BLOCK_NS, name.as_bytes())
|
||||||
|
};
|
||||||
let id = match b.explicit_id {
|
let id = match b.explicit_id {
|
||||||
Some(id) => {
|
Some(id) => {
|
||||||
let taken_elsewhere =
|
let elsewhere = !old.contains_key(&id)
|
||||||
!used.contains(&id) && g.get_block(id)?.is_some_and(|x| x.page_id != pid);
|
&& !used.contains(&id)
|
||||||
if used.contains(&id) || taken_elsewhere {
|
&& g.get_block(id)?.is_some_and(|x| x.page_id != pid);
|
||||||
|
if used.contains(&id) || (elsewhere && !tracked.contains_key(&id)) {
|
||||||
report.warnings.push(format!(
|
report.warnings.push(format!(
|
||||||
"{}: duplicate block id {id}, generated a new one",
|
"{}: duplicate block id {id}, generated a new one",
|
||||||
d.rel
|
d.rel
|
||||||
));
|
));
|
||||||
fallback()
|
fallback(&mut dups)
|
||||||
} else {
|
} else {
|
||||||
id
|
id
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => fallback(),
|
None => fallback(&mut dups),
|
||||||
};
|
};
|
||||||
used.insert(id);
|
used.insert(id);
|
||||||
ids.push(id);
|
ids.push(id);
|
||||||
}
|
}
|
||||||
let blocks: Vec<Block> = d
|
|
||||||
.blocks
|
// New root blocks of a page that already has content are appended after it.
|
||||||
.iter()
|
let mut roots_after: Option<String> = None;
|
||||||
.enumerate()
|
if first_import && !existing.is_empty() {
|
||||||
.map(|(i, b)| Block {
|
roots_after = existing
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, b)| b.parent_id.is_none())
|
||||||
|
.map(|(_, b)| b.position.clone())
|
||||||
|
.max();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut written = 0usize;
|
||||||
|
let mut kept: Vec<String> = Vec::new();
|
||||||
|
for (i, b) in d.blocks.iter().enumerate() {
|
||||||
|
let mut position = b.position.clone();
|
||||||
|
if b.parent.is_none() && roots_after.is_some() {
|
||||||
|
position = synapse_core::position::between(roots_after.as_deref(), None);
|
||||||
|
roots_after = Some(position.clone());
|
||||||
|
}
|
||||||
|
let block = Block {
|
||||||
id: ids[i],
|
id: ids[i],
|
||||||
page_id: pid,
|
page_id: pid,
|
||||||
parent_id: b.parent.map(|p| ids[p]),
|
parent_id: b.parent.map(|p| ids[p]),
|
||||||
position: b.position.clone(),
|
position,
|
||||||
content: b.content.clone(),
|
content: b.content.clone(),
|
||||||
properties: b.properties.clone(),
|
properties: b.properties.clone(),
|
||||||
collapsed: b.collapsed,
|
collapsed: b.collapsed,
|
||||||
created_at: d.created,
|
created_at: d.created,
|
||||||
updated_at: d.updated,
|
updated_at: d.updated,
|
||||||
})
|
};
|
||||||
.collect();
|
let new_hash = track::state_hash(&block);
|
||||||
|
match (old.get(&block.id), tracked.get(&block.id)) {
|
||||||
let page = g.get_page(pid)?;
|
(None, None) => {
|
||||||
let props_differ = page.as_ref().is_some_and(|p| p.properties != d.props);
|
// Only explicit ids can collide with blocks living elsewhere.
|
||||||
let old: HashMap<Uuid, &Block> = existing.iter().map(|(_, b)| (b.id, b)).collect();
|
if b.explicit_id.is_some()
|
||||||
let same_blocks = old.len() == blocks.len()
|
&& let Some(other) = g.get_block(block.id)?
|
||||||
&& blocks.iter().all(|b| {
|
&& other.page_id != pid
|
||||||
old.get(&b.id).is_some_and(|o| {
|
{
|
||||||
(
|
continue; // moved away from this page in Synapse
|
||||||
o.parent_id,
|
}
|
||||||
&o.position,
|
g.put_block(&block)?;
|
||||||
&o.content,
|
track::set_block(g, &block, &d.rel, &new_hash)?;
|
||||||
&o.properties,
|
written += 1;
|
||||||
o.collapsed,
|
}
|
||||||
) == (
|
(None, Some(h)) => {
|
||||||
b.parent_id,
|
// Deleted in Synapse: only resurrect when the file changed it since.
|
||||||
&b.position,
|
if *h != new_hash && g.get_block(block.id)?.is_none() {
|
||||||
&b.content,
|
kept.push(format!("{}: block deleted in Synapse kept deleted", d.rel));
|
||||||
&b.properties,
|
}
|
||||||
b.collapsed,
|
}
|
||||||
)
|
(Some(cur), Some(h)) => {
|
||||||
})
|
let cur_hash = track::state_hash(cur);
|
||||||
});
|
if cur_hash == new_hash {
|
||||||
if existed && same_blocks && !props_differ {
|
if *h != new_hash {
|
||||||
report.unchanged += 1;
|
track::set_block(g, &block, &d.rel, &new_hash)?;
|
||||||
} else {
|
}
|
||||||
for b in &blocks {
|
} else if cur_hash == *h {
|
||||||
g.put_block(b)?;
|
// untouched in Synapse: file wins
|
||||||
}
|
g.put_block(&block)?;
|
||||||
let stale: Vec<Uuid> = old
|
track::set_block(g, &block, &d.rel, &new_hash)?;
|
||||||
.keys()
|
written += 1;
|
||||||
.filter(|id| !used.contains(id))
|
} else {
|
||||||
.copied()
|
if *h != new_hash {
|
||||||
.collect();
|
kept.push(format!(
|
||||||
for id in stale {
|
"{}: block {} edited in both Synapse and the file, kept the Synapse version",
|
||||||
match g.delete_block(id) {
|
d.rel, block.id
|
||||||
Ok(()) | Err(synapse_core::Error::NotFound(_)) => {}
|
));
|
||||||
Err(e) => return Err(e),
|
}
|
||||||
|
track::set_block(g, cur, &d.rel, &cur_hash)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(Some(cur), None) => {
|
||||||
|
// A Synapse block with the same (explicit) id that was never imported.
|
||||||
|
if track::state_hash(cur) != new_hash {
|
||||||
|
kept.push(format!(
|
||||||
|
"{}: block {} already exists with other content, kept it",
|
||||||
|
d.rel, block.id
|
||||||
|
));
|
||||||
|
}
|
||||||
|
track::set_block(g, cur, &d.rel, &track::state_hash(cur))?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if props_differ {
|
}
|
||||||
g.set_page_properties(pid, d.props.clone())?;
|
report.warnings.extend(kept);
|
||||||
|
|
||||||
|
// Imported blocks that vanished from the file: delete only those untouched in Synapse
|
||||||
|
// and without native descendants.
|
||||||
|
let mut deleted = 0usize;
|
||||||
|
let stale: Vec<(&Uuid, &String)> = tracked
|
||||||
|
.iter()
|
||||||
|
.filter(|(id, _)| !used.contains(id))
|
||||||
|
.collect();
|
||||||
|
if !stale.is_empty() {
|
||||||
|
let tree = g.page_tree(pid)?;
|
||||||
|
let mut kids: HashMap<Uuid, Vec<&Block>> = HashMap::new();
|
||||||
|
let mut byid: HashMap<Uuid, &Block> = HashMap::new();
|
||||||
|
for (_, b) in &tree {
|
||||||
|
byid.insert(b.id, b);
|
||||||
|
if let Some(p) = b.parent_id {
|
||||||
|
kids.entry(p).or_default().push(b);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
report.blocks += blocks.len();
|
let stale_ids: HashSet<Uuid> = stale.iter().map(|(id, _)| **id).collect();
|
||||||
|
for (id, hash) in &stale {
|
||||||
|
let Some(b) = byid.get(id) else {
|
||||||
|
track::drop_block(g, **id)?;
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let mut subtree = vec![*b];
|
||||||
|
let mut i = 0;
|
||||||
|
while i < subtree.len() {
|
||||||
|
if let Some(k) = kids.get(&subtree[i].id) {
|
||||||
|
subtree.extend(k.iter().copied());
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
let clean = subtree.iter().all(|x| {
|
||||||
|
stale_ids.contains(&x.id)
|
||||||
|
&& tracked
|
||||||
|
.get(&x.id)
|
||||||
|
.is_some_and(|h| *h == track::state_hash(x))
|
||||||
|
});
|
||||||
|
if track::state_hash(b) == **hash && clean {
|
||||||
|
g.delete_block(b.id)?;
|
||||||
|
deleted += 1;
|
||||||
|
for x in subtree {
|
||||||
|
track::drop_block(g, x.id)?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
report.warnings.push(format!(
|
||||||
|
"{}: block {} was removed from the file but edited or extended in Synapse, kept",
|
||||||
|
d.rel, b.id
|
||||||
|
));
|
||||||
|
track::drop_block(g, b.id)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Page properties: merge into native pages, follow the file while unedited.
|
||||||
|
let page = g
|
||||||
|
.get_page(pid)?
|
||||||
|
.ok_or_else(|| synapse_core::Error::NotFound(pid.to_string()))?;
|
||||||
|
let stored = track::page_props_hash(g, &d.rel)?;
|
||||||
|
let cur_hash = track::props_hash(&page.properties);
|
||||||
|
let new_hash = track::props_hash(&d.props);
|
||||||
|
let mut props_changed = false;
|
||||||
|
if (existed || d.journal.is_some()) && cur_hash != new_hash {
|
||||||
|
let mut next = page.properties.clone();
|
||||||
|
match &stored {
|
||||||
|
Some(h) if *h == cur_hash => next = d.props.clone(),
|
||||||
|
Some(_) => {
|
||||||
|
if Some(&new_hash) != stored.as_ref() {
|
||||||
|
report.warnings.push(format!(
|
||||||
|
"{}: page properties edited in Synapse, kept",
|
||||||
|
d.rel
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
for (k, v) in &d.props {
|
||||||
|
next.entry(k.clone()).or_insert_with(|| v.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if next != page.properties {
|
||||||
|
let mut np = page.clone();
|
||||||
|
np.properties = next;
|
||||||
|
if d.journal.is_none() {
|
||||||
|
np.updated_at = d.updated;
|
||||||
|
}
|
||||||
|
g.put_page(&np)?;
|
||||||
|
props_changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let final_props = g.get_page(pid)?.map(|p| p.properties).unwrap_or_default();
|
||||||
|
let final_hash = track::props_hash(&final_props);
|
||||||
|
if stored.as_deref() != Some(final_hash.as_str()) {
|
||||||
|
track::set_page(g, &d.rel, pid, &final_hash)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
if existed && written == 0 && deleted == 0 && !props_changed {
|
||||||
|
report.unchanged += 1;
|
||||||
|
} else {
|
||||||
|
report.blocks += written;
|
||||||
if d.journal.is_some() {
|
if d.journal.is_some() {
|
||||||
report.journals += 1;
|
report.journals += 1;
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
//! Bookkeeping of what the importer wrote, so re-imports never clobber native Synapse content.
|
||||||
|
//! The tables are local to the graph database and not part of the op log.
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use synapse_core::{Block, BlockId, Graph, PageId, Properties, Result};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub fn init(g: &Graph) -> Result<()> {
|
||||||
|
g.conn().execute_batch(
|
||||||
|
"CREATE TABLE IF NOT EXISTS import_pages(
|
||||||
|
source_path TEXT PRIMARY KEY, page_id TEXT NOT NULL, props_hash TEXT NOT NULL);
|
||||||
|
CREATE TABLE IF NOT EXISTS import_blocks(
|
||||||
|
block_id TEXT PRIMARY KEY, page_id TEXT NOT NULL, source_path TEXT NOT NULL,
|
||||||
|
content_hash TEXT NOT NULL);
|
||||||
|
CREATE INDEX IF NOT EXISTS import_blocks_page ON import_blocks(page_id);",
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fnv(parts: &[&[u8]]) -> String {
|
||||||
|
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||||
|
for p in parts {
|
||||||
|
for b in p.iter().chain(&[0u8]) {
|
||||||
|
h ^= u64::from(*b);
|
||||||
|
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
format!("{h:016x}")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn json(props: &Properties) -> String {
|
||||||
|
serde_json::to_string(&Value::Object(props.clone())).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hash used for deriving fallback ids (ignores `collapsed`).
|
||||||
|
pub fn id_hash(content: &str, props: &Properties) -> String {
|
||||||
|
fnv(&[content.as_bytes(), json(props).as_bytes()])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hash of the user-editable state of a block.
|
||||||
|
pub fn state_hash(b: &Block) -> String {
|
||||||
|
fnv(&[
|
||||||
|
b.content.as_bytes(),
|
||||||
|
json(&b.properties).as_bytes(),
|
||||||
|
&[u8::from(b.collapsed)],
|
||||||
|
])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn props_hash(p: &Properties) -> String {
|
||||||
|
fnv(&[json(p).as_bytes()])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn page_of(g: &Graph, source: &str) -> Result<Option<PageId>> {
|
||||||
|
let mut st = g
|
||||||
|
.conn()
|
||||||
|
.prepare_cached("SELECT page_id FROM import_pages WHERE source_path=?1")?;
|
||||||
|
let rows: Vec<String> = st
|
||||||
|
.query_map([source], |r| r.get(0))?
|
||||||
|
.collect::<std::result::Result<_, _>>()?;
|
||||||
|
Ok(rows.first().and_then(|s| Uuid::parse_str(s).ok()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn page_props_hash(g: &Graph, source: &str) -> Result<Option<String>> {
|
||||||
|
let mut st = g
|
||||||
|
.conn()
|
||||||
|
.prepare_cached("SELECT props_hash FROM import_pages WHERE source_path=?1")?;
|
||||||
|
let rows: Vec<String> = st
|
||||||
|
.query_map([source], |r| r.get(0))?
|
||||||
|
.collect::<std::result::Result<_, _>>()?;
|
||||||
|
Ok(rows.into_iter().next())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_page(g: &Graph, source: &str, page: PageId, props_hash: &str) -> Result<()> {
|
||||||
|
g.conn().execute(
|
||||||
|
"INSERT OR REPLACE INTO import_pages(source_path, page_id, props_hash) VALUES (?1, ?2, ?3)",
|
||||||
|
[source, &page.to_string(), props_hash],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `block id → state hash at import` for the blocks this importer wrote on `page`.
|
||||||
|
pub fn blocks_of(g: &Graph, page: PageId) -> Result<HashMap<BlockId, String>> {
|
||||||
|
let mut st = g
|
||||||
|
.conn()
|
||||||
|
.prepare_cached("SELECT block_id, content_hash FROM import_blocks WHERE page_id=?1")?;
|
||||||
|
let rows = st.query_map([page.to_string()], |r| {
|
||||||
|
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
|
||||||
|
})?;
|
||||||
|
let mut out = HashMap::new();
|
||||||
|
for r in rows {
|
||||||
|
let (id, h) = r?;
|
||||||
|
if let Ok(id) = Uuid::parse_str(&id) {
|
||||||
|
out.insert(id, h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set_block(g: &Graph, b: &Block, source: &str, hash: &str) -> Result<()> {
|
||||||
|
g.conn()
|
||||||
|
.prepare_cached(
|
||||||
|
"INSERT OR REPLACE INTO import_blocks(block_id, page_id, source_path, content_hash)
|
||||||
|
VALUES (?1, ?2, ?3, ?4)",
|
||||||
|
)?
|
||||||
|
.execute([&b.id.to_string(), &b.page_id.to_string(), source, hash])?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn drop_block(g: &Graph, id: BlockId) -> Result<()> {
|
||||||
|
g.conn().execute(
|
||||||
|
"DELETE FROM import_blocks WHERE block_id=?1",
|
||||||
|
[id.to_string()],
|
||||||
|
)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -182,3 +182,155 @@ fn copy_dir(from: &Path, to: &Path) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn mini_graph(files: &[(&str, &str)]) -> tempfile::TempDir {
|
||||||
|
let src = tempfile::tempdir().unwrap();
|
||||||
|
for (rel, text) in files {
|
||||||
|
let p = src.path().join(rel);
|
||||||
|
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||||
|
std::fs::write(p, text).unwrap();
|
||||||
|
}
|
||||||
|
src
|
||||||
|
}
|
||||||
|
|
||||||
|
fn imp(src: &Path, g: &Graph) -> Report {
|
||||||
|
import_logseq(src, g, &ImportOptions::default(), |_| {}).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn native_blocks_survive_import_and_reimport() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let g = Graph::open(dir.path()).unwrap();
|
||||||
|
let page = g.ensure_page("Notes", None).unwrap();
|
||||||
|
g.insert_block(
|
||||||
|
page.id,
|
||||||
|
synapse_core::Placement::LastChildOf(None),
|
||||||
|
"native",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let today = g.today_journal().unwrap();
|
||||||
|
g.insert_block(
|
||||||
|
today.id,
|
||||||
|
synapse_core::Placement::LastChildOf(None),
|
||||||
|
"today native",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let src = mini_graph(&[("pages/Notes.md", "- from logseq\n- second\n")]);
|
||||||
|
|
||||||
|
imp(src.path(), &g);
|
||||||
|
let t = texts(&g, "Notes");
|
||||||
|
assert_eq!(t[0].1, "native");
|
||||||
|
assert_eq!(t[1].1, "from logseq", "imported blocks are appended");
|
||||||
|
|
||||||
|
// file drops a block, user edited another one in Synapse
|
||||||
|
let second = g.page_tree(page.id).unwrap()[2].1.clone();
|
||||||
|
g.update_block(second.id, "second (edited in Synapse)")
|
||||||
|
.unwrap();
|
||||||
|
std::fs::write(src.path().join("pages/Notes.md"), "- from logseq changed\n").unwrap();
|
||||||
|
let r = imp(src.path(), &g);
|
||||||
|
let t: Vec<String> = texts(&g, "Notes").into_iter().map(|x| x.1).collect();
|
||||||
|
assert!(t.contains(&"native".to_string()));
|
||||||
|
assert!(
|
||||||
|
t.contains(&"second (edited in Synapse)".to_string()),
|
||||||
|
"{t:?}"
|
||||||
|
);
|
||||||
|
assert!(t.contains(&"from logseq changed".to_string()));
|
||||||
|
assert!(!t.contains(&"from logseq".to_string()));
|
||||||
|
assert!(
|
||||||
|
r.warnings.iter().any(|w| w.contains("edited")),
|
||||||
|
"{:?}",
|
||||||
|
r.warnings
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
texts(&g, &synapse_core::journal_title(g.today())),
|
||||||
|
vec![(0, "today native".to_string())]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn imported_journal_merges_with_native_today() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let g = Graph::open(dir.path()).unwrap();
|
||||||
|
let today = g.today_journal().unwrap();
|
||||||
|
g.insert_block(today.id, synapse_core::Placement::LastChildOf(None), "mine")
|
||||||
|
.unwrap();
|
||||||
|
let name = g.today().format("%Y_%m_%d").to_string();
|
||||||
|
let src = mini_graph(&[(&format!("journals/{name}.md"), "- old entry\n")]);
|
||||||
|
imp(src.path(), &g);
|
||||||
|
imp(src.path(), &g);
|
||||||
|
let t: Vec<String> = texts(&g, &synapse_core::journal_title(g.today()))
|
||||||
|
.into_iter()
|
||||||
|
.map(|x| x.1)
|
||||||
|
.collect();
|
||||||
|
assert_eq!(t, vec!["mine", "old entry"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn failing_document_is_rolled_back() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let g = Graph::open(dir.path()).unwrap();
|
||||||
|
g.conn()
|
||||||
|
.execute_batch(
|
||||||
|
"CREATE TRIGGER boom BEFORE INSERT ON blocks WHEN NEW.content='boom'
|
||||||
|
BEGIN SELECT RAISE(ABORT, 'boom'); END;",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let src = mini_graph(&[
|
||||||
|
("pages/Bad.md", "- fine\n- boom\n"),
|
||||||
|
("pages/Good.md", "- ok\n"),
|
||||||
|
]);
|
||||||
|
let r = imp(src.path(), &g);
|
||||||
|
assert!(
|
||||||
|
r.warnings.iter().any(|w| w.contains("Bad.md")),
|
||||||
|
"{:?}",
|
||||||
|
r.warnings
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
texts(&g, "Bad").is_empty(),
|
||||||
|
"partial blocks must not be committed"
|
||||||
|
);
|
||||||
|
assert_eq!(texts(&g, "Good").len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn inserting_a_block_keeps_other_ids_stable() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let g = Graph::open(dir.path()).unwrap();
|
||||||
|
let src = mini_graph(&[("pages/P.md", "- a\n\t- a1\n- b\n- b\n")]);
|
||||||
|
imp(src.path(), &g);
|
||||||
|
let ids = |g: &Graph| -> Vec<(String, uuid::Uuid)> {
|
||||||
|
let p = g.page_by_title("P").unwrap().unwrap();
|
||||||
|
g.page_tree(p.id)
|
||||||
|
.unwrap()
|
||||||
|
.into_iter()
|
||||||
|
.map(|(_, b)| (b.content, b.id))
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
let before = ids(&g);
|
||||||
|
std::fs::write(
|
||||||
|
src.path().join("pages/P.md"),
|
||||||
|
"- NEW\n- a\n\t- a1\n- b\n- b\n",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
imp(src.path(), &g);
|
||||||
|
let after = ids(&g);
|
||||||
|
assert_eq!(after.len(), 5);
|
||||||
|
for old in &before {
|
||||||
|
assert!(after.contains(old), "{old:?} changed id: {after:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn renamed_page_is_not_duplicated() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let g = Graph::open(dir.path()).unwrap();
|
||||||
|
let src = mini_graph(&[("pages/Old.md", "- one\n")]);
|
||||||
|
imp(src.path(), &g);
|
||||||
|
let p = g.page_by_title("Old").unwrap().unwrap();
|
||||||
|
g.rename_page(p.id, "Renamed").unwrap();
|
||||||
|
std::fs::write(src.path().join("pages/Old.md"), "- one\n- two\n").unwrap();
|
||||||
|
imp(src.path(), &g);
|
||||||
|
assert!(g.page_by_title("Old").unwrap().is_none());
|
||||||
|
let t = texts(&g, "Renamed");
|
||||||
|
assert_eq!(t.len(), 2);
|
||||||
|
}
|
||||||
+17
-7
@@ -27,11 +27,21 @@ CLI: `cargo run --release -p synapse-import --example import -- <logseq_dir> <gr
|
|||||||
them. `origin_journal` = earliest journal referencing the page (aliases resolved), else the
|
them. `origin_journal` = earliest journal referencing the page (aliases resolved), else the
|
||||||
file's creation day. Journal pages keep core's midnight timestamps.
|
file's creation day. Journal pages keep core's midnight timestamps.
|
||||||
|
|
||||||
## Re-import
|
## Re-import and native content
|
||||||
Idempotent. Blocks without `id::` get UUIDv5 ids from `(page title, ordinal)`, so a re-import
|
The importer records what it wrote in two local tables (`import_pages`: source file → page id,
|
||||||
upserts the same rows; identical pages are counted in `Report::unchanged` and not touched. Pages
|
`import_blocks`: block id → state hash). Re-imports use them so Synapse content is never lost:
|
||||||
that changed are rewritten and stale blocks deleted (`ExistingPages::Update`, default);
|
- Pages are found by source file first, so a page renamed in Synapse is updated, not duplicated.
|
||||||
`ExistingPages::Skip` leaves any page that already has blocks alone (keeps edits made in Synapse).
|
- Block ids: Logseq `id::` when present, otherwise UUIDv5 of (source file, parent id, content,
|
||||||
|
duplicate index). Inserting or moving a block elsewhere in a file does not change other ids.
|
||||||
|
- Only blocks the importer wrote are ever overwritten or deleted, and only while unedited in
|
||||||
|
Synapse. Edited blocks keep the Synapse version (warning if the file changed too); a removed
|
||||||
|
block that was edited or has native children is kept (warning). Native blocks are never touched.
|
||||||
|
- First import into an existing page (e.g. today's journal) appends the imported blocks after the
|
||||||
|
native ones; page properties are merged without overriding existing keys.
|
||||||
|
- A block deleted in Synapse stays deleted unless the file changed it.
|
||||||
|
- Each document is written in its own savepoint; a failure rolls the document back and becomes a
|
||||||
|
warning. The whole write phase is one transaction.
|
||||||
|
- `ExistingPages::Skip` leaves any page that already has blocks alone.
|
||||||
|
|
||||||
## Report / progress
|
## Report / progress
|
||||||
`Progress { phase, done, total }` (phases: Scanning, Assets, Parsing, Pages, Blocks) and
|
`Progress { phase, done, total }` (phases: Scanning, Assets, Parsing, Pages, Blocks) and
|
||||||
@@ -39,5 +49,5 @@ that changed are rewritten and stale blocks deleted (`ExistingPages::Update`, de
|
|||||||
|
|
||||||
## Known limits
|
## Known limits
|
||||||
- Not parsed: org-mode syntax, whiteboards, `draws/`, namespace parent stubs, Logseq queries.
|
- Not parsed: org-mode syntax, whiteboards, `draws/`, namespace parent stubs, Logseq queries.
|
||||||
- Sequential commits (core has no nestable transaction): ~7k blocks/s; 10k pages × 20 blocks ≈ 30 s,
|
- Speed is bound by core's per-block savepoint inside the import transaction: 208k blocks
|
||||||
typical graphs a few seconds.
|
(10k pages) ≈ 60 s; re-importing an unchanged graph ≈ 1.3 s.
|
||||||
Reference in new issue
Block a user