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    Ok(recorded_version(pool, VERSION_TABLE).await?)
83}
84
85/// Bring the schema up to [`latest_version`]. Idempotent, safe to call from
86/// several processes at once, and refuses databases written by newer code.
87pub(crate) async fn run(pool: &SqlitePool) -> Result<(), Error> {
88    apply(pool, VERSION_TABLE, MIGRATIONS)
89        .await
90        .map_err(Into::into)
91}
92
93/// The table this store records its versions in.
94const VERSION_TABLE: &str = "schema_migrations";
95
96/// Why [`apply`] stopped.
97#[derive(Debug, thiserror::Error)]
98pub enum MigrateError {
99    #[error("sqlite: {0}")]
100    Sqlx(#[from] sqlx::Error),
101    /// The database was written by a newer build.
102    #[error("schema version {found} is newer than this build supports ({supported})")]
103    SchemaTooNew { found: i64, supported: i64 },
104    /// One step failed; the database stays at the version before it.
105    #[error("migration {version} ({name}) failed: {source}")]
106    Step {
107        version: i64,
108        name: &'static str,
109        source: sqlx::Error,
110    },
111}
112
113impl From<MigrateError> for Error {
114    fn from(error: MigrateError) -> Self {
115        match error {
116            MigrateError::Sqlx(error) => Error::Sqlx(error),
117            MigrateError::SchemaTooNew { found, supported } => {
118                Error::SchemaTooNew { found, supported }
119            }
120            MigrateError::Step {
121                version,
122                name,
123                source,
124            } => Error::Migration {
125                version,
126                name,
127                source,
128            },
129        }
130    }
131}
132
133/// The highest version recorded in `table` (0 for none).
134pub async fn recorded_version(pool: &SqlitePool, table: &str) -> sqlx::Result<i64> {
135    let version: Option<i64> = sqlx::query_scalar(sqlx::AssertSqlSafe(format!(
136        "SELECT MAX(version) FROM {table}"
137    )))
138    .fetch_one(pool)
139    .await?;
140    Ok(version.unwrap_or(0))
141}
142
143/// Apply `migrations` (strictly increasing versions from 1) that `table`
144/// has not recorded, each in its own `BEGIN IMMEDIATE` transaction with the
145/// row that records it, and refuse a database a newer build wrote. A store
146/// sharing the database file keeps its own `table`, so the version
147/// sequences never collide. Idempotent and safe from several processes.
148pub async fn apply(
149    pool: &SqlitePool,
150    table: &'static str,
151    migrations: &[Migration],
152) -> Result<(), MigrateError> {
153    debug_assert!(
154        migrations
155            .windows(2)
156            .all(|w| w[1].version == w[0].version + 1)
157    );
158    sqlx::query(sqlx::AssertSqlSafe(format!(
159        "CREATE TABLE IF NOT EXISTS {table} (
160            version    INTEGER PRIMARY KEY,
161            applied_at TEXT NOT NULL
162        )"
163    )))
164    .execute(pool)
165    .await?;
166
167    let found = recorded_version(pool, table).await?;
168    let supported = migrations.last().map(|m| m.version).unwrap_or(0);
169    if found > supported {
170        return Err(MigrateError::SchemaTooNew { found, supported });
171    }
172    let claim = format!(
173        "INSERT OR IGNORE INTO {table} (version, applied_at)
174         VALUES (?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
175    );
176    for migration in migrations.iter().filter(|m| m.version > found) {
177        let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
178        // Claim the version first: this takes the write lock, and if another
179        // process applied it meanwhile the insert is ignored and we skip.
180        let claimed = sqlx::query(sqlx::AssertSqlSafe(claim.as_str()))
181            .bind(migration.version)
182            .execute(&mut *tx)
183            .await?
184            .rows_affected();
185        if claimed == 0 {
186            tx.rollback().await?;
187            continue;
188        }
189        sqlx::Executor::execute(&mut *tx, migration.sql)
190            .await
191            .map_err(|source| MigrateError::Step {
192                version: migration.version,
193                name: migration.name,
194                source,
195            })?;
196        tx.commit().await?;
197    }
198    Ok(())
199}
200
201/// Compile-time check: opening must stay spawnable. `sqlx::raw_sql` on a
202/// transaction trips a higher-ranked lifetime bug that makes the future
203/// `!Send`, which is why the migration body uses `Executor::execute`.
204#[allow(dead_code)]
205fn assert_send(pool: SqlitePool) {
206    fn is_send<T: Send>(_: T) {}
207    is_send(run(&pool));
208    is_send(crate::SqliteStore::open("x"));
209}