steid

@jamesgill /

Rust4.3 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.
37pub async fn migrate(pool: &SqlitePool) -> Result<(), sqlx::Error> {
38 sqlx::migrate!("./migrations")
39 .run(pool)
40 .await
41 .map_err(|error| sqlx::Error::Migrate(Box::new(error)))
42}
43
44/// The expand/deploy/contract rule, enforced.
45///
46/// A sibling rather than part of `mod tests` below: it is a different subject — what a
47/// migration is allowed to *say*, not whether this module works — and it is longer than
48/// the module it hangs off.
49#[cfg(test)]
50#[path = "database_compat_tests.rs"]
51mod compat_tests;
52
53#[cfg(test)]
54pub(crate) mod test_support {
55 use super::*;
56
57 /// A migrated, isolated in-memory database for tests.
58 ///
59 /// `:memory:` is per-connection, so the pool is capped at one connection —
60 /// otherwise each checkout gets its own empty database and writes vanish.
61 pub async fn test_pool() -> SqlitePool {
62 let options = SqliteConnectOptions::from_str("sqlite::memory:")
63 .expect("in-memory url should parse")
64 .foreign_keys(true);
65
66 let pool = SqlitePoolOptions::new()
67 .max_connections(1)
68 .connect_with(options)
69 .await
70 .expect("in-memory database should open");
71
72 migrate(&pool).await.expect("migrations should apply");
73
74 pool
75 }
76}
77
78#[cfg(test)]
79mod tests {
80 use super::*;
81 use sqlx::Row;
82
83 #[tokio::test]
84 async fn migrations_apply_to_a_fresh_database() {
85 let pool = test_support::test_pool().await;
86
87 let tables: Vec<String> =
88 sqlx::query("select name from sqlite_master where type = 'table'")
89 .fetch_all(&pool)
90 .await
91 .expect("query")
92 .into_iter()
93 .map(|row| row.get::<String, _>("name"))
94 .collect();
95
96 for expected in ["orgs", "users", "memberships"] {
97 assert!(
98 tables.iter().any(|name| name == expected),
99 "expected a {expected} table, got {tables:?}"
100 );
101 }
102 }
103
104 #[tokio::test]
105 async fn foreign_keys_are_enforced() {
106 let pool = test_support::test_pool().await;
107
108 // A user pointing at an org that doesn't exist must be refused. If this ever
109 // passes, `foreign_keys(true)` has been lost and the schema's references have
110 // quietly become decorative.
111 let result = sqlx::query(
112 "insert into users (id, email, password_hash, personal_org_id)
113 values ('u1', 'dev@example.com', 'hash', 'org-that-does-not-exist')",
114 )
115 .execute(&pool)
116 .await;
117
118 assert!(result.is_err(), "expected the foreign key to be enforced");
119 }
120
121 #[tokio::test]
122 async fn migrations_are_idempotent() {
123 let pool = test_support::test_pool().await;
124
125 migrate(&pool).await.expect("re-running should be a no-op");
126 }
127}