use sqlx::SqlitePool;
use crate::Error;
#[derive(Debug, Clone, Copy)]
pub struct Migration {
pub version: i64,
pub name: &'static str,
pub sql: &'static str,
}
pub const MIGRATIONS: &[Migration] = &[
Migration {
version: 1,
name: "run_events_and_run_states",
sql: r#"
CREATE TABLE run_events (
run_id TEXT NOT NULL,
seq INTEGER NOT NULL,
event_type TEXT NOT NULL,
payload TEXT NOT NULL CHECK (json_valid(payload)),
created_at TEXT NOT NULL,
PRIMARY KEY (run_id, seq)
) WITHOUT ROWID;
CREATE TABLE run_states (
run_id TEXT PRIMARY KEY NOT NULL,
agent_id TEXT NOT NULL,
session_id TEXT NOT NULL,
state TEXT NOT NULL CHECK (json_valid(state)),
updated_at TEXT NOT NULL
);
CREATE INDEX idx_run_states_session ON run_states (session_id, updated_at);
-- The journal is append-only.
CREATE TRIGGER run_events_no_update BEFORE UPDATE ON run_events
BEGIN SELECT RAISE(ABORT, 'run_events is append-only'); END;
CREATE TRIGGER run_events_no_delete BEFORE DELETE ON run_events
BEGIN SELECT RAISE(ABORT, 'run_events is append-only'); END;
"#,
},
Migration {
version: 2,
name: "channel_approvals",
sql: r#"
-- Open `ChannelRunner` approvals (`SqliteApprovalStore`). The scope columns
-- mirror the JSON so they can be queried and indexed; `record` is the whole
-- `StoredApproval` and is what is loaded back.
CREATE TABLE channel_approvals (
prompt_id TEXT PRIMARY KEY NOT NULL,
session_id TEXT NOT NULL,
channel TEXT NOT NULL,
conversation_id TEXT NOT NULL,
expires_at_ms INTEGER NOT NULL,
record TEXT NOT NULL CHECK (json_valid(record)),
saved_at TEXT NOT NULL
);
CREATE INDEX idx_channel_approvals_session ON channel_approvals (session_id);
"#,
},
];
pub fn latest_version() -> i64 {
MIGRATIONS.last().map(|m| m.version).unwrap_or(0)
}
pub async fn current_version(pool: &SqlitePool) -> Result<i64, Error> {
let version: Option<i64> = sqlx::query_scalar("SELECT MAX(version) FROM schema_migrations")
.fetch_one(pool)
.await?;
Ok(version.unwrap_or(0))
}
pub(crate) async fn run(pool: &SqlitePool) -> Result<(), Error> {
debug_assert!(
MIGRATIONS
.windows(2)
.all(|w| w[1].version == w[0].version + 1)
);
sqlx::query(
"CREATE TABLE IF NOT EXISTS schema_migrations (
version INTEGER PRIMARY KEY,
applied_at TEXT NOT NULL
)",
)
.execute(pool)
.await?;
let found = current_version(pool).await?;
let supported = latest_version();
if found > supported {
return Err(Error::SchemaTooNew { found, supported });
}
for migration in MIGRATIONS.iter().filter(|m| m.version > found) {
let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
let claimed = sqlx::query(
"INSERT OR IGNORE INTO schema_migrations (version, applied_at)
VALUES (?, strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))",
)
.bind(migration.version)
.execute(&mut *tx)
.await?
.rows_affected();
if claimed == 0 {
tx.rollback().await?;
continue;
}
sqlx::Executor::execute(&mut *tx, migration.sql)
.await
.map_err(|source| Error::Migration {
version: migration.version,
name: migration.name,
source,
})?;
tx.commit().await?;
}
Ok(())
}
#[allow(dead_code)]
fn assert_send(pool: SqlitePool) {
fn is_send<T: Send>(_: T) {}
is_send(run(&pool));
is_send(crate::SqliteStore::open("x"));
}