clm-kernel 0.0.17

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! Layer 2: Portable SQLite Container Compilation and Parsing.
//! Canonical Path: kernel/clm_rust_core/src/layer2/portable_sqlite.rs
//! Parity: TypeScript `src/layer2/portableSqlite.ts`, Python `clm/layer2/portable_sqlite.py`

#[cfg(any(feature = "native", feature = "db"))]
pub use inner::*;

#[cfg(any(feature = "native", feature = "db"))]
mod inner {
    use std::io::Write;
    use rusqlite::{params, Connection};
    use serde::{Deserialize, Serialize};

    pub const SQLITE_HEADER: &[u8] = b"SQLite format 3\0";

    pub const CANONICAL_SCHEMA: &str = r#"
PRAGMA foreign_keys = OFF;

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
);

CREATE TABLE IF NOT EXISTS handle_history (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    handle TEXT NOT NULL,
    previous_hash TEXT NOT NULL,
    changed_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS mcard_meta (
    key TEXT PRIMARY KEY,
    value TEXT NOT NULL
);
"#;

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct PortableSqliteCard {
        pub hash: String,
        pub content: Vec<u8>,
        pub g_time: String,
        pub handle: Option<String>,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ParsedCard {
        pub hash: String,
        pub content: Vec<u8>,
        pub g_time: String,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ParsedHandle {
        pub handle: String,
        pub current_hash: String,
        pub updated_at: String,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ParsedHistory {
        pub handle: String,
        pub previous_hash: String,
        pub changed_at: String,
    }

    #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
    pub struct ParsedMeta {
        pub key: String,
        pub value: String,
    }

    #[derive(Debug, Clone, Serialize, Deserialize)]
    pub struct ParsedPortableSqlite {
        pub tables: Vec<String>,
        pub cards: Vec<ParsedCard>,
        pub handles: Vec<ParsedHandle>,
        pub history: Vec<ParsedHistory>,
        pub meta: Vec<ParsedMeta>,
    }

    pub fn compile_portable_sqlite(
        cards: &[PortableSqliteCard],
        schema_profile: Option<&str>,
        exported_at: Option<&str>,
        exported_by: Option<&str>,
    ) -> Result<Vec<u8>, String> {
        let temp_file = tempfile::NamedTempFile::new().map_err(|e| e.to_string())?;
        let temp_path = temp_file.path();

        {
            let conn = Connection::open(temp_path).map_err(|e| e.to_string())?;
            conn.execute_batch(CANONICAL_SCHEMA).map_err(|e| e.to_string())?;

            // Virtual column compatibility
            let _ = conn.execute_batch(
                "ALTER TABLE handle_registry ADD COLUMN hash TEXT GENERATED ALWAYS AS (current_hash) VIRTUAL;
                 ALTER TABLE handle_history ADD COLUMN hash TEXT GENERATED ALWAYS AS (previous_hash) VIRTUAL;
                 ALTER TABLE handle_history ADD COLUMN created_at TEXT GENERATED ALWAYS AS (changed_at) VIRTUAL;"
            );

            let profile = schema_profile.unwrap_or("portable-3.0.3");
            let author = exported_by.unwrap_or("RustCLM");
            let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true);
            let ts = exported_at.unwrap_or(&now);

            conn.execute(
                "INSERT OR REPLACE INTO mcard_meta (key, value) VALUES (?1, ?2), (?3, ?4), (?5, ?6), (?7, ?8);",
                params![
                    "schema_profile", profile,
                    "exported_at", ts,
                    "card_count", cards.len().to_string(),
                    "exported_by", author
                ],
            ).map_err(|e| e.to_string())?;

            let mut insert_card = conn.prepare(
                "INSERT OR REPLACE INTO card (hash, content, g_time) VALUES (?1, ?2, ?3);"
            ).map_err(|e| e.to_string())?;

            let mut insert_handle = conn.prepare(
                "INSERT OR REPLACE INTO handle_registry (handle, current_hash, updated_at) VALUES (?1, ?2, ?3);"
            ).map_err(|e| e.to_string())?;

            let mut insert_history = conn.prepare(
                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?1, ?2, ?3);"
            ).map_err(|e| e.to_string())?;

            for card in cards {
                insert_card.execute(params![card.hash, card.content, card.g_time]).map_err(|e| e.to_string())?;
                if let Some(ref h) = card.handle {
                    insert_handle.execute(params![h, card.hash, card.g_time]).map_err(|e| e.to_string())?;
                    insert_history.execute(params![h, card.hash, card.g_time]).map_err(|e| e.to_string())?;
                }
            }
        }

        std::fs::read(temp_path).map_err(|e| e.to_string())
    }

    pub fn parse_portable_sqlite(bytes: &[u8]) -> Result<ParsedPortableSqlite, String> {
        if bytes.len() < 16 {
            return Err("File too small to be a valid SQLite database".to_string());
        }
        if !bytes.starts_with(SQLITE_HEADER) {
            return Err("Invalid SQLite 3 binary header (magic bytes mismatch)".to_string());
        }

        let mut temp_file = tempfile::NamedTempFile::new().map_err(|e| e.to_string())?;
        temp_file.write_all(bytes).map_err(|e| e.to_string())?;
        let temp_path = temp_file.path();

        let conn = Connection::open(temp_path).map_err(|e| e.to_string())?;

        let mut stmt = conn.prepare("SELECT name FROM sqlite_master WHERE type='table';").map_err(|e| e.to_string())?;
        let table_iter = stmt.query_map([], |r| r.get::<_, String>(0)).map_err(|e| e.to_string())?;
        let mut tables = Vec::new();
        for t in table_iter {
            tables.push(t.map_err(|e| e.to_string())?);
        }

        let mut cards = Vec::new();
        if tables.contains(&"card".to_string()) {
            let mut s = conn.prepare("SELECT hash, content, g_time FROM card;").map_err(|e| e.to_string())?;
            let rows = s.query_map([], |r| {
                Ok(ParsedCard {
                    hash: r.get(0)?,
                    content: r.get(1)?,
                    g_time: r.get(2)?,
                })
            }).map_err(|e| e.to_string())?;
            for c in rows {
                cards.push(c.map_err(|e| e.to_string())?);
            }
        }

        let mut handles = Vec::new();
        if tables.contains(&"handle_registry".to_string()) {
            let mut s = conn.prepare("SELECT handle, current_hash, updated_at FROM handle_registry;").map_err(|e| e.to_string())?;
            let rows = s.query_map([], |r| {
                Ok(ParsedHandle {
                    handle: r.get(0)?,
                    current_hash: r.get(1)?,
                    updated_at: r.get(2)?,
                })
            }).map_err(|e| e.to_string())?;
            for h in rows {
                handles.push(h.map_err(|e| e.to_string())?);
            }
        }

        let mut history = Vec::new();
        if tables.contains(&"handle_history".to_string()) {
            let mut s = conn.prepare("SELECT handle, previous_hash, changed_at FROM handle_history;").map_err(|e| e.to_string())?;
            let rows = s.query_map([], |r| {
                Ok(ParsedHistory {
                    handle: r.get(0)?,
                    previous_hash: r.get(1)?,
                    changed_at: r.get(2)?,
                })
            }).map_err(|e| e.to_string())?;
            for h in rows {
                history.push(h.map_err(|e| e.to_string())?);
            }
        }

        let mut meta = Vec::new();
        if tables.contains(&"mcard_meta".to_string()) {
            let mut s = conn.prepare("SELECT key, value FROM mcard_meta;").map_err(|e| e.to_string())?;
            let rows = s.query_map([], |r| {
                Ok(ParsedMeta {
                    key: r.get(0)?,
                    value: r.get(1)?,
                })
            }).map_err(|e| e.to_string())?;
            for m in rows {
                meta.push(m.map_err(|e| e.to_string())?);
            }
        }

        Ok(ParsedPortableSqlite {
            tables,
            cards,
            handles,
            history,
            meta,
        })
    }
}