use rusqlite::{params, Connection};
pub const CORE_TABLES: [&str; 3] = ["card", "handle_registry", "handle_history"];
pub fn put(conn: &Connection, content: &[u8], g_time: &str) -> Result<String, String> {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(content);
let hash = format!("{:x}", h.finalize());
conn.execute(
"INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3)",
params![hash, content, g_time],
)
.map_err(|e| format!("put failed: {}", e))?;
Ok(hash)
}
pub fn get(conn: &Connection, hash: &str) -> Result<Option<(Vec<u8>, String)>, String> {
conn.query_row(
"SELECT content, g_time FROM card WHERE hash = ?1",
params![hash],
|row| Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, String>(1)?)),
)
.map(Some)
.or_else(|e| match e {
rusqlite::Error::QueryReturnedNoRows => Ok(None),
other => Err(format!("get failed: {}", other)),
})
}
pub fn has(conn: &Connection, hash: &str) -> Result<bool, String> {
crate::db::card_exists_cached(conn, hash).map_err(|e| format!("has failed: {}", e))
}
pub fn count(conn: &Connection) -> Result<i64, String> {
conn.query_row("SELECT COUNT(*) FROM card", [], |r| r.get(0))
.map_err(|e| format!("count failed: {}", e))
}
pub fn register_handle(conn: &Connection, handle: &str, hash: &str, at: &str) -> Result<bool, String> {
let current: Option<String> = conn
.query_row(
"SELECT current_hash FROM handle_registry WHERE handle = ?1",
params![handle],
|r| r.get(0),
)
.ok();
match current {
None => {
conn.execute(
"INSERT INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3)",
params![handle, hash, at],
)
.map_err(|e| format!("register_handle failed: {}", e))?;
conn.execute(
"INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
params![handle, hash, at],
)
.map_err(|e| format!("register_handle history failed: {}", e))?;
Ok(true)
}
Some(prev) if prev != hash => {
conn.execute(
"INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3)",
params![handle, prev, at],
)
.map_err(|e| format!("register_handle history failed: {}", e))?;
conn.execute(
"UPDATE handle_registry SET current_hash = ?1, updated_at = ?2 WHERE handle = ?3",
params![hash, at, handle],
)
.map_err(|e| format!("register_handle update failed: {}", e))?;
Ok(true)
}
Some(_) => Ok(false),
}
}
pub fn resolve_handle(conn: &Connection, handle: &str) -> Result<Option<String>, String> {
crate::db::resolve_handle_hash_cached(conn, handle)
.map_err(|e| format!("resolve_handle failed: {}", e))
}
pub fn handle_history(conn: &Connection, handle: &str) -> Result<Vec<String>, String> {
let mut stmt = conn
.prepare("SELECT previous_hash FROM handle_history WHERE handle = ?1 ORDER BY rowid ASC")
.map_err(|e| format!("handle_history prepare failed: {}", e))?;
let rows = stmt
.query_map(params![handle], |r| r.get::<_, String>(0))
.map_err(|e| format!("handle_history failed: {}", e))?;
rows.collect::<rusqlite::Result<Vec<String>>>()
.map_err(|e| format!("handle_history read failed: {}", e))
}
#[cfg(test)]
mod tests {
use super::*;
fn tape() -> Connection {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch(
"CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);
CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, updated_at TEXT NOT NULL);
CREATE TABLE handle_history (handle TEXT NOT NULL, previous_hash TEXT NOT NULL, changed_at TEXT NOT NULL);",
)
.unwrap();
conn
}
#[test]
fn the_six_operations_are_bound_by_name() {
let c = tape();
let at = "2026-01-01T00:00:00Z";
let h = put(&c, b"alpha", at).unwrap();
assert_eq!(count(&c).unwrap(), 1);
assert!(has(&c, &h).unwrap());
assert_eq!(get(&c, &h).unwrap().unwrap().0, b"alpha");
assert!(register_handle(&c, "urn:mcard:mcard:content:x", &h, at).unwrap());
assert_eq!(resolve_handle(&c, "urn:mcard:mcard:content:x").unwrap().unwrap(), h);
assert_eq!(handle_history(&c, "urn:mcard:mcard:content:x").unwrap().len(), 1);
}
#[test]
fn td02_identical_content_writes_nothing() {
let c = tape();
let at = "2026-01-01T00:00:00Z";
put(&c, b"alpha", at).unwrap();
put(&c, b"alpha", at).unwrap();
assert_eq!(count(&c).unwrap(), 1, "content addressing IS the identity");
}
#[test]
fn td03_a_noop_binding_records_nothing() {
let c = tape();
let at = "2026-01-01T00:00:00Z";
let h = put(&c, b"alpha", at).unwrap();
register_handle(&c, "urn:mcard:mcard:content:x", &h, at).unwrap();
assert!(!register_handle(&c, "urn:mcard:mcard:content:x", &h, at).unwrap());
assert_eq!(handle_history(&c, "urn:mcard:mcard:content:x").unwrap().len(), 1);
}
#[test]
fn td04_a_move_appends_exactly_one_row() {
let c = tape();
let at = "2026-01-01T00:00:00Z";
let a = put(&c, b"alpha", at).unwrap();
let b = put(&c, b"bravo", at).unwrap();
register_handle(&c, "urn:mcard:mcard:content:x", &a, at).unwrap();
register_handle(&c, "urn:mcard:mcard:content:x", &b, at).unwrap();
assert_eq!(handle_history(&c, "urn:mcard:mcard:content:x").unwrap().len(), 2);
}
#[test]
fn td01_exactly_three_tables() {
let c = tape();
let mut stmt = c
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
.unwrap();
let tables: Vec<String> = stmt.query_map([], |r| r.get(0)).unwrap().map(|r| r.unwrap()).collect();
assert_eq!(tables, vec!["card", "handle_history", "handle_registry"]);
}
}