mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-27 07:46:25 +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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,806 @@
|
||||
use serde_json::json;
|
||||
use synapse_core::{
|
||||
Error, Graph, HubConversion, NewPage, Op, PageId, PageKind, Placement, is_legacy_page,
|
||||
namespace_parent,
|
||||
};
|
||||
|
||||
fn graph() -> (tempfile::TempDir, Graph) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let g = Graph::open(dir.path()).unwrap();
|
||||
(dir, g)
|
||||
}
|
||||
|
||||
fn page(g: &Graph, title: &str, blocks: &[&str]) -> PageId {
|
||||
let p = g.ensure_page(title, None).unwrap();
|
||||
for b in blocks {
|
||||
g.insert_block(p.id, Placement::LastChildOf(None), b)
|
||||
.unwrap();
|
||||
}
|
||||
p.id
|
||||
}
|
||||
|
||||
fn hub(g: &Graph, title: &str) -> PageId {
|
||||
g.create_hub(title, "").unwrap().id
|
||||
}
|
||||
|
||||
fn titles(g: &Graph, ids: &[PageId]) -> Vec<String> {
|
||||
ids.iter()
|
||||
.map(|&i| g.get_page(i).unwrap().unwrap().title)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn texts(g: &Graph, id: PageId) -> Vec<(usize, String)> {
|
||||
g.page_tree(id)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|(d, b)| (d, b.content))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn invalid<T: std::fmt::Debug>(r: synapse_core::Result<T>) -> bool {
|
||||
matches!(r, Err(Error::Invalid(_)))
|
||||
}
|
||||
|
||||
/// Ships every op of `from` newer than `after` to `to`; returns how many applied.
|
||||
fn ship(from: &Graph, to: &Graph, after: i64) -> usize {
|
||||
from.ops_since(after, 100_000)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|r| to.apply_remote(&r.hlc, &r.op).unwrap())
|
||||
.count()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_belongs_to_at_most_one_hub() {
|
||||
let (_d, g) = graph();
|
||||
let media = g.create_hub("Media", " Things I watch ").unwrap();
|
||||
assert_eq!(media.kind, PageKind::Hub);
|
||||
assert_eq!(media.description, "Things I watch");
|
||||
let work = hub(&g, "Work");
|
||||
let books = hub(&g, "Books");
|
||||
let zeta = page(&g, "Zeta", &["z"]);
|
||||
let alpha = page(&g, "Alpha", &["a"]);
|
||||
|
||||
g.add_to_hub(zeta, media.id).unwrap();
|
||||
g.add_to_hub(alpha, media.id).unwrap();
|
||||
g.add_to_hub(books, media.id).unwrap();
|
||||
// Duplicates are no-ops.
|
||||
let seq = g.last_seq().unwrap();
|
||||
g.add_to_hub(alpha, media.id).unwrap();
|
||||
assert_eq!(g.last_seq().unwrap(), seq);
|
||||
|
||||
// Sub-hubs first, then notes, each by title.
|
||||
assert_eq!(
|
||||
titles(&g, &g.hub_members(media.id).unwrap()),
|
||||
["Books", "Alpha", "Zeta"]
|
||||
);
|
||||
assert_eq!(titles(&g, &g.hubs_of(alpha).unwrap()), ["Media"]);
|
||||
|
||||
// A page lives in one hub: adding it elsewhere moves it.
|
||||
g.add_to_hub(alpha, work).unwrap();
|
||||
assert_eq!(titles(&g, &g.hubs_of(alpha).unwrap()), ["Work"]);
|
||||
assert_eq!(g.get_page(alpha).unwrap().unwrap().hubs, [work]);
|
||||
assert_eq!(
|
||||
titles(&g, &g.hub_members(media.id).unwrap()),
|
||||
["Books", "Zeta"]
|
||||
);
|
||||
assert!(invalid(g.set_page_hubs(zeta, vec![work, media.id])));
|
||||
let p = g.set_page_hubs(zeta, vec![work, work]).unwrap();
|
||||
assert_eq!(p.hubs, [work]);
|
||||
g.remove_from_hub(zeta, work).unwrap();
|
||||
assert!(g.hubs_of(zeta).unwrap().is_empty());
|
||||
// A template cannot leave its hub.
|
||||
let t = g.hub_template(work).unwrap();
|
||||
assert!(invalid(g.add_to_hub(t, media.id)));
|
||||
|
||||
let s = g.set_hub_description(media.id, "Screen and paper").unwrap();
|
||||
assert_eq!(s.description, "Screen and paper");
|
||||
assert!(invalid(g.set_hub_description(zeta, "x")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hubs_have_no_blocks() {
|
||||
let (_d, g) = graph();
|
||||
let h = hub(&g, "Hub");
|
||||
let n = page(&g, "Note", &["one"]);
|
||||
assert!(invalid(g.insert_block(
|
||||
h,
|
||||
Placement::LastChildOf(None),
|
||||
"x"
|
||||
)));
|
||||
let b = g.page_tree(n).unwrap()[0].1.clone();
|
||||
assert!(invalid(g.move_block(b.id, h, Placement::LastChildOf(None))));
|
||||
let mut moved = b.clone();
|
||||
moved.page_id = h;
|
||||
assert!(invalid(g.put_block(&moved)));
|
||||
assert!(g.page_tree(h).unwrap().is_empty());
|
||||
// A date title cannot be a hub.
|
||||
assert!(invalid(g.create_hub("2024-01-02", "")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn membership_validation_and_cycles() {
|
||||
let (_d, g) = graph();
|
||||
let a = hub(&g, "A");
|
||||
let b = hub(&g, "B");
|
||||
let c = hub(&g, "C");
|
||||
let note = page(&g, "Note", &[]);
|
||||
let j = g
|
||||
.journal(chrono::NaiveDate::from_ymd_opt(2024, 1, 2).unwrap())
|
||||
.unwrap();
|
||||
g.add_to_hub(b, a).unwrap(); // A ⊃ B
|
||||
g.add_to_hub(c, b).unwrap(); // B ⊃ C
|
||||
|
||||
assert!(invalid(g.add_to_hub(a, a)), "self");
|
||||
assert!(invalid(g.add_to_hub(a, c)), "A inside C would be a cycle");
|
||||
assert!(invalid(g.add_to_hub(a, b)), "direct cycle");
|
||||
assert!(invalid(g.add_to_hub(j.id, a)), "journals are never members");
|
||||
assert!(invalid(g.add_to_hub(note, note)));
|
||||
assert!(invalid(g.add_to_hub(a, note)), "a note is not a hub");
|
||||
assert!(matches!(
|
||||
g.add_to_hub(note, synapse_core::new_id()),
|
||||
Err(Error::NotFound(_))
|
||||
));
|
||||
// A note can be in a hub nested anywhere; a hub can be in two branches (DAG).
|
||||
g.add_to_hub(note, c).unwrap();
|
||||
g.add_to_hub(c, a).unwrap();
|
||||
let s = g.structure().unwrap();
|
||||
let info = |id| s.hubs.iter().find(|h| h.page == id).unwrap();
|
||||
assert_eq!(info(a).members, [b, c]);
|
||||
assert_eq!(info(c).depth, 1, "shortest path from a root");
|
||||
assert_eq!(s.home[¬e], c);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_page_cleans_memberships() {
|
||||
let (_d, g) = graph();
|
||||
let h = hub(&g, "H");
|
||||
let other = hub(&g, "Other");
|
||||
let n = page(&g, "N", &["x"]);
|
||||
g.add_to_hub(n, h).unwrap();
|
||||
g.add_to_hub(h, other).unwrap();
|
||||
|
||||
let seq = g.last_seq().unwrap();
|
||||
g.delete_page(h).unwrap();
|
||||
assert!(g.get_page(n).unwrap().unwrap().hubs.is_empty());
|
||||
let logged: Vec<_> = g
|
||||
.ops_since(seq, 100)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.filter_map(|r| match r.op {
|
||||
Op::UpsertPage { page } => Some(page),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert!(logged.iter().any(|p| p.id == n && p.hubs.is_empty()));
|
||||
assert!(g.hub_members(other).unwrap().is_empty());
|
||||
|
||||
g.delete_page(n).unwrap();
|
||||
let s = g.structure().unwrap();
|
||||
assert_eq!(s.hubs.len(), 1);
|
||||
assert!(s.hubs[0].members.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversion_preview() {
|
||||
let (_d, g) = graph();
|
||||
g.set_now(Some(1_700_000_000_000));
|
||||
let p = page(
|
||||
&g,
|
||||
"Entretenimiento/TV/Anime",
|
||||
&[
|
||||
"## Series",
|
||||
"[[Naruto]]",
|
||||
"#Bleach, [[2024-01-02]]",
|
||||
"type:: [[Genre]]",
|
||||
"My **favourite** ones, see [[One Piece]] and #[[Death Note]]",
|
||||
"[[Entretenimiento/TV/Anime]]",
|
||||
"[[Naruto]] again with words",
|
||||
],
|
||||
);
|
||||
// A dangling alias (its page is gone) must not break anything.
|
||||
let gone = page(&g, "Gone", &[]);
|
||||
g.set_alias("Ghost", Some(gone)).unwrap();
|
||||
g.conn()
|
||||
.execute("DELETE FROM pages WHERE id=?1", [gone.to_string()])
|
||||
.unwrap();
|
||||
page(&g, "Uses", &["mentions [[Ghost]]"]);
|
||||
|
||||
let prop = page(&g, "Props", &[]);
|
||||
let mut props = serde_json::Map::new();
|
||||
props.insert("parent".into(), json!("[[Entretenimiento/TV/Anime]]"));
|
||||
g.set_page_properties(prop, props).unwrap();
|
||||
g.set_alias("Animu", Some(p)).unwrap();
|
||||
page(&g, "Tagger", &["watch #Animu"]);
|
||||
page(
|
||||
&g,
|
||||
"BlockProp",
|
||||
&["x\ncategory:: [[Entretenimiento/TV/Anime]]"],
|
||||
);
|
||||
let j = g
|
||||
.journal(chrono::NaiveDate::from_ymd_opt(2024, 3, 3).unwrap())
|
||||
.unwrap();
|
||||
g.insert_block(j.id, Placement::LastChildOf(None), "#Animu")
|
||||
.unwrap();
|
||||
|
||||
let pv = g.hub_conversion_preview(p).unwrap();
|
||||
assert_eq!(pv.suggested_title, "Anime");
|
||||
assert_eq!(
|
||||
pv.suggested_description,
|
||||
"My favourite ones, see One Piece and Death Note"
|
||||
);
|
||||
assert_eq!(
|
||||
titles(&g, &pv.members),
|
||||
[
|
||||
"Naruto",
|
||||
"Bleach",
|
||||
"One Piece",
|
||||
"Death Note",
|
||||
"Props",
|
||||
"BlockProp",
|
||||
"Tagger"
|
||||
]
|
||||
);
|
||||
assert_eq!(pv.prose_blocks, 2);
|
||||
assert_eq!(pv.blocks, 7);
|
||||
|
||||
let plain = page(&g, "Plain", &[]);
|
||||
let pv = g.hub_conversion_preview(plain).unwrap();
|
||||
assert_eq!(pv.suggested_title, "Plain");
|
||||
assert!(pv.suggested_description.is_empty() && pv.members.is_empty());
|
||||
assert!(invalid(g.hub_conversion_preview(j.id)));
|
||||
let h = hub(&g, "Hub");
|
||||
assert!(invalid(g.hub_conversion_preview(h)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_hub_shortens_title_and_keeps_outline() {
|
||||
let (_d, g) = graph();
|
||||
let p = page(&g, "Media/Anime", &["Intro text", "[[Naruto]]"]);
|
||||
let root = g.page_tree(p).unwrap()[0].1.id;
|
||||
g.insert_block(p, Placement::LastChildOf(Some(root)), "child")
|
||||
.unwrap();
|
||||
let parent = hub(&g, "Media");
|
||||
g.add_to_hub(p, parent).unwrap();
|
||||
let refr = page(&g, "Elsewhere", &["see [[Media/Anime]]"]);
|
||||
let naruto = g.page_by_title("Naruto").unwrap().unwrap().id;
|
||||
let j = g
|
||||
.journal(chrono::NaiveDate::from_ymd_opt(2024, 1, 2).unwrap())
|
||||
.unwrap();
|
||||
|
||||
let h = g
|
||||
.convert_to_hub(
|
||||
p,
|
||||
&HubConversion {
|
||||
title: "Anime".into(),
|
||||
description: " Japanese animation ".into(),
|
||||
// Journals and cycles (the hub's own parent) are skipped silently.
|
||||
members: vec![naruto, j.id, parent, naruto],
|
||||
keep_outline_as: Some("Anime (notes)".into()),
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(h.title, "Anime");
|
||||
assert!(h.is_hub() && h.description == "Japanese animation");
|
||||
assert_eq!(h.hubs, [parent], "the hub stays where it was");
|
||||
assert!(g.page_tree(p).unwrap().is_empty());
|
||||
assert_eq!(texts(&g, refr), [(0, "see [[Anime]]".to_string())]);
|
||||
let note = g.page_by_title("Anime (notes)").unwrap().unwrap();
|
||||
assert_eq!(
|
||||
texts(&g, note.id),
|
||||
[
|
||||
(0, "Intro text".to_string()),
|
||||
(1, "child".to_string()),
|
||||
(0, "[[Naruto]]".to_string())
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
titles(&g, &g.hub_members(p).unwrap()),
|
||||
["Anime (notes)", "Naruto"]
|
||||
);
|
||||
assert!(g.get_page(parent).unwrap().unwrap().hubs.is_empty());
|
||||
|
||||
// Back to a note: description, then one link per member; members leave the hub.
|
||||
let n = g.convert_to_note(p).unwrap();
|
||||
assert_eq!(n.kind, PageKind::Note);
|
||||
assert!(n.description.is_empty());
|
||||
assert_eq!(
|
||||
texts(&g, p),
|
||||
[
|
||||
(0, "Japanese animation".to_string()),
|
||||
(0, "[[Anime (notes)]]".to_string()),
|
||||
(0, "[[Naruto]]".to_string())
|
||||
]
|
||||
);
|
||||
assert!(g.hub_members(p).unwrap().is_empty());
|
||||
assert!(g.get_page(naruto).unwrap().unwrap().hubs.is_empty());
|
||||
assert!(invalid(g.convert_to_note(p)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_hub_without_outline_and_title_clash() {
|
||||
let (_d, g) = graph();
|
||||
let p = page(&g, "Projects/Ideas", &["[[A]]", "some prose"]);
|
||||
page(&g, "Ideas", &["taken"]);
|
||||
let before = g.last_seq().unwrap();
|
||||
let clash = g.convert_to_hub(
|
||||
p,
|
||||
&HubConversion {
|
||||
title: "Ideas".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert!(matches!(clash, Err(Error::Conflict(_))), "{clash:?}");
|
||||
// Nothing changed.
|
||||
assert_eq!(g.last_seq().unwrap(), before);
|
||||
let cur = g.get_page(p).unwrap().unwrap();
|
||||
assert_eq!(cur.title, "Projects/Ideas");
|
||||
assert!(!cur.is_hub());
|
||||
assert_eq!(g.page_tree(p).unwrap().len(), 2);
|
||||
|
||||
// An existing title for the kept-outline note is refused too.
|
||||
let clash = g.convert_to_hub(
|
||||
p,
|
||||
&HubConversion {
|
||||
title: "Projects/Ideas".into(),
|
||||
keep_outline_as: Some("ideas".into()),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert!(matches!(clash, Err(Error::Conflict(_))));
|
||||
assert_eq!(g.page_tree(p).unwrap().len(), 2);
|
||||
|
||||
let a = g.page_by_title("A").unwrap().unwrap().id;
|
||||
let h = g
|
||||
.convert_to_hub(
|
||||
p,
|
||||
&HubConversion {
|
||||
title: "Projects/Ideas".into(),
|
||||
description: String::new(),
|
||||
members: vec![a],
|
||||
keep_outline_as: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(h.title, "Projects/Ideas");
|
||||
assert!(g.page_tree(p).unwrap().is_empty());
|
||||
assert_eq!(g.hub_members(p).unwrap(), [a]);
|
||||
assert!(invalid(g.convert_to_hub(p, &HubConversion::default())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structure_depth_home_and_dangling_ids() {
|
||||
let (_d, g) = graph();
|
||||
let root = hub(&g, "Root");
|
||||
let sub = hub(&g, "Sub");
|
||||
let leaf = page(&g, "Leaf", &[]);
|
||||
let r1 = page(&g, "R1", &[]);
|
||||
g.add_to_hub(sub, root).unwrap();
|
||||
g.add_to_hub(leaf, sub).unwrap();
|
||||
g.add_to_hub(r1, root).unwrap();
|
||||
// Dangling ids: a deleted page and a note.
|
||||
let gone = synapse_core::new_id();
|
||||
let mut p = g.get_page(r1).unwrap().unwrap();
|
||||
p.hubs.push(gone);
|
||||
p.hubs.push(leaf);
|
||||
g.put_page(&p).unwrap();
|
||||
|
||||
let s = g.structure().unwrap();
|
||||
let info = |id| s.hubs.iter().find(|h| h.page == id).unwrap();
|
||||
assert_eq!((info(root).depth, info(sub).depth), (0, 1));
|
||||
assert_eq!(info(root).members, [sub, r1]);
|
||||
assert_eq!(info(sub).members, [leaf]);
|
||||
assert_eq!(s.home[&leaf], sub, "deepest wins");
|
||||
assert_eq!(
|
||||
(s.home[&sub], s.home[&root], s.home[&r1]),
|
||||
(sub, root, root)
|
||||
);
|
||||
assert_eq!(s.hubs.len(), 2);
|
||||
assert_eq!(g.hubs_of(r1).unwrap(), [root]);
|
||||
let alone = page(&g, "Alone", &[]);
|
||||
assert!(!g.structure().unwrap().home.contains_key(&alone));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replicas_converge_in_any_order_and_break_concurrent_cycles() {
|
||||
let (_a, a) = graph();
|
||||
let (_b, b) = graph();
|
||||
let h = a.create_hub("Hub", "desc").unwrap().id;
|
||||
let x = hub(&a, "X");
|
||||
let n = page(&a, "Note", &["text"]);
|
||||
a.add_to_hub(n, h).unwrap();
|
||||
a.add_to_hub(x, h).unwrap();
|
||||
|
||||
// Out of order: members' pages arrive before the hub page.
|
||||
let mut ops = a.ops_since(0, 1000).unwrap();
|
||||
ops.reverse();
|
||||
for r in &ops {
|
||||
b.apply_remote(&r.hlc, &r.op).unwrap();
|
||||
}
|
||||
let hub_b = b.get_page(h).unwrap().unwrap();
|
||||
assert!(hub_b.is_hub() && hub_b.description == "desc");
|
||||
assert_eq!(b.structure().unwrap(), a.structure().unwrap());
|
||||
assert_eq!(b.hub_members(h).unwrap(), [x, n]);
|
||||
// Idempotent: replaying applies nothing; applied ops were re-logged on B.
|
||||
assert_eq!(ship(&a, &b, 0), 0);
|
||||
assert!(
|
||||
b.ops_since(0, 1000)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|r| matches!(&r.op, Op::UpsertPage { page } if page.id == n && page.hubs == [h]))
|
||||
);
|
||||
// Hub deletion on B reaches A, members included.
|
||||
let seq_b = b.last_seq().unwrap();
|
||||
b.delete_page(x).unwrap();
|
||||
ship(&b, &a, seq_b);
|
||||
assert!(a.get_page(x).unwrap().is_none());
|
||||
assert_eq!(a.hub_members(h).unwrap(), [n]);
|
||||
|
||||
// Concurrent cycle: A puts Y in Z while B puts Z in Y.
|
||||
let y = hub(&a, "Y");
|
||||
let z = hub(&a, "Z");
|
||||
ship(&a, &b, 0);
|
||||
let (sa, sb) = (a.last_seq().unwrap(), b.last_seq().unwrap());
|
||||
a.add_to_hub(y, z).unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
b.add_to_hub(z, y).unwrap();
|
||||
ship(&a, &b, sa);
|
||||
ship(&b, &a, sb);
|
||||
let (s1, s2) = (a.structure().unwrap(), b.structure().unwrap());
|
||||
assert_eq!(s1, s2);
|
||||
let members = |s: &synapse_core::Structure, id| {
|
||||
s.hubs
|
||||
.iter()
|
||||
.find(|h| h.page == id)
|
||||
.unwrap()
|
||||
.members
|
||||
.clone()
|
||||
};
|
||||
// The older write (Y in Z) stands; the one closing the cycle is ignored.
|
||||
assert_eq!(members(&s1, z), [y]);
|
||||
assert!(members(&s1, y).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_ops_and_v2_databases_load() {
|
||||
// An op written before page kinds existed.
|
||||
let id = synapse_core::new_id();
|
||||
let op: Op = serde_json::from_value(json!({
|
||||
"type": "upsert_page",
|
||||
"page": {"id": id, "title": "Old", "journal_date": null, "origin_journal": null,
|
||||
"properties": {}, "created_at": 1, "updated_at": 2}
|
||||
}))
|
||||
.unwrap();
|
||||
let Op::UpsertPage { page } = op else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(page.kind, PageKind::Note);
|
||||
assert!(page.description.is_empty() && page.hubs.is_empty());
|
||||
|
||||
// A database created with the v2 schema.
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
{
|
||||
let conn = rusqlite::Connection::open(dir.path().join("synapse.db")).unwrap();
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
INSERT INTO meta VALUES ('schema', '2'), ('actor', 'oldactor0001');
|
||||
CREATE TABLE pages (
|
||||
id TEXT PRIMARY KEY, title TEXT NOT NULL, title_key TEXT NOT NULL UNIQUE,
|
||||
journal_date TEXT UNIQUE, origin_journal TEXT,
|
||||
properties TEXT NOT NULL DEFAULT '{}', created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL, hlc TEXT NOT NULL);
|
||||
CREATE TABLE aliases (alias_key TEXT PRIMARY KEY, alias TEXT NOT NULL,
|
||||
page_id TEXT NOT NULL, hlc TEXT NOT NULL DEFAULT '');",
|
||||
)
|
||||
.unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO pages VALUES (?1, 'Legacy', 'legacy', NULL, NULL, '{}', 1, 2, '0000000000001-00000-oldactor0001')",
|
||||
[id.to_string()],
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
let g = Graph::open(dir.path()).unwrap();
|
||||
let schema: String = g
|
||||
.conn()
|
||||
.query_row("SELECT value FROM meta WHERE key='schema'", [], |r| {
|
||||
r.get(0)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(schema, "5");
|
||||
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();
|
||||
g.add_to_hub(id, h.id).unwrap();
|
||||
assert_eq!(g.hub_members(h.id).unwrap(), [id]);
|
||||
g.add_page_tag(id, "idea").unwrap();
|
||||
assert_eq!(g.pages_with_tag("idea").unwrap(), [id]);
|
||||
drop(g);
|
||||
// Reopening keeps everything (migration is idempotent).
|
||||
let g = Graph::open(dir.path()).unwrap();
|
||||
assert_eq!(g.hub_members(h.id).unwrap(), [id]);
|
||||
let n = g.create_page(NewPage::titled("After")).unwrap();
|
||||
assert_eq!(n.kind, PageKind::Note);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn namespace_helpers() {
|
||||
assert_eq!(namespace_parent("A/B/C"), Some("A/B"));
|
||||
assert_eq!(namespace_parent("A / B"), Some("A"));
|
||||
assert_eq!(namespace_parent("A"), None);
|
||||
assert_eq!(namespace_parent("/A"), None);
|
||||
assert_eq!(namespace_parent("A/"), None);
|
||||
assert_eq!(namespace_parent("A//B"), None);
|
||||
|
||||
let (_d, g) = graph();
|
||||
let ab = page(&g, "A/B", &[]);
|
||||
let abc = page(&g, "A/B/C", &[]);
|
||||
let ad = page(&g, "A/d", &[]);
|
||||
page(&g, "X/Y/Z", &[]);
|
||||
let kids = g.namespace_children("a").unwrap();
|
||||
assert_eq!(
|
||||
kids,
|
||||
vec![("A/B".to_string(), Some(ab)), ("A/d".to_string(), Some(ad))]
|
||||
);
|
||||
assert_eq!(
|
||||
g.namespace_children("A/B").unwrap(),
|
||||
vec![("A/B/C".to_string(), Some(abc))]
|
||||
);
|
||||
// Virtual intermediate levels.
|
||||
assert_eq!(
|
||||
g.namespace_children("X").unwrap(),
|
||||
vec![("X/Y".to_string(), None)]
|
||||
);
|
||||
assert_eq!(g.namespace_children("X/Y").unwrap().len(), 1);
|
||||
assert!(g.namespace_children("nothing").unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_titles() {
|
||||
for t in [
|
||||
"contents",
|
||||
"TODO",
|
||||
"All pages",
|
||||
"hls__book_123",
|
||||
"In-Progress",
|
||||
] {
|
||||
assert!(is_legacy_page(t), "{t}");
|
||||
}
|
||||
for t in ["Todo list", "Projects", "hls"] {
|
||||
assert!(!is_legacy_page(t), "{t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_hub_has_a_hidden_template_that_seeds_new_notes() {
|
||||
let (_d, g) = graph();
|
||||
let h = hub(&g, "Fun");
|
||||
let t = g.hub_template(h).unwrap();
|
||||
assert_eq!(g.get_page(t).unwrap().unwrap().kind, PageKind::Template);
|
||||
assert_eq!(g.hub_template(h).unwrap(), t, "idempotent");
|
||||
// Hidden from members, listings and the structure.
|
||||
assert!(g.hub_members(h).unwrap().is_empty());
|
||||
assert!(
|
||||
g.list_pages(true, 100, 0)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.all(|p| p.id != t)
|
||||
);
|
||||
assert!(g.structure().unwrap().hubs[0].members.is_empty());
|
||||
|
||||
let root = g
|
||||
.insert_block(t, Placement::LastChildOf(None), "Rating")
|
||||
.unwrap();
|
||||
g.insert_block(t, Placement::LastChildOf(Some(root.id)), "Notes")
|
||||
.unwrap();
|
||||
let n = g.create_page_from_template(h, "Chess").unwrap();
|
||||
assert_eq!(g.hubs_of(n.id).unwrap(), vec![h]);
|
||||
assert_eq!(
|
||||
texts(&g, n.id),
|
||||
vec![(0, "Rating".to_string()), (1, "Notes".to_string())]
|
||||
);
|
||||
|
||||
// An empty template is fine, and the template cannot be deleted alone.
|
||||
let h2 = hub(&g, "Empty");
|
||||
let n2 = g.create_page_from_template(h2, "Blank").unwrap();
|
||||
assert!(texts(&g, n2.id).is_empty());
|
||||
assert!(invalid(g.delete_page(t)));
|
||||
g.delete_page(h).unwrap();
|
||||
assert!(g.get_page(t).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converting_to_a_hub_creates_a_template_and_back_removes_it() {
|
||||
let (_d, g) = graph();
|
||||
let p = page(&g, "Projects", &["a"]);
|
||||
g.convert_to_hub(
|
||||
p,
|
||||
&HubConversion {
|
||||
title: "Projects".into(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let t = g.hub_template(p).unwrap();
|
||||
g.convert_to_note(p).unwrap();
|
||||
assert!(g.get_page(t).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tags_are_pages_many_per_page() {
|
||||
let (_d, g) = graph();
|
||||
let a = page(&g, "Rust", &["x"]);
|
||||
let b = page(&g, "Madrid", &["y"]);
|
||||
|
||||
g.add_page_tag(a, " #Tecnología ").unwrap();
|
||||
g.add_page_tag(a, "herramientas").unwrap();
|
||||
g.add_page_tag(a, "TECNOLOGÍA").unwrap(); // same tag, other case
|
||||
g.add_page_tag(b, "Tecnología").unwrap();
|
||||
assert_eq!(
|
||||
g.get_page(a).unwrap().unwrap().tags,
|
||||
["Tecnología", "herramientas"]
|
||||
);
|
||||
// The first use creates the tag page; it is an ordinary page of kind tag.
|
||||
let tp = g.page_by_title("tecnología").unwrap().unwrap();
|
||||
assert_eq!(tp.kind, PageKind::Tag);
|
||||
assert_eq!(tp.title, "Tecnología");
|
||||
g.insert_block(tp.id, Placement::LastChildOf(None), "About tech")
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
g.pages_with_tag("tecnologia").unwrap().len(),
|
||||
0,
|
||||
"accents matter"
|
||||
);
|
||||
let mut with = g.pages_with_tag("Tecnología").unwrap();
|
||||
with.sort();
|
||||
let mut want = vec![a, b];
|
||||
want.sort();
|
||||
assert_eq!(with, want);
|
||||
|
||||
let cat = g.tag_catalog().unwrap();
|
||||
assert_eq!((cat[0].name.as_str(), cat[0].count), ("Tecnología", 2));
|
||||
assert_eq!((cat[1].name.as_str(), cat[1].count), ("herramientas", 1));
|
||||
assert_eq!(cat.len(), 2, "no seeded tags: tags are pages you create");
|
||||
|
||||
g.remove_page_tag(a, "TECNOLOGÍA").unwrap();
|
||||
assert_eq!(g.pages_with_tag("Tecnología").unwrap(), [b]);
|
||||
assert!(
|
||||
g.page_by_title("Tecnología").unwrap().is_some(),
|
||||
"the tag page stays"
|
||||
);
|
||||
g.set_page_tags(a, vec![]).unwrap();
|
||||
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
|
||||
|
||||
// Rules.
|
||||
let j = g
|
||||
.journal(chrono::NaiveDate::from_ymd_opt(2026, 1, 2).unwrap())
|
||||
.unwrap();
|
||||
assert!(invalid(g.add_page_tag(j.id, "x")));
|
||||
let h = hub(&g, "H");
|
||||
let t = g.hub_template(h).unwrap();
|
||||
assert!(invalid(g.add_page_tag(t, "x")));
|
||||
assert!(invalid(g.add_page_tag(a, &"x".repeat(49))));
|
||||
assert!(invalid(g.add_page_tag(a, "H")), "a hub cannot be a tag");
|
||||
assert!(invalid(g.add_page_tag(a, "Rust")), "not its own tag");
|
||||
assert!(
|
||||
invalid(g.add_page_tag(tp.id, "x")),
|
||||
"tag pages are not tagged"
|
||||
);
|
||||
g.add_page_tag(a, " ").unwrap(); // blank: ignored
|
||||
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
|
||||
|
||||
// Deleting a tagged page drops it from the index.
|
||||
g.delete_page(b).unwrap();
|
||||
assert!(g.pages_with_tag("Tecnología").unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_note_becomes_a_tag_page_when_used_as_a_tag() {
|
||||
let (_d, g) = graph();
|
||||
let n = page(&g, "Neurociencia", &["brains", "memory"]);
|
||||
let other = page(&g, "Plasticidad", &["x"]);
|
||||
g.add_page_tag(other, "neurociencia").unwrap();
|
||||
let p = g.get_page(n).unwrap().unwrap();
|
||||
assert_eq!(p.kind, PageKind::Tag);
|
||||
assert_eq!(texts(&g, n).len(), 2, "its content is kept");
|
||||
assert_eq!(g.get_page(other).unwrap().unwrap().tags, ["Neurociencia"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_or_deleting_a_tag_page_keeps_members_in_step() {
|
||||
let (_d, g) = graph();
|
||||
let a = page(&g, "A", &["x"]);
|
||||
let b = page(&g, "B", &["y"]);
|
||||
g.add_page_tag(a, "web").unwrap();
|
||||
g.add_page_tag(b, "Web").unwrap();
|
||||
g.add_page_tag(b, "otro").unwrap();
|
||||
let tag = g.page_by_title("web").unwrap().unwrap().id;
|
||||
g.rename_page(tag, "Sitios web").unwrap();
|
||||
assert_eq!(g.get_page(a).unwrap().unwrap().tags, ["Sitios web"]);
|
||||
assert_eq!(g.get_page(b).unwrap().unwrap().tags, ["Sitios web", "otro"]);
|
||||
assert_eq!(g.pages_with_tag("Sitios web").unwrap().len(), 2);
|
||||
assert!(g.pages_with_tag("web").unwrap().is_empty());
|
||||
|
||||
g.delete_page(tag).unwrap();
|
||||
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
|
||||
assert_eq!(g.get_page(b).unwrap().unwrap().tags, ["otro"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tags_without_a_page_get_one_when_the_graph_opens() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let id = {
|
||||
let g = Graph::open(dir.path()).unwrap();
|
||||
let id = page(&g, "Old", &["x"]);
|
||||
g.add_page_tag(id, "Idea").unwrap();
|
||||
// Simulate a pre-v5 database: the tag exists only on the note.
|
||||
let tag = g.page_by_title("Idea").unwrap().unwrap().id;
|
||||
g.conn()
|
||||
.execute("DELETE FROM pages WHERE id=?1", [tag.to_string()])
|
||||
.unwrap();
|
||||
id
|
||||
};
|
||||
let g = Graph::open(dir.path()).unwrap();
|
||||
let tag = g.page_by_title("idea").unwrap().unwrap();
|
||||
assert_eq!((tag.kind, tag.title.as_str()), (PageKind::Tag, "Idea"));
|
||||
assert_eq!(g.pages_with_tag("Idea").unwrap(), [id]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn types_are_names_many_per_page_with_a_seeded_vocabulary() {
|
||||
let (_d, g) = graph();
|
||||
let a = page(&g, "Ana", &["x"]);
|
||||
let b = page(&g, "Madrid", &["y"]);
|
||||
let pages_before = g.list_pages(true, 100, 0).unwrap().len();
|
||||
|
||||
g.add_page_type(a, " Persona ").unwrap();
|
||||
g.add_page_type(a, "cliente").unwrap();
|
||||
g.add_page_type(a, "PERSONA").unwrap();
|
||||
g.add_page_type(b, "lugar").unwrap();
|
||||
assert_eq!(
|
||||
g.get_page(a).unwrap().unwrap().types,
|
||||
["Persona", "cliente"]
|
||||
);
|
||||
// Types never become pages.
|
||||
assert_eq!(g.list_pages(true, 100, 0).unwrap().len(), pages_before);
|
||||
assert!(g.page_by_title("persona").unwrap().is_none());
|
||||
|
||||
let cat = g.type_catalog().unwrap();
|
||||
assert!(cat.iter().any(|t| t.name == "Persona" && t.count == 1));
|
||||
let names: Vec<&str> = cat.iter().map(|t| t.name.as_str()).collect();
|
||||
assert!(names.contains(&"empresa"), "unused suggestions are listed");
|
||||
assert_eq!(
|
||||
names
|
||||
.iter()
|
||||
.filter(|n| n.to_lowercase() == "persona")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
|
||||
g.remove_page_type(a, "persona").unwrap();
|
||||
assert_eq!(g.get_page(a).unwrap().unwrap().types, ["cliente"]);
|
||||
let j = g
|
||||
.journal(chrono::NaiveDate::from_ymd_opt(2026, 1, 2).unwrap())
|
||||
.unwrap();
|
||||
assert!(invalid(g.add_page_type(j.id, "x")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tags_sync_with_the_page() {
|
||||
let (_a, a) = graph();
|
||||
let (_b, b) = graph();
|
||||
let p = page(&a, "Note", &["x"]);
|
||||
a.add_page_tag(p, "idea").unwrap();
|
||||
a.add_page_tag(p, "proyecto").unwrap();
|
||||
a.add_page_type(p, "concepto").unwrap();
|
||||
ship(&a, &b, 0);
|
||||
let q = b.get_page(p).unwrap().unwrap();
|
||||
assert_eq!(q.tags, ["idea", "proyecto"]);
|
||||
assert_eq!(q.types, ["concepto"]);
|
||||
assert_eq!(b.pages_with_tag("IDEA").unwrap(), [p]);
|
||||
// The tag pages travel with it.
|
||||
assert_eq!(
|
||||
b.page_by_title("idea").unwrap().unwrap().kind,
|
||||
PageKind::Tag
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user