use sqlx::SqlitePool;
use crate::error::{MemoryError, Result};
pub use aidaemon_store_sqlite::Migration;
pub const MIGRATIONS: &[Migration] = &[
Migration {
version: 1,
name: "facts_episodes_fts",
sql: r#"
CREATE TABLE memory_facts (
id TEXT PRIMARY KEY NOT NULL,
scope TEXT NOT NULL,
category TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
confidence REAL NOT NULL,
source_run_id TEXT,
source_session_id TEXT,
source_excerpt TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
superseded_at TEXT,
recall_count INTEGER NOT NULL DEFAULT 0,
last_recalled_at TEXT,
embedding BLOB,
embedding_model TEXT
);
-- At most one active row per key; superseded rows are history.
CREATE UNIQUE INDEX idx_memory_facts_active
ON memory_facts (scope, category, key) WHERE superseded_at IS NULL;
CREATE INDEX idx_memory_facts_history ON memory_facts (scope, category, key, created_at);
CREATE INDEX idx_memory_facts_superseded ON memory_facts (superseded_at)
WHERE superseded_at IS NOT NULL;
-- Lexical index over ACTIVE facts only, maintained in the same transaction
-- as every write.
CREATE VIRTUAL TABLE memory_facts_fts USING fts5(
fact_id UNINDEXED,
scope UNINDEXED,
content,
tokenize = 'unicode61'
);
CREATE TABLE memory_episodes (
id TEXT PRIMARY KEY NOT NULL,
scope TEXT NOT NULL,
session_id TEXT NOT NULL,
summary TEXT NOT NULL,
topics TEXT NOT NULL CHECK (json_valid(topics)),
importance REAL NOT NULL,
created_at TEXT NOT NULL,
recall_count INTEGER NOT NULL DEFAULT 0,
last_recalled_at TEXT,
embedding BLOB,
embedding_model TEXT
);
CREATE INDEX idx_memory_episodes_scope ON memory_episodes (scope, created_at);
CREATE VIRTUAL TABLE memory_episodes_fts USING fts5(
episode_id UNINDEXED,
scope UNINDEXED,
content,
tokenize = 'unicode61'
);
"#,
},
Migration {
version: 2,
name: "record_access",
sql: r#"
ALTER TABLE memory_facts ADD COLUMN privacy TEXT NOT NULL DEFAULT 'private';
ALTER TABLE memory_facts ADD COLUMN channel_id TEXT;
ALTER TABLE memory_episodes ADD COLUMN privacy TEXT NOT NULL DEFAULT 'private';
ALTER TABLE memory_episodes ADD COLUMN channel_id TEXT;
"#,
},
];
pub fn latest_version() -> i64 {
MIGRATIONS.last().map(|m| m.version).unwrap_or(0)
}
pub(crate) async fn current_version(pool: &SqlitePool) -> Result<i64> {
Ok(aidaemon_store_sqlite::recorded_version(pool, VERSION_TABLE).await?)
}
const VERSION_TABLE: &str = "memory_schema_migrations";
pub(crate) async fn run(pool: &SqlitePool) -> Result<()> {
aidaemon_store_sqlite::apply_migrations(pool, VERSION_TABLE, MIGRATIONS)
.await
.map_err(|error| match error {
aidaemon_store_sqlite::MigrateError::Sqlx(error) => MemoryError::Sqlx(error),
aidaemon_store_sqlite::MigrateError::SchemaTooNew { found, supported } => {
MemoryError::SchemaTooNew { found, supported }
}
aidaemon_store_sqlite::MigrateError::Step {
version,
name,
source,
} => MemoryError::Migration {
version,
name,
source,
},
})
}