Skip to main content

aidaemon_store_sqlite/
migrations.rs

1//! Versioned, embedded schema migrations.
2//!
3//! Each migration runs in its own transaction together with the row that
4//! records it in `schema_migrations`, so a crash mid-migration leaves the
5//! database at the previous version. Migrations are append-only: never edit
6//! a released entry, add a new one with the next version instead.
7
8use sqlx::SqlitePool;
9
10use crate::Error;
11
12/// One schema step.
13#[derive(Debug, Clone, Copy)]
14pub struct Migration {
15    /// Strictly increasing, starting at 1.
16    pub version: i64,
17    pub name: &'static str,
18    pub sql: &'static str,
19}
20
21/// Every migration this build knows, in order.
22pub const MIGRATIONS: &[Migration] = &[
23    Migration {
24        version: 1,
25        name: "run_events_and_run_states",
26        sql: r#"
27CREATE TABLE run_events (
28    run_id     TEXT    NOT NULL,
29    seq        INTEGER NOT NULL,
30    event_type TEXT    NOT NULL,
31    payload    TEXT    NOT NULL CHECK (json_valid(payload)),
32    created_at TEXT    NOT NULL,
33    PRIMARY KEY (run_id, seq)
34) WITHOUT ROWID;
35
36CREATE TABLE run_states (
37    run_id     TEXT PRIMARY KEY NOT NULL,
38    agent_id   TEXT NOT NULL,
39    session_id TEXT NOT NULL,
40    state      TEXT NOT NULL CHECK (json_valid(state)),
41    updated_at TEXT NOT NULL
42);
43
44CREATE INDEX idx_run_states_session ON run_states (session_id, updated_at);
45
46-- The journal is append-only.
47CREATE TRIGGER run_events_no_update BEFORE UPDATE ON run_events
48BEGIN SELECT RAISE(ABORT, 'run_events is append-only'); END;
49CREATE TRIGGER run_events_no_delete BEFORE DELETE ON run_events
50BEGIN SELECT RAISE(ABORT, 'run_events is append-only'); END;
51"#,
52    },
53    Migration {
54        version: 2,
55        name: "channel_approvals",
56        sql: r#"
57-- Open `ChannelRunner` approvals (`SqliteApprovalStore`). The scope columns
58-- mirror the JSON so they can be queried and indexed; `record` is the whole
59-- `StoredApproval` and is what is loaded back.
60CREATE TABLE channel_approvals (
61    prompt_id       TEXT    PRIMARY KEY NOT NULL,
62    session_id      TEXT    NOT NULL,
63    channel         TEXT    NOT NULL,
64    conversation_id TEXT    NOT NULL,
65    expires_at_ms   INTEGER NOT NULL,
66    record          TEXT    NOT NULL CHECK (json_valid(record)),
67    saved_at        TEXT    NOT NULL
68);
69
70CREATE INDEX idx_channel_approvals_session ON channel_approvals (session_id);
71"#,
72    },
73];
74
75/// The newest schema version this build understands.
76pub fn latest_version() -> i64 {
77    MIGRATIONS.last().map(|m| m.version).unwrap_or(0)
78}
79
80/// The version recorded in the database (0 for a fresh one).
81pub async fn current_version(pool: &SqlitePool) -> Result<i64, Error> {
82    let version: Option<i64> = sqlx::query_scalar("SELECT MAX(version) FROM schema_migrations")
83        .fetch_one(pool)
84        .await?;
85    Ok(version.unwrap_or(0))
86}
87
88/// Bring the schema up to [`latest_version`]. Idempotent, safe to call from
89/// several processes at once, and refuses databases written by newer code.
90pub(crate) async fn run(pool: &SqlitePool) -> Result<(), Error> {
91    debug_assert!(
92        MIGRATIONS
93            .windows(2)
94            .all(|w| w[1].version == w[0].version + 1)
95    );
96
97    sqlx::query(
98        "CREATE TABLE IF NOT EXISTS schema_migrations (
99            version    INTEGER PRIMARY KEY,
100            applied_at TEXT NOT NULL
101        )",
102    )
103    .execute(pool)
104    .await?;
105
106    let found = current_version(pool).await?;
107    let supported = latest_version();
108    if found > supported {
109        return Err(Error::SchemaTooNew { found, supported });
110    }
111
112    for migration in MIGRATIONS.iter().filter(|m| m.version > found) {
113        let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
114        // Claim the version first: this takes the write lock, and if another
115        // process applied it meanwhile the insert is ignored and we skip.
116        let claimed = sqlx::query(
117            "INSERT OR IGNORE INTO schema_migrations (version, applied_at)
118             VALUES (?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))",
119        )
120        .bind(migration.version)
121        .execute(&mut *tx)
122        .await?
123        .rows_affected();
124        if claimed == 0 {
125            tx.rollback().await?;
126            continue;
127        }
128        sqlx::Executor::execute(&mut *tx, migration.sql)
129            .await
130            .map_err(|source| Error::Migration {
131                version: migration.version,
132                name: migration.name,
133                source,
134            })?;
135        tx.commit().await?;
136    }
137    Ok(())
138}
139
140/// Compile-time check: opening must stay spawnable. `sqlx::raw_sql` on a
141/// transaction trips a higher-ranked lifetime bug that makes the future
142/// `!Send`, which is why the migration body uses `Executor::execute`.
143#[allow(dead_code)]
144fn assert_send(pool: SqlitePool) {
145    fn is_send<T: Send>(_: T) {}
146    is_send(run(&pool));
147    is_send(crate::SqliteStore::open("x"));
148}