claw-core 0.1.2

Embedded local database engine for ClawDB — an agent-native cognitive database
Documentation
//! Schema validation helpers for claw-core.
//!
//! This module exposes lightweight runtime checks that verify the claw-core
//! schema is in an expected state after migrations have been applied. Checks
//! are run on engine startup (when `auto_migrate` is enabled) to guard
//! against partial migrations or external schema corruption.

use sqlx::SqlitePool;

use crate::error::{ClawError, ClawResult};

/// Verify that all expected claw-core tables are present in the database.
///
/// Returns `Ok(())` if every required table exists, or a [`ClawError::Config`]
/// listing the missing tables.
///
/// # Errors
///
/// Returns a [`ClawError`] if the introspection query fails or a table is
/// missing.
pub async fn validate_schema(pool: &SqlitePool) -> ClawResult<()> {
    let required_tables = [
        "active_memory",
        "session_state",
        "tool_output",
        "context",
        "memories",
        "sessions",
    ];

    let rows: Vec<(String,)> =
        sqlx::query_as("SELECT name FROM sqlite_master WHERE type = 'table'")
            .fetch_all(pool)
            .await?;

    let existing: std::collections::HashSet<&str> =
        rows.iter().map(|(name,)| name.as_str()).collect();

    let missing: Vec<&str> = required_tables
        .iter()
        .copied()
        .filter(|t| !existing.contains(t))
        .collect();

    if missing.is_empty() {
        Ok(())
    } else {
        Err(ClawError::Config(format!(
            "schema validation failed — missing tables: {}",
            missing.join(", ")
        )))
    }
}