use crate::error::{ClmError, StorageErrorCode, Result};
use rusqlite::Connection;
pub struct Migration {
pub version: i64,
pub description: &'static str,
pub sql_up: &'static str,
}
pub const MIGRATION_1_BASELINE: Migration = Migration {
version: 1,
description: "Baseline Monadic Core Schema (card, handle_registry, handle_history)",
sql_up: "
-- INV-TAPE-01: three tables, three columns each. The kind is not a column
-- (INV-TAPE-01a): the handle names it and `kindOf` decides it. Lifecycle is
-- external (INV-TAPE-04): tombstones and their reasons live in a sidecar tape,
-- not in a `change_type` column and not in a `card_tombstone` table.
CREATE TABLE IF NOT EXISTS card (
hash TEXT PRIMARY KEY,
content BLOB NOT NULL,
g_time TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS handle_registry (
handle TEXT PRIMARY KEY,
current_hash TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY (current_hash) REFERENCES card(hash)
);
CREATE INDEX IF NOT EXISTS idx_handle_current_hash ON handle_registry(current_hash);
CREATE TABLE IF NOT EXISTS handle_history (
handle TEXT NOT NULL,
previous_hash TEXT NOT NULL,
changed_at TEXT NOT NULL,
FOREIGN KEY (handle) REFERENCES handle_registry(handle),
FOREIGN KEY (previous_hash) REFERENCES card(hash)
);
CREATE INDEX IF NOT EXISTS idx_handle_history_handle ON handle_history(handle);
",
};
pub fn apply_migrations(conn: &mut Connection, _pillar: &str) -> Result<()> {
conn.execute_batch(MIGRATION_1_BASELINE.sql_up).map_err(|e| {
ClmError::storage(
StorageErrorCode::InvalidSchemaVersion,
format!("Failed to initialize baseline Monadic Core schema: {}", e),
)
})?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_migrations_apply_baseline() {
let mut conn = Connection::open_in_memory().unwrap();
apply_migrations(&mut conn, "content_memory").unwrap();
let count: i64 = conn
.query_row("SELECT count(*) FROM card", [], |r| r.get(0))
.unwrap();
assert_eq!(count, 0);
let aux_exists: bool = conn
.query_row(
"SELECT count(*) > 0 FROM sqlite_master WHERE type='table' AND name='_clm_schema_migrations'",
[],
|r| r.get(0),
)
.unwrap();
assert!(!aux_exists);
}
}