mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 23:36:20 +00:00
feat(core): hubs, tag pages and types, with ffi, history and import support
Hubs and templates are page kinds; tags are pages of kind tag linked by a TAGGED edge; types are plain names on the page. Schema v5. Snapshots carry synapse-kind/tags/types. Also adapts search, import and server tests. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
91a8276966
commit
b800248d67
35 files changed
+7983
-141
No files matched your search
@@ -13,8 +13,16 @@ pub mod parse;
|
||||
pub mod position;
|
||||
mod schema;
|
||||
pub mod store;
|
||||
pub mod structure;
|
||||
pub mod synapse;
|
||||
pub mod tags;
|
||||
pub mod types;
|
||||
|
||||
pub use error::{Error, Result};
|
||||
pub use model::*;
|
||||
pub use store::Graph;
|
||||
pub use structure::{
|
||||
HubConversion, HubInfo, HubPreview, Structure, is_legacy_page, namespace_parent,
|
||||
};
|
||||
pub use tags::{MAX_TAG_CHARS, TagInfo, normalize_tag};
|
||||
pub use types::SUGGESTED_TYPES;
|
||||
@@ -11,6 +11,40 @@ pub fn new_id() -> Uuid {
|
||||
Uuid::now_v7()
|
||||
}
|
||||
|
||||
/// What a page is: a note (an outline of blocks), a hub (a container of pages with a short
|
||||
/// description and an ordered member list, and no blocks) or a template (the outline that new
|
||||
/// notes of a hub start from; every hub owns exactly one, see `Graph::hub_template`).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PageKind {
|
||||
#[default]
|
||||
Note,
|
||||
Hub,
|
||||
Template,
|
||||
/// A topic page: notes point at it from their `tags`.
|
||||
Tag,
|
||||
}
|
||||
|
||||
impl PageKind {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
PageKind::Note => "note",
|
||||
PageKind::Hub => "hub",
|
||||
PageKind::Template => "template",
|
||||
PageKind::Tag => "tag",
|
||||
}
|
||||
}
|
||||
/// Unknown values read as notes.
|
||||
pub fn parse(s: &str) -> Self {
|
||||
match s {
|
||||
"hub" => PageKind::Hub,
|
||||
"template" => PageKind::Template,
|
||||
"tag" => PageKind::Tag,
|
||||
_ => PageKind::Note,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Page {
|
||||
pub id: PageId,
|
||||
@@ -22,12 +56,38 @@ pub struct Page {
|
||||
pub properties: Properties,
|
||||
pub created_at: i64,
|
||||
pub updated_at: i64,
|
||||
/// Defaults to `Note` so ops and snapshots from older versions parse.
|
||||
#[serde(default)]
|
||||
pub kind: PageKind,
|
||||
/// Short plain-text description (hubs).
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
/// Hubs this page belongs to (its "parents", like tags). Ids may dangle (deleted pages,
|
||||
/// pages no longer hubs); readers ignore those.
|
||||
#[serde(default)]
|
||||
pub hubs: Vec<PageId>,
|
||||
/// Titles of the tag pages ([`PageKind::Tag`]) this page is filed under, any number; see
|
||||
/// `tags`. Always in step with the tag pages (created on first use).
|
||||
#[serde(default)]
|
||||
pub tags: Vec<String>,
|
||||
/// What kind of thing this is ("persona", "lugar"...): plain names, not pages; see `types`.
|
||||
#[serde(default)]
|
||||
pub types: Vec<String>,
|
||||
}
|
||||
|
||||
impl Page {
|
||||
pub fn is_journal(&self) -> bool {
|
||||
self.journal_date.is_some()
|
||||
}
|
||||
pub fn is_hub(&self) -> bool {
|
||||
self.kind == PageKind::Hub
|
||||
}
|
||||
pub fn is_template(&self) -> bool {
|
||||
self.kind == PageKind::Template
|
||||
}
|
||||
pub fn is_tag(&self) -> bool {
|
||||
self.kind == PageKind::Tag
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -126,7 +126,7 @@ fn scan_line(line: &str, is_prop: bool, refs: &mut Refs) {
|
||||
}
|
||||
|
||||
/// Finds the `]]` closing a `[[` that opened before `from`, allowing nested `[[..]]`.
|
||||
fn find_close(s: &str, from: usize) -> Option<usize> {
|
||||
pub(crate) fn find_close(s: &str, from: usize) -> Option<usize> {
|
||||
let mut depth = 0;
|
||||
let mut i = from;
|
||||
while i + 1 < s.len() {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
pub const VERSION: i64 = 2;
|
||||
use rusqlite::OptionalExtension;
|
||||
|
||||
pub const VERSION: i64 = 5;
|
||||
|
||||
pub const SCHEMA: &str = r#"
|
||||
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
@@ -12,7 +14,12 @@ CREATE TABLE IF NOT EXISTS pages (
|
||||
properties TEXT NOT NULL DEFAULT '{}',
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
hlc TEXT NOT NULL
|
||||
hlc TEXT NOT NULL,
|
||||
kind TEXT NOT NULL DEFAULT 'note',
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
hubs TEXT NOT NULL DEFAULT '[]',
|
||||
tags TEXT NOT NULL DEFAULT '[]',
|
||||
types TEXT NOT NULL DEFAULT '[]'
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS pages_updated ON pages(updated_at);
|
||||
CREATE INDEX IF NOT EXISTS pages_origin ON pages(origin_journal);
|
||||
@@ -25,6 +32,23 @@ CREATE TABLE IF NOT EXISTS aliases (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS aliases_page ON aliases(page_id);
|
||||
|
||||
-- Derived index of `pages.hubs` (hub membership lives on the member page), kept in step on
|
||||
-- every page write like `refs`.
|
||||
CREATE TABLE IF NOT EXISTS page_hubs (
|
||||
page_id TEXT NOT NULL,
|
||||
hub_id TEXT NOT NULL,
|
||||
PRIMARY KEY (page_id, hub_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS page_hubs_hub ON page_hubs(hub_id);
|
||||
|
||||
-- Derived index of `pages.tags` (normalised tag key per page), kept in step on every page write.
|
||||
CREATE TABLE IF NOT EXISTS page_tags (
|
||||
page_id TEXT NOT NULL,
|
||||
tag_key TEXT NOT NULL,
|
||||
PRIMARY KEY (page_id, tag_key)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS page_tags_key ON page_tags(tag_key);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS blocks (
|
||||
id TEXT PRIMARY KEY,
|
||||
page_id TEXT NOT NULL,
|
||||
@@ -92,6 +116,44 @@ CREATE TABLE IF NOT EXISTS ops (
|
||||
);
|
||||
"#;
|
||||
|
||||
/// Rebuilds the `page_tags` index from every page's `tags` column.
|
||||
pub fn rebuild_page_tags(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
||||
conn.execute("DELETE FROM page_tags", [])?;
|
||||
let rows: Vec<(String, String)> = {
|
||||
let mut st = conn.prepare("SELECT id, tags FROM pages WHERE tags != '[]'")?;
|
||||
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
|
||||
.collect::<rusqlite::Result<_>>()?
|
||||
};
|
||||
let mut ins =
|
||||
conn.prepare("INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)")?;
|
||||
for (id, tags) in rows {
|
||||
let tags: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
|
||||
for t in tags {
|
||||
ins.execute([&id, &crate::model::title_key(&t)])?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rebuilds the `page_hubs` index from every page's `hubs` column.
|
||||
pub fn rebuild_page_hubs(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
||||
conn.execute("DELETE FROM page_hubs", [])?;
|
||||
let rows: Vec<(String, String)> = {
|
||||
let mut st = conn.prepare("SELECT id, hubs FROM pages WHERE hubs != '[]'")?;
|
||||
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
|
||||
.collect::<rusqlite::Result<_>>()?
|
||||
};
|
||||
let mut ins =
|
||||
conn.prepare("INSERT OR IGNORE INTO page_hubs(page_id, hub_id) VALUES (?1, ?2)")?;
|
||||
for (id, hubs) in rows {
|
||||
let hubs: Vec<uuid::Uuid> = serde_json::from_str(&hubs).unwrap_or_default();
|
||||
for h in hubs.into_iter().take(1) {
|
||||
ins.execute([&id, &h.to_string()])?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Upgrades databases created by older versions in place.
|
||||
pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
||||
let has_alias_hlc: bool = conn
|
||||
@@ -100,6 +162,36 @@ pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
|
||||
if !has_alias_hlc {
|
||||
conn.execute_batch("ALTER TABLE aliases ADD COLUMN hlc TEXT NOT NULL DEFAULT ''")?;
|
||||
}
|
||||
// v3: page kinds (hubs), descriptions and hub membership; `page_hubs` is created by
|
||||
// `SCHEMA` and rebuilt from `pages.hubs`.
|
||||
for (col, ddl) in [
|
||||
("kind", "kind TEXT NOT NULL DEFAULT 'note'"),
|
||||
("description", "description TEXT NOT NULL DEFAULT ''"),
|
||||
("hubs", "hubs TEXT NOT NULL DEFAULT '[]'"),
|
||||
// v4: free-form tags per page; `page_tags` is created by `SCHEMA`.
|
||||
("tags", "tags TEXT NOT NULL DEFAULT '[]'"),
|
||||
// v5: tag pages (kind 'tag') and plain-name types per page.
|
||||
("types", "types TEXT NOT NULL DEFAULT '[]'"),
|
||||
] {
|
||||
let has: bool = conn
|
||||
.prepare("SELECT 1 FROM pragma_table_info('pages') WHERE name=?1")?
|
||||
.exists([col])?;
|
||||
if !has {
|
||||
conn.execute_batch(&format!("ALTER TABLE pages ADD COLUMN {ddl}"))?;
|
||||
}
|
||||
}
|
||||
let version: Option<i64> = conn
|
||||
.query_row("SELECT value FROM meta WHERE key='schema'", [], |r| {
|
||||
r.get::<_, String>(0)
|
||||
})
|
||||
.optional()?
|
||||
.and_then(|v| v.parse().ok());
|
||||
if version.is_some_and(|v| v < 3) {
|
||||
rebuild_page_hubs(conn)?;
|
||||
}
|
||||
if version.is_some_and(|v| v < 4) {
|
||||
rebuild_page_tags(conn)?;
|
||||
}
|
||||
conn.execute(
|
||||
"INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)",
|
||||
[VERSION.to_string()],
|
||||
|
||||
@@ -21,8 +21,7 @@ pub fn journal_id(date: NaiveDate) -> PageId {
|
||||
Uuid::new_v5(&JOURNAL_NS, journal_title(date).as_bytes())
|
||||
}
|
||||
|
||||
const PAGE_COLS: &str =
|
||||
"id, title, journal_date, origin_journal, properties, created_at, updated_at";
|
||||
const PAGE_COLS: &str = "id, title, journal_date, origin_journal, properties, created_at, updated_at, kind, description, hubs, tags, types";
|
||||
const BLOCK_COLS: &str =
|
||||
"id, page_id, parent_id, position, content, properties, collapsed, created_at, updated_at";
|
||||
|
||||
@@ -76,13 +75,15 @@ impl Graph {
|
||||
clock.observe(&last);
|
||||
}
|
||||
let blobs = BlobStore::open(dir.join("blobs"))?;
|
||||
Ok(Self {
|
||||
let graph = Self {
|
||||
conn,
|
||||
blobs,
|
||||
clock,
|
||||
dir,
|
||||
now_override: Cell::new(None),
|
||||
})
|
||||
};
|
||||
graph.repair_tag_pages()?;
|
||||
Ok(graph)
|
||||
}
|
||||
|
||||
/// Runs `f` atomically. Calls nest (SQLite savepoints), so callers such as importers can
|
||||
@@ -99,12 +100,16 @@ impl Graph {
|
||||
}
|
||||
|
||||
/// `execute` through the statement cache (hot paths run millions of times on imports).
|
||||
fn exec<P: rusqlite::Params>(&self, sql: &str, params: P) -> rusqlite::Result<usize> {
|
||||
pub(crate) fn exec<P: rusqlite::Params>(
|
||||
&self,
|
||||
sql: &str,
|
||||
params: P,
|
||||
) -> rusqlite::Result<usize> {
|
||||
self.conn.prepare_cached(sql)?.execute(params)
|
||||
}
|
||||
|
||||
/// `query_row` through the statement cache.
|
||||
fn row<T, P: rusqlite::Params>(
|
||||
pub(crate) fn row<T, P: rusqlite::Params>(
|
||||
&self,
|
||||
sql: &str,
|
||||
params: P,
|
||||
@@ -124,7 +129,7 @@ impl Graph {
|
||||
|
||||
/// Atomic scope for one graph operation: a savepoint at top level, a no-op when an
|
||||
/// enclosing transaction already provides atomicity.
|
||||
fn tx(&self) -> Result<Tx<'_>> {
|
||||
pub(crate) fn tx(&self) -> Result<Tx<'_>> {
|
||||
if self.conn.is_autocommit() {
|
||||
return self.savepoint();
|
||||
}
|
||||
@@ -214,7 +219,16 @@ impl Graph {
|
||||
Ok(page)
|
||||
}
|
||||
|
||||
fn create_page_tx(&self, new: NewPage) -> Result<Page> {
|
||||
pub(crate) fn create_page_tx(&self, new: NewPage) -> Result<Page> {
|
||||
self.create_page_kind_tx(new, PageKind::Note, String::new())
|
||||
}
|
||||
|
||||
pub(crate) fn create_page_kind_tx(
|
||||
&self,
|
||||
new: NewPage,
|
||||
kind: PageKind,
|
||||
description: String,
|
||||
) -> Result<Page> {
|
||||
let title = new.title.trim().to_string();
|
||||
if title.is_empty() {
|
||||
return Err(Error::Invalid("empty page title".into()));
|
||||
@@ -238,6 +252,11 @@ impl Graph {
|
||||
properties: new.properties,
|
||||
created_at: new.created_at.unwrap_or(now),
|
||||
updated_at: new.updated_at.unwrap_or(now),
|
||||
kind,
|
||||
description,
|
||||
hubs: Vec::new(),
|
||||
tags: Vec::new(),
|
||||
types: Vec::new(),
|
||||
};
|
||||
self.write_page(&page, &self.tick())?;
|
||||
Ok(page)
|
||||
@@ -270,10 +289,11 @@ impl Graph {
|
||||
|
||||
/// Pages ordered by last update (most recent first).
|
||||
pub fn list_pages(&self, include_journals: bool, limit: u32, offset: u32) -> Result<Vec<Page>> {
|
||||
// Templates are reached through their hub, never listed as pages.
|
||||
let filter = if include_journals {
|
||||
""
|
||||
"WHERE kind != 'template'"
|
||||
} else {
|
||||
"WHERE journal_date IS NULL"
|
||||
"WHERE journal_date IS NULL AND kind != 'template'"
|
||||
};
|
||||
let mut st = self.conn.prepare_cached(&format!(
|
||||
"SELECT {PAGE_COLS} FROM pages {filter} ORDER BY updated_at DESC LIMIT ?1 OFFSET ?2"
|
||||
@@ -338,9 +358,12 @@ impl Graph {
|
||||
st.query_map([&old_key], |r| r.get(0))?
|
||||
.collect::<std::result::Result<_, _>>()?
|
||||
};
|
||||
page.title = new_title.to_string();
|
||||
let old_title = std::mem::replace(&mut page.title, new_title.to_string());
|
||||
page.updated_at = self.now_ms();
|
||||
self.write_page(&page, &self.tick())?;
|
||||
if page.is_tag() {
|
||||
self.retitle_tag(&old_title, new_title)?;
|
||||
}
|
||||
for bid in referencing {
|
||||
if let Some(mut b) = self.get_block(parse_id(&bid)?)? {
|
||||
let rewritten = parse::rewrite_refs(&b.content, &old_key, new_title);
|
||||
@@ -365,9 +388,34 @@ impl Graph {
|
||||
Ok(page)
|
||||
}
|
||||
|
||||
/// Deletes a page and all its blocks.
|
||||
/// Deletes a page and all its blocks; when it is a hub, its members leave it.
|
||||
pub fn delete_page(&self, id: PageId) -> Result<()> {
|
||||
let tx = self.tx()?;
|
||||
if let Some(p) = self.get_page(id)? {
|
||||
if p.is_template() {
|
||||
return Err(Error::Invalid(
|
||||
"a template cannot be deleted on its own; it goes with its hub".into(),
|
||||
));
|
||||
}
|
||||
if p.is_hub() {
|
||||
for t in self.hub_template_ids(id)? {
|
||||
self.delete_page_rows(t)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.delete_page_rows(id)?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn delete_page_rows(&self, id: PageId) -> Result<()> {
|
||||
// Members of a deleted hub leave it (each member page is rewritten and logged).
|
||||
self.drop_hub_from_members(id)?;
|
||||
if let Some(p) = self.get_page(id)?
|
||||
&& p.is_tag()
|
||||
{
|
||||
self.drop_tag_from_members(&p.title)?;
|
||||
}
|
||||
let ids: Vec<String> = {
|
||||
let mut st = self
|
||||
.conn
|
||||
@@ -379,7 +427,6 @@ impl Graph {
|
||||
self.remove_block_row(parse_id(&b)?, &self.tick())?;
|
||||
}
|
||||
self.remove_page_row(id, &self.tick())?;
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -437,6 +484,11 @@ impl Graph {
|
||||
properties: Properties::new(),
|
||||
created_at: ms,
|
||||
updated_at: ms,
|
||||
kind: PageKind::Note,
|
||||
description: String::new(),
|
||||
hubs: Vec::new(),
|
||||
tags: Vec::new(),
|
||||
types: Vec::new(),
|
||||
};
|
||||
self.write_page(&page, &self.tick())?;
|
||||
Ok(page)
|
||||
@@ -593,6 +645,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> {
|
||||
self.ensure_not_hub(page)?;
|
||||
let tx = self.tx()?;
|
||||
let (parent_id, position) = self.resolve_placement(page, at)?;
|
||||
let now = self.now_ms();
|
||||
@@ -615,6 +668,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<()> {
|
||||
self.ensure_not_hub(block.page_id)?;
|
||||
let tx = self.tx()?;
|
||||
self.write_block(block, &self.tick())?;
|
||||
self.ensure_ref_pages(block)?;
|
||||
@@ -660,6 +714,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> {
|
||||
self.ensure_not_hub(page)?;
|
||||
let tx = self.tx()?;
|
||||
let mut b = self
|
||||
.get_block(id)?
|
||||
@@ -712,6 +767,21 @@ impl Graph {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Hubs have no outline: block writes into them are refused.
|
||||
fn ensure_not_hub(&self, page: PageId) -> Result<()> {
|
||||
let kind: Option<String> = self
|
||||
.row(
|
||||
"SELECT kind FROM pages WHERE id=?1",
|
||||
[page.to_string()],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.optional()?;
|
||||
if kind.as_deref() == Some(PageKind::Hub.as_str()) {
|
||||
return Err(Error::Invalid("hubs have no blocks".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn descendants(&self, id: BlockId) -> Result<Vec<BlockId>> {
|
||||
let mut st = self.conn.prepare_cached(
|
||||
"WITH RECURSIVE d(id) AS (SELECT id FROM blocks WHERE parent_id=?1
|
||||
@@ -878,7 +948,7 @@ impl Graph {
|
||||
}
|
||||
|
||||
/// Bumps `updated_at` and records today's activity for a page.
|
||||
fn touch_page(&self, page: PageId) -> Result<()> {
|
||||
pub(crate) fn touch_page(&self, page: PageId) -> Result<()> {
|
||||
let now = self.now_ms();
|
||||
let day = journal_title(day_of(now));
|
||||
self.exec(
|
||||
@@ -1110,11 +1180,11 @@ impl Graph {
|
||||
|
||||
// ----------------------------------------------------------- raw writes
|
||||
|
||||
fn tick(&self) -> String {
|
||||
pub(crate) fn tick(&self) -> String {
|
||||
self.clock.tick(self.now_ms())
|
||||
}
|
||||
|
||||
fn log(&self, hlc: &str, op: &Op) -> Result<()> {
|
||||
pub(crate) fn log(&self, hlc: &str, op: &Op) -> Result<()> {
|
||||
self.exec(
|
||||
"INSERT INTO ops(hlc, payload) VALUES (?1, ?2)",
|
||||
params![hlc, serde_json::to_string(op)?],
|
||||
@@ -1122,17 +1192,17 @@ impl Graph {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_page(&self, page: &Page, hlc: &str) -> Result<()> {
|
||||
pub(crate) fn write_page(&self, page: &Page, hlc: &str) -> Result<()> {
|
||||
self.write_page_row(page, hlc)?;
|
||||
self.log(hlc, &Op::UpsertPage { page: page.clone() })
|
||||
}
|
||||
|
||||
fn write_page_row(&self, p: &Page, hlc: &str) -> Result<()> {
|
||||
self.exec(
|
||||
"INSERT INTO pages(id, title, title_key, journal_date, origin_journal, properties, created_at, updated_at, hlc)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
|
||||
"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)
|
||||
ON CONFLICT(id) DO UPDATE SET title=?2, title_key=?3, journal_date=?4, origin_journal=?5,
|
||||
properties=?6, created_at=?7, updated_at=?8, hlc=?9",
|
||||
properties=?6, created_at=?7, updated_at=?8, hlc=?9, kind=?10, description=?11, hubs=?12, tags=?13, types=?14",
|
||||
params![
|
||||
p.id.to_string(),
|
||||
p.title,
|
||||
@@ -1142,9 +1212,30 @@ impl Graph {
|
||||
serde_json::to_string(&p.properties)?,
|
||||
p.created_at,
|
||||
p.updated_at,
|
||||
hlc
|
||||
hlc,
|
||||
p.kind.as_str(),
|
||||
p.description,
|
||||
serde_json::to_string(&p.hubs)?,
|
||||
serde_json::to_string(&p.tags)?,
|
||||
serde_json::to_string(&p.types)?
|
||||
],
|
||||
)?;
|
||||
let id = p.id.to_string();
|
||||
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&id])?;
|
||||
for t in &p.tags {
|
||||
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) {
|
||||
self.exec(
|
||||
"INSERT OR IGNORE INTO page_hubs(page_id, hub_id) VALUES (?1, ?2)",
|
||||
params![id, h.to_string()],
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1177,6 +1268,10 @@ impl Graph {
|
||||
.execute("DELETE FROM page_activity WHERE page_id=?1", [&s])?;
|
||||
self.conn
|
||||
.execute("DELETE FROM synapses WHERE a=?1 OR b=?1", [&s])?;
|
||||
// Only the page's own memberships: rows naming it as a hub mirror other pages'
|
||||
// `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])?;
|
||||
self.exec(
|
||||
"INSERT OR REPLACE INTO tombstones(id, hlc) VALUES (?1, ?2)",
|
||||
params![s, hlc],
|
||||
@@ -1329,7 +1424,7 @@ impl Graph {
|
||||
}
|
||||
|
||||
/// Savepoint guard: rolled back on drop unless committed.
|
||||
struct Tx<'a> {
|
||||
pub(crate) struct Tx<'a> {
|
||||
conn: &'a Connection,
|
||||
/// Whether this guard opened a savepoint (false when nested in a transaction).
|
||||
active: bool,
|
||||
@@ -1337,7 +1432,7 @@ struct Tx<'a> {
|
||||
}
|
||||
|
||||
impl Tx<'_> {
|
||||
fn commit(mut self) -> Result<()> {
|
||||
pub(crate) fn commit(mut self) -> Result<()> {
|
||||
if self.active {
|
||||
self.conn.execute_batch("RELEASE graph")?;
|
||||
}
|
||||
@@ -1397,6 +1492,11 @@ fn page_row(r: &Row) -> rusqlite::Result<Page> {
|
||||
properties: props(r.get(4)?),
|
||||
created_at: r.get(5)?,
|
||||
updated_at: r.get(6)?,
|
||||
kind: PageKind::parse(&r.get::<_, String>(7)?),
|
||||
description: r.get(8)?,
|
||||
hubs: serde_json::from_str(&r.get::<_, String>(9)?).unwrap_or_default(),
|
||||
tags: serde_json::from_str(&r.get::<_, String>(10)?).unwrap_or_default(),
|
||||
types: serde_json::from_str(&r.get::<_, String>(11)?).unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,226 @@
|
||||
//! Tags: topic pages ("neurociencia", "finanzas") that notes are filed under.
|
||||
//!
|
||||
//! A tag is a page of kind [`PageKind::Tag`]: it has an outline, backlinks and a place in the
|
||||
//! graph like any note. A page lists the titles of its tag pages in [`Page::tags`] (synced
|
||||
//! with the page, last writer wins), any number of them, and a derived `page_tags` index
|
||||
//! answers "which pages have this tag". Tagging with a title that has no page creates the tag
|
||||
//! page; tagging with an existing note turns that note into a tag page. Renaming or deleting
|
||||
//! a tag page keeps its members in step. Names compare case-insensitively ([`title_key`]).
|
||||
//! What a page *is* ("persona", "lugar") is a different, name-only mechanism: see `types`.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::model::{NewPage, Page, PageId, PageKind, title_key};
|
||||
use crate::store::{Graph, parse_id};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Longest tag (or type) name, in characters.
|
||||
pub const MAX_TAG_CHARS: usize = 48;
|
||||
|
||||
/// A tag with the number of pages filed under it (tag pages with no members count 0).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct TagInfo {
|
||||
pub name: String,
|
||||
pub count: u32,
|
||||
/// Part of the seeded suggestions (types only; tag pages are never seeded).
|
||||
pub suggested: bool,
|
||||
}
|
||||
|
||||
/// Cleans a tag name: leading `#` dropped, whitespace collapsed. `None` when nothing is left.
|
||||
pub fn normalize_tag(raw: &str) -> Option<String> {
|
||||
let t = raw.trim().trim_start_matches('#');
|
||||
let t = t.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
(!t.is_empty()).then_some(t)
|
||||
}
|
||||
|
||||
impl Graph {
|
||||
/// The tag page called `name`, created (or made out of a note of that name) on demand.
|
||||
fn ensure_tag_page(&self, name: &str) -> Result<Page> {
|
||||
if let Some(mut p) = self.page_by_title(name)? {
|
||||
return match p.kind {
|
||||
PageKind::Tag => Ok(p),
|
||||
PageKind::Note if !p.is_journal() => {
|
||||
p.kind = PageKind::Tag;
|
||||
p.updated_at = self.now_ms();
|
||||
self.write_page(&p, &self.tick())?;
|
||||
Ok(p)
|
||||
}
|
||||
_ => Err(Error::Invalid(format!(
|
||||
"{name:?} is a hub, template or journal and cannot be a tag"
|
||||
))),
|
||||
};
|
||||
}
|
||||
self.create_page_kind_tx(NewPage::titled(name), PageKind::Tag, String::new())
|
||||
}
|
||||
|
||||
/// Replaces the tags of `page` (names cleaned, duplicates dropped case-insensitively,
|
||||
/// order kept; each becomes the title of a tag page). Journals, templates and tag pages
|
||||
/// cannot be tagged, nor can a page be tagged with itself.
|
||||
pub fn set_page_tags(&self, page: PageId, tags: Vec<String>) -> Result<Page> {
|
||||
let tx = self.tx()?;
|
||||
let mut p = self
|
||||
.get_page(page)?
|
||||
.ok_or_else(|| Error::NotFound(page.to_string()))?;
|
||||
let mut wanted: Vec<String> = Vec::with_capacity(tags.len());
|
||||
for raw in tags {
|
||||
let Some(t) = normalize_tag(&raw) else {
|
||||
continue;
|
||||
};
|
||||
if t.chars().count() > MAX_TAG_CHARS {
|
||||
return Err(Error::Invalid(format!(
|
||||
"tag {t:?} is longer than {MAX_TAG_CHARS} characters"
|
||||
)));
|
||||
}
|
||||
if !wanted.iter().any(|x| title_key(x) == title_key(&t)) {
|
||||
wanted.push(t);
|
||||
}
|
||||
}
|
||||
if (p.is_journal() || p.is_template() || p.is_tag()) && !wanted.is_empty() {
|
||||
return Err(Error::Invalid(
|
||||
"journals, templates and tag pages cannot have tags".into(),
|
||||
));
|
||||
}
|
||||
if wanted.iter().any(|t| title_key(t) == title_key(&p.title)) {
|
||||
return Err(Error::Invalid("a page cannot be its own tag".into()));
|
||||
}
|
||||
let mut next = Vec::with_capacity(wanted.len());
|
||||
for t in wanted {
|
||||
next.push(self.ensure_tag_page(&t)?.title);
|
||||
}
|
||||
if next == p.tags {
|
||||
tx.commit()?;
|
||||
return Ok(p);
|
||||
}
|
||||
p.tags = next;
|
||||
p.updated_at = self.now_ms();
|
||||
self.write_page(&p, &self.tick())?;
|
||||
tx.commit()?;
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Adds a tag (no-op when the page already has it).
|
||||
pub fn add_page_tag(&self, page: PageId, tag: &str) -> Result<Page> {
|
||||
let p = self
|
||||
.get_page(page)?
|
||||
.ok_or_else(|| Error::NotFound(page.to_string()))?;
|
||||
let mut tags = p.tags;
|
||||
tags.push(tag.to_string());
|
||||
self.set_page_tags(page, tags)
|
||||
}
|
||||
|
||||
/// Removes a tag (no-op when the page does not have it). The tag page stays.
|
||||
pub fn remove_page_tag(&self, page: PageId, tag: &str) -> Result<Page> {
|
||||
let p = self
|
||||
.get_page(page)?
|
||||
.ok_or_else(|| Error::NotFound(page.to_string()))?;
|
||||
let key = title_key(tag);
|
||||
let tags = p.tags.into_iter().filter(|t| title_key(t) != key).collect();
|
||||
self.set_page_tags(page, tags)
|
||||
}
|
||||
|
||||
/// Pages carrying `tag`, most recently updated first.
|
||||
pub fn pages_with_tag(&self, tag: &str) -> Result<Vec<PageId>> {
|
||||
let mut st = self.conn().prepare_cached(
|
||||
"SELECT p.id FROM page_tags t JOIN pages p ON p.id = t.page_id
|
||||
WHERE t.tag_key=?1 ORDER BY p.updated_at DESC, p.id",
|
||||
)?;
|
||||
let rows = st.query_map([title_key(tag)], |r| r.get::<_, String>(0))?;
|
||||
rows.map(|r| parse_id(&r?)).collect()
|
||||
}
|
||||
|
||||
/// Tags of every tagged page, as stored.
|
||||
pub fn all_page_tags(&self) -> Result<HashMap<PageId, Vec<String>>> {
|
||||
let mut st = self
|
||||
.conn()
|
||||
.prepare_cached("SELECT id, tags FROM pages WHERE tags != '[]'")?;
|
||||
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
|
||||
let mut out = HashMap::new();
|
||||
for row in rows {
|
||||
let (id, tags) = row?;
|
||||
out.insert(
|
||||
parse_id(&id)?,
|
||||
serde_json::from_str(&tags).unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Every tag page with the number of pages under it: most used first, then by name.
|
||||
pub fn tag_catalog(&self) -> Result<Vec<TagInfo>> {
|
||||
let mut st = self.conn().prepare_cached(
|
||||
"SELECT p.title, (SELECT COUNT(*) FROM page_tags t WHERE t.tag_key = p.title_key)
|
||||
FROM pages p WHERE p.kind = 'tag'",
|
||||
)?;
|
||||
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, u32>(1)?)))?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
let (name, count) = row?;
|
||||
out.push(TagInfo {
|
||||
name,
|
||||
count,
|
||||
suggested: false,
|
||||
});
|
||||
}
|
||||
out.sort_by(|a, b| {
|
||||
b.count
|
||||
.cmp(&a.count)
|
||||
.then_with(|| title_key(&a.name).cmp(&title_key(&b.name)))
|
||||
});
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A tag page was renamed: its members now list the new title.
|
||||
pub(crate) fn retitle_tag(&self, old: &str, new: &str) -> Result<()> {
|
||||
for id in self.pages_with_tag(old)? {
|
||||
if let Some(mut p) = self.get_page(id)? {
|
||||
let key = title_key(old);
|
||||
for t in &mut p.tags {
|
||||
if title_key(t) == key {
|
||||
*t = new.to_string();
|
||||
}
|
||||
}
|
||||
self.write_page(&p, &self.tick())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A tag page was deleted: its members stop listing it.
|
||||
pub(crate) fn drop_tag_from_members(&self, title: &str) -> Result<()> {
|
||||
let key = title_key(title);
|
||||
for id in self.pages_with_tag(title)? {
|
||||
if let Some(mut p) = self.get_page(id)? {
|
||||
p.tags.retain(|t| title_key(t) != key);
|
||||
self.write_page(&p, &self.tick())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Databases from before tag pages (or snapshots of them) list tags that have no page:
|
||||
/// create the missing pages, keeping the spelling first used.
|
||||
pub(crate) fn repair_tag_pages(&self) -> Result<()> {
|
||||
let missing: Vec<String> = {
|
||||
let mut st = self.conn().prepare_cached(
|
||||
"SELECT DISTINCT tag_key FROM page_tags
|
||||
WHERE tag_key NOT IN (SELECT title_key FROM pages)",
|
||||
)?;
|
||||
st.query_map([], |r| r.get(0))?
|
||||
.collect::<std::result::Result<_, _>>()?
|
||||
};
|
||||
if missing.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let tx = self.tx()?;
|
||||
let mut done = std::collections::HashSet::new();
|
||||
for (_, tags) in self.all_page_tags()? {
|
||||
for t in tags {
|
||||
let key = title_key(&t);
|
||||
if missing.contains(&key) && done.insert(key) {
|
||||
self.ensure_tag_page(&t)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
tx.commit()?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
//! Types: what kind of thing a page is ("persona", "lugar", "empresa").
|
||||
//!
|
||||
//! Types are plain names from a small vocabulary, not pages: a page carries its own list
|
||||
//! ([`Page::types`], synced with the page, last writer wins). Topics are a different
|
||||
//! mechanism: see `tags`.
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::model::{Page, PageId, title_key};
|
||||
use crate::store::Graph;
|
||||
use crate::tags::{MAX_TAG_CHARS, TagInfo, normalize_tag};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Types offered in pickers before they are used anywhere (the seed of the vocabulary).
|
||||
pub const SUGGESTED_TYPES: [&str; 10] = [
|
||||
"persona",
|
||||
"lugar",
|
||||
"empresa",
|
||||
"cliente",
|
||||
"herramienta",
|
||||
"concepto",
|
||||
"idea",
|
||||
"evento",
|
||||
"recurso",
|
||||
"receta",
|
||||
];
|
||||
|
||||
impl Graph {
|
||||
/// Replaces the types of `page` (names cleaned, duplicates dropped case-insensitively,
|
||||
/// order kept). Journals and templates cannot be typed.
|
||||
pub fn set_page_types(&self, page: PageId, types: Vec<String>) -> Result<Page> {
|
||||
let tx = self.tx()?;
|
||||
let mut p = self
|
||||
.get_page(page)?
|
||||
.ok_or_else(|| Error::NotFound(page.to_string()))?;
|
||||
let mut next: Vec<String> = Vec::with_capacity(types.len());
|
||||
for raw in types {
|
||||
let Some(t) = normalize_tag(&raw) else {
|
||||
continue;
|
||||
};
|
||||
if t.chars().count() > MAX_TAG_CHARS {
|
||||
return Err(Error::Invalid(format!(
|
||||
"type {t:?} is longer than {MAX_TAG_CHARS} characters"
|
||||
)));
|
||||
}
|
||||
if !next.iter().any(|x| title_key(x) == title_key(&t)) {
|
||||
next.push(t);
|
||||
}
|
||||
}
|
||||
if next == p.types {
|
||||
tx.commit()?;
|
||||
return Ok(p);
|
||||
}
|
||||
if (p.is_journal() || p.is_template()) && !next.is_empty() {
|
||||
return Err(Error::Invalid(
|
||||
"journals and templates cannot have types".into(),
|
||||
));
|
||||
}
|
||||
p.types = next;
|
||||
p.updated_at = self.now_ms();
|
||||
self.write_page(&p, &self.tick())?;
|
||||
tx.commit()?;
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// Adds a type (no-op when the page already has it).
|
||||
pub fn add_page_type(&self, page: PageId, ty: &str) -> Result<Page> {
|
||||
let p = self
|
||||
.get_page(page)?
|
||||
.ok_or_else(|| Error::NotFound(page.to_string()))?;
|
||||
let mut types = p.types;
|
||||
types.push(ty.to_string());
|
||||
self.set_page_types(page, types)
|
||||
}
|
||||
|
||||
/// Removes a type (no-op when the page does not have it).
|
||||
pub fn remove_page_type(&self, page: PageId, ty: &str) -> Result<Page> {
|
||||
let p = self
|
||||
.get_page(page)?
|
||||
.ok_or_else(|| Error::NotFound(page.to_string()))?;
|
||||
let key = title_key(ty);
|
||||
let types = p
|
||||
.types
|
||||
.into_iter()
|
||||
.filter(|t| title_key(t) != key)
|
||||
.collect();
|
||||
self.set_page_types(page, types)
|
||||
}
|
||||
|
||||
/// The vocabulary: every type in use (spelling of its first page) plus the suggestions not
|
||||
/// used yet. Used types first by count then name, then unused suggestions in seed order.
|
||||
pub fn type_catalog(&self) -> Result<Vec<TagInfo>> {
|
||||
let mut st = self.conn().prepare_cached(
|
||||
"SELECT types FROM pages WHERE types != '[]' ORDER BY created_at, id",
|
||||
)?;
|
||||
let rows = st.query_map([], |r| r.get::<_, String>(0))?;
|
||||
let mut used: HashMap<String, (String, u32)> = HashMap::new();
|
||||
for row in rows {
|
||||
let types: Vec<String> = serde_json::from_str(&row?).unwrap_or_default();
|
||||
for t in types {
|
||||
used.entry(title_key(&t)).or_insert((t, 0)).1 += 1;
|
||||
}
|
||||
}
|
||||
let suggested = |k: &str| SUGGESTED_TYPES.iter().any(|s| title_key(s) == k);
|
||||
let mut out: Vec<TagInfo> = used
|
||||
.iter()
|
||||
.map(|(k, (name, count))| TagInfo {
|
||||
name: name.clone(),
|
||||
count: *count,
|
||||
suggested: suggested(k),
|
||||
})
|
||||
.collect();
|
||||
out.sort_by(|a, b| {
|
||||
b.count
|
||||
.cmp(&a.count)
|
||||
.then_with(|| title_key(&a.name).cmp(&title_key(&b.name)))
|
||||
});
|
||||
for s in SUGGESTED_TYPES {
|
||||
if !used.contains_key(&title_key(s)) {
|
||||
out.push(TagInfo {
|
||||
name: s.to_string(),
|
||||
count: 0,
|
||||
suggested: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user