feat(core): a page's direct hub is an implicit tag

Members of a hub are indexed under the hub's title in page_tags, tag_catalog and the
graph tag nodes, merged with a same-name type or tag. Hub rename, delete and
membership changes re-index the derived index (no ops). Schema v7 rebuilds it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 03:52:04 +01:00
1 parent 3585ce67af
commit 6f483ce763
10 files changed
+273 -77

No files matched your search

+67 -18
View File
@@ -1,6 +1,6 @@
use rusqlite::OptionalExtension;
pub const VERSION: i64 = 6;
pub const VERSION: i64 = 7;
pub const SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
@@ -116,28 +116,74 @@ CREATE TABLE IF NOT EXISTS ops (
);
"#;
/// Rebuilds the `page_tags` index from every page's `tags` column and first type (the type
/// implies a tag of the same name). Malformed JSON values count as empty.
pub fn rebuild_page_tags(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
conn.execute("DELETE FROM page_tags", [])?;
let rows: Vec<(String, String, String)> = {
let mut st =
conn.prepare("SELECT id, tags, types FROM pages WHERE tags != '[]' OR types != '[]'")?;
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))?
.collect::<rusqlite::Result<_>>()?
};
/// Every page's tag sources: `tags`, `types` and the title of its direct hub (an implicit tag,
/// only for notes: hubs, templates and journals get none). Joined through `page_hubs`, which
/// holds at most one row per page. `?1` limits the result to one page id (NULL: all pages).
pub const TAG_SOURCES_SQL: &str = "SELECT p.id, p.tags, p.types, h.title FROM pages p
LEFT JOIN page_hubs ph ON ph.page_id = p.id AND p.kind = 'note' AND p.journal_date IS NULL
LEFT JOIN pages h ON h.id = ph.hub_id AND h.kind = 'hub'
WHERE (?1 IS NULL OR p.id = ?1)";
/// One page's tag sources, see [`TAG_SOURCES_SQL`]. Malformed JSON values count as empty.
pub struct TagSource {
pub id: String,
pub tags: Vec<String>,
pub types: Vec<String>,
pub hub: Option<String>,
}
/// Reads [`TagSource`]s for one page or (`None`) all of them.
pub fn tag_sources(
conn: &rusqlite::Connection,
only: Option<&str>,
) -> rusqlite::Result<Vec<TagSource>> {
let mut st = conn.prepare_cached(TAG_SOURCES_SQL)?;
let rows = st.query_map([only], |r| {
let tags: String = r.get(1)?;
let types: String = r.get(2)?;
Ok(TagSource {
id: r.get(0)?,
tags: serde_json::from_str(&tags).unwrap_or_default(),
types: serde_json::from_str(&types).unwrap_or_default(),
hub: r.get(3)?,
})
})?;
rows.collect()
}
impl TagSource {
/// Every tag name: listed tags, the first type and the hub title (one type per page).
pub fn names(&self) -> impl Iterator<Item = &String> {
self.tags
.iter()
.chain(self.types.iter().take(1))
.chain(self.hub.iter())
}
}
fn insert_tag_rows(conn: &rusqlite::Connection, sources: &[TagSource]) -> rusqlite::Result<()> {
let mut ins =
conn.prepare("INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)")?;
for (id, tags, types) in rows {
let tags: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
let types: Vec<String> = serde_json::from_str(&types).unwrap_or_default();
for t in tags.iter().chain(types.iter().take(1)) {
ins.execute([&id, &crate::model::title_key(t)])?;
conn.prepare_cached("INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)")?;
for src in sources {
for t in src.names() {
ins.execute([&src.id, &crate::model::title_key(t)])?;
}
}
Ok(())
}
/// Rebuilds the `page_tags` index from every page's tags, first type and hub.
pub fn rebuild_page_tags(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
conn.execute("DELETE FROM page_tags", [])?;
insert_tag_rows(conn, &tag_sources(conn, None)?)
}
/// Rewrites the `page_tags` rows of one page (derived data: no ops needed).
pub fn reindex_page_tags(conn: &rusqlite::Connection, id: &str) -> rusqlite::Result<()> {
conn.execute("DELETE FROM page_tags WHERE page_id=?1", [id])?;
insert_tag_rows(conn, &tag_sources(conn, Some(id))?)
}
/// 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<()> {
@@ -219,9 +265,12 @@ pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
if version.is_some_and(|v| v < 3) {
rebuild_page_hubs(conn)?;
}
// v6 rebuilds `page_tags` too, which also covers the v4 rebuild.
// v6 rebuilds `page_tags` too, which covers the v4 and v7 rebuilds.
if version.is_some_and(|v| v < 6) {
migrate_v6(conn)?;
} else if version.is_some_and(|v| v < 7) {
// v7: a page's hub title is an implicit tag, so the index changes.
rebuild_page_tags(conn)?;
}
conn.execute(
"INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)",
+21 -9
View File
@@ -1214,15 +1214,6 @@ impl Graph {
],
)?;
let id = p.id.to_string();
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
// type: older replicas may sync more, and only the first counts).
for t in tags.iter().chain(p.types.iter().take(1)) {
self.exec(
"INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)",
params![id, title_key(t)],
)?;
}
self.exec("DELETE FROM page_hubs WHERE page_id=?1", [&id])?;
// A page belongs to one hub: only the first entry counts (older replicas may sync more).
for h in p.hubs.iter().take(1) {
@@ -1231,6 +1222,25 @@ impl Graph {
params![id, h.to_string()],
)?;
}
// Tag index: tags, type and direct hub. The hub's title is an implicit tag of its
// members, so they are re-indexed too (this page may be a hub, renamed or converted).
schema::reindex_page_tags(&self.conn, &id)?;
self.reindex_hub_members(&id)?;
Ok(())
}
/// Re-indexes the tags of every page whose direct hub is `hub`.
pub(crate) fn reindex_hub_members(&self, hub: &str) -> Result<()> {
let ids: Vec<String> = {
let mut st = self
.conn
.prepare_cached("SELECT page_id FROM page_hubs WHERE hub_id=?1")?;
st.query_map([hub], |r| r.get(0))?
.collect::<std::result::Result<_, _>>()?
};
for m in ids {
schema::reindex_page_tags(&self.conn, &m)?;
}
Ok(())
}
@@ -1267,6 +1277,8 @@ impl Graph {
// `hubs` and dangle until those pages are rewritten.
self.exec("DELETE FROM page_hubs WHERE page_id=?1", [&s])?;
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&s])?;
// Members of a deleted hub lose its implicit tag.
self.reindex_hub_members(&s)?;
self.exec(
"INSERT OR REPLACE INTO tombstones(id, hlc) VALUES (?1, ?2)",
params![s, hlc],
+21 -35
View File
@@ -9,6 +9,7 @@
use crate::error::{Error, Result};
use crate::model::{Page, PageId, title_key};
use crate::schema;
use crate::store::{Graph, parse_id};
use std::collections::{HashMap, HashSet};
@@ -113,52 +114,36 @@ impl Graph {
rows.map(|r| parse_id(&r?)).collect()
}
/// Tags of every tagged page: the listed ones, then the type if not already among them
/// (each type implies a tag), names as stored.
/// Tags of every tagged page: the listed ones, then the type and the hub title if not
/// already among them (each implies a tag), names as stored.
pub fn all_page_tags(&self) -> Result<HashMap<PageId, Vec<String>>> {
let mut st = self.conn().prepare_cached(
"SELECT id, tags, types FROM pages WHERE tags != '[]' OR types != '[]'",
)?;
let rows = st.query_map([], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, String>(1)?,
r.get::<_, String>(2)?,
))
})?;
let mut out = HashMap::new();
for row in rows {
let (id, tags, types) = row?;
let mut all: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
let types: Vec<String> = serde_json::from_str(&types).unwrap_or_default();
for t in types.into_iter().take(1) {
if !all.iter().any(|x| title_key(x) == title_key(&t)) {
all.push(t);
for src in schema::tag_sources(self.conn(), None)? {
let mut all: Vec<String> = Vec::new();
for t in src.names() {
if !all.iter().any(|x| title_key(x) == title_key(t)) {
all.push(t.clone());
}
}
out.insert(parse_id(&id)?, all);
if !all.is_empty() {
out.insert(parse_id(&src.id)?, all);
}
}
Ok(out)
}
/// Every tag in use, listed or implied by a type: spelling of its first page, with its page
/// count. Most used first, then by name.
/// Every tag in use (listed, implied by a type or by the page's hub): spelling of its first
/// page, with its page count. Most used first, then by name.
pub fn tag_catalog(&self) -> Result<Vec<TagInfo>> {
let mut st = self.conn().prepare_cached(
"SELECT tags, types FROM pages WHERE tags != '[]' OR types != '[]'
ORDER BY created_at, id",
)?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
let mut used: HashMap<String, (String, u32)> = HashMap::new();
for row in rows {
let (tags, types) = row?;
let tags: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
let types: Vec<String> = serde_json::from_str(&types).unwrap_or_default();
let mut sources = schema::tag_sources(self.conn(), None)?;
sources.sort_by(|a, b| a.id.cmp(&b.id));
for src in sources {
let mut seen = HashSet::new();
for t in tags.into_iter().chain(types.into_iter().take(1)) {
let key = title_key(&t);
for t in src.names() {
let key = title_key(t);
if seen.insert(key.clone()) {
used.entry(key).or_insert((t, 0)).1 += 1;
used.entry(key).or_insert((t.clone(), 0)).1 += 1;
}
}
}
@@ -180,7 +165,8 @@ impl Graph {
/// Renames a tag everywhere: in the `tags` and `types` of every page carrying it (one
/// transaction; each page is rewritten and logged, so it syncs). When a page already lists
/// `new`, the two merge. Returns the number of pages changed.
/// `new`, the two merge. Returns the number of pages changed. A hub's implicit tag is never renamed (the hub page
/// is not touched): only explicit tags and types change.
pub fn rename_tag(&self, old: &str, new: &str) -> Result<usize> {
let new = normalize_tag(new).ok_or_else(|| Error::Invalid("empty tag name".into()))?;
if new.chars().count() > MAX_TAG_CHARS {
+86 -1
View File
@@ -506,7 +506,7 @@ fn old_ops_and_v2_databases_load() {
r.get(0)
})
.unwrap();
assert_eq!(schema, "6");
assert_eq!(schema, "7");
let p = g.get_page(id).unwrap().unwrap();
assert_eq!((p.kind, p.title.as_str()), (PageKind::Note, "Legacy"));
let h = g.create_hub("New hub", "").unwrap();
@@ -911,3 +911,88 @@ fn remote_upserts_store_tags_sorted() {
["alfa", "Beta", "zeta"]
);
}
#[test]
fn a_direct_hub_is_an_implicit_tag_of_its_members() {
let (_d, g) = graph();
let anime = hub(&g, "Anime");
let media = hub(&g, "Media");
g.add_to_hub(anime, media).unwrap();
let a = page(&g, "A", &["x"]);
let b = page(&g, "B", &["x"]);
g.add_to_hub(a, anime).unwrap();
g.add_to_hub(b, anime).unwrap();
// The hub tag is not stored in `tags`, ancestors do not count, hubs and templates get none.
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
let mut got = g.pages_with_tag("anime").unwrap();
got.sort();
let mut want = vec![a, b];
want.sort();
assert_eq!(got, want);
assert!(g.pages_with_tag("Media").unwrap().is_empty());
let tmpl = g.hub_template(anime).unwrap();
assert!(!g.pages_with_tag("Anime").unwrap().contains(&tmpl));
assert!(!g.pages_with_tag("Anime").unwrap().contains(&anime));
// Merges with a same-name type: one tag, the page counted once.
g.set_page_type(a, Some("anime")).unwrap();
let cat = g.tag_catalog().unwrap();
assert_eq!(
cat.iter()
.filter(|t| t.name.to_lowercase() == "anime")
.count(),
1
);
assert_eq!(
cat.iter()
.find(|t| t.name.to_lowercase() == "anime")
.unwrap()
.count,
2
);
assert_eq!(g.all_page_tags().unwrap()[&a], ["anime"]);
// Renaming the hub re-indexes its members without touching them.
g.rename_page(anime, "Series").unwrap();
assert!(
g.pages_with_tag("Anime").unwrap().contains(&a),
"type still implies it"
);
assert!(!g.pages_with_tag("Anime").unwrap().contains(&b));
assert!(g.pages_with_tag("Series").unwrap().contains(&b));
// Moving a page between hubs moves the implicit tag; leaving the hub drops it.
g.add_to_hub(b, media).unwrap();
assert!(!g.pages_with_tag("Series").unwrap().contains(&b));
assert_eq!(g.pages_with_tag("Media").unwrap(), [b]);
g.remove_from_hub(b, media).unwrap();
assert!(g.pages_with_tag("Media").unwrap().is_empty());
// rename_tag never renames the hub; only explicit tags and types.
g.add_to_hub(b, media).unwrap();
assert_eq!(g.rename_tag("Media", "Press").unwrap(), 0);
assert_eq!(g.get_page(media).unwrap().unwrap().title, "Media");
assert_eq!(g.pages_with_tag("Media").unwrap(), [b]);
// Deleting the hub removes the tag from its members.
g.delete_page(media).unwrap();
assert!(g.pages_with_tag("Media").unwrap().is_empty());
}
#[test]
fn v6_databases_gain_hub_tags() {
let dir = tempfile::tempdir().unwrap();
let a = {
let g = Graph::open(dir.path()).unwrap();
let h = hub(&g, "Anime");
let a = page(&g, "A", &["x"]);
g.add_to_hub(a, h).unwrap();
g.conn().execute("DELETE FROM page_tags", []).unwrap();
g.conn()
.execute("UPDATE meta SET value='6' WHERE key='schema'", [])
.unwrap();
a
};
let g = Graph::open(dir.path()).unwrap();
assert_eq!(g.pages_with_tag("anime").unwrap(), [a]);
}