forge
Explore
Log in

Don't you dare go Hollow

im

Clone
★ 0

0 watching0 forksRustAGPL-3.0542.8 KiBb9f0726Tahinli27 days ago34 commits

migrate.rs87 lines, 2.8 KiBHistoryRawDownload
1//! Migration runner. Applied versions are recorded in `schema_migrations`.
2//!
3//! A migration file is never edited once applied; a change is a new numbered file. Each migration
4//! runs in its own transaction together with its `schema_migrations` row, so a failure leaves
5//! nothing half-applied.
6
7use turso::Connection;
8
9use crate::error::{Error, Result};
10use crate::time::now_stamp;
11
12/// `(version, sql)` in ascending order, with no gaps. Add each new file here.
13pub const MIGRATIONS: &[(u32, &str)] = &[
14 (1, include_str!("../../migrations/0001_init.sql")),
15 (
16 2,
17 include_str!("../../migrations/0002_sessions_cap_and_language.sql"),
18 ),
19 (
20 3,
21 include_str!("../../migrations/0003_consumed_pending_logins.sql"),
22 ),
23 (
24 4,
25 include_str!("../../migrations/0004_revoked_access_tokens.sql"),
26 ),
27 (5, include_str!("../../migrations/0005_outbox_jti.sql")),
28 (
29 6,
30 include_str!("../../migrations/0006_mail_outbox_recipient.sql"),
31 ),
32 (
33 7,
34 include_str!("../../migrations/0007_code_access_token.sql"),
35 ),
36];
37
38fn migration_err(e: turso::Error) -> Error {
39 Error::Migration(e.to_string())
40}
41
42/// Applies every migration whose version is not yet recorded. Running it again is a no-op.
43pub async fn migrate(conn: &Connection) -> Result<()> {
44 conn.execute_batch(
45 "CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, applied_at TEXT NOT NULL)",
46 )
47 .await
48 .map_err(migration_err)?;
49
50 let applied = applied_versions(conn).await?;
51 for &(version, sql) in MIGRATIONS {
52 let version = i64::from(version);
53 if applied.contains(&version) {
54 continue;
55 }
56 let tx = conn.unchecked_transaction().await.map_err(migration_err)?;
57 tx.execute_batch(sql).await.map_err(migration_err)?;
58 tx.execute(
59 "INSERT INTO schema_migrations (version, applied_at) VALUES (?1, ?2)",
60 (version, now_stamp()),
61 )
62 .await
63 .map_err(migration_err)?;
64 tx.commit().await.map_err(migration_err)?;
65 tracing::info!(version, "applied database migration");
66 }
67 Ok(())
68}
69
70async fn applied_versions(conn: &Connection) -> Result<Vec<i64>> {
71 let mut rows = conn
72 .query("SELECT version FROM schema_migrations ORDER BY version", ())
73 .await
74 .map_err(migration_err)?;
75 let mut versions = Vec::new();
76 while let Some(row) = rows.next().await.map_err(migration_err)? {
77 match row.get_value(0).map_err(migration_err)? {
78 turso::Value::Integer(v) => versions.push(v),
79 _ => {
80 return Err(Error::Migration(
81 "schema_migrations.version is not an integer".into(),
82 ));
83 }
84 }
85 }
86 Ok(versions)
87}