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 Ok(recorded_version(pool, VERSION_TABLE).await?)
83}
84
85pub(crate) async fn run(pool: &SqlitePool) -> Result<(), Error> {
88 apply(pool, VERSION_TABLE, MIGRATIONS)
89 .await
90 .map_err(Into::into)
91}
92
93const VERSION_TABLE: &str = "schema_migrations";
95
96#[derive(Debug, thiserror::Error)]
98pub enum MigrateError {
99 #[error("sqlite: {0}")]
100 Sqlx(#[from] sqlx::Error),
101 #[error("schema version {found} is newer than this build supports ({supported})")]
103 SchemaTooNew { found: i64, supported: i64 },
104 #[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
133pub 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
143pub 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 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#[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}