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