use crate::error::{Error, Result};
use rusqlite::Connection;
use std::path::Path;
const SCHEMA_VERSION: u32 = 2;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Link {
pub source: String,
pub target: String,
pub note: Option<String>,
pub created_at: String,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Bookmark {
pub id: String,
pub file_path: String,
pub created_at: String,
}
pub struct LinkStore {
conn: Connection,
}
impl LinkStore {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
let conn = Connection::open(path)?;
conn.busy_timeout(std::time::Duration::from_secs(5))?;
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.pragma_update(None, "foreign_keys", "ON")?;
let store = LinkStore { conn };
store.run_migrations()?;
Ok(store)
}
fn run_migrations(&self) -> Result<()> {
self.conn.execute_batch(
"CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER NOT NULL
);",
)?;
let current_version: Option<u32> = self
.conn
.query_row(
"SELECT version FROM schema_version LIMIT 1",
[],
|row| row.get(0),
)
.ok();
match current_version {
None => {
self.apply_v1_schema()?;
self.apply_v2_schema()?;
self.conn.execute(
"INSERT INTO schema_version (version) VALUES (?)",
[SCHEMA_VERSION],
)?;
}
Some(1) => {
self.apply_v2_schema()?;
self.conn
.execute("UPDATE schema_version SET version = ?", [SCHEMA_VERSION])?;
}
Some(v) if v == SCHEMA_VERSION => {
}
Some(v) if v < SCHEMA_VERSION => {
let _ = v;
}
Some(v) => {
return Err(Error::SchemaTooNew {
found: v,
supported: SCHEMA_VERSION,
});
}
}
Ok(())
}
fn apply_v1_schema(&self) -> Result<()> {
self.conn.execute_batch(
r#"
CREATE TABLE IF NOT EXISTS links (
id INTEGER PRIMARY KEY,
source TEXT NOT NULL,
target TEXT NOT NULL,
note TEXT,
created_at TEXT NOT NULL,
UNIQUE(source, target)
);
CREATE TABLE IF NOT EXISTS purple_numbers (
id INTEGER PRIMARY KEY,
doc_path TEXT NOT NULL,
para_id TEXT NOT NULL,
content_hash TEXT NOT NULL,
UNIQUE(doc_path, para_id)
);
CREATE INDEX IF NOT EXISTS idx_links_source ON links(source);
CREATE INDEX IF NOT EXISTS idx_links_target ON links(target);
CREATE INDEX IF NOT EXISTS idx_purple_doc ON purple_numbers(doc_path);
"#,
)?;
Ok(())
}
fn apply_v2_schema(&self) -> Result<()> {
self.conn.execute_batch(
r#"
CREATE TABLE IF NOT EXISTS bookmarks (
id TEXT PRIMARY KEY,
file_path TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_bookmarks_path ON bookmarks(file_path);
"#,
)?;
Ok(())
}
pub fn create_link(&self, source: &str, target: &str, note: Option<&str>) -> Result<()> {
let now = chrono::Utc::now().to_rfc3339();
let result = self.conn.execute(
"INSERT INTO links (source, target, note, created_at) VALUES (?, ?, ?, ?)",
rusqlite::params![source, target, note, now],
);
match result {
Ok(_) => Ok(()),
Err(rusqlite::Error::SqliteFailure(e, _))
if e.code == rusqlite::ErrorCode::ConstraintViolation =>
{
Err(Error::LinkAlreadyExists {
uri_a: source.to_string(),
uri_b: target.to_string(),
})
}
Err(e) => Err(Error::DatabaseError(e)),
}
}
pub fn list_links(&self, uri: &str) -> Result<Vec<Link>> {
let mut stmt = self.conn.prepare(
"SELECT source, target, note, created_at FROM links WHERE source = ? OR target = ?",
)?;
let links = stmt.query_map(rusqlite::params![uri, uri], |row| {
Ok(Link {
source: row.get(0)?,
target: row.get(1)?,
note: row.get(2)?,
created_at: row.get(3)?,
})
})?;
let mut result = Vec::new();
for link in links {
result.push(link?);
}
Ok(result)
}
pub fn list_all_links(&self) -> Result<Vec<Link>> {
let mut stmt = self
.conn
.prepare("SELECT source, target, note, created_at FROM links ORDER BY created_at")?;
let rows = stmt.query_map([], |row| {
Ok(Link {
source: row.get(0)?,
target: row.get(1)?,
note: row.get(2)?,
created_at: row.get(3)?,
})
})?;
rows.map(|r| r.map_err(Error::DatabaseError)).collect()
}
pub fn delete_link(&self, source: &str, target: &str) -> Result<()> {
self.conn.execute(
"DELETE FROM links WHERE (source = ? AND target = ?) OR (source = ? AND target = ?)",
rusqlite::params![source, target, target, source],
)?;
Ok(())
}
pub fn link_count(&self) -> Result<u64> {
let count: i64 =
self.conn
.query_row("SELECT COUNT(*) FROM links", [], |row| row.get(0))?;
Ok(count as u64)
}
pub fn scan_stale_links(&self) -> Result<(Vec<Link>, usize)> {
let all_links: Vec<Link> = {
let mut stmt = self
.conn
.prepare("SELECT source, target, note, created_at FROM links")?;
let rows = stmt.query_map([], |row| {
Ok(Link {
source: row.get(0)?,
target: row.get(1)?,
note: row.get(2)?,
created_at: row.get(3)?,
})
})?;
rows.filter_map(|r| r.ok()).collect()
};
let total = all_links.len();
let stale = all_links
.into_iter()
.filter(|link| uri_file_missing(&link.source) || uri_file_missing(&link.target))
.collect();
Ok((stale, total))
}
pub fn scan_stale_bookmarks(&self) -> Result<(Vec<Bookmark>, usize)> {
let all = self.list_bookmarks()?;
let total = all.len();
let stale = all
.into_iter()
.filter(|b| !std::path::Path::new(&b.file_path).exists())
.collect();
Ok((stale, total))
}
pub fn delete_links_involving(&self, uris: &[String]) -> Result<usize> {
let mut removed = 0;
for uri in uris {
removed += self.conn.execute(
"DELETE FROM links WHERE source = ? OR target = ?",
rusqlite::params![uri, uri],
)?;
}
Ok(removed)
}
pub fn delete_bookmarks_by_ids(&self, ids: &[String]) -> Result<usize> {
let mut removed = 0;
for id in ids {
removed += self
.conn
.execute("DELETE FROM bookmarks WHERE id = ?", rusqlite::params![id])?;
}
Ok(removed)
}
pub fn store_bookmark(&self, file_path: &str) -> Result<String> {
let existing: Option<String> = self
.conn
.query_row(
"SELECT id FROM bookmarks WHERE file_path = ? LIMIT 1",
rusqlite::params![file_path],
|row| row.get(0),
)
.ok();
if let Some(id) = existing {
return Ok(id);
}
let id = new_uuid_v4();
let now = chrono::Utc::now().to_rfc3339();
self.conn.execute(
"INSERT INTO bookmarks (id, file_path, created_at) VALUES (?, ?, ?)",
rusqlite::params![id, file_path, now],
)?;
Ok(id)
}
pub fn import_bookmark(&self, id: &str, file_path: &str) -> Result<()> {
let exists: bool = self
.conn
.query_row(
"SELECT 1 FROM bookmarks WHERE id = ?",
rusqlite::params![id],
|_| Ok(true),
)
.unwrap_or(false);
if exists {
return Err(Error::BookmarkAlreadyExists { id: id.to_string() });
}
let now = chrono::Utc::now().to_rfc3339();
self.conn.execute(
"INSERT INTO bookmarks (id, file_path, created_at) VALUES (?, ?, ?)",
rusqlite::params![id, file_path, now],
)?;
Ok(())
}
pub fn lookup_bookmark(&self, id: &str) -> Result<Option<String>> {
let path: Option<String> = self
.conn
.query_row(
"SELECT file_path FROM bookmarks WHERE id = ?",
rusqlite::params![id],
|row| row.get(0),
)
.ok();
Ok(path)
}
pub fn update_bookmark_path(&self, id: &str, new_path: &str) -> Result<bool> {
let rows = self.conn.execute(
"UPDATE bookmarks SET file_path = ? WHERE id = ?",
rusqlite::params![new_path, id],
)?;
Ok(rows > 0)
}
pub fn list_bookmarks(&self) -> Result<Vec<Bookmark>> {
let mut stmt = self
.conn
.prepare("SELECT id, file_path, created_at FROM bookmarks ORDER BY created_at")?;
let bookmarks = stmt.query_map([], |row| {
Ok(Bookmark {
id: row.get(0)?,
file_path: row.get(1)?,
created_at: row.get(2)?,
})
})?;
let mut result = Vec::new();
for b in bookmarks {
result.push(b?);
}
Ok(result)
}
}
fn uri_file_missing(uri: &str) -> bool {
use crate::uri::{HookUri, UriType};
match HookUri::parse(uri) {
Ok(h) => match h.uri_type {
UriType::File(path) => !path.exists(),
_ => false,
},
Err(_) => false,
}
}
fn new_uuid_v4() -> String {
use std::time::{SystemTime, UNIX_EPOCH};
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let t = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos() as u64;
let c = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let a = t.wrapping_mul(6364136223846793005).wrapping_add(c ^ 0xdeadbeefcafe);
let b = c.wrapping_mul(2862933555777941757).wrapping_add(t ^ 0x1234567890abcdef);
let p0 = (a >> 32) as u32;
let p1 = ((a >> 16) & 0xffff) as u16;
let p2 = 0x4000u16 | ((a & 0x0fff) as u16);
let p3 = 0x8000u16 | (((b >> 48) & 0x3fff) as u16);
let p4 = b & 0x0000_ffff_ffff_ffff;
format!("{p0:08x}-{p1:04x}-{p2:04x}-{p3:04x}-{p4:012x}")
}
#[cfg(test)]
mod tests {
use super::*;
use base64::Engine as _;
use tempfile::TempDir;
fn make_store() -> (TempDir, LinkStore) {
let tmpdir = TempDir::new().unwrap();
let store_path = tmpdir.path().join("test.db");
let store = LinkStore::open(&store_path).unwrap();
(tmpdir, store)
}
#[test]
fn test_store_roundtrip() {
let (_dir, store) = make_store();
store
.create_link("hook://file/a", "hook://file/b", Some("test note"))
.unwrap();
let links = store.list_links("hook://file/a").unwrap();
assert_eq!(links.len(), 1);
assert_eq!(links[0].note, Some("test note".to_string()));
}
#[test]
fn test_bidirectional_query() {
let (_dir, store) = make_store();
store
.create_link("hook://file/a", "hook://file/b", None)
.unwrap();
assert_eq!(store.list_links("hook://file/a").unwrap().len(), 1);
assert_eq!(store.list_links("hook://file/b").unwrap().len(), 1);
assert_eq!(store.list_links("hook://file/c").unwrap().len(), 0);
}
#[test]
fn test_duplicate_link_returns_friendly_error() {
let (_dir, store) = make_store();
store
.create_link("hook://file/a", "hook://file/b", None)
.unwrap();
let result = store.create_link("hook://file/a", "hook://file/b", None);
assert!(matches!(result, Err(Error::LinkAlreadyExists { .. })));
let msg = result.unwrap_err().to_string();
assert!(msg.contains("already exists"));
}
#[test]
fn test_delete_link() {
let (_dir, store) = make_store();
store
.create_link("hook://file/a", "hook://file/b", None)
.unwrap();
assert_eq!(store.list_links("hook://file/a").unwrap().len(), 1);
store
.delete_link("hook://file/a", "hook://file/b")
.unwrap();
assert_eq!(store.list_links("hook://file/a").unwrap().len(), 0);
}
#[test]
fn test_delete_link_symmetric() {
let (_dir, store) = make_store();
store
.create_link("hook://file/a", "hook://file/b", None)
.unwrap();
store
.delete_link("hook://file/b", "hook://file/a") .unwrap();
assert_eq!(store.list_links("hook://file/a").unwrap().len(), 0);
}
#[test]
fn test_link_count() {
let (_dir, store) = make_store();
assert_eq!(store.link_count().unwrap(), 0);
store
.create_link("hook://file/a", "hook://file/b", None)
.unwrap();
store
.create_link("hook://file/a", "hook://file/c", None)
.unwrap();
assert_eq!(store.link_count().unwrap(), 2);
}
#[test]
fn test_schema_version_persists() {
let tmpdir = TempDir::new().unwrap();
let store_path = tmpdir.path().join("versioned.db");
{
let _store = LinkStore::open(&store_path).unwrap();
}
let store = LinkStore::open(&store_path).unwrap();
assert_eq!(store.link_count().unwrap(), 0);
}
#[test]
fn test_schema_too_new_rejected() {
let tmpdir = TempDir::new().unwrap();
let store_path = tmpdir.path().join("future.db");
{
let conn = Connection::open(&store_path).unwrap();
conn.execute_batch(
"CREATE TABLE schema_version (version INTEGER NOT NULL);
INSERT INTO schema_version VALUES (9999);",
)
.unwrap();
}
let result = LinkStore::open(&store_path);
assert!(matches!(result, Err(Error::SchemaTooNew { .. })));
}
#[test]
fn test_bookmark_create_and_lookup() {
let (_dir, store) = make_store();
let id = store.store_bookmark("/Users/alice/notes.md").unwrap();
assert!(!id.is_empty());
let path = store.lookup_bookmark(&id).unwrap();
assert_eq!(path, Some("/Users/alice/notes.md".to_string()));
}
#[test]
fn test_bookmark_create_is_idempotent() {
let (_dir, store) = make_store();
let id1 = store.store_bookmark("/Users/alice/notes.md").unwrap();
let id2 = store.store_bookmark("/Users/alice/notes.md").unwrap();
assert_eq!(id1, id2, "Same path should return same bookmark UUID");
}
#[test]
fn test_bookmark_lookup_unknown_returns_none() {
let (_dir, store) = make_store();
let result = store
.lookup_bookmark("00000000-0000-4000-8000-000000000000")
.unwrap();
assert!(result.is_none());
}
#[test]
fn test_bookmark_update_path() {
let (_dir, store) = make_store();
let id = store.store_bookmark("/old/path.md").unwrap();
let updated = store.update_bookmark_path(&id, "/new/path.md").unwrap();
assert!(updated);
let path = store.lookup_bookmark(&id).unwrap();
assert_eq!(path, Some("/new/path.md".to_string()));
}
#[test]
fn test_bookmark_update_unknown_returns_false() {
let (_dir, store) = make_store();
let updated = store
.update_bookmark_path("00000000-0000-4000-8000-000000000000", "/foo.md")
.unwrap();
assert!(!updated);
}
#[test]
fn test_bookmark_list() {
let (_dir, store) = make_store();
store.store_bookmark("/file/a.md").unwrap();
store.store_bookmark("/file/b.md").unwrap();
let bookmarks = store.list_bookmarks().unwrap();
assert_eq!(bookmarks.len(), 2);
}
#[test]
fn test_bookmark_uuid_format() {
let (_dir, store) = make_store();
let id = store.store_bookmark("/any/path.md").unwrap();
let parts: Vec<&str> = id.split('-').collect();
assert_eq!(parts.len(), 5, "UUID must have 5 hyphen-separated parts");
assert_eq!(parts[0].len(), 8);
assert_eq!(parts[1].len(), 4);
assert_eq!(parts[2].len(), 4);
assert_eq!(parts[3].len(), 4);
assert_eq!(parts[4].len(), 12);
}
#[test]
fn test_schema_v1_migrates_to_v2() {
let tmpdir = TempDir::new().unwrap();
let store_path = tmpdir.path().join("v1.db");
{
let conn = Connection::open(&store_path).unwrap();
conn.execute_batch(
"CREATE TABLE schema_version (version INTEGER NOT NULL);
INSERT INTO schema_version VALUES (1);
CREATE TABLE links (
id INTEGER PRIMARY KEY,
source TEXT NOT NULL,
target TEXT NOT NULL,
note TEXT,
created_at TEXT NOT NULL,
UNIQUE(source, target)
);",
)
.unwrap();
}
let store = LinkStore::open(&store_path).unwrap();
let id = store.store_bookmark("/migrated/file.md").unwrap();
assert!(!id.is_empty());
}
#[test]
fn test_scan_stale_links_all_live() {
let (_dir, store) = make_store();
store
.create_link("hook://bookmark/abc-123", "hook://bookmark/def-456", None)
.unwrap();
let (stale, total) = store.scan_stale_links().unwrap();
assert_eq!(total, 1);
assert_eq!(stale.len(), 0, "non-file URIs should never be stale");
}
#[test]
fn test_scan_stale_links_with_missing_file() {
let tmpdir = TempDir::new().unwrap();
let store_path = tmpdir.path().join("test.db");
let store = LinkStore::open(&store_path).unwrap();
let real_file = tmpdir.path().join("real.md");
std::fs::write(&real_file, "# Real").unwrap();
let real_uri = format!(
"hook://file/{}",
base64::engine::general_purpose::URL_SAFE_NO_PAD
.encode(real_file.to_string_lossy().as_bytes())
);
let ghost_uri = "hook://file/L25vbmV4aXN0ZW50L2ZpbGUubWQ";
store.create_link(&real_uri, ghost_uri, None).unwrap();
let (stale, total) = store.scan_stale_links().unwrap();
assert_eq!(total, 1);
assert_eq!(stale.len(), 1, "link to missing file should be stale");
}
#[test]
fn test_scan_stale_bookmarks() {
let (_dir, store) = make_store();
store.store_bookmark("/absolutely/does/not/exist/file.md").unwrap();
let (stale, total) = store.scan_stale_bookmarks().unwrap();
assert_eq!(total, 1);
assert_eq!(stale.len(), 1);
}
#[test]
fn test_scan_stale_bookmarks_live_path() {
let tmpdir = TempDir::new().unwrap();
let store_path = tmpdir.path().join("test.db");
let store = LinkStore::open(&store_path).unwrap();
let real = tmpdir.path().join("exists.md");
std::fs::write(&real, "hi").unwrap();
store.store_bookmark(real.to_str().unwrap()).unwrap();
let (stale, total) = store.scan_stale_bookmarks().unwrap();
assert_eq!(total, 1);
assert_eq!(stale.len(), 0, "live path should not be stale");
}
#[test]
fn test_delete_links_involving() {
let (_dir, store) = make_store();
store
.create_link("hook://file/a", "hook://file/b", None)
.unwrap();
store
.create_link("hook://file/a", "hook://file/c", None)
.unwrap();
assert_eq!(store.link_count().unwrap(), 2);
let removed = store
.delete_links_involving(&["hook://file/a".to_string()])
.unwrap();
assert_eq!(removed, 2, "both links referencing 'a' should be deleted");
assert_eq!(store.link_count().unwrap(), 0);
}
#[test]
fn test_delete_bookmarks_by_ids() {
let (_dir, store) = make_store();
let id1 = store.store_bookmark("/file/one.md").unwrap();
let id2 = store.store_bookmark("/file/two.md").unwrap();
assert_eq!(store.list_bookmarks().unwrap().len(), 2);
let removed = store.delete_bookmarks_by_ids(&[id1]).unwrap();
assert_eq!(removed, 1);
let remaining = store.list_bookmarks().unwrap();
assert_eq!(remaining.len(), 1);
assert_eq!(remaining[0].id, id2);
}
#[test]
fn test_list_all_links() {
let (_dir, store) = make_store();
store
.create_link("hook://file/a", "hook://file/b", Some("note"))
.unwrap();
store
.create_link("hook://file/c", "hook://file/d", None)
.unwrap();
let all = store.list_all_links().unwrap();
assert_eq!(all.len(), 2);
}
#[test]
fn test_import_bookmark_idempotent() {
let (_dir, store) = make_store();
store.import_bookmark("fixed-uuid-1234", "/path/to/file.md").unwrap();
let result = store.import_bookmark("fixed-uuid-1234", "/path/to/file.md");
assert!(
matches!(result, Err(Error::BookmarkAlreadyExists { .. })),
"duplicate bookmark UUID should return BookmarkAlreadyExists"
);
assert_eq!(store.list_bookmarks().unwrap().len(), 1);
}
#[test]
fn test_import_bookmark_different_uuids() {
let (_dir, store) = make_store();
store.import_bookmark("uuid-aaa", "/file/a.md").unwrap();
store.import_bookmark("uuid-bbb", "/file/b.md").unwrap();
assert_eq!(store.list_bookmarks().unwrap().len(), 2);
}
}