mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-27 07:46:25 +00:00
fix(core): sort tags on every write and make the v6 migration tolerant and transactional
Tags are sorted and deduplicated by title_key in the migration and in write_page_row (remote ops included). The migration runs in one transaction, rebuilds page_tags once and repairs malformed tags/types values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
50e5572575
commit
3585ce67af
5 files changed
+118
-28
No files matched your search
@@ -117,31 +117,50 @@ CREATE TABLE IF NOT EXISTS ops (
|
|||||||
"#;
|
"#;
|
||||||
|
|
||||||
/// Rebuilds the `page_tags` index from every page's `tags` column and first type (the type
|
/// Rebuilds the `page_tags` index from every page's `tags` column and first type (the type
|
||||||
/// implies a tag of the same name).
|
/// implies a tag of the same name). Malformed JSON values count as empty.
|
||||||
pub fn rebuild_page_tags(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
pub fn rebuild_page_tags(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
||||||
conn.execute("DELETE FROM page_tags", [])?;
|
conn.execute("DELETE FROM page_tags", [])?;
|
||||||
let rows: Vec<(String, String)> = {
|
let rows: Vec<(String, String, String)> = {
|
||||||
let mut st = conn.prepare(
|
let mut st =
|
||||||
"SELECT id, json_group_array(value) FROM (
|
conn.prepare("SELECT id, tags, types FROM pages WHERE tags != '[]' OR types != '[]'")?;
|
||||||
SELECT pages.id AS id, j.value AS value FROM pages, json_each(pages.tags) j
|
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?
|
||||||
UNION ALL
|
|
||||||
SELECT pages.id AS id, j.value AS value FROM pages, json_each(pages.types) j WHERE j.key = 0
|
|
||||||
) GROUP BY id",
|
|
||||||
)?;
|
|
||||||
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
|
|
||||||
.collect::<rusqlite::Result<_>>()?
|
.collect::<rusqlite::Result<_>>()?
|
||||||
};
|
};
|
||||||
let mut ins =
|
let mut ins =
|
||||||
conn.prepare("INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)")?;
|
conn.prepare("INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)")?;
|
||||||
for (id, tags) in rows {
|
for (id, tags, types) in rows {
|
||||||
let tags: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
|
let tags: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
|
||||||
for t in tags {
|
let types: Vec<String> = serde_json::from_str(&types).unwrap_or_default();
|
||||||
ins.execute([&id, &crate::model::title_key(&t)])?;
|
for t in tags.iter().chain(types.iter().take(1)) {
|
||||||
|
ins.execute([&id, &crate::model::title_key(t)])?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// v6: tag pages become notes, tags are sorted and deduplicated, a page keeps one type.
|
||||||
|
/// Malformed `tags`/`types` values are repaired to empty lists.
|
||||||
|
fn migrate_v6(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
||||||
|
conn.execute("UPDATE pages SET kind='note' WHERE kind='tag'", [])?;
|
||||||
|
let rows: Vec<(String, String, String)> = {
|
||||||
|
let mut st = conn.prepare("SELECT id, tags, types FROM pages")?;
|
||||||
|
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?
|
||||||
|
.collect::<rusqlite::Result<_>>()?
|
||||||
|
};
|
||||||
|
let mut upd = conn.prepare("UPDATE pages SET tags=?2, types=?3 WHERE id=?1")?;
|
||||||
|
for (id, tags, types) in rows {
|
||||||
|
let tags_v: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
|
||||||
|
let mut types_v: Vec<String> = serde_json::from_str(&types).unwrap_or_default();
|
||||||
|
types_v.truncate(1);
|
||||||
|
let tags_n = serde_json::to_string(&crate::tags::sorted_tags(&tags_v)).unwrap_or_default();
|
||||||
|
let types_n = serde_json::to_string(&types_v).unwrap_or_default();
|
||||||
|
if tags_n != tags || types_n != types {
|
||||||
|
upd.execute([&id, &tags_n, &types_n])?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rebuild_page_tags(conn)
|
||||||
|
}
|
||||||
|
|
||||||
/// Rebuilds the `page_hubs` index from every page's `hubs` column.
|
/// Rebuilds the `page_hubs` index from every page's `hubs` column.
|
||||||
pub fn rebuild_page_hubs(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
pub fn rebuild_page_hubs(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
||||||
conn.execute("DELETE FROM page_hubs", [])?;
|
conn.execute("DELETE FROM page_hubs", [])?;
|
||||||
@@ -193,27 +212,28 @@ pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
|||||||
})
|
})
|
||||||
.optional()?
|
.optional()?
|
||||||
.and_then(|v| v.parse().ok());
|
.and_then(|v| v.parse().ok());
|
||||||
|
// One transaction: much faster, and an interrupted migration leaves the old version
|
||||||
|
// stamp, so it simply runs again (every step is idempotent).
|
||||||
|
conn.execute_batch("BEGIN IMMEDIATE")?;
|
||||||
|
let run = || -> rusqlite::Result<()> {
|
||||||
if version.is_some_and(|v| v < 3) {
|
if version.is_some_and(|v| v < 3) {
|
||||||
rebuild_page_hubs(conn)?;
|
rebuild_page_hubs(conn)?;
|
||||||
}
|
}
|
||||||
if version.is_some_and(|v| v < 4) {
|
// v6 rebuilds `page_tags` too, which also covers the v4 rebuild.
|
||||||
rebuild_page_tags(conn)?;
|
|
||||||
}
|
|
||||||
if version.is_some_and(|v| v < 6) {
|
if version.is_some_and(|v| v < 6) {
|
||||||
// v6: tags and types are names only, one type per page. Old tag pages become plain notes (title,
|
migrate_v6(conn)?;
|
||||||
// outline and links kept); their members keep the name in `tags`.
|
|
||||||
conn.execute("UPDATE pages SET kind='note' WHERE kind='tag'", [])?;
|
|
||||||
// A page has one type: keep the first of several.
|
|
||||||
conn.execute(
|
|
||||||
"UPDATE pages SET types = json_array(json_extract(types, '$[0]'))
|
|
||||||
WHERE json_array_length(types) > 1",
|
|
||||||
[],
|
|
||||||
)?;
|
|
||||||
rebuild_page_tags(conn)?;
|
|
||||||
}
|
}
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)",
|
"INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)",
|
||||||
[VERSION.to_string()],
|
[VERSION.to_string()],
|
||||||
)?;
|
)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
};
|
||||||
|
match run() {
|
||||||
|
Ok(()) => conn.execute_batch("COMMIT"),
|
||||||
|
Err(e) => {
|
||||||
|
let _ = conn.execute_batch("ROLLBACK");
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1189,6 +1189,8 @@ impl Graph {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn write_page_row(&self, p: &Page, hlc: &str) -> Result<()> {
|
fn write_page_row(&self, p: &Page, hlc: &str) -> Result<()> {
|
||||||
|
// Remote ops may carry tags in insertion order: store them sorted and deduplicated.
|
||||||
|
let tags = crate::tags::sorted_tags(&p.tags);
|
||||||
self.exec(
|
self.exec(
|
||||||
"INSERT INTO pages(id, title, title_key, journal_date, origin_journal, properties, created_at, updated_at, hlc, kind, description, hubs, tags, types)
|
"INSERT INTO pages(id, title, title_key, journal_date, origin_journal, properties, created_at, updated_at, hlc, kind, description, hubs, tags, types)
|
||||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)
|
||||||
@@ -1207,7 +1209,7 @@ impl Graph {
|
|||||||
p.kind.as_str(),
|
p.kind.as_str(),
|
||||||
p.description,
|
p.description,
|
||||||
serde_json::to_string(&p.hubs)?,
|
serde_json::to_string(&p.hubs)?,
|
||||||
serde_json::to_string(&p.tags)?,
|
serde_json::to_string(&tags)?,
|
||||||
serde_json::to_string(&p.types)?
|
serde_json::to_string(&p.types)?
|
||||||
],
|
],
|
||||||
)?;
|
)?;
|
||||||
@@ -1215,7 +1217,7 @@ impl Graph {
|
|||||||
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&id])?;
|
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&id])?;
|
||||||
// The type implies a tag of the same name, so the index covers both (a page has one
|
// The type implies a tag of the same name, so the index covers both (a page has one
|
||||||
// type: older replicas may sync more, and only the first counts).
|
// type: older replicas may sync more, and only the first counts).
|
||||||
for t in p.tags.iter().chain(p.types.iter().take(1)) {
|
for t in tags.iter().chain(p.types.iter().take(1)) {
|
||||||
self.exec(
|
self.exec(
|
||||||
"INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)",
|
"INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)",
|
||||||
params![id, title_key(t)],
|
params![id, title_key(t)],
|
||||||
|
|||||||
@@ -31,6 +31,18 @@ pub fn normalize_tag(raw: &str) -> Option<String> {
|
|||||||
(!t.is_empty()).then_some(t)
|
(!t.is_empty()).then_some(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Tags sorted by [`title_key`], duplicates (case-insensitive) dropped keeping the first.
|
||||||
|
pub(crate) fn sorted_tags(tags: &[String]) -> Vec<String> {
|
||||||
|
let mut out: Vec<String> = Vec::with_capacity(tags.len());
|
||||||
|
for t in tags {
|
||||||
|
if !out.iter().any(|x| title_key(x) == title_key(t)) {
|
||||||
|
out.push(t.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.sort_by_cached_key(|t| title_key(t));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
impl Graph {
|
impl Graph {
|
||||||
/// Replaces the tags of `page` (names cleaned, duplicates dropped case-insensitively,
|
/// Replaces the tags of `page` (names cleaned, duplicates dropped case-insensitively,
|
||||||
/// kept sorted by [`title_key`]). Journals and templates cannot be tagged.
|
/// kept sorted by [`title_key`]). Journals and templates cannot be tagged.
|
||||||
|
|||||||
@@ -856,3 +856,58 @@ fn tags_and_type_sync_with_the_page() {
|
|||||||
["ocurrencia", "proyecto"]
|
["ocurrencia", "proyecto"]
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn v5_migration_sorts_tags_and_survives_malformed_rows() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let (a, bad, bad2) = {
|
||||||
|
let g = Graph::open(dir.path()).unwrap();
|
||||||
|
let a = page(&g, "A", &["x"]);
|
||||||
|
let bad = page(&g, "Bad", &["x"]);
|
||||||
|
let bad2 = page(&g, "Bad2", &["x"]);
|
||||||
|
let set = |id: PageId, tags: &str, types: &str| {
|
||||||
|
g.conn()
|
||||||
|
.execute(
|
||||||
|
"UPDATE pages SET tags=?2, types=?3 WHERE id=?1",
|
||||||
|
[id.to_string(), tags.to_string(), types.to_string()],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
};
|
||||||
|
set(a, "[\"zeta\",\"Alfa\",\"alfa\"]", "[\"persona\"]");
|
||||||
|
set(bad, "not json", "[]");
|
||||||
|
set(bad2, "[\"ok\"]", "{oops");
|
||||||
|
g.conn()
|
||||||
|
.execute("UPDATE meta SET value='5' WHERE key='schema'", [])
|
||||||
|
.unwrap();
|
||||||
|
(a, bad, bad2)
|
||||||
|
};
|
||||||
|
let g = Graph::open(dir.path()).unwrap();
|
||||||
|
assert_eq!(g.get_page(a).unwrap().unwrap().tags, ["Alfa", "zeta"]);
|
||||||
|
assert_eq!(g.pages_with_tag("alfa").unwrap(), [a]);
|
||||||
|
assert_eq!(g.pages_with_tag("persona").unwrap(), [a]);
|
||||||
|
assert!(g.get_page(bad).unwrap().unwrap().tags.is_empty());
|
||||||
|
let p = g.get_page(bad2).unwrap().unwrap();
|
||||||
|
assert_eq!((p.tags, p.types), (vec!["ok".to_string()], vec![]));
|
||||||
|
assert_eq!(g.pages_with_tag("ok").unwrap(), [bad2]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn remote_upserts_store_tags_sorted() {
|
||||||
|
let id = synapse_core::new_id();
|
||||||
|
let op: Op = serde_json::from_value(json!({
|
||||||
|
"type": "upsert_page",
|
||||||
|
"page": {"id": id, "title": "N", "journal_date": null, "origin_journal": null,
|
||||||
|
"properties": {}, "created_at": 1, "updated_at": 2, "kind": "note",
|
||||||
|
"tags": ["zeta", "Beta", "beta", "alfa"], "types": []}
|
||||||
|
}))
|
||||||
|
.unwrap();
|
||||||
|
let (_d, g) = graph();
|
||||||
|
assert!(
|
||||||
|
g.apply_remote("0000000000003-00000-oldactor0001", &op)
|
||||||
|
.unwrap()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
g.get_page(id).unwrap().unwrap().tags,
|
||||||
|
["alfa", "Beta", "zeta"]
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -41,6 +41,7 @@ crates may add their own tables to the same database (prefix them: `search_*`, `
|
|||||||
the first; `PageKind` has no `Tag` any more and "tag" parses as a note.
|
the first; `PageKind` has no `Tag` any more and "tag" parses as a note.
|
||||||
- In the graph (`synapse-ffi`) every tag in use is a virtual node (`GraphNode.is_tag`, id
|
- In the graph (`synapse-ffi`) every tag in use is a virtual node (`GraphNode.is_tag`, id
|
||||||
`tag:<title_key>`, no page), with a `TAGGED` edge from each tagged page (type included).
|
`tag:<title_key>`, no page), with a `TAGGED` edge from each tagged page (type included).
|
||||||
|
- Known limitations: replicas still on the old schema may overwrite tags with stale values (LWW per page), and `rename_tag` is a bulk page edit, so concurrent edits on another replica can undo part of it.
|
||||||
- Exports use `synapse-tags::` and `synapse-type::` (see `history.md`).
|
- Exports use `synapse-tags::` and `synapse-type::` (see `history.md`).
|
||||||
|
|
||||||
## Hubs and namespaces (`synapse-core::structure`)
|
## Hubs and namespaces (`synapse-core::structure`)
|
||||||
|
|||||||
Reference in new issue
Block a user