aidaemon_store_sqlite/
migrations.rs1use sqlx::SqlitePool;
9
10use crate::Error;
11
12#[derive(Debug, Clone, Copy)]
14pub struct Migration {
15 pub version: i64,
17 pub name: &'static str,
18 pub sql: &'static str,
19}
20
21pub 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
75pub fn latest_version() -> i64 {
77 MIGRATIONS.last().map(|m| m.version).unwrap_or(0)
78}
79
80pub 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
88pub(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 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#[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}