claw-core 0.1.2

Embedded local database engine for ClawDB — an agent-native cognitive database
Documentation
//! Lightweight FTS and B-tree index helpers for claw-core.
//!
//! This module exposes helpers that create and query SQLite FTS5 full-text
//! search virtual tables and ordinary B-tree indexes on the claw-core schema
//! tables. Index creation is idempotent (`CREATE INDEX IF NOT EXISTS`).

use sqlx::SqlitePool;

use crate::error::ClawResult;

/// Helpers for managing lightweight indexes on claw-core tables.
///
/// All methods are idempotent and safe to call multiple times (they use
/// `IF NOT EXISTS` guards internally).
pub struct IndexManager<'a> {
    pool: &'a SqlitePool,
}

impl<'a> IndexManager<'a> {
    /// Create a new [`IndexManager`] bound to `pool`.
    pub fn new(pool: &'a SqlitePool) -> Self {
        IndexManager { pool }
    }

    /// Create a B-tree index on `active_memory(agent_id)` if it does not
    /// already exist.
    ///
    /// # Errors
    ///
    /// Returns a [`crate::error::ClawError`] if the SQL execution fails.
    pub async fn ensure_active_memory_agent_index(&self) -> ClawResult<()> {
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_active_memory_agent_id \
             ON active_memory (agent_id)",
        )
        .execute(self.pool)
        .await?;
        Ok(())
    }

    /// Create a B-tree index on `session_state(session_id)` if it does not
    /// already exist.
    ///
    /// # Errors
    ///
    /// Returns a [`crate::error::ClawError`] if the SQL execution fails.
    pub async fn ensure_session_index(&self) -> ClawResult<()> {
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_session_state_session_id \
             ON session_state (session_id)",
        )
        .execute(self.pool)
        .await?;
        Ok(())
    }

    /// Create a B-tree index on `tool_output(tool_name, created_at)` if it
    /// does not already exist.
    ///
    /// # Errors
    ///
    /// Returns a [`crate::error::ClawError`] if the SQL execution fails.
    pub async fn ensure_tool_output_index(&self) -> ClawResult<()> {
        sqlx::query(
            "CREATE INDEX IF NOT EXISTS idx_tool_output_tool_name_created_at \
             ON tool_output (tool_name, created_at)",
        )
        .execute(self.pool)
        .await?;
        Ok(())
    }
}

impl<'a> std::fmt::Debug for IndexManager<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IndexManager").finish_non_exhaustive()
    }
}