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> {
let algorithm = match crate::layer0::gtime::parse_g_time(g_time) {
crate::layer0::gtime::ParsedGTime::Declared(value) => value.algorithm,
_ => return Err("tape writes require an explicit supported algorithm in g_time".to_string()),
};
let record = crate::layer0::mcard_record::MCardRecord {
hash: crate::hash::raw_hash_bytes_for(&algorithm, content)?,
content: content.to_vec(), g_time: g_time.to_string(),
};
crate::layer2::record_store::insert_record(conn, &record).map_err(|error| error.to_string())?;
Ok(record.hash)
}
pub fn get(conn: &Connection, hash: &str) -> Result<Option<(Vec<u8>, String)>, String> {
crate::layer2::record_store::read_record(conn, hash)
.map(|record| record.map(|record| (record.content, record.g_time)))
.map_err(|error| error.to_string())
}
pub fn has(conn: &Connection, hash: &str) -> Result<bool, String> {
get(conn, hash).map(|record| record.is_some())
}
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> {
get(conn, hash)?.ok_or_else(|| "cannot bind a missing card".to_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(crate::layer0::runtime_contract::SQLITE_DDL_V3_1)
.unwrap();
conn
}
#[test]
fn the_six_operations_are_bound_by_name() {
let c = tape();
let at = "blake3|2026-01-01T00:00:00Z|UTC";
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 = "blake3|2026-01-01T00:00:00Z|UTC";
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 = "blake3|2026-01-01T00:00:00Z|UTC";
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 = "blake3|2026-01-01T00:00:00Z|UTC";
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"]);
}
}