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: crate::layer0::runtime_contract::SQLITE_DDL_V3_1,
};
pub fn apply_migrations(conn: &mut Connection, _pillar: &str) -> Result<()> {
let table_name = "handle_registry";
let col_name = "created_at";
let check_sql = format!(
"SELECT count(*) > 0 FROM pragma_table_info('{}') WHERE name = '{}'",
table_name, col_name
);
let has_created_at: bool = conn
.query_row(&check_sql, [], |r| r.get(0))
.unwrap_or(false);
if has_created_at {
let _ = conn.execute_batch("ALTER TABLE handle_registry DROP COLUMN created_at;");
}
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);
}
}