clm_rust_core/layer2/db/
migrations.rs1use crate::error::{ClmError, StorageErrorCode, Result};
8use rusqlite::Connection;
9
10pub struct Migration {
12 pub version: i64,
13 pub description: &'static str,
14 pub sql_up: &'static str,
15}
16
17pub const MIGRATION_1_BASELINE: Migration = Migration {
24 version: 1,
25 description: "Baseline Monadic Core Schema (card, handle_registry, handle_history)",
26 sql_up: crate::layer0::runtime_contract::SQLITE_DDL_V3_1,
27};
28
29pub fn apply_migrations(conn: &mut Connection, _pillar: &str) -> Result<()> {
31 let table_name = "handle_registry";
34 let col_name = "created_at";
35 let check_sql = format!(
36 "SELECT count(*) > 0 FROM pragma_table_info('{}') WHERE name = '{}'",
37 table_name, col_name
38 );
39 let has_created_at: bool = conn
40 .query_row(&check_sql, [], |r| r.get(0))
41 .unwrap_or(false);
42 if has_created_at {
43 let _ = conn.execute_batch("ALTER TABLE handle_registry DROP COLUMN created_at;");
44 }
45
46 conn.execute_batch(MIGRATION_1_BASELINE.sql_up).map_err(|e| {
47 ClmError::storage(
48 StorageErrorCode::InvalidSchemaVersion,
49 format!("Failed to initialize baseline Monadic Core schema: {}", e),
50 )
51 })?;
52 Ok(())
53}
54
55#[cfg(test)]
56mod tests {
57 use super::*;
58
59 #[test]
60 fn test_migrations_apply_baseline() {
61 let mut conn = Connection::open_in_memory().unwrap();
62 apply_migrations(&mut conn, "content_memory").unwrap();
63
64 let count: i64 = conn
66 .query_row("SELECT count(*) FROM card", [], |r| r.get(0))
67 .unwrap();
68 assert_eq!(count, 0);
69
70 let aux_exists: bool = conn
72 .query_row(
73 "SELECT count(*) > 0 FROM sqlite_master WHERE type='table' AND name='_clm_schema_migrations'",
74 [],
75 |r| r.get(0),
76 )
77 .unwrap();
78 assert!(!aux_exists);
79 }
80}