second-brain-core 0.9.0

Core library for second-brain: KuzuDB graph storage, BGE embeddings, and weighted query engine
Documentation
//! Stores as older binaries left them, so a dependent crate's tests can
//! exercise the migration a normal `SqliteStore::open` runs. Behind the
//! `test-support` feature because nothing in production should build one.

use std::path::Path;

use anyhow::{Context, Result, ensure};
use rusqlite::Connection;

use super::ddl;

/// Creates a new store file at `path` whose schema stops at ladder
/// `version` (`BASELINE_VERSION..=SCHEMA_VERSION`), as a binary built when
/// that was the current version would have left it. Returns the open
/// connection so the caller can seed rows at that version; drop it before
/// opening the store, which then migrates it the rest of the way.
pub fn create_store_at_version(path: &Path, version: i64) -> Result<Connection> {
    ensure!(
        !path.exists(),
        "{} already exists; stamping a store back to an older version would \
         make its next open re-run migrations over it",
        path.display()
    );
    let conn =
        Connection::open(path).with_context(|| format!("creating store at {}", path.display()))?;
    ddl::create_at_version(&conn, version)?;
    Ok(conn)
}

#[cfg(test)]
mod tests {
    use rusqlite::Connection;
    use uuid::Uuid;

    use super::create_store_at_version;
    use crate::sqlite_store::{BASELINE_VERSION, SCHEMA_VERSION, SqliteStore};
    use crate::store::Store;

    fn user_version(conn: &Connection) -> i64 {
        conn.query_row("PRAGMA user_version", [], |r| r.get(0))
            .unwrap()
    }

    fn recorded_versions(conn: &Connection) -> Vec<i64> {
        let mut stmt = conn
            .prepare("SELECT version FROM schema_migrations ORDER BY version")
            .unwrap();
        stmt.query_map([], |r| r.get(0))
            .unwrap()
            .collect::<rusqlite::Result<Vec<i64>>>()
            .unwrap()
    }

    #[test]
    fn a_baseline_store_migrates_on_a_normal_open_and_keeps_its_rows() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("v1.db");
        let id = Uuid::new_v4();

        let conn = create_store_at_version(&path, BASELINE_VERSION).unwrap();
        assert_eq!(user_version(&conn), BASELINE_VERSION);
        conn.execute(
            "INSERT INTO memories (id, content, memory_type, confidence, created_at, \
             updated_at, last_accessed, source, source_id, machine_id) \
             VALUES (?1, 'seeded at the baseline', 'semantic', 0.5, '2026-01-01T00:00:00Z', \
             '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z', 'test', 'src-1', 'm')",
            [id.to_string()],
        )
        .unwrap();
        drop(conn);

        let store = SqliteStore::open(&path, "m".to_string()).unwrap();
        assert_eq!(
            store.get_memory(id).unwrap().unwrap().content,
            "seeded at the baseline"
        );
        drop(store);

        let conn = Connection::open(&path).unwrap();
        assert_eq!(user_version(&conn), SCHEMA_VERSION);
        assert_eq!(
            recorded_versions(&conn),
            ((BASELINE_VERSION + 1)..=SCHEMA_VERSION).collect::<Vec<_>>(),
            "a baseline store predates schema_migrations, so only the steps the open ran are recorded"
        );
    }

    #[test]
    fn every_ladder_version_can_be_built_and_then_opened() {
        for version in BASELINE_VERSION..=SCHEMA_VERSION {
            let dir = tempfile::tempdir().unwrap();
            let path = dir.path().join("store.db");

            let conn = create_store_at_version(&path, version).unwrap();
            assert_eq!(user_version(&conn), version);
            drop(conn);

            drop(SqliteStore::open(&path, "m".to_string()).unwrap());
            let conn = Connection::open(&path).unwrap();
            assert_eq!(
                user_version(&conn),
                SCHEMA_VERSION,
                "from version {version}"
            );
        }
    }

    #[test]
    fn versions_off_the_ladder_and_existing_files_are_refused() {
        let dir = tempfile::tempdir().unwrap();

        for version in [BASELINE_VERSION - 1, SCHEMA_VERSION + 1] {
            let path = dir.path().join(format!("v{version}.db"));
            assert!(create_store_at_version(&path, version).is_err());
        }

        let path = dir.path().join("taken.db");
        drop(SqliteStore::open(&path, "m".to_string()).unwrap());
        assert!(
            create_store_at_version(&path, BASELINE_VERSION).is_err(),
            "stamping an existing store back down would make the next open re-run migrations over it"
        );
    }
}