steid

@jamesgill /

Rust5.5 KBCode·Blame·History·Raw
1use std::str::FromStr;
2
3use sqlx::SqlitePool;
4use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
5
6/// Opens the SQLite pool and brings the schema up to date.
7///
8/// The pool is cheap to clone and shared by reference across every request, so it is
9/// registered once as Topcoat app context rather than rebuilt per handler.
10pub async fn connect(database_url: &str) -> Result<SqlitePool, sqlx::Error> {
11 let pool = open(database_url).await?;
12
13 migrate(&pool).await?;
14
15 Ok(pool)
16}
17
18/// Opens the pool and applies nothing.
19///
20/// For `steid backup`, which must not migrate: the backup may be taken by a control
21/// plane while an older binary is still serving from the same file, and a schema change
22/// applied as a side effect of copying the database would change the database it was
23/// asked to copy.
24pub async fn open(database_url: &str) -> Result<SqlitePool, sqlx::Error> {
25 // SQLite ignores foreign keys unless asked, per connection. Without this the
26 // references in the schema are documentation rather than constraints, and the
27 // ordering our use cases are careful about stops being enforced at all.
28 let options = SqliteConnectOptions::from_str(database_url)?.foreign_keys(true);
29
30 SqlitePoolOptions::new().connect_with(options).await
31}
32
33/// Applies any migrations the database has not seen.
34///
35/// Embedded at compile time, so the binary carries its own schema and there is no
36/// separate migration step to forget on deploy.
37///
38/// **A migration this binary does not know is ignored, not refused.** That is the
39/// database a rollback meets: a newer release migrated it, failed, and this binary was
40/// put back in its place.
41///
42/// - Migrations are expand-only (`plans/architecture.md`, "Migrations"), so this binary
43/// is *able* to read a schema a later release has added to.
44/// - sqlx's default stops it from trying. `ignore_missing: false` makes an applied
45/// migration missing from the embedded set `VersionMissing`, the binary exits, and
46/// systemd restarts it for ever.
47/// - Only the unknown versions are excused. Every migration this binary *does* carry is
48/// still checked against its stored checksum, so an edited shipped migration is still
49/// `VersionMismatch`.
50///
51/// It only helps a rollback *to* a binary that carries it: 0.8.1 and later. Every path
52/// that migrates comes through here — `steid` itself, `reset-password` and `restore`
53/// (with or without `--replace`) call [`connect`] — and `backup` calls [`open`] and
54/// migrates nothing.
55pub async fn migrate(pool: &SqlitePool) -> Result<(), sqlx::Error> {
56 let mut migrator = sqlx::migrate!("./migrations");
57 migrator.set_ignore_missing(true);
58
59 migrator
60 .run(pool)
61 .await
62 .map_err(|error| sqlx::Error::Migrate(Box::new(error)))
63}
64
65/// The expand/deploy/contract rule, enforced, and what a binary must survive meeting.
66///
67/// A sibling rather than part of `mod tests` below: it is a different subject — what a
68/// migration is allowed to *say*, and which databases a release must still boot
69/// against, not whether this module works — and it is longer than the module it hangs
70/// off.
71#[cfg(test)]
72#[path = "database_compat_tests.rs"]
73mod compat_tests;
74
75#[cfg(test)]
76pub(crate) mod test_support {
77 use super::*;
78
79 /// A migrated, isolated in-memory database for tests.
80 ///
81 /// `:memory:` is per-connection, so the pool is capped at one connection —
82 /// otherwise each checkout gets its own empty database and writes vanish.
83 pub async fn test_pool() -> SqlitePool {
84 let options = SqliteConnectOptions::from_str("sqlite::memory:")
85 .expect("in-memory url should parse")
86 .foreign_keys(true);
87
88 let pool = SqlitePoolOptions::new()
89 .max_connections(1)
90 .connect_with(options)
91 .await
92 .expect("in-memory database should open");
93
94 migrate(&pool).await.expect("migrations should apply");
95
96 pool
97 }
98}
99
100#[cfg(test)]
101mod tests {
102 use super::*;
103 use sqlx::Row;
104
105 #[tokio::test]
106 async fn migrations_apply_to_a_fresh_database() {
107 let pool = test_support::test_pool().await;
108
109 let tables: Vec<String> =
110 sqlx::query("select name from sqlite_master where type = 'table'")
111 .fetch_all(&pool)
112 .await
113 .expect("query")
114 .into_iter()
115 .map(|row| row.get::<String, _>("name"))
116 .collect();
117
118 for expected in ["orgs", "users", "memberships"] {
119 assert!(
120 tables.iter().any(|name| name == expected),
121 "expected a {expected} table, got {tables:?}"
122 );
123 }
124 }
125
126 #[tokio::test]
127 async fn foreign_keys_are_enforced() {
128 let pool = test_support::test_pool().await;
129
130 // A user pointing at an org that doesn't exist must be refused. If this ever
131 // passes, `foreign_keys(true)` has been lost and the schema's references have
132 // quietly become decorative.
133 let result = sqlx::query(
134 "insert into users (id, email, password_hash, personal_org_id)
135 values ('u1', 'dev@example.com', 'hash', 'org-that-does-not-exist')",
136 )
137 .execute(&pool)
138 .await;
139
140 assert!(result.is_err(), "expected the foreign key to be enforced");
141 }
142
143 #[tokio::test]
144 async fn migrations_are_idempotent() {
145 let pool = test_support::test_pool().await;
146
147 migrate(&pool).await.expect("re-running should be a no-op");
148 }
149}