|
| 1 | +//! Embedded SQLx migrations for Buzz. |
| 2 | +//! |
| 3 | +//! Fresh deployments apply the checked-in SQL files under `migrations/`. |
| 4 | +//! Existing pre-SQLx deployments are baselined when core Buzz tables already |
| 5 | +//! exist but `_sqlx_migrations` does not, so startup will not try to replay the |
| 6 | +//! initial schema over a live database. |
| 7 | +
|
| 8 | +use sqlx::PgPool; |
| 9 | + |
| 10 | +use crate::Result; |
| 11 | + |
| 12 | +static MIGRATOR: sqlx::migrate::Migrator = sqlx::migrate!("../../migrations"); |
| 13 | + |
| 14 | +#[cfg(test)] |
| 15 | +static SCHEMA_SQL: &str = include_str!("../../../schema/schema.sql"); |
| 16 | + |
| 17 | +const BASELINE_MIGRATION_VERSIONS: &[i64] = &[1, 2]; |
| 18 | + |
| 19 | +/// Run all pending Buzz database migrations. |
| 20 | +pub async fn run_migrations(pool: &PgPool) -> Result<()> { |
| 21 | + baseline_existing_database(pool).await?; |
| 22 | + MIGRATOR.run(pool).await?; |
| 23 | + Ok(()) |
| 24 | +} |
| 25 | + |
| 26 | +async fn baseline_existing_database(pool: &PgPool) -> Result<()> { |
| 27 | + if migrations_table_exists(pool).await? || !pre_sqlx_schema_exists(pool).await? { |
| 28 | + return Ok(()); |
| 29 | + } |
| 30 | + |
| 31 | + ensure_migrations_table(pool).await?; |
| 32 | + |
| 33 | + for version in BASELINE_MIGRATION_VERSIONS { |
| 34 | + let migration = MIGRATOR |
| 35 | + .iter() |
| 36 | + .find(|migration| migration.version == *version) |
| 37 | + .expect("baseline migration version must exist in embedded migrator"); |
| 38 | + |
| 39 | + sqlx::query( |
| 40 | + r#" |
| 41 | + INSERT INTO _sqlx_migrations |
| 42 | + (version, description, success, checksum, execution_time) |
| 43 | + VALUES ($1, $2, TRUE, $3, 0) |
| 44 | + ON CONFLICT (version) DO NOTHING |
| 45 | + "#, |
| 46 | + ) |
| 47 | + .bind(migration.version) |
| 48 | + .bind(&*migration.description) |
| 49 | + .bind(&*migration.checksum) |
| 50 | + .execute(pool) |
| 51 | + .await?; |
| 52 | + } |
| 53 | + |
| 54 | + tracing::info!( |
| 55 | + versions = ?BASELINE_MIGRATION_VERSIONS, |
| 56 | + "Baselined existing Buzz database for SQLx migrations" |
| 57 | + ); |
| 58 | + |
| 59 | + Ok(()) |
| 60 | +} |
| 61 | + |
| 62 | +async fn migrations_table_exists(pool: &PgPool) -> Result<bool> { |
| 63 | + let exists = sqlx::query_scalar::<_, bool>( |
| 64 | + r#" |
| 65 | + SELECT EXISTS ( |
| 66 | + SELECT 1 |
| 67 | + FROM information_schema.tables |
| 68 | + WHERE table_schema = 'public' |
| 69 | + AND table_name = '_sqlx_migrations' |
| 70 | + ) |
| 71 | + "#, |
| 72 | + ) |
| 73 | + .fetch_one(pool) |
| 74 | + .await?; |
| 75 | + |
| 76 | + Ok(exists) |
| 77 | +} |
| 78 | + |
| 79 | +async fn pre_sqlx_schema_exists(pool: &PgPool) -> Result<bool> { |
| 80 | + let exists = sqlx::query_scalar::<_, bool>( |
| 81 | + r#" |
| 82 | + SELECT EXISTS ( |
| 83 | + SELECT 1 |
| 84 | + FROM information_schema.tables |
| 85 | + WHERE table_schema = 'public' |
| 86 | + AND table_name = 'events' |
| 87 | + ) AND EXISTS ( |
| 88 | + SELECT 1 |
| 89 | + FROM information_schema.tables |
| 90 | + WHERE table_schema = 'public' |
| 91 | + AND table_name = 'channels' |
| 92 | + ) |
| 93 | + "#, |
| 94 | + ) |
| 95 | + .fetch_one(pool) |
| 96 | + .await?; |
| 97 | + |
| 98 | + Ok(exists) |
| 99 | +} |
| 100 | + |
| 101 | +async fn ensure_migrations_table(pool: &PgPool) -> Result<()> { |
| 102 | + sqlx::query( |
| 103 | + r#" |
| 104 | + CREATE TABLE IF NOT EXISTS _sqlx_migrations ( |
| 105 | + version BIGINT PRIMARY KEY, |
| 106 | + description TEXT NOT NULL, |
| 107 | + installed_on TIMESTAMPTZ NOT NULL DEFAULT now(), |
| 108 | + success BOOLEAN NOT NULL, |
| 109 | + checksum BYTEA NOT NULL, |
| 110 | + execution_time BIGINT NOT NULL |
| 111 | + ) |
| 112 | + "#, |
| 113 | + ) |
| 114 | + .execute(pool) |
| 115 | + .await?; |
| 116 | + |
| 117 | + Ok(()) |
| 118 | +} |
| 119 | + |
| 120 | +#[cfg(test)] |
| 121 | +mod tests { |
| 122 | + use super::*; |
| 123 | + use sqlx::PgPool; |
| 124 | + |
| 125 | + const TEST_DB_URL: &str = "postgres://buzz:buzz_dev@localhost:5432/buzz"; |
| 126 | + |
| 127 | + #[test] |
| 128 | + fn embedded_migrator_contains_initial_schema_and_d_tag_backfill() { |
| 129 | + let migrations: Vec<_> = MIGRATOR.iter().collect(); |
| 130 | + |
| 131 | + assert_eq!(migrations.len(), 2); |
| 132 | + assert_eq!(migrations[0].version, 1); |
| 133 | + assert_eq!(&*migrations[0].description, "initial schema"); |
| 134 | + assert!( |
| 135 | + migrations[0].sql.as_str().contains("CREATE TABLE channels"), |
| 136 | + "initial schema migration should include Buzz core tables" |
| 137 | + ); |
| 138 | + assert!( |
| 139 | + migrations[0] |
| 140 | + .sql |
| 141 | + .as_str() |
| 142 | + .contains("CREATE TABLE IF NOT EXISTS relay_members"), |
| 143 | + "initial schema migration should include relay_members" |
| 144 | + ); |
| 145 | + |
| 146 | + assert_eq!(migrations[1].version, 2); |
| 147 | + assert_eq!(&*migrations[1].description, "backfill d tag"); |
| 148 | + assert!( |
| 149 | + migrations[1].sql.as_str().contains("UPDATE events"), |
| 150 | + "second migration should backfill existing event rows" |
| 151 | + ); |
| 152 | + } |
| 153 | + |
| 154 | + async fn connect_test_pool() -> PgPool { |
| 155 | + let database_url = std::env::var("BUZZ_TEST_DATABASE_URL") |
| 156 | + .or_else(|_| std::env::var("DATABASE_URL")) |
| 157 | + .unwrap_or_else(|_| TEST_DB_URL.to_owned()); |
| 158 | + |
| 159 | + PgPool::connect(&database_url) |
| 160 | + .await |
| 161 | + .expect("connect to test DB") |
| 162 | + } |
| 163 | + |
| 164 | + async fn reset_public_schema(pool: &PgPool) { |
| 165 | + sqlx::query("DROP SCHEMA IF EXISTS public CASCADE") |
| 166 | + .execute(pool) |
| 167 | + .await |
| 168 | + .expect("drop public schema"); |
| 169 | + sqlx::query("CREATE SCHEMA IF NOT EXISTS public") |
| 170 | + .execute(pool) |
| 171 | + .await |
| 172 | + .expect("create public schema"); |
| 173 | + } |
| 174 | + |
| 175 | + async fn applied_versions(pool: &PgPool) -> Vec<i64> { |
| 176 | + sqlx::query_scalar::<_, i64>( |
| 177 | + "SELECT version FROM _sqlx_migrations WHERE success ORDER BY version", |
| 178 | + ) |
| 179 | + .fetch_all(pool) |
| 180 | + .await |
| 181 | + .expect("read applied migrations") |
| 182 | + } |
| 183 | + |
| 184 | + #[tokio::test] |
| 185 | + #[ignore = "requires Postgres"] |
| 186 | + async fn run_migrations_applies_embedded_versions_on_fresh_database() { |
| 187 | + let pool = connect_test_pool().await; |
| 188 | + reset_public_schema(&pool).await; |
| 189 | + |
| 190 | + run_migrations(&pool).await.expect("run migrations"); |
| 191 | + |
| 192 | + assert_eq!(applied_versions(&pool).await, vec![1, 2]); |
| 193 | + let events_exists = sqlx::query_scalar::<_, bool>( |
| 194 | + "SELECT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'events')", |
| 195 | + ) |
| 196 | + .fetch_one(&pool) |
| 197 | + .await |
| 198 | + .expect("check events table"); |
| 199 | + assert!(events_exists); |
| 200 | + } |
| 201 | + |
| 202 | + #[tokio::test] |
| 203 | + #[ignore = "requires Postgres"] |
| 204 | + async fn run_migrations_baselines_existing_schema_and_preserves_allowlist_backfill_path() { |
| 205 | + let pool = connect_test_pool().await; |
| 206 | + reset_public_schema(&pool).await; |
| 207 | + sqlx::raw_sql(SCHEMA_SQL) |
| 208 | + .execute(&pool) |
| 209 | + .await |
| 210 | + .expect("load pre-SQLx schema snapshot"); |
| 211 | + sqlx::query( |
| 212 | + "INSERT INTO pubkey_allowlist (pubkey, added_at) VALUES (decode($1, 'hex'), now())", |
| 213 | + ) |
| 214 | + .bind("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") |
| 215 | + .execute(&pool) |
| 216 | + .await |
| 217 | + .expect("seed legacy allowlist row"); |
| 218 | + |
| 219 | + run_migrations(&pool).await.expect("baseline migrations"); |
| 220 | + |
| 221 | + assert_eq!(applied_versions(&pool).await, vec![1, 2]); |
| 222 | + let allowlist_count = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM pubkey_allowlist") |
| 223 | + .fetch_one(&pool) |
| 224 | + .await |
| 225 | + .expect("count allowlist rows"); |
| 226 | + assert_eq!( |
| 227 | + allowlist_count, 1, |
| 228 | + "baseline must not drop legacy allowlist rows before relay startup backfills them" |
| 229 | + ); |
| 230 | + |
| 231 | + let inserted = crate::relay_members::backfill_from_allowlist(&pool) |
| 232 | + .await |
| 233 | + .expect("backfill legacy allowlist rows"); |
| 234 | + assert_eq!(inserted, 1); |
| 235 | + let relay_member_count = sqlx::query_scalar::<_, i64>( |
| 236 | + "SELECT COUNT(*) FROM relay_members WHERE pubkey = $1 AND role = 'member'", |
| 237 | + ) |
| 238 | + .bind("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") |
| 239 | + .fetch_one(&pool) |
| 240 | + .await |
| 241 | + .expect("count backfilled relay member"); |
| 242 | + assert_eq!(relay_member_count, 1); |
| 243 | + } |
| 244 | +} |
0 commit comments