use anyhow::{Context, Result};
use include_dir::{include_dir, Dir};
use sqlx::{pool::PoolConnection, Connection, PgPool, Postgres};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use tokio::time::Instant;
static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
const DDL_LOCK_TIMEOUT_SQL: &str = "SET LOCAL lock_timeout = '250ms'";
const DDL_RETRY_BUDGET: Duration = Duration::from_secs(10);
const NOTIFICATION_TRIGGERS: &[(&str, &str)] = &[
("worker_queue", "trg_notify_worker_work"),
("worker_queue", "trg_notify_worker_work_released"),
("orchestrator_queue", "trg_notify_orch_work"),
("orchestrator_queue", "trg_notify_orch_work_released"),
("orchestrator_queue", "trg_notify_orch_work_consumed"),
("sessions", "trg_notify_session_lease"),
];
const BASE_TABLES: &[&str] = &[
"instances",
"executions",
"history",
"orchestrator_queue",
"worker_queue",
"instance_locks",
];
const ALL_CORE_TABLES: &[&str] = &[
"instances",
"executions",
"history",
"orchestrator_queue",
"worker_queue",
"instance_locks",
"sessions",
"kv_store",
"kv_delta",
];
#[derive(Debug)]
struct Migration {
version: i64,
name: String,
sql: String,
}
pub struct MigrationRunner {
pool: Arc<PgPool>,
schema_name: String,
}
struct MigrationConnection {
connection: PoolConnection<Postgres>,
reusable: bool,
}
impl Drop for MigrationConnection {
fn drop(&mut self) {
if !self.reusable {
self.connection.close_on_drop();
}
}
}
impl MigrationRunner {
pub fn new(pool: Arc<PgPool>, schema_name: String) -> Self {
Self { pool, schema_name }
}
fn advisory_lock_key(&self) -> i64 {
const OFFSET: u64 = 0xcbf29ce484222325;
const PRIME: u64 = 0x100000001b3;
let mut hash = OFFSET;
for b in b"duroxide_pg:migrations:" {
hash ^= *b as u64;
hash = hash.wrapping_mul(PRIME);
}
for b in self.schema_name.as_bytes() {
hash ^= *b as u64;
hash = hash.wrapping_mul(PRIME);
}
hash as i64
}
async fn lock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
let key = self.advisory_lock_key();
sqlx::query("SELECT pg_advisory_lock($1)")
.bind(key)
.execute(&mut *conn)
.await?;
Ok(())
}
async fn unlock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
let key = self.advisory_lock_key();
let unlocked: bool = sqlx::query_scalar("SELECT pg_advisory_unlock($1)")
.bind(key)
.fetch_one(&mut *conn)
.await
.context("Releasing the migration advisory lock")?;
anyhow::ensure!(
unlocked,
"Migration advisory lock was not held for schema {:?}",
self.schema_name
);
Ok(())
}
pub async fn migrate(&self) -> Result<()> {
self.migrate_with_notifications(false).await
}
pub(crate) async fn migrate_with_notifications(&self, notifications: bool) -> Result<()> {
let mut guard = MigrationConnection {
connection: self.pool.acquire().await?,
reusable: false,
};
let conn = &mut *guard.connection;
self.lock_for_migrations(conn).await?;
let result: Result<()> = async {
self.check_no_unknown_migrations(conn).await?;
self.migrate_inner(conn).await?;
if notifications {
self.enable_notifications(conn).await?;
}
Ok(())
}
.await;
let unlock_result = self.unlock_for_migrations(conn).await;
result?;
unlock_result?;
guard.reusable = true;
Ok(())
}
pub async fn verify(&self) -> Result<()> {
self.verify_with_notifications(false).await
}
pub(crate) async fn verify_with_notifications(&self, notifications: bool) -> Result<()> {
let mut conn = self.pool.acquire().await?;
let conn = &mut *conn;
let table_exists = self.check_migration_table_exists(conn).await?;
if !table_exists {
anyhow::bail!(
"duroxide migrations not initialized: schema {:?} does not \
contain _duroxide_migrations. Construct a provider with \
MigrationPolicy::ApplyAll (the default) from a process with \
DDL privileges before using MigrationPolicy::VerifyOnly.",
self.schema_name
);
}
self.check_no_unknown_migrations(conn).await?;
let migrations = Self::load_migrations()?;
let applied = self.get_applied_versions(conn).await?;
self.validate_applied_prefix(&migrations, &applied)?;
let existing_tables = self.get_existing_core_relations(conn).await?;
self.validate_core_table_state(&applied, &existing_tables)?;
let applied: std::collections::HashSet<i64> = applied.into_iter().collect();
let mut missing: Vec<i64> = migrations
.iter()
.map(|m| m.version)
.filter(|v| !applied.contains(v))
.collect();
missing.sort_unstable();
if !missing.is_empty() {
anyhow::bail!(
"duroxide migrations not up to date in schema {:?}: missing \
versions {:?}. Run migrations from a provider configured with \
MigrationPolicy::ApplyAll before constructing VerifyOnly \
providers.",
self.schema_name,
missing,
);
}
if notifications
&& self.notification_trigger_counts(conn).await?.1 != NOTIFICATION_TRIGGERS.len() as i64
{
anyhow::bail!(
"long-poll notifications are not enabled in schema {:?}. \
Construct a provider with MigrationPolicy::ApplyAll and \
long_poll.enabled = true from a process with DDL privileges first.",
self.schema_name,
);
}
Ok(())
}
async fn notification_trigger_counts(
&self,
conn: &mut sqlx::postgres::PgConnection,
) -> Result<(i64, i64)> {
let (relations, names): (Vec<_>, Vec<_>) = NOTIFICATION_TRIGGERS
.iter()
.map(|(table, trigger)| (format!("{}.{table}", self.schema_name), *trigger))
.unzip();
let counts: (i64, i64) = sqlx::query_as(
"SELECT COUNT(*), COUNT(*) FILTER (WHERE tgenabled IN ('O', 'A')) \
FROM pg_catalog.pg_trigger \
JOIN unnest($1::TEXT[], $2::TEXT[]) expected(relation, name) \
ON tgrelid = expected.relation::REGCLASS AND tgname = expected.name",
)
.bind(relations)
.bind(names)
.fetch_one(conn)
.await?;
anyhow::ensure!(
counts.0 == NOTIFICATION_TRIGGERS.len() as i64,
"long-poll notification triggers are missing in schema {:?}; repair the schema before enabling long-polling",
self.schema_name,
);
Ok(counts)
}
async fn enable_notifications(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
if self.notification_trigger_counts(conn).await?.1 == NOTIFICATION_TRIGGERS.len() as i64 {
return Ok(());
}
let deadline = Instant::now() + DDL_RETRY_BUDGET;
loop {
let result = async {
let mut tx = conn.begin().await?;
let result = async {
sqlx::query(DDL_LOCK_TIMEOUT_SQL).execute(&mut *tx).await?;
for table in ["worker_queue", "orchestrator_queue", "sessions"] {
sqlx::query(&format!(
"LOCK TABLE {}.{table} IN SHARE ROW EXCLUSIVE MODE",
self.schema_name,
))
.execute(&mut *tx)
.await?;
}
for (table, trigger) in NOTIFICATION_TRIGGERS {
sqlx::query(&format!(
"ALTER TABLE {}.{table} ENABLE TRIGGER {trigger}",
self.schema_name,
))
.execute(&mut *tx)
.await?;
}
Ok(())
}
.await;
Self::finish_ddl(tx, result).await
}
.await;
match result {
Ok(()) => return Ok(()),
Err(error) => {
if !self
.retry_ddl(&error, deadline, "activating long-poll notifications")
.await
{
return Err(error.context(format!(
"Failed to activate long-poll notifications in schema {:?}",
self.schema_name
)));
}
}
}
}
}
async fn finish_ddl(
tx: sqlx::Transaction<'_, sqlx::Postgres>,
result: Result<()>,
) -> Result<()> {
match result {
Ok(()) => tx.commit().await.context("Committing DDL transaction"),
Err(error) => {
tx.rollback()
.await
.with_context(|| format!("Rolling back DDL after {error:#}"))?;
Err(error)
}
}
}
async fn retry_ddl(&self, error: &anyhow::Error, deadline: Instant, operation: &str) -> bool {
let sqlstate = error
.downcast_ref::<sqlx::Error>()
.and_then(sqlx::Error::as_database_error)
.and_then(|error| error.code());
if !matches!(sqlstate.as_deref(), Some("40P01" | "55P03")) || Instant::now() >= deadline {
return false;
}
tracing::warn!(
schema = %self.schema_name,
operation,
sqlstate = sqlstate.as_deref(),
error = %format_args!("{error:#}"),
"DDL lock contention; retrying the rolled-back transaction"
);
let jitter = Duration::from_millis(50 + u64::from(uuid::Uuid::new_v4().as_bytes()[0]));
tokio::time::sleep(jitter.min(deadline.saturating_duration_since(Instant::now()))).await;
Instant::now() < deadline
}
async fn check_no_unknown_migrations(
&self,
conn: &mut sqlx::postgres::PgConnection,
) -> Result<()> {
if !self.check_migration_table_exists(conn).await? {
return Ok(());
}
let applied = self.get_applied_versions(conn).await?;
let expected: std::collections::HashSet<i64> = Self::load_migrations()?
.into_iter()
.map(|m| m.version)
.collect();
let mut unknown: Vec<i64> = applied
.into_iter()
.filter(|v| !expected.contains(v))
.collect();
unknown.sort_unstable();
if !unknown.is_empty() {
anyhow::bail!(
"schema {:?} has migrations not recognized by this version of \
the code: {:?}. The database schema is ahead of the code. \
Update the code to a compatible version.",
self.schema_name,
unknown,
);
}
Ok(())
}
async fn check_migration_table_exists(
&self,
conn: &mut sqlx::postgres::PgConnection,
) -> Result<bool> {
let relation_kind: Option<String> = sqlx::query_scalar(
"SELECT c.relkind::text \
FROM pg_catalog.pg_class c \
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
WHERE n.nspname = $1 AND c.relname = '_duroxide_migrations'",
)
.bind(&self.schema_name)
.fetch_optional(&mut *conn)
.await?;
match relation_kind.as_deref() {
None => Ok(false),
Some("r" | "p") => Ok(true),
Some(kind) => anyhow::bail!(
"duroxide migration tracking object in schema {:?} has PostgreSQL \
relation kind {:?}, not a base table; refusing to read or replace it",
self.schema_name,
kind,
),
}
}
fn validate_applied_prefix(
&self,
migrations: &[Migration],
applied_versions: &[i64],
) -> Result<()> {
for (index, (migration, applied)) in
migrations.iter().zip(applied_versions.iter()).enumerate()
{
if migration.version != *applied {
anyhow::bail!(
"duroxide migration history is inconsistent in schema {:?}: \
expected version {} at ledger position {}, but found version {}. \
Applied migrations must be an ordered prefix of the bundled \
migrations; refusing to apply migrations or modify the ledger.",
self.schema_name,
migration.version,
index + 1,
applied,
);
}
}
if applied_versions.len() > migrations.len() {
anyhow::bail!(
"duroxide migration history is inconsistent in schema {:?}: \
the ledger contains {} entries, but this binary bundles only {}. \
Refusing to apply migrations or modify the ledger.",
self.schema_name,
applied_versions.len(),
migrations.len(),
);
}
Ok(())
}
fn expected_core_tables(applied_versions: &[i64]) -> HashSet<String> {
let Some(latest) = applied_versions.last().copied() else {
return HashSet::new();
};
let mut expected: HashSet<String> =
BASE_TABLES.iter().map(|name| (*name).to_string()).collect();
if latest >= 14 {
expected.insert("sessions".to_string());
}
if latest >= 18 {
expected.insert("kv_store".to_string());
}
if latest >= 20 {
expected.insert("kv_delta".to_string());
}
expected
}
fn validate_core_table_state(
&self,
applied_versions: &[i64],
existing_relations: &HashMap<String, String>,
) -> Result<()> {
let expected_tables = Self::expected_core_tables(applied_versions);
let mut missing: Vec<&str> = expected_tables
.iter()
.filter(|name| !existing_relations.contains_key(*name))
.map(String::as_str)
.collect();
let mut wrong_kind: Vec<(&str, &str)> = expected_tables
.iter()
.filter_map(|name| {
existing_relations.get(name).and_then(|kind| {
(!matches!(kind.as_str(), "r" | "p")).then_some((name.as_str(), kind.as_str()))
})
})
.collect();
let mut unexpected: Vec<&str> = existing_relations
.keys()
.filter(|name| !expected_tables.contains(*name))
.map(String::as_str)
.collect();
missing.sort_unstable();
wrong_kind.sort_unstable();
unexpected.sort_unstable();
if !wrong_kind.is_empty() {
anyhow::bail!(
"duroxide schema {:?} has required relations {:?} with non-table \
PostgreSQL relation kinds. The schema may be corrupted; refusing \
to apply migrations or modify the ledger automatically.",
self.schema_name,
wrong_kind,
);
}
if !missing.is_empty() {
anyhow::bail!(
"duroxide migration history in schema {:?} requires tables {:?}, \
but they are missing. The schema may be corrupted; refusing to \
apply migrations or modify the ledger automatically.",
self.schema_name,
missing,
);
}
if !unexpected.is_empty() {
anyhow::bail!(
"duroxide schema {:?} contains tables {:?} that are not represented \
by its migration ledger. The schema may be corrupted; refusing to \
apply migrations or modify the ledger automatically.",
self.schema_name,
unexpected,
);
}
Ok(())
}
async fn migrate_inner(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
let schema_exists = self.check_schema_exists(conn).await?;
if !schema_exists && self.schema_name != "public" {
sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS {}", self.schema_name))
.execute(&mut *conn)
.await?;
}
let migrations = Self::load_migrations()?;
tracing::debug!(
"Loaded {} migrations for schema {}",
migrations.len(),
self.schema_name
);
let tracking_exists = self.check_migration_table_exists(conn).await?;
let existing_tables = self.get_existing_core_relations(conn).await?;
if !tracking_exists && !existing_tables.is_empty() {
let mut relations: Vec<(&str, &str)> = existing_tables
.iter()
.map(|(name, kind)| (name.as_str(), kind.as_str()))
.collect();
relations.sort_unstable();
anyhow::bail!(
"duroxide relations {:?} exist in schema {:?}, but the migration \
tracking table is missing. The schema may be corrupted; refusing \
to create a new ledger or apply migrations automatically.",
relations,
self.schema_name,
);
}
if !tracking_exists {
self.ensure_migration_table(conn).await?;
}
let applied_versions = self.get_applied_versions(conn).await?;
self.validate_applied_prefix(&migrations, &applied_versions)?;
self.validate_core_table_state(&applied_versions, &existing_tables)?;
tracing::debug!("Applied migrations: {:?}", applied_versions);
for migration in migrations.into_iter().skip(applied_versions.len()) {
tracing::debug!(
"Applying migration {}: {}",
migration.version,
migration.name
);
self.apply_migration(conn, &migration).await?;
}
Ok(())
}
fn load_migrations() -> Result<Vec<Migration>> {
let mut migrations = Vec::new();
let mut files: Vec<_> = MIGRATIONS
.files()
.filter(|file| file.path().extension().and_then(|ext| ext.to_str()) == Some("sql"))
.collect();
files.sort_by_key(|f| f.path());
for file in files {
let file_name = file
.path()
.file_name()
.and_then(|n| n.to_str())
.ok_or_else(|| anyhow::anyhow!("Invalid filename in migrations"))?;
let sql = file
.contents_utf8()
.ok_or_else(|| anyhow::anyhow!("Migration file is not valid UTF-8: {file_name}"))?
.to_string();
let version = Self::parse_version(file_name)?;
let name = file_name.to_string();
migrations.push(Migration { version, name, sql });
}
Ok(migrations)
}
fn parse_version(filename: &str) -> Result<i64> {
let version_str = filename
.split('_')
.next()
.ok_or_else(|| anyhow::anyhow!("Invalid migration filename: {filename}"))?;
version_str
.parse::<i64>()
.map_err(|e| anyhow::anyhow!("Invalid migration version {version_str}: {e}"))
}
async fn ensure_migration_table(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
sqlx::query(&format!(
r#"
CREATE TABLE IF NOT EXISTS {}._duroxide_migrations (
version BIGINT PRIMARY KEY,
name TEXT NOT NULL,
applied_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
)
"#,
self.schema_name
))
.execute(&mut *conn)
.await?;
Ok(())
}
async fn check_schema_exists(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<bool> {
let exists = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = $1)",
)
.bind(&self.schema_name)
.fetch_one(&mut *conn)
.await?;
Ok(exists)
}
async fn get_existing_core_relations(
&self,
conn: &mut sqlx::postgres::PgConnection,
) -> Result<HashMap<String, String>> {
let known_tables: Vec<String> = ALL_CORE_TABLES
.iter()
.map(|name| (*name).to_string())
.collect();
let relations: Vec<(String, String)> = sqlx::query_as(
"SELECT c.relname::text, c.relkind::text \
FROM pg_catalog.pg_class c \
JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
WHERE n.nspname = $1 AND c.relname = ANY($2::text[])",
)
.bind(&self.schema_name)
.bind(&known_tables)
.fetch_all(&mut *conn)
.await?;
Ok(relations.into_iter().collect())
}
async fn get_applied_versions(
&self,
conn: &mut sqlx::postgres::PgConnection,
) -> Result<Vec<i64>> {
let versions: Vec<i64> = sqlx::query_scalar(&format!(
"SELECT version FROM {}._duroxide_migrations ORDER BY version",
self.schema_name
))
.fetch_all(&mut *conn)
.await?;
Ok(versions)
}
fn split_sql_statements(sql: &str) -> Vec<String> {
let mut statements = Vec::new();
let mut current_statement = String::new();
let chars: Vec<char> = sql.chars().collect();
let mut i = 0;
let mut in_dollar_quote = false;
let mut dollar_tag: Option<String> = None;
while i < chars.len() {
let ch = chars[i];
if !in_dollar_quote {
if ch == '$' {
let mut tag = String::new();
tag.push(ch);
i += 1;
while i < chars.len() {
let next_ch = chars[i];
if next_ch == '$' {
tag.push(next_ch);
dollar_tag = Some(tag.clone());
in_dollar_quote = true;
current_statement.push_str(&tag);
i += 1;
break;
} else if next_ch.is_alphanumeric() || next_ch == '_' {
tag.push(next_ch);
i += 1;
} else {
current_statement.push(ch);
break;
}
}
} else if ch == ';' {
current_statement.push(ch);
let trimmed = current_statement.trim().to_string();
if !trimmed.is_empty() {
statements.push(trimmed);
}
current_statement.clear();
i += 1;
} else {
current_statement.push(ch);
i += 1;
}
} else {
current_statement.push(ch);
if ch == '$' {
let tag = dollar_tag.as_ref().unwrap();
let mut matches = true;
for (j, tag_char) in tag.chars().enumerate() {
if j == 0 {
continue; }
if i + j >= chars.len() || chars[i + j] != tag_char {
matches = false;
break;
}
}
if matches {
for _ in 0..(tag.len() - 1) {
if i + 1 < chars.len() {
current_statement.push(chars[i + 1]);
i += 1;
}
}
in_dollar_quote = false;
dollar_tag = None;
}
}
i += 1;
}
}
let trimmed = current_statement.trim().to_string();
if !trimmed.is_empty() {
statements.push(trimmed);
}
statements
}
fn migration_search_path_stmt(schema_name: &str) -> String {
format!("SET LOCAL search_path TO {schema_name}, pg_temp")
}
async fn apply_migration(
&self,
conn: &mut sqlx::postgres::PgConnection,
migration: &Migration,
) -> Result<()> {
let deadline = Instant::now() + DDL_RETRY_BUDGET;
loop {
match self.apply_migration_once(conn, migration).await {
Ok(()) => return Ok(()),
Err(error) => {
if !self.retry_ddl(&error, deadline, &migration.name).await {
return Err(error);
}
}
}
}
}
async fn apply_migration_once(
&self,
conn: &mut sqlx::postgres::PgConnection,
migration: &Migration,
) -> Result<()> {
let sql = migration.sql.trim();
let cleaned_sql: String = sql
.lines()
.map(|line| {
if let Some(idx) = line.find("--") {
let before = &line[..idx];
if before.matches('\'').count() % 2 == 0 {
line[..idx].trim()
} else {
line
}
} else {
line
}
})
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
.join("\n");
let statements = Self::split_sql_statements(&cleaned_sql);
tracing::debug!(
"Executing {} statements for migration {}",
statements.len(),
migration.version
);
let mut tx = conn.begin().await?;
let result =
async {
sqlx::query(DDL_LOCK_TIMEOUT_SQL).execute(&mut *tx).await?;
sqlx::query(&Self::migration_search_path_stmt(&self.schema_name))
.execute(&mut *tx)
.await?;
for (idx, statement) in statements.iter().enumerate() {
if !statement.trim().is_empty() {
tracing::debug!(
"Executing statement {} of {}: {}...",
idx + 1,
statements.len(),
&statement.chars().take(50).collect::<String>()
);
sqlx::query(statement)
.execute(&mut *tx)
.await
.map_err(|error| {
let message = format!(
"Failed to execute statement {} in migration {}: {error}\nStatement: {}",
idx + 1, migration.version, statement
);
anyhow::Error::new(error).context(message)
})?;
}
}
sqlx::query(&format!(
"INSERT INTO {}._duroxide_migrations (version, name) VALUES ($1, $2)",
self.schema_name
))
.bind(migration.version)
.bind(&migration.name)
.execute(&mut *tx)
.await?;
Ok(())
}
.await;
Self::finish_ddl(tx, result).await?;
tracing::info!(
"Applied migration {}: {}",
migration.version,
migration.name
);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn migration_connection_is_reused_after_successful_unlock() {
dotenvy::dotenv().ok();
let Ok(url) = std::env::var("DATABASE_URL") else {
eprintln!("DATABASE_URL not set; skipping migration connection database test");
return;
};
let pool = sqlx::postgres::PgPoolOptions::new()
.min_connections(1)
.max_connections(1)
.connect(&url)
.await
.unwrap();
let mut control = sqlx::PgConnection::connect(&url).await.unwrap();
let schema = format!("reuse_migration_{}", uuid::Uuid::new_v4().simple());
let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
let original_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
.fetch_one(&pool)
.await
.unwrap();
let mut results = Vec::new();
for notifications in [false, false, true] {
runner
.migrate_with_notifications(notifications)
.await
.unwrap();
let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
.fetch_one(&pool)
.await
.unwrap();
let unlocked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)")
.bind(runner.advisory_lock_key())
.fetch_one(&mut control)
.await
.unwrap();
results.push((pid, unlocked));
}
pool.close().await;
sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
.execute(&mut control)
.await
.unwrap();
for (pid, unlocked) in results {
assert_eq!(
pid, original_pid,
"migration success must not force a new connection"
);
assert!(
unlocked,
"the reused connection must not retain the migration lock"
);
}
}
#[tokio::test]
async fn migration_connection_is_discarded_when_unlock_is_not_confirmed() {
dotenvy::dotenv().ok();
let Ok(url) = std::env::var("DATABASE_URL") else {
eprintln!("DATABASE_URL not set; skipping migration unlock database test");
return;
};
let pool = sqlx::postgres::PgPoolOptions::new()
.min_connections(1)
.max_connections(1)
.connect(&url)
.await
.unwrap();
let mut control = sqlx::PgConnection::connect(&url).await.unwrap();
let schema = format!("lost_migration_lock_{}", uuid::Uuid::new_v4().simple());
let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
sqlx::query(&format!("CREATE SCHEMA {schema}"))
.execute(&mut control)
.await
.unwrap();
runner.ensure_migration_table(&mut control).await.unwrap();
let versions: Vec<_> = MigrationRunner::load_migrations()
.unwrap()
.iter()
.map(|m| m.version)
.collect();
let last = versions.last().unwrap();
sqlx::Executor::execute(&mut control, format!(
"CREATE FUNCTION {schema}.release_lock_early() RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN PERFORM pg_advisory_unlock_all(); RETURN NEW; END $$;
CREATE TRIGGER release_lock_early AFTER INSERT ON {schema}._duroxide_migrations
FOR EACH ROW WHEN (NEW.version = {last}) EXECUTE FUNCTION {schema}.release_lock_early();"
).as_str()).await.unwrap();
let before: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
.fetch_one(&pool)
.await
.unwrap();
let error = runner
.migrate()
.await
.expect_err("an unconfirmed unlock is not success");
let after: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
.fetch_one(&pool)
.await
.unwrap();
let applied = runner.get_applied_versions(&mut control).await.unwrap();
let unlocked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)")
.bind(runner.advisory_lock_key())
.fetch_one(&mut control)
.await
.unwrap();
pool.close().await;
sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
.execute(&mut control)
.await
.unwrap();
assert!(
error
.to_string()
.contains("Migration advisory lock was not held"),
"{error:#}"
);
assert_ne!(
after, before,
"failed unlock must not return the connection to the pool"
);
assert_eq!(
applied, versions,
"a cleanup error must not rewrite committed migration records"
);
assert!(unlocked);
}
#[tokio::test]
async fn migration_connection_is_discarded_when_lock_acquisition_is_cancelled() {
dotenvy::dotenv().ok();
let Ok(url) = std::env::var("DATABASE_URL") else {
eprintln!("DATABASE_URL not set; skipping migration cancellation database test");
return;
};
let pool = sqlx::postgres::PgPoolOptions::new()
.min_connections(1)
.max_connections(1)
.connect(&url)
.await
.unwrap();
let mut control = sqlx::PgConnection::connect(&url).await.unwrap();
let schema = format!("cancel_migration_{}", uuid::Uuid::new_v4().simple());
let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
let key = runner.advisory_lock_key();
let before: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
.fetch_one(&pool)
.await
.unwrap();
sqlx::query("SELECT pg_advisory_lock($1)")
.bind(key)
.execute(&mut control)
.await
.unwrap();
let migration = tokio::spawn(async move { runner.migrate().await });
let waiting = tokio::time::timeout(Duration::from_secs(3), async {
loop {
let blocked: bool = sqlx::query_scalar(
"SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE pid = $1 AND wait_event = 'advisory')",
).bind(before).fetch_one(&mut control).await.unwrap();
if blocked {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
}).await;
migration.abort();
assert!(migration.await.unwrap_err().is_cancelled());
sqlx::query("SELECT pg_advisory_unlock($1)")
.bind(key)
.execute(&mut control)
.await
.unwrap();
let after = tokio::time::timeout(
Duration::from_secs(3),
sqlx::query_scalar::<_, i32>("SELECT pg_backend_pid()").fetch_one(&pool),
)
.await
.expect("cancellation must release the pool slot")
.unwrap();
let exited = tokio::time::timeout(Duration::from_secs(3), async {
loop {
let gone: bool = sqlx::query_scalar(
"SELECT NOT EXISTS(SELECT 1 FROM pg_stat_activity WHERE pid = $1)",
)
.bind(before)
.fetch_one(&mut control)
.await
.unwrap();
if gone {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await;
let absent: bool = sqlx::query_scalar("SELECT to_regnamespace($1) IS NULL")
.bind(&schema)
.fetch_one(&mut control)
.await
.unwrap();
let unlocked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)")
.bind(key)
.fetch_one(&mut control)
.await
.unwrap();
pool.close().await;
sqlx::query(&format!("DROP SCHEMA IF EXISTS {schema} CASCADE"))
.execute(&mut control)
.await
.unwrap();
waiting.expect("migration must reach the advisory-lock wait");
exited.expect("the cancelled session must exit rather than keep its advisory lock");
assert_ne!(after, before);
assert!(
absent,
"cancellation before acquiring the lock must not apply DDL"
);
assert!(
unlocked,
"no cancelled session may retain the migration lock"
);
}
#[tokio::test]
async fn migration_statement_display_preserves_database_message_and_source() {
dotenvy::dotenv().ok();
let Ok(url) = std::env::var("DATABASE_URL") else {
eprintln!("DATABASE_URL not set; skipping migration error database test");
return;
};
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect(&url)
.await
.unwrap();
let schema = format!("migration_error_{}", uuid::Uuid::new_v4().simple());
let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
let mut connection = pool.acquire().await.unwrap();
sqlx::query(&format!("CREATE SCHEMA {schema}"))
.execute(&mut *connection)
.await
.unwrap();
runner
.ensure_migration_table(&mut connection)
.await
.unwrap();
let valid = Migration {
version: 1,
name: "0001_error_fixture.sql".to_string(),
sql: "CREATE TABLE history_probe (id INTEGER PRIMARY KEY, valid BOOLEAN);
INSERT INTO history_probe VALUES (7, false);
CREATE FUNCTION validate_history_probe() RETURNS VOID LANGUAGE plpgsql AS $$
DECLARE bad_id INTEGER;
BEGIN
SELECT id INTO bad_id FROM history_probe WHERE NOT valid LIMIT 1;
IF FOUND THEN
RAISE EXCEPTION 'Malformed history: instance=damaged-history execution_id=1 event_id=%', bad_id
USING ERRCODE = '22023';
END IF;
END $$;".to_string(),
};
runner
.apply_migration(&mut connection, &valid)
.await
.unwrap();
let snapshot = format!(
"SELECT jsonb_build_object(
'ledger', (SELECT jsonb_agg(to_jsonb(m) ORDER BY version) FROM {schema}._duroxide_migrations m),
'history', (SELECT jsonb_agg(to_jsonb(h) ORDER BY id) FROM {schema}.history_probe h),
'function', pg_get_functiondef('{schema}.validate_history_probe()'::regprocedure))"
);
let before: serde_json::Value = sqlx::query_scalar(&snapshot)
.fetch_one(&mut *connection)
.await
.unwrap();
let invalid = Migration {
version: 2,
name: "0002_validate_history.sql".to_string(),
sql: "INSERT INTO history_probe VALUES (8, true);
ALTER FUNCTION validate_history_probe() STABLE;
SELECT validate_history_probe();"
.to_string(),
};
let error = runner
.apply_migration(&mut connection, &invalid)
.await
.unwrap_err();
let after: serde_json::Value = sqlx::query_scalar(&snapshot)
.fetch_one(&mut *connection)
.await
.unwrap();
sqlx::query(&format!("UPDATE {schema}.history_probe SET valid = true"))
.execute(&mut *connection)
.await
.unwrap();
runner
.apply_migration(&mut connection, &invalid)
.await
.unwrap();
let versions = runner.get_applied_versions(&mut connection).await.unwrap();
sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
.execute(&mut *connection)
.await
.unwrap();
drop(connection);
pool.close().await;
assert_eq!(
after, before,
"failed migration must preserve its ledger, function, and history"
);
assert_eq!(versions, vec![1, 2]);
let database_error = error
.downcast_ref::<sqlx::Error>()
.and_then(sqlx::Error::as_database_error)
.expect("retain the database source");
assert_eq!(database_error.code().as_deref(), Some("22023"));
let display = error.to_string();
for expected in [
"Failed to execute statement 3 in migration 2",
"Malformed history: instance=damaged-history execution_id=1 event_id=7",
"Statement: SELECT validate_history_probe();",
] {
assert!(
display.contains(expected),
"missing {expected:?} in Display: {display}"
);
}
}
#[tokio::test]
async fn ddl_retry_logs_sqlstate_and_full_error_context() {
#[derive(Clone, Default)]
struct Capture(Arc<std::sync::Mutex<Vec<u8>>>);
impl std::io::Write for Capture {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
dotenvy::dotenv().ok();
let Ok(url) = std::env::var("DATABASE_URL") else {
eprintln!("DATABASE_URL not set; skipping DDL logging database test");
return;
};
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect(&url)
.await
.unwrap();
let runner = MigrationRunner::new(Arc::new(pool.clone()), "diagnostic_test".to_string());
let captured = Capture::default();
let writer = captured.clone();
let subscriber = tracing_subscriber::fmt()
.without_time()
.with_ansi(false)
.with_env_filter("off,duroxide_pg::migrations=warn")
.with_writer(move || writer.clone())
.finish();
let _guard = tracing::subscriber::set_default(subscriber);
for (code, message) in [
("40P01", "simulated migration deadlock"),
("55P03", "simulated migration lock timeout"),
] {
let error = sqlx::query(&format!(
"DO $$ BEGIN RAISE EXCEPTION '{message}' USING ERRCODE = '{code}'; END $$"
))
.execute(&pool)
.await
.unwrap_err();
let error = anyhow::Error::new(error).context("outer migration statement context");
assert!(
runner
.retry_ddl(
&error,
Instant::now() + Duration::from_secs(5),
"test migration"
)
.await
);
let output = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
assert!(
output.contains("sqlstate=") && output.contains(code),
"{output}"
);
assert!(
output.contains("outer migration statement context") && output.contains(message),
"{output}"
);
}
pool.close().await;
}
#[test]
fn embedded_migration_versions_are_unique_and_increasing() {
let migrations = MigrationRunner::load_migrations().expect("load embedded migrations");
assert!(!migrations.is_empty(), "expected embedded SQL migrations");
for pair in migrations.windows(2) {
assert!(
pair[0].version < pair[1].version,
"embedded migrations must have unique, increasing versions: {} then {}",
pair[0].name,
pair[1].name,
);
}
}
#[test]
fn migration_search_path_pins_pg_temp_last() {
let stmt = MigrationRunner::migration_search_path_stmt("duroxide");
assert_eq!(stmt, "SET LOCAL search_path TO duroxide, pg_temp");
}
}