duroxide_pg/
migrations.rs1use anyhow::Result;
5use include_dir::{include_dir, Dir};
6use sqlx::Connection;
7use sqlx::PgPool;
8use std::sync::Arc;
9
10static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
11
12#[derive(Debug)]
14struct Migration {
15 version: i64,
16 name: String,
17 sql: String,
18}
19
20pub struct MigrationRunner {
22 pool: Arc<PgPool>,
23 schema_name: String,
24}
25
26impl MigrationRunner {
27 pub fn new(pool: Arc<PgPool>, schema_name: String) -> Self {
29 Self { pool, schema_name }
30 }
31
32 fn advisory_lock_key(&self) -> i64 {
33 const OFFSET: u64 = 0xcbf29ce484222325;
36 const PRIME: u64 = 0x100000001b3;
37
38 let mut hash = OFFSET;
39 for b in b"duroxide_pg:migrations:" {
40 hash ^= *b as u64;
41 hash = hash.wrapping_mul(PRIME);
42 }
43 for b in self.schema_name.as_bytes() {
44 hash ^= *b as u64;
45 hash = hash.wrapping_mul(PRIME);
46 }
47
48 hash as i64
49 }
50
51 async fn lock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
52 let key = self.advisory_lock_key();
53 sqlx::query("SELECT pg_advisory_lock($1)")
56 .bind(key)
57 .execute(&mut *conn)
58 .await?;
59 Ok(())
60 }
61
62 async fn unlock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) {
63 let key = self.advisory_lock_key();
64 let _ = sqlx::query("SELECT pg_advisory_unlock($1)")
66 .bind(key)
67 .execute(&mut *conn)
68 .await;
69 }
70
71 pub async fn migrate(&self) -> Result<()> {
73 let mut conn = self.pool.acquire().await?;
74 let conn = &mut *conn;
75 self.lock_for_migrations(conn).await?;
76
77 let result = match self.check_no_unknown_migrations(conn).await {
82 Ok(()) => self.migrate_inner(conn).await,
83 Err(e) => Err(e),
84 };
85 self.unlock_for_migrations(conn).await;
86
87 result
88 }
89
90 pub async fn verify(&self) -> Result<()> {
101 let mut conn = self.pool.acquire().await?;
102 let conn = &mut *conn;
103
104 let table_exists: bool = sqlx::query_scalar(
106 "SELECT EXISTS(SELECT 1 FROM information_schema.tables \
107 WHERE table_schema = $1 AND table_name = '_duroxide_migrations')",
108 )
109 .bind(&self.schema_name)
110 .fetch_one(&mut *conn)
111 .await?;
112
113 if !table_exists {
114 anyhow::bail!(
115 "duroxide migrations not initialized: schema {:?} does not \
116 contain _duroxide_migrations. Construct a provider with \
117 MigrationPolicy::ApplyAll (the default) from a process with \
118 DDL privileges before using MigrationPolicy::VerifyOnly.",
119 self.schema_name
120 );
121 }
122
123 self.check_no_unknown_migrations(conn).await?;
126
127 let migrations = self.load_migrations()?;
128 let applied: std::collections::HashSet<i64> =
129 self.get_applied_versions(conn).await?.into_iter().collect();
130
131 let mut missing: Vec<i64> = migrations
132 .iter()
133 .map(|m| m.version)
134 .filter(|v| !applied.contains(v))
135 .collect();
136 missing.sort_unstable();
137
138 if !missing.is_empty() {
139 anyhow::bail!(
140 "duroxide migrations not up to date in schema {:?}: missing \
141 versions {:?}. Run migrations from a provider configured with \
142 MigrationPolicy::ApplyAll before constructing VerifyOnly \
143 providers.",
144 self.schema_name,
145 missing,
146 );
147 }
148
149 if !self.check_tables_exist(conn).await.unwrap_or(false) {
150 anyhow::bail!(
151 "duroxide migrations recorded as complete in schema {:?}, but \
152 core tables are missing. The schema may be corrupted; run \
153 migrations from a provider configured with \
154 MigrationPolicy::ApplyAll before constructing VerifyOnly \
155 providers.",
156 self.schema_name,
157 );
158 }
159
160 Ok(())
161 }
162
163 async fn check_no_unknown_migrations(
173 &self,
174 conn: &mut sqlx::postgres::PgConnection,
175 ) -> Result<()> {
176 let tracking_exists: bool = sqlx::query_scalar(
177 "SELECT EXISTS(SELECT 1 FROM information_schema.tables \
178 WHERE table_schema = $1 AND table_name = '_duroxide_migrations')",
179 )
180 .bind(&self.schema_name)
181 .fetch_one(&mut *conn)
182 .await?;
183
184 if !tracking_exists {
185 return Ok(());
186 }
187
188 let applied = self.get_applied_versions(conn).await?;
189 let expected: std::collections::HashSet<i64> = self
190 .load_migrations()?
191 .into_iter()
192 .map(|m| m.version)
193 .collect();
194
195 let mut unknown: Vec<i64> = applied
196 .into_iter()
197 .filter(|v| !expected.contains(v))
198 .collect();
199 unknown.sort_unstable();
200
201 if !unknown.is_empty() {
202 anyhow::bail!(
203 "schema {:?} has migrations not recognized by this version of \
204 the code: {:?}. The database schema is ahead of the code. \
205 Update the code to a compatible version.",
206 self.schema_name,
207 unknown,
208 );
209 }
210
211 Ok(())
212 }
213
214 async fn migrate_inner(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
215 if self.schema_name != "public" {
217 sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS {}", self.schema_name))
218 .execute(&mut *conn)
219 .await?;
220 }
221
222 let migrations = self.load_migrations()?;
224
225 tracing::debug!(
226 "Loaded {} migrations for schema {}",
227 migrations.len(),
228 self.schema_name
229 );
230
231 self.ensure_migration_table(conn).await?;
233
234 let applied_versions = self.get_applied_versions(conn).await?;
236
237 tracing::debug!("Applied migrations: {:?}", applied_versions);
238
239 let tables_exist = self.check_tables_exist(conn).await.unwrap_or(false);
242
243 for migration in migrations {
245 let should_apply = if !applied_versions.contains(&migration.version) {
246 true } else if !tables_exist {
248 tracing::warn!(
250 "Migration {} is marked as applied but tables don't exist, re-applying",
251 migration.version
252 );
253 sqlx::query(&format!(
255 "DELETE FROM {}._duroxide_migrations WHERE version = $1",
256 self.schema_name
257 ))
258 .bind(migration.version)
259 .execute(&mut *conn)
260 .await?;
261 true
262 } else {
263 false };
265
266 if should_apply {
267 tracing::debug!(
268 "Applying migration {}: {}",
269 migration.version,
270 migration.name
271 );
272 self.apply_migration(conn, &migration).await?;
273 } else {
274 tracing::debug!(
275 "Skipping migration {}: {} (already applied)",
276 migration.version,
277 migration.name
278 );
279 }
280 }
281
282 Ok(())
283 }
284
285 fn load_migrations(&self) -> Result<Vec<Migration>> {
287 let mut migrations = Vec::new();
288
289 let mut files: Vec<_> = MIGRATIONS
291 .files()
292 .filter(|file| file.path().extension().and_then(|ext| ext.to_str()) == Some("sql"))
293 .collect();
294
295 files.sort_by_key(|f| f.path());
297
298 for file in files {
299 let file_name = file
300 .path()
301 .file_name()
302 .and_then(|n| n.to_str())
303 .ok_or_else(|| anyhow::anyhow!("Invalid filename in migrations"))?;
304
305 let sql = file
306 .contents_utf8()
307 .ok_or_else(|| anyhow::anyhow!("Migration file is not valid UTF-8: {file_name}"))?
308 .to_string();
309
310 let version = self.parse_version(file_name)?;
311 let name = file_name.to_string();
312
313 migrations.push(Migration { version, name, sql });
314 }
315
316 Ok(migrations)
317 }
318
319 fn parse_version(&self, filename: &str) -> Result<i64> {
321 let version_str = filename
322 .split('_')
323 .next()
324 .ok_or_else(|| anyhow::anyhow!("Invalid migration filename: {filename}"))?;
325
326 version_str
327 .parse::<i64>()
328 .map_err(|e| anyhow::anyhow!("Invalid migration version {version_str}: {e}"))
329 }
330
331 async fn ensure_migration_table(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
333 sqlx::query(&format!(
335 r#"
336 CREATE TABLE IF NOT EXISTS {}._duroxide_migrations (
337 version BIGINT PRIMARY KEY,
338 name TEXT NOT NULL,
339 applied_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
340 )
341 "#,
342 self.schema_name
343 ))
344 .execute(&mut *conn)
345 .await?;
346
347 Ok(())
348 }
349
350 async fn check_tables_exist(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<bool> {
352 let exists: bool = sqlx::query_scalar(
354 "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = 'instances')",
355 )
356 .bind(&self.schema_name)
357 .fetch_one(&mut *conn)
358 .await?;
359
360 Ok(exists)
361 }
362
363 async fn get_applied_versions(
365 &self,
366 conn: &mut sqlx::postgres::PgConnection,
367 ) -> Result<Vec<i64>> {
368 let versions: Vec<i64> = sqlx::query_scalar(&format!(
369 "SELECT version FROM {}._duroxide_migrations ORDER BY version",
370 self.schema_name
371 ))
372 .fetch_all(&mut *conn)
373 .await?;
374
375 Ok(versions)
376 }
377
378 fn split_sql_statements(sql: &str) -> Vec<String> {
381 let mut statements = Vec::new();
382 let mut current_statement = String::new();
383 let chars: Vec<char> = sql.chars().collect();
384 let mut i = 0;
385 let mut in_dollar_quote = false;
386 let mut dollar_tag: Option<String> = None;
387
388 while i < chars.len() {
389 let ch = chars[i];
390
391 if !in_dollar_quote {
392 if ch == '$' {
394 let mut tag = String::new();
395 tag.push(ch);
396 i += 1;
397
398 while i < chars.len() {
400 let next_ch = chars[i];
401 if next_ch == '$' {
402 tag.push(next_ch);
403 dollar_tag = Some(tag.clone());
404 in_dollar_quote = true;
405 current_statement.push_str(&tag);
406 i += 1;
407 break;
408 } else if next_ch.is_alphanumeric() || next_ch == '_' {
409 tag.push(next_ch);
410 i += 1;
411 } else {
412 current_statement.push(ch);
414 break;
415 }
416 }
417 } else if ch == ';' {
418 current_statement.push(ch);
420 let trimmed = current_statement.trim().to_string();
421 if !trimmed.is_empty() {
422 statements.push(trimmed);
423 }
424 current_statement.clear();
425 i += 1;
426 } else {
427 current_statement.push(ch);
428 i += 1;
429 }
430 } else {
431 current_statement.push(ch);
433
434 if ch == '$' {
436 let tag = dollar_tag.as_ref().unwrap();
437 let mut matches = true;
438
439 for (j, tag_char) in tag.chars().enumerate() {
441 if j == 0 {
442 continue; }
444 if i + j >= chars.len() || chars[i + j] != tag_char {
445 matches = false;
446 break;
447 }
448 }
449
450 if matches {
451 for _ in 0..(tag.len() - 1) {
453 if i + 1 < chars.len() {
454 current_statement.push(chars[i + 1]);
455 i += 1;
456 }
457 }
458 in_dollar_quote = false;
459 dollar_tag = None;
460 }
461 }
462 i += 1;
463 }
464 }
465
466 let trimmed = current_statement.trim().to_string();
468 if !trimmed.is_empty() {
469 statements.push(trimmed);
470 }
471
472 statements
473 }
474
475 fn migration_search_path_stmt(schema_name: &str) -> String {
486 format!("SET LOCAL search_path TO {schema_name}, pg_temp")
487 }
488
489 async fn apply_migration(
491 &self,
492 conn: &mut sqlx::postgres::PgConnection,
493 migration: &Migration,
494 ) -> Result<()> {
495 let mut tx = conn.begin().await?;
497
498 sqlx::query(&Self::migration_search_path_stmt(&self.schema_name))
506 .execute(&mut *tx)
507 .await?;
508
509 let sql = migration.sql.trim();
511 let cleaned_sql: String = sql
512 .lines()
513 .map(|line| {
514 if let Some(idx) = line.find("--") {
516 let before = &line[..idx];
518 if before.matches('\'').count() % 2 == 0 {
519 line[..idx].trim()
521 } else {
522 line
523 }
524 } else {
525 line
526 }
527 })
528 .filter(|line| !line.is_empty())
529 .collect::<Vec<_>>()
530 .join("\n");
531
532 let statements = Self::split_sql_statements(&cleaned_sql);
534
535 tracing::debug!(
536 "Executing {} statements for migration {}",
537 statements.len(),
538 migration.version
539 );
540
541 for (idx, statement) in statements.iter().enumerate() {
542 if !statement.trim().is_empty() {
543 tracing::debug!(
544 "Executing statement {} of {}: {}...",
545 idx + 1,
546 statements.len(),
547 &statement.chars().take(50).collect::<String>()
548 );
549 sqlx::query(statement)
550 .execute(&mut *tx)
551 .await
552 .map_err(|e| {
553 anyhow::anyhow!(
554 "Failed to execute statement {} in migration {}: {}\nStatement: {}",
555 idx + 1,
556 migration.version,
557 e,
558 statement
559 )
560 })?;
561 }
562 }
563
564 sqlx::query(&format!(
566 "INSERT INTO {}._duroxide_migrations (version, name) VALUES ($1, $2)",
567 self.schema_name
568 ))
569 .bind(migration.version)
570 .bind(&migration.name)
571 .execute(&mut *tx)
572 .await?;
573
574 tx.commit().await?;
576
577 tracing::info!(
578 "Applied migration {}: {}",
579 migration.version,
580 migration.name
581 );
582
583 Ok(())
584 }
585}
586
587#[cfg(test)]
588mod tests {
589 use super::*;
590
591 #[test]
592 fn migration_search_path_pins_pg_temp_last() {
593 let stmt = MigrationRunner::migration_search_path_stmt("duroxide");
597 assert_eq!(stmt, "SET LOCAL search_path TO duroxide, pg_temp");
598 }
599}