Skip to main content

clm_rust_core/layer2/db/
migrations.rs

1//! Versioned Schema Migrations for SQLite Tri-Database Pillars.
2//!
3//! Provides deterministic schema initialization conforming to INV-TAPE-01:
4//! Three tables (card, handle_registry, handle_history), three columns each.
5//! All auxiliary tables have been eliminated (INV-TAPE-01 / ORC-23 / ORC-26).
6
7use crate::error::{ClmError, StorageErrorCode, Result};
8use rusqlite::Connection;
9
10/// Represents a versioned schema migration step.
11pub struct Migration {
12    pub version: i64,
13    pub description: &'static str,
14    pub sql_up: &'static str,
15}
16
17/// Baseline migration 1: The Monadic Core (card, handle_registry, handle_history).
18///
19/// INV-TAPE-01: three tables, three columns each. The kind is not a column (INV-TAPE-01a): the
20/// handle names it and `kindOf` decides it. Lifecycle is external (INV-TAPE-04): tombstones and
21/// their reasons live in a sidecar tape, not in a `change_type` column or a `card_tombstone` table.
22/// The DDL is generated from `schema/mcard_schema.sql` into the runtime contract (INV-594).
23pub 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
29/// Applies the canonical baseline schema (INV-TAPE-01) to the given database connection.
30pub fn apply_migrations(conn: &mut Connection, _pillar: &str) -> Result<()> {
31    // If handle_registry already exists with legacy created_at column (pre-v4.0.0 Triad),
32    // drop it to conform to INV-TAPE-01 (3 tables, 3 columns each).
33    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        // Verify card table exists
65        let count: i64 = conn
66            .query_row("SELECT count(*) FROM card", [], |r| r.get(0))
67            .unwrap();
68        assert_eq!(count, 0);
69
70        // Verify no auxiliary tables were created (INV-TAPE-01)
71        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}