1use anyhow::Result;
5use include_dir::{include_dir, Dir};
6use sqlx::Connection;
7use sqlx::PgPool;
8use std::collections::{HashMap, HashSet};
9use std::sync::Arc;
10
11static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
12
13const BASE_TABLES: &[&str] = &[
14 "instances",
15 "executions",
16 "history",
17 "orchestrator_queue",
18 "worker_queue",
19 "instance_locks",
20];
21const ALL_CORE_TABLES: &[&str] = &[
22 "instances",
23 "executions",
24 "history",
25 "orchestrator_queue",
26 "worker_queue",
27 "instance_locks",
28 "sessions",
29 "kv_store",
30 "kv_delta",
31];
32
33#[derive(Debug)]
35struct Migration {
36 version: i64,
37 name: String,
38 sql: String,
39}
40
41pub struct MigrationRunner {
43 pool: Arc<PgPool>,
44 schema_name: String,
45}
46
47impl MigrationRunner {
48 pub fn new(pool: Arc<PgPool>, schema_name: String) -> Self {
50 Self { pool, schema_name }
51 }
52
53 fn advisory_lock_key(&self) -> i64 {
54 const OFFSET: u64 = 0xcbf29ce484222325;
57 const PRIME: u64 = 0x100000001b3;
58
59 let mut hash = OFFSET;
60 for b in b"duroxide_pg:migrations:" {
61 hash ^= *b as u64;
62 hash = hash.wrapping_mul(PRIME);
63 }
64 for b in self.schema_name.as_bytes() {
65 hash ^= *b as u64;
66 hash = hash.wrapping_mul(PRIME);
67 }
68
69 hash as i64
70 }
71
72 async fn lock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
73 let key = self.advisory_lock_key();
74 sqlx::query("SELECT pg_advisory_lock($1)")
77 .bind(key)
78 .execute(&mut *conn)
79 .await?;
80 Ok(())
81 }
82
83 async fn unlock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) {
84 let key = self.advisory_lock_key();
85 let _ = sqlx::query("SELECT pg_advisory_unlock($1)")
87 .bind(key)
88 .execute(&mut *conn)
89 .await;
90 }
91
92 pub async fn migrate(&self) -> Result<()> {
94 let mut conn = self.pool.acquire().await?;
95 let conn = &mut *conn;
96 self.lock_for_migrations(conn).await?;
97
98 let result = match self.check_no_unknown_migrations(conn).await {
103 Ok(()) => self.migrate_inner(conn).await,
104 Err(e) => Err(e),
105 };
106 self.unlock_for_migrations(conn).await;
107
108 result
109 }
110
111 pub async fn verify(&self) -> Result<()> {
122 let mut conn = self.pool.acquire().await?;
123 let conn = &mut *conn;
124
125 let table_exists = self.check_migration_table_exists(conn).await?;
127
128 if !table_exists {
129 anyhow::bail!(
130 "duroxide migrations not initialized: schema {:?} does not \
131 contain _duroxide_migrations. Construct a provider with \
132 MigrationPolicy::ApplyAll (the default) from a process with \
133 DDL privileges before using MigrationPolicy::VerifyOnly.",
134 self.schema_name
135 );
136 }
137
138 self.check_no_unknown_migrations(conn).await?;
141
142 let migrations = self.load_migrations()?;
143 let applied = self.get_applied_versions(conn).await?;
144 self.validate_applied_prefix(&migrations, &applied)?;
145 let existing_tables = self.get_existing_core_relations(conn).await?;
146 self.validate_core_table_state(&applied, &existing_tables)?;
147 let applied: std::collections::HashSet<i64> = applied.into_iter().collect();
148
149 let mut missing: Vec<i64> = migrations
150 .iter()
151 .map(|m| m.version)
152 .filter(|v| !applied.contains(v))
153 .collect();
154 missing.sort_unstable();
155
156 if !missing.is_empty() {
157 anyhow::bail!(
158 "duroxide migrations not up to date in schema {:?}: missing \
159 versions {:?}. Run migrations from a provider configured with \
160 MigrationPolicy::ApplyAll before constructing VerifyOnly \
161 providers.",
162 self.schema_name,
163 missing,
164 );
165 }
166
167 Ok(())
168 }
169
170 async fn check_no_unknown_migrations(
180 &self,
181 conn: &mut sqlx::postgres::PgConnection,
182 ) -> Result<()> {
183 if !self.check_migration_table_exists(conn).await? {
184 return Ok(());
185 }
186
187 let applied = self.get_applied_versions(conn).await?;
188 let expected: std::collections::HashSet<i64> = self
189 .load_migrations()?
190 .into_iter()
191 .map(|m| m.version)
192 .collect();
193
194 let mut unknown: Vec<i64> = applied
195 .into_iter()
196 .filter(|v| !expected.contains(v))
197 .collect();
198 unknown.sort_unstable();
199
200 if !unknown.is_empty() {
201 anyhow::bail!(
202 "schema {:?} has migrations not recognized by this version of \
203 the code: {:?}. The database schema is ahead of the code. \
204 Update the code to a compatible version.",
205 self.schema_name,
206 unknown,
207 );
208 }
209
210 Ok(())
211 }
212
213 async fn check_migration_table_exists(
214 &self,
215 conn: &mut sqlx::postgres::PgConnection,
216 ) -> Result<bool> {
217 let relation_kind: Option<String> = sqlx::query_scalar(
218 "SELECT c.relkind::text \
219 FROM pg_catalog.pg_class c \
220 JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
221 WHERE n.nspname = $1 AND c.relname = '_duroxide_migrations'",
222 )
223 .bind(&self.schema_name)
224 .fetch_optional(&mut *conn)
225 .await?;
226
227 match relation_kind.as_deref() {
228 None => Ok(false),
229 Some("r" | "p") => Ok(true),
230 Some(kind) => anyhow::bail!(
231 "duroxide migration tracking object in schema {:?} has PostgreSQL \
232 relation kind {:?}, not a base table; refusing to read or replace it",
233 self.schema_name,
234 kind,
235 ),
236 }
237 }
238
239 fn validate_applied_prefix(
240 &self,
241 migrations: &[Migration],
242 applied_versions: &[i64],
243 ) -> Result<()> {
244 for (index, (migration, applied)) in
245 migrations.iter().zip(applied_versions.iter()).enumerate()
246 {
247 if migration.version != *applied {
248 anyhow::bail!(
249 "duroxide migration history is inconsistent in schema {:?}: \
250 expected version {} at ledger position {}, but found version {}. \
251 Applied migrations must be an ordered prefix of the bundled \
252 migrations; refusing to apply migrations or modify the ledger.",
253 self.schema_name,
254 migration.version,
255 index + 1,
256 applied,
257 );
258 }
259 }
260
261 if applied_versions.len() > migrations.len() {
262 anyhow::bail!(
263 "duroxide migration history is inconsistent in schema {:?}: \
264 the ledger contains {} entries, but this binary bundles only {}. \
265 Refusing to apply migrations or modify the ledger.",
266 self.schema_name,
267 applied_versions.len(),
268 migrations.len(),
269 );
270 }
271
272 Ok(())
273 }
274
275 fn expected_core_tables(applied_versions: &[i64]) -> HashSet<String> {
276 let Some(latest) = applied_versions.last().copied() else {
277 return HashSet::new();
278 };
279
280 let mut expected: HashSet<String> =
281 BASE_TABLES.iter().map(|name| (*name).to_string()).collect();
282 if latest >= 14 {
283 expected.insert("sessions".to_string());
284 }
285 if latest >= 18 {
286 expected.insert("kv_store".to_string());
287 }
288 if latest >= 20 {
289 expected.insert("kv_delta".to_string());
290 }
291 expected
292 }
293
294 fn validate_core_table_state(
295 &self,
296 applied_versions: &[i64],
297 existing_relations: &HashMap<String, String>,
298 ) -> Result<()> {
299 let expected_tables = Self::expected_core_tables(applied_versions);
300 let mut missing: Vec<&str> = expected_tables
301 .iter()
302 .filter(|name| !existing_relations.contains_key(*name))
303 .map(String::as_str)
304 .collect();
305 let mut wrong_kind: Vec<(&str, &str)> = expected_tables
306 .iter()
307 .filter_map(|name| {
308 existing_relations.get(name).and_then(|kind| {
309 (!matches!(kind.as_str(), "r" | "p")).then_some((name.as_str(), kind.as_str()))
310 })
311 })
312 .collect();
313 let mut unexpected: Vec<&str> = existing_relations
314 .keys()
315 .filter(|name| !expected_tables.contains(*name))
316 .map(String::as_str)
317 .collect();
318 missing.sort_unstable();
319 wrong_kind.sort_unstable();
320 unexpected.sort_unstable();
321
322 if !wrong_kind.is_empty() {
323 anyhow::bail!(
324 "duroxide schema {:?} has required relations {:?} with non-table \
325 PostgreSQL relation kinds. The schema may be corrupted; refusing \
326 to apply migrations or modify the ledger automatically.",
327 self.schema_name,
328 wrong_kind,
329 );
330 }
331
332 if !missing.is_empty() {
333 anyhow::bail!(
334 "duroxide migration history in schema {:?} requires tables {:?}, \
335 but they are missing. The schema may be corrupted; refusing to \
336 apply migrations or modify the ledger automatically.",
337 self.schema_name,
338 missing,
339 );
340 }
341
342 if !unexpected.is_empty() {
343 anyhow::bail!(
344 "duroxide schema {:?} contains tables {:?} that are not represented \
345 by its migration ledger. The schema may be corrupted; refusing to \
346 apply migrations or modify the ledger automatically.",
347 self.schema_name,
348 unexpected,
349 );
350 }
351
352 Ok(())
353 }
354
355 async fn migrate_inner(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
356 let schema_exists = self.check_schema_exists(conn).await?;
357 if !schema_exists && self.schema_name != "public" {
358 sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS {}", self.schema_name))
359 .execute(&mut *conn)
360 .await?;
361 }
362
363 let migrations = self.load_migrations()?;
365
366 tracing::debug!(
367 "Loaded {} migrations for schema {}",
368 migrations.len(),
369 self.schema_name
370 );
371
372 let tracking_exists = self.check_migration_table_exists(conn).await?;
373 let existing_tables = self.get_existing_core_relations(conn).await?;
374
375 if !tracking_exists && !existing_tables.is_empty() {
376 let mut relations: Vec<(&str, &str)> = existing_tables
377 .iter()
378 .map(|(name, kind)| (name.as_str(), kind.as_str()))
379 .collect();
380 relations.sort_unstable();
381 anyhow::bail!(
382 "duroxide relations {:?} exist in schema {:?}, but the migration \
383 tracking table is missing. The schema may be corrupted; refusing \
384 to create a new ledger or apply migrations automatically.",
385 relations,
386 self.schema_name,
387 );
388 }
389
390 if !tracking_exists {
391 self.ensure_migration_table(conn).await?;
392 }
393
394 let applied_versions = self.get_applied_versions(conn).await?;
395 self.validate_applied_prefix(&migrations, &applied_versions)?;
396 self.validate_core_table_state(&applied_versions, &existing_tables)?;
397 tracing::debug!("Applied migrations: {:?}", applied_versions);
398
399 for migration in migrations.into_iter().skip(applied_versions.len()) {
400 tracing::debug!(
401 "Applying migration {}: {}",
402 migration.version,
403 migration.name
404 );
405 self.apply_migration(conn, &migration).await?;
406 }
407
408 Ok(())
409 }
410
411 fn load_migrations(&self) -> Result<Vec<Migration>> {
413 let mut migrations = Vec::new();
414
415 let mut files: Vec<_> = MIGRATIONS
417 .files()
418 .filter(|file| file.path().extension().and_then(|ext| ext.to_str()) == Some("sql"))
419 .collect();
420
421 files.sort_by_key(|f| f.path());
423
424 for file in files {
425 let file_name = file
426 .path()
427 .file_name()
428 .and_then(|n| n.to_str())
429 .ok_or_else(|| anyhow::anyhow!("Invalid filename in migrations"))?;
430
431 let sql = file
432 .contents_utf8()
433 .ok_or_else(|| anyhow::anyhow!("Migration file is not valid UTF-8: {file_name}"))?
434 .to_string();
435
436 let version = self.parse_version(file_name)?;
437 let name = file_name.to_string();
438
439 migrations.push(Migration { version, name, sql });
440 }
441
442 Ok(migrations)
443 }
444
445 fn parse_version(&self, filename: &str) -> Result<i64> {
447 let version_str = filename
448 .split('_')
449 .next()
450 .ok_or_else(|| anyhow::anyhow!("Invalid migration filename: {filename}"))?;
451
452 version_str
453 .parse::<i64>()
454 .map_err(|e| anyhow::anyhow!("Invalid migration version {version_str}: {e}"))
455 }
456
457 async fn ensure_migration_table(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
459 sqlx::query(&format!(
461 r#"
462 CREATE TABLE IF NOT EXISTS {}._duroxide_migrations (
463 version BIGINT PRIMARY KEY,
464 name TEXT NOT NULL,
465 applied_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
466 )
467 "#,
468 self.schema_name
469 ))
470 .execute(&mut *conn)
471 .await?;
472
473 Ok(())
474 }
475
476 async fn check_schema_exists(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<bool> {
477 let exists = sqlx::query_scalar(
478 "SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = $1)",
479 )
480 .bind(&self.schema_name)
481 .fetch_one(&mut *conn)
482 .await?;
483
484 Ok(exists)
485 }
486
487 async fn get_existing_core_relations(
488 &self,
489 conn: &mut sqlx::postgres::PgConnection,
490 ) -> Result<HashMap<String, String>> {
491 let known_tables: Vec<String> = ALL_CORE_TABLES
492 .iter()
493 .map(|name| (*name).to_string())
494 .collect();
495 let relations: Vec<(String, String)> = sqlx::query_as(
496 "SELECT c.relname::text, c.relkind::text \
497 FROM pg_catalog.pg_class c \
498 JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
499 WHERE n.nspname = $1 AND c.relname = ANY($2::text[])",
500 )
501 .bind(&self.schema_name)
502 .bind(&known_tables)
503 .fetch_all(&mut *conn)
504 .await?;
505
506 Ok(relations.into_iter().collect())
507 }
508
509 async fn get_applied_versions(
511 &self,
512 conn: &mut sqlx::postgres::PgConnection,
513 ) -> Result<Vec<i64>> {
514 let versions: Vec<i64> = sqlx::query_scalar(&format!(
515 "SELECT version FROM {}._duroxide_migrations ORDER BY version",
516 self.schema_name
517 ))
518 .fetch_all(&mut *conn)
519 .await?;
520
521 Ok(versions)
522 }
523
524 fn split_sql_statements(sql: &str) -> Vec<String> {
527 let mut statements = Vec::new();
528 let mut current_statement = String::new();
529 let chars: Vec<char> = sql.chars().collect();
530 let mut i = 0;
531 let mut in_dollar_quote = false;
532 let mut dollar_tag: Option<String> = None;
533
534 while i < chars.len() {
535 let ch = chars[i];
536
537 if !in_dollar_quote {
538 if ch == '$' {
540 let mut tag = String::new();
541 tag.push(ch);
542 i += 1;
543
544 while i < chars.len() {
546 let next_ch = chars[i];
547 if next_ch == '$' {
548 tag.push(next_ch);
549 dollar_tag = Some(tag.clone());
550 in_dollar_quote = true;
551 current_statement.push_str(&tag);
552 i += 1;
553 break;
554 } else if next_ch.is_alphanumeric() || next_ch == '_' {
555 tag.push(next_ch);
556 i += 1;
557 } else {
558 current_statement.push(ch);
560 break;
561 }
562 }
563 } else if ch == ';' {
564 current_statement.push(ch);
566 let trimmed = current_statement.trim().to_string();
567 if !trimmed.is_empty() {
568 statements.push(trimmed);
569 }
570 current_statement.clear();
571 i += 1;
572 } else {
573 current_statement.push(ch);
574 i += 1;
575 }
576 } else {
577 current_statement.push(ch);
579
580 if ch == '$' {
582 let tag = dollar_tag.as_ref().unwrap();
583 let mut matches = true;
584
585 for (j, tag_char) in tag.chars().enumerate() {
587 if j == 0 {
588 continue; }
590 if i + j >= chars.len() || chars[i + j] != tag_char {
591 matches = false;
592 break;
593 }
594 }
595
596 if matches {
597 for _ in 0..(tag.len() - 1) {
599 if i + 1 < chars.len() {
600 current_statement.push(chars[i + 1]);
601 i += 1;
602 }
603 }
604 in_dollar_quote = false;
605 dollar_tag = None;
606 }
607 }
608 i += 1;
609 }
610 }
611
612 let trimmed = current_statement.trim().to_string();
614 if !trimmed.is_empty() {
615 statements.push(trimmed);
616 }
617
618 statements
619 }
620
621 fn migration_search_path_stmt(schema_name: &str) -> String {
632 format!("SET LOCAL search_path TO {schema_name}, pg_temp")
633 }
634
635 async fn apply_migration(
637 &self,
638 conn: &mut sqlx::postgres::PgConnection,
639 migration: &Migration,
640 ) -> Result<()> {
641 let mut tx = conn.begin().await?;
643
644 sqlx::query(&Self::migration_search_path_stmt(&self.schema_name))
652 .execute(&mut *tx)
653 .await?;
654
655 let sql = migration.sql.trim();
657 let cleaned_sql: String = sql
658 .lines()
659 .map(|line| {
660 if let Some(idx) = line.find("--") {
662 let before = &line[..idx];
664 if before.matches('\'').count() % 2 == 0 {
665 line[..idx].trim()
667 } else {
668 line
669 }
670 } else {
671 line
672 }
673 })
674 .filter(|line| !line.is_empty())
675 .collect::<Vec<_>>()
676 .join("\n");
677
678 let statements = Self::split_sql_statements(&cleaned_sql);
680
681 tracing::debug!(
682 "Executing {} statements for migration {}",
683 statements.len(),
684 migration.version
685 );
686
687 for (idx, statement) in statements.iter().enumerate() {
688 if !statement.trim().is_empty() {
689 tracing::debug!(
690 "Executing statement {} of {}: {}...",
691 idx + 1,
692 statements.len(),
693 &statement.chars().take(50).collect::<String>()
694 );
695 sqlx::query(statement)
696 .execute(&mut *tx)
697 .await
698 .map_err(|e| {
699 anyhow::anyhow!(
700 "Failed to execute statement {} in migration {}: {}\nStatement: {}",
701 idx + 1,
702 migration.version,
703 e,
704 statement
705 )
706 })?;
707 }
708 }
709
710 sqlx::query(&format!(
712 "INSERT INTO {}._duroxide_migrations (version, name) VALUES ($1, $2)",
713 self.schema_name
714 ))
715 .bind(migration.version)
716 .bind(&migration.name)
717 .execute(&mut *tx)
718 .await?;
719
720 tx.commit().await?;
722
723 tracing::info!(
724 "Applied migration {}: {}",
725 migration.version,
726 migration.name
727 );
728
729 Ok(())
730 }
731}
732
733#[cfg(test)]
734mod tests {
735 use super::*;
736
737 #[test]
738 fn migration_search_path_pins_pg_temp_last() {
739 let stmt = MigrationRunner::migration_search_path_stmt("duroxide");
743 assert_eq!(stmt, "SET LOCAL search_path TO duroxide, pg_temp");
744 }
745}