Skip to main content

engram_core/migrations/
mod.rs

1//! Idempotent startup migrations gated by `schema_meta(key, value)`.
2
3pub mod tags_format_v1;
4
5use engram_storage::Database;
6
7use crate::error::CoreError;
8
9pub use tags_format_v1::{TAGS_FORMAT_KEY, TAGS_FORMAT_TARGET_VALUE, TagsFormatV1Stats};
10
11const ENV_DRY_RUN: &str = "ENGRAM_MIGRATIONS_DRY_RUN";
12const ENV_TAGS_STRICT: &str = "ENGRAM_TAGS_MIGRATION_STRICT";
13
14#[derive(Debug, Default, Clone, PartialEq, Eq)]
15pub struct MigrationReport {
16    pub tags_format_v1: Option<TagsFormatV1Stats>,
17}
18
19pub fn run_pending(database: &Database) -> Result<MigrationReport, CoreError> {
20    let dry_run = std::env::var(ENV_DRY_RUN).is_ok();
21    let strict = std::env::var(ENV_TAGS_STRICT).is_ok();
22    let tags_format_v1 = tags_format_v1::run(database, dry_run, strict)?;
23    Ok(MigrationReport { tags_format_v1 })
24}
25
26pub(crate) fn read_meta(database: &Database, key: &str) -> Result<Option<String>, CoreError> {
27    use rusqlite::OptionalExtension;
28    database
29        .connection()
30        .query_row(
31            "SELECT value FROM schema_meta WHERE key = ?1",
32            [key],
33            |row| row.get::<_, String>(0),
34        )
35        .optional()
36        .map_err(|error| CoreError::MigrationFailed(format!("schema_meta read: {error}")))
37}
38
39pub(crate) fn write_meta(database: &Database, key: &str, value: &str) -> Result<(), CoreError> {
40    database
41        .connection()
42        .execute(
43            "INSERT OR REPLACE INTO schema_meta(key, value) VALUES (?1, ?2)",
44            [key, value],
45        )
46        .map_err(|error| CoreError::MigrationFailed(format!("schema_meta write: {error}")))?;
47    Ok(())
48}