Skip to main content

duroxide_pg/
migrations.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use anyhow::{Context, Result};
5use include_dir::{include_dir, Dir};
6use sqlx::{pool::PoolConnection, Connection, PgPool, Postgres};
7use std::collections::{HashMap, HashSet};
8use std::sync::Arc;
9use std::time::Duration;
10use tokio::time::Instant;
11
12// Touch this module when adding embedded files so incremental builds see them. Latest: 0030.
13static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
14
15const DDL_LOCK_TIMEOUT_SQL: &str = "SET LOCAL lock_timeout = '250ms'";
16const DDL_RETRY_BUDGET: Duration = Duration::from_secs(10);
17const NOTIFICATION_TRIGGERS: &[(&str, &str)] = &[
18    ("worker_queue", "trg_notify_worker_work"),
19    ("worker_queue", "trg_notify_worker_work_released"),
20    ("orchestrator_queue", "trg_notify_orch_work"),
21    ("orchestrator_queue", "trg_notify_orch_work_released"),
22    ("orchestrator_queue", "trg_notify_orch_work_consumed"),
23    ("sessions", "trg_notify_session_lease"),
24];
25
26const BASE_TABLES: &[&str] = &[
27    "instances",
28    "executions",
29    "history",
30    "orchestrator_queue",
31    "worker_queue",
32    "instance_locks",
33];
34const ALL_CORE_TABLES: &[&str] = &[
35    "instances",
36    "executions",
37    "history",
38    "orchestrator_queue",
39    "worker_queue",
40    "instance_locks",
41    "sessions",
42    "kv_store",
43    "kv_delta",
44];
45
46/// Migration metadata
47#[derive(Debug)]
48struct Migration {
49    version: i64,
50    name: String,
51    sql: String,
52}
53
54/// Migration runner that handles schema-qualified migrations
55pub struct MigrationRunner {
56    pool: Arc<PgPool>,
57    schema_name: String,
58}
59
60struct MigrationConnection {
61    connection: PoolConnection<Postgres>,
62    reusable: bool,
63}
64
65impl Drop for MigrationConnection {
66    fn drop(&mut self) {
67        if !self.reusable {
68            self.connection.close_on_drop();
69        }
70    }
71}
72
73impl MigrationRunner {
74    /// Create a new migration runner
75    pub fn new(pool: Arc<PgPool>, schema_name: String) -> Self {
76        Self { pool, schema_name }
77    }
78
79    fn advisory_lock_key(&self) -> i64 {
80        // Stable 64-bit FNV-1a hash over (namespace + schema name).
81        // This avoids using Rust's DefaultHasher (randomized per-process).
82        const OFFSET: u64 = 0xcbf29ce484222325;
83        const PRIME: u64 = 0x100000001b3;
84
85        let mut hash = OFFSET;
86        for b in b"duroxide_pg:migrations:" {
87            hash ^= *b as u64;
88            hash = hash.wrapping_mul(PRIME);
89        }
90        for b in self.schema_name.as_bytes() {
91            hash ^= *b as u64;
92            hash = hash.wrapping_mul(PRIME);
93        }
94
95        hash as i64
96    }
97
98    async fn lock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
99        let key = self.advisory_lock_key();
100        // Session lock (not xact lock) so it spans multiple transactions.
101        // We explicitly unlock at the end.
102        sqlx::query("SELECT pg_advisory_lock($1)")
103            .bind(key)
104            .execute(&mut *conn)
105            .await?;
106        Ok(())
107    }
108
109    async fn unlock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
110        let key = self.advisory_lock_key();
111        let unlocked: bool = sqlx::query_scalar("SELECT pg_advisory_unlock($1)")
112            .bind(key)
113            .fetch_one(&mut *conn)
114            .await
115            .context("Releasing the migration advisory lock")?;
116        anyhow::ensure!(
117            unlocked,
118            "Migration advisory lock was not held for schema {:?}",
119            self.schema_name
120        );
121        Ok(())
122    }
123
124    /// Run all pending migrations
125    pub async fn migrate(&self) -> Result<()> {
126        self.migrate_with_notifications(false).await
127    }
128
129    pub(crate) async fn migrate_with_notifications(&self, notifications: bool) -> Result<()> {
130        // Cancellation or failed unlocking must not return a session lock to the pool.
131        let mut guard = MigrationConnection {
132            connection: self.pool.acquire().await?,
133            reusable: false,
134        };
135        let conn = &mut *guard.connection;
136        self.lock_for_migrations(conn).await?;
137
138        // Reject unknown migrations while holding the advisory lock so that an
139        // older binary cannot rewrite a schema that is ahead of its code.
140        // Short-circuit: do NOT run migrate_inner if unknown migrations are
141        // detected.
142        let result: Result<()> = async {
143            self.check_no_unknown_migrations(conn).await?;
144            self.migrate_inner(conn).await?;
145            if notifications {
146                self.enable_notifications(conn).await?;
147            }
148            Ok(())
149        }
150        .await;
151        let unlock_result = self.unlock_for_migrations(conn).await;
152        result?;
153        unlock_result?;
154        guard.reusable = true;
155        Ok(())
156    }
157
158    /// Verify that the migration tracking table exists and that every embedded
159    /// migration has already been applied. Does not take the migration
160    /// advisory lock and does not create or modify any database objects.
161    ///
162    /// Returns an error if the `_duroxide_migrations` table is missing in
163    /// `schema_name` or if any bundled migration version is absent from it.
164    ///
165    /// Intended for processes that must not perform DDL (e.g. application
166    /// backends, where a separately privileged worker is responsible for
167    /// applying schema changes).
168    pub async fn verify(&self) -> Result<()> {
169        self.verify_with_notifications(false).await
170    }
171
172    pub(crate) async fn verify_with_notifications(&self, notifications: bool) -> Result<()> {
173        let mut conn = self.pool.acquire().await?;
174        let conn = &mut *conn;
175
176        // Check that the tracking table exists in the target schema.
177        let table_exists = self.check_migration_table_exists(conn).await?;
178
179        if !table_exists {
180            anyhow::bail!(
181                "duroxide migrations not initialized: schema {:?} does not \
182                 contain _duroxide_migrations. Construct a provider with \
183                 MigrationPolicy::ApplyAll (the default) from a process with \
184                 DDL privileges before using MigrationPolicy::VerifyOnly.",
185                self.schema_name
186            );
187        }
188
189        // Reject schemas that have migrations the running binary does not
190        // recognize (schema is ahead of the code).
191        self.check_no_unknown_migrations(conn).await?;
192
193        let migrations = Self::load_migrations()?;
194        let applied = self.get_applied_versions(conn).await?;
195        self.validate_applied_prefix(&migrations, &applied)?;
196        let existing_tables = self.get_existing_core_relations(conn).await?;
197        self.validate_core_table_state(&applied, &existing_tables)?;
198        let applied: std::collections::HashSet<i64> = applied.into_iter().collect();
199
200        let mut missing: Vec<i64> = migrations
201            .iter()
202            .map(|m| m.version)
203            .filter(|v| !applied.contains(v))
204            .collect();
205        missing.sort_unstable();
206
207        if !missing.is_empty() {
208            anyhow::bail!(
209                "duroxide migrations not up to date in schema {:?}: missing \
210                 versions {:?}. Run migrations from a provider configured with \
211                 MigrationPolicy::ApplyAll before constructing VerifyOnly \
212                 providers.",
213                self.schema_name,
214                missing,
215            );
216        }
217
218        if notifications
219            && self.notification_trigger_counts(conn).await?.1 != NOTIFICATION_TRIGGERS.len() as i64
220        {
221            anyhow::bail!(
222                "long-poll notifications are not enabled in schema {:?}. \
223                 Construct a provider with MigrationPolicy::ApplyAll and \
224                 long_poll.enabled = true from a process with DDL privileges first.",
225                self.schema_name,
226            );
227        }
228
229        Ok(())
230    }
231
232    async fn notification_trigger_counts(
233        &self,
234        conn: &mut sqlx::postgres::PgConnection,
235    ) -> Result<(i64, i64)> {
236        let (relations, names): (Vec<_>, Vec<_>) = NOTIFICATION_TRIGGERS
237            .iter()
238            .map(|(table, trigger)| (format!("{}.{table}", self.schema_name), *trigger))
239            .unzip();
240        let counts: (i64, i64) = sqlx::query_as(
241            "SELECT COUNT(*), COUNT(*) FILTER (WHERE tgenabled IN ('O', 'A')) \
242             FROM pg_catalog.pg_trigger \
243             JOIN unnest($1::TEXT[], $2::TEXT[]) expected(relation, name) \
244               ON tgrelid = expected.relation::REGCLASS AND tgname = expected.name",
245        )
246        .bind(relations)
247        .bind(names)
248        .fetch_one(conn)
249        .await?;
250        anyhow::ensure!(
251            counts.0 == NOTIFICATION_TRIGGERS.len() as i64,
252            "long-poll notification triggers are missing in schema {:?}; repair the schema before enabling long-polling",
253            self.schema_name,
254        );
255        Ok(counts)
256    }
257
258    async fn enable_notifications(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
259        if self.notification_trigger_counts(conn).await?.1 == NOTIFICATION_TRIGGERS.len() as i64 {
260            return Ok(());
261        }
262
263        let deadline = Instant::now() + DDL_RETRY_BUDGET;
264        loop {
265            let result = async {
266                let mut tx = conn.begin().await?;
267                let result = async {
268                    sqlx::query(DDL_LOCK_TIMEOUT_SQL).execute(&mut *tx).await?;
269                    // Match acknowledgments, but bound every wait because admin
270                    // deletion can acquire the queue locks in the opposite order.
271                    for table in ["worker_queue", "orchestrator_queue", "sessions"] {
272                        sqlx::query(&format!(
273                            "LOCK TABLE {}.{table} IN SHARE ROW EXCLUSIVE MODE",
274                            self.schema_name,
275                        ))
276                        .execute(&mut *tx)
277                        .await?;
278                    }
279                    for (table, trigger) in NOTIFICATION_TRIGGERS {
280                        sqlx::query(&format!(
281                            "ALTER TABLE {}.{table} ENABLE TRIGGER {trigger}",
282                            self.schema_name,
283                        ))
284                        .execute(&mut *tx)
285                        .await?;
286                    }
287                    Ok(())
288                }
289                .await;
290                Self::finish_ddl(tx, result).await
291            }
292            .await;
293            match result {
294                Ok(()) => return Ok(()),
295                Err(error) => {
296                    if !self
297                        .retry_ddl(&error, deadline, "activating long-poll notifications")
298                        .await
299                    {
300                        return Err(error.context(format!(
301                            "Failed to activate long-poll notifications in schema {:?}",
302                            self.schema_name
303                        )));
304                    }
305                }
306            }
307        }
308    }
309
310    async fn finish_ddl(
311        tx: sqlx::Transaction<'_, sqlx::Postgres>,
312        result: Result<()>,
313    ) -> Result<()> {
314        match result {
315            Ok(()) => tx.commit().await.context("Committing DDL transaction"),
316            Err(error) => {
317                tx.rollback()
318                    .await
319                    .with_context(|| format!("Rolling back DDL after {error:#}"))?;
320                Err(error)
321            }
322        }
323    }
324
325    async fn retry_ddl(&self, error: &anyhow::Error, deadline: Instant, operation: &str) -> bool {
326        let sqlstate = error
327            .downcast_ref::<sqlx::Error>()
328            .and_then(sqlx::Error::as_database_error)
329            .and_then(|error| error.code());
330        if !matches!(sqlstate.as_deref(), Some("40P01" | "55P03")) || Instant::now() >= deadline {
331            return false;
332        }
333        tracing::warn!(
334            schema = %self.schema_name,
335            operation,
336            sqlstate = sqlstate.as_deref(),
337            error = %format_args!("{error:#}"),
338            "DDL lock contention; retrying the rolled-back transaction"
339        );
340        let jitter = Duration::from_millis(50 + u64::from(uuid::Uuid::new_v4().as_bytes()[0]));
341        tokio::time::sleep(jitter.min(deadline.saturating_duration_since(Instant::now()))).await;
342        Instant::now() < deadline
343    }
344
345    /// Check that the database has no migrations the running binary does not
346    /// recognize. Used by both `migrate()` (to refuse running DDL against a
347    /// schema ahead of the code) and `verify()` (to refuse claiming
348    /// successful verification of an unknown schema).
349    ///
350    /// Returns `Ok(())` if the tracking table does not yet exist: under
351    /// `ApplyAll` it will be created by `migrate_inner`, and under
352    /// `VerifyOnly` the missing table is reported separately before this is
353    /// called.
354    async fn check_no_unknown_migrations(
355        &self,
356        conn: &mut sqlx::postgres::PgConnection,
357    ) -> Result<()> {
358        if !self.check_migration_table_exists(conn).await? {
359            return Ok(());
360        }
361
362        let applied = self.get_applied_versions(conn).await?;
363        let expected: std::collections::HashSet<i64> = Self::load_migrations()?
364            .into_iter()
365            .map(|m| m.version)
366            .collect();
367
368        let mut unknown: Vec<i64> = applied
369            .into_iter()
370            .filter(|v| !expected.contains(v))
371            .collect();
372        unknown.sort_unstable();
373
374        if !unknown.is_empty() {
375            anyhow::bail!(
376                "schema {:?} has migrations not recognized by this version of \
377                 the code: {:?}. The database schema is ahead of the code. \
378                 Update the code to a compatible version.",
379                self.schema_name,
380                unknown,
381            );
382        }
383
384        Ok(())
385    }
386
387    async fn check_migration_table_exists(
388        &self,
389        conn: &mut sqlx::postgres::PgConnection,
390    ) -> Result<bool> {
391        let relation_kind: Option<String> = sqlx::query_scalar(
392            "SELECT c.relkind::text \
393             FROM pg_catalog.pg_class c \
394             JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
395             WHERE n.nspname = $1 AND c.relname = '_duroxide_migrations'",
396        )
397        .bind(&self.schema_name)
398        .fetch_optional(&mut *conn)
399        .await?;
400
401        match relation_kind.as_deref() {
402            None => Ok(false),
403            Some("r" | "p") => Ok(true),
404            Some(kind) => anyhow::bail!(
405                "duroxide migration tracking object in schema {:?} has PostgreSQL \
406                 relation kind {:?}, not a base table; refusing to read or replace it",
407                self.schema_name,
408                kind,
409            ),
410        }
411    }
412
413    fn validate_applied_prefix(
414        &self,
415        migrations: &[Migration],
416        applied_versions: &[i64],
417    ) -> Result<()> {
418        for (index, (migration, applied)) in
419            migrations.iter().zip(applied_versions.iter()).enumerate()
420        {
421            if migration.version != *applied {
422                anyhow::bail!(
423                    "duroxide migration history is inconsistent in schema {:?}: \
424                     expected version {} at ledger position {}, but found version {}. \
425                     Applied migrations must be an ordered prefix of the bundled \
426                     migrations; refusing to apply migrations or modify the ledger.",
427                    self.schema_name,
428                    migration.version,
429                    index + 1,
430                    applied,
431                );
432            }
433        }
434
435        if applied_versions.len() > migrations.len() {
436            anyhow::bail!(
437                "duroxide migration history is inconsistent in schema {:?}: \
438                 the ledger contains {} entries, but this binary bundles only {}. \
439                 Refusing to apply migrations or modify the ledger.",
440                self.schema_name,
441                applied_versions.len(),
442                migrations.len(),
443            );
444        }
445
446        Ok(())
447    }
448
449    fn expected_core_tables(applied_versions: &[i64]) -> HashSet<String> {
450        let Some(latest) = applied_versions.last().copied() else {
451            return HashSet::new();
452        };
453
454        let mut expected: HashSet<String> =
455            BASE_TABLES.iter().map(|name| (*name).to_string()).collect();
456        if latest >= 14 {
457            expected.insert("sessions".to_string());
458        }
459        if latest >= 18 {
460            expected.insert("kv_store".to_string());
461        }
462        if latest >= 20 {
463            expected.insert("kv_delta".to_string());
464        }
465        expected
466    }
467
468    fn validate_core_table_state(
469        &self,
470        applied_versions: &[i64],
471        existing_relations: &HashMap<String, String>,
472    ) -> Result<()> {
473        let expected_tables = Self::expected_core_tables(applied_versions);
474        let mut missing: Vec<&str> = expected_tables
475            .iter()
476            .filter(|name| !existing_relations.contains_key(*name))
477            .map(String::as_str)
478            .collect();
479        let mut wrong_kind: Vec<(&str, &str)> = expected_tables
480            .iter()
481            .filter_map(|name| {
482                existing_relations.get(name).and_then(|kind| {
483                    (!matches!(kind.as_str(), "r" | "p")).then_some((name.as_str(), kind.as_str()))
484                })
485            })
486            .collect();
487        let mut unexpected: Vec<&str> = existing_relations
488            .keys()
489            .filter(|name| !expected_tables.contains(*name))
490            .map(String::as_str)
491            .collect();
492        missing.sort_unstable();
493        wrong_kind.sort_unstable();
494        unexpected.sort_unstable();
495
496        if !wrong_kind.is_empty() {
497            anyhow::bail!(
498                "duroxide schema {:?} has required relations {:?} with non-table \
499                 PostgreSQL relation kinds. The schema may be corrupted; refusing \
500                 to apply migrations or modify the ledger automatically.",
501                self.schema_name,
502                wrong_kind,
503            );
504        }
505
506        if !missing.is_empty() {
507            anyhow::bail!(
508                "duroxide migration history in schema {:?} requires tables {:?}, \
509                 but they are missing. The schema may be corrupted; refusing to \
510                 apply migrations or modify the ledger automatically.",
511                self.schema_name,
512                missing,
513            );
514        }
515
516        if !unexpected.is_empty() {
517            anyhow::bail!(
518                "duroxide schema {:?} contains tables {:?} that are not represented \
519                 by its migration ledger. The schema may be corrupted; refusing to \
520                 apply migrations or modify the ledger automatically.",
521                self.schema_name,
522                unexpected,
523            );
524        }
525
526        Ok(())
527    }
528
529    async fn migrate_inner(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
530        let schema_exists = self.check_schema_exists(conn).await?;
531        if !schema_exists && self.schema_name != "public" {
532            sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS {}", self.schema_name))
533                .execute(&mut *conn)
534                .await?;
535        }
536
537        // Load migrations from filesystem
538        let migrations = Self::load_migrations()?;
539
540        tracing::debug!(
541            "Loaded {} migrations for schema {}",
542            migrations.len(),
543            self.schema_name
544        );
545
546        let tracking_exists = self.check_migration_table_exists(conn).await?;
547        let existing_tables = self.get_existing_core_relations(conn).await?;
548
549        if !tracking_exists && !existing_tables.is_empty() {
550            let mut relations: Vec<(&str, &str)> = existing_tables
551                .iter()
552                .map(|(name, kind)| (name.as_str(), kind.as_str()))
553                .collect();
554            relations.sort_unstable();
555            anyhow::bail!(
556                "duroxide relations {:?} exist in schema {:?}, but the migration \
557                 tracking table is missing. The schema may be corrupted; refusing \
558                 to create a new ledger or apply migrations automatically.",
559                relations,
560                self.schema_name,
561            );
562        }
563
564        if !tracking_exists {
565            self.ensure_migration_table(conn).await?;
566        }
567
568        let applied_versions = self.get_applied_versions(conn).await?;
569        self.validate_applied_prefix(&migrations, &applied_versions)?;
570        self.validate_core_table_state(&applied_versions, &existing_tables)?;
571        tracing::debug!("Applied migrations: {:?}", applied_versions);
572
573        for migration in migrations.into_iter().skip(applied_versions.len()) {
574            tracing::debug!(
575                "Applying migration {}: {}",
576                migration.version,
577                migration.name
578            );
579            self.apply_migration(conn, &migration).await?;
580        }
581
582        Ok(())
583    }
584
585    /// Load migrations from the embedded migrations directory
586    fn load_migrations() -> Result<Vec<Migration>> {
587        let mut migrations = Vec::new();
588
589        // Get all files from embedded directory
590        let mut files: Vec<_> = MIGRATIONS
591            .files()
592            .filter(|file| file.path().extension().and_then(|ext| ext.to_str()) == Some("sql"))
593            .collect();
594
595        // Sort by path to ensure consistent ordering
596        files.sort_by_key(|f| f.path());
597
598        for file in files {
599            let file_name = file
600                .path()
601                .file_name()
602                .and_then(|n| n.to_str())
603                .ok_or_else(|| anyhow::anyhow!("Invalid filename in migrations"))?;
604
605            let sql = file
606                .contents_utf8()
607                .ok_or_else(|| anyhow::anyhow!("Migration file is not valid UTF-8: {file_name}"))?
608                .to_string();
609
610            let version = Self::parse_version(file_name)?;
611            let name = file_name.to_string();
612
613            migrations.push(Migration { version, name, sql });
614        }
615
616        Ok(migrations)
617    }
618
619    /// Parse version number from migration filename (e.g., "0001_initial.sql" -> 1)
620    fn parse_version(filename: &str) -> Result<i64> {
621        let version_str = filename
622            .split('_')
623            .next()
624            .ok_or_else(|| anyhow::anyhow!("Invalid migration filename: {filename}"))?;
625
626        version_str
627            .parse::<i64>()
628            .map_err(|e| anyhow::anyhow!("Invalid migration version {version_str}: {e}"))
629    }
630
631    /// Ensure migration tracking table exists
632    async fn ensure_migration_table(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
633        // Create migration table in the target schema
634        sqlx::query(&format!(
635            r#"
636            CREATE TABLE IF NOT EXISTS {}._duroxide_migrations (
637                version BIGINT PRIMARY KEY,
638                name TEXT NOT NULL,
639                applied_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
640            )
641            "#,
642            self.schema_name
643        ))
644        .execute(&mut *conn)
645        .await?;
646
647        Ok(())
648    }
649
650    async fn check_schema_exists(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<bool> {
651        let exists = sqlx::query_scalar(
652            "SELECT EXISTS(SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname = $1)",
653        )
654        .bind(&self.schema_name)
655        .fetch_one(&mut *conn)
656        .await?;
657
658        Ok(exists)
659    }
660
661    async fn get_existing_core_relations(
662        &self,
663        conn: &mut sqlx::postgres::PgConnection,
664    ) -> Result<HashMap<String, String>> {
665        let known_tables: Vec<String> = ALL_CORE_TABLES
666            .iter()
667            .map(|name| (*name).to_string())
668            .collect();
669        let relations: Vec<(String, String)> = sqlx::query_as(
670            "SELECT c.relname::text, c.relkind::text \
671             FROM pg_catalog.pg_class c \
672             JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace \
673             WHERE n.nspname = $1 AND c.relname = ANY($2::text[])",
674        )
675        .bind(&self.schema_name)
676        .bind(&known_tables)
677        .fetch_all(&mut *conn)
678        .await?;
679
680        Ok(relations.into_iter().collect())
681    }
682
683    /// Get list of applied migration versions
684    async fn get_applied_versions(
685        &self,
686        conn: &mut sqlx::postgres::PgConnection,
687    ) -> Result<Vec<i64>> {
688        let versions: Vec<i64> = sqlx::query_scalar(&format!(
689            "SELECT version FROM {}._duroxide_migrations ORDER BY version",
690            self.schema_name
691        ))
692        .fetch_all(&mut *conn)
693        .await?;
694
695        Ok(versions)
696    }
697
698    /// Split SQL into statements, respecting dollar-quoted strings ($$...$$)
699    /// This handles stored procedures and other constructs that use dollar-quoting
700    fn split_sql_statements(sql: &str) -> Vec<String> {
701        let mut statements = Vec::new();
702        let mut current_statement = String::new();
703        let chars: Vec<char> = sql.chars().collect();
704        let mut i = 0;
705        let mut in_dollar_quote = false;
706        let mut dollar_tag: Option<String> = None;
707
708        while i < chars.len() {
709            let ch = chars[i];
710
711            if !in_dollar_quote {
712                // Check for start of dollar-quoted string
713                if ch == '$' {
714                    let mut tag = String::new();
715                    tag.push(ch);
716                    i += 1;
717
718                    // Collect the tag (e.g., $$, $tag$, $function$)
719                    while i < chars.len() {
720                        let next_ch = chars[i];
721                        if next_ch == '$' {
722                            tag.push(next_ch);
723                            dollar_tag = Some(tag.clone());
724                            in_dollar_quote = true;
725                            current_statement.push_str(&tag);
726                            i += 1;
727                            break;
728                        } else if next_ch.is_alphanumeric() || next_ch == '_' {
729                            tag.push(next_ch);
730                            i += 1;
731                        } else {
732                            // Not a dollar quote, just a $ character
733                            current_statement.push(ch);
734                            break;
735                        }
736                    }
737                } else if ch == ';' {
738                    // End of statement (only if not in dollar quote)
739                    current_statement.push(ch);
740                    let trimmed = current_statement.trim().to_string();
741                    if !trimmed.is_empty() {
742                        statements.push(trimmed);
743                    }
744                    current_statement.clear();
745                    i += 1;
746                } else {
747                    current_statement.push(ch);
748                    i += 1;
749                }
750            } else {
751                // Inside dollar-quoted string
752                current_statement.push(ch);
753
754                // Check for end of dollar-quoted string
755                if ch == '$' {
756                    let tag = dollar_tag.as_ref().unwrap();
757                    let mut matches = true;
758
759                    // Check if the following characters match the closing tag
760                    for (j, tag_char) in tag.chars().enumerate() {
761                        if j == 0 {
762                            continue; // Skip first $ (we already matched it)
763                        }
764                        if i + j >= chars.len() || chars[i + j] != tag_char {
765                            matches = false;
766                            break;
767                        }
768                    }
769
770                    if matches {
771                        // Found closing tag - consume remaining tag characters
772                        for _ in 0..(tag.len() - 1) {
773                            if i + 1 < chars.len() {
774                                current_statement.push(chars[i + 1]);
775                                i += 1;
776                            }
777                        }
778                        in_dollar_quote = false;
779                        dollar_tag = None;
780                    }
781                }
782                i += 1;
783            }
784        }
785
786        // Add remaining statement if any
787        let trimmed = current_statement.trim().to_string();
788        if !trimmed.is_empty() {
789            statements.push(trimmed);
790        }
791
792        statements
793    }
794
795    /// Build the `SET LOCAL search_path` statement used while applying a migration.
796    ///
797    /// `pg_temp` is pinned last so it sits at the lowest priority instead of its
798    /// implicit highest-priority position, preventing a temporary object from
799    /// shadowing the unqualified references a migration resolves via the
800    /// `search_path`. This is defense-in-depth (CVE-2018-1058); `pg_catalog` is left
801    /// unlisted so PostgreSQL keeps it implicitly first.
802    ///
803    /// `schema_name` is validated at provider construction
804    /// (`^[A-Za-z_][A-Za-z0-9_]*$`), so direct interpolation here is safe.
805    fn migration_search_path_stmt(schema_name: &str) -> String {
806        format!("SET LOCAL search_path TO {schema_name}, pg_temp")
807    }
808
809    /// Apply a single migration
810    async fn apply_migration(
811        &self,
812        conn: &mut sqlx::postgres::PgConnection,
813        migration: &Migration,
814    ) -> Result<()> {
815        let deadline = Instant::now() + DDL_RETRY_BUDGET;
816        loop {
817            match self.apply_migration_once(conn, migration).await {
818                Ok(()) => return Ok(()),
819                Err(error) => {
820                    if !self.retry_ddl(&error, deadline, &migration.name).await {
821                        return Err(error);
822                    }
823                }
824            }
825        }
826    }
827
828    async fn apply_migration_once(
829        &self,
830        conn: &mut sqlx::postgres::PgConnection,
831        migration: &Migration,
832    ) -> Result<()> {
833        // Remove comment lines and split SQL into individual statements
834        let sql = migration.sql.trim();
835        let cleaned_sql: String = sql
836            .lines()
837            .map(|line| {
838                // Remove full-line comments
839                if let Some(idx) = line.find("--") {
840                    // Check if -- is inside a string (simple check)
841                    let before = &line[..idx];
842                    if before.matches('\'').count() % 2 == 0 {
843                        // Even number of quotes means -- is not in a string
844                        line[..idx].trim()
845                    } else {
846                        line
847                    }
848                } else {
849                    line
850                }
851            })
852            .filter(|line| !line.is_empty())
853            .collect::<Vec<_>>()
854            .join("\n");
855
856        // Split by semicolon, but respect dollar-quoted strings ($$...$$)
857        let statements = Self::split_sql_statements(&cleaned_sql);
858
859        tracing::debug!(
860            "Executing {} statements for migration {}",
861            statements.len(),
862            migration.version
863        );
864
865        let mut tx = conn.begin().await?;
866        let result =
867            async {
868                sqlx::query(DDL_LOCK_TIMEOUT_SQL).execute(&mut *tx).await?;
869                sqlx::query(&Self::migration_search_path_stmt(&self.schema_name))
870                    .execute(&mut *tx)
871                    .await?;
872                for (idx, statement) in statements.iter().enumerate() {
873                    if !statement.trim().is_empty() {
874                        tracing::debug!(
875                            "Executing statement {} of {}: {}...",
876                            idx + 1,
877                            statements.len(),
878                            &statement.chars().take(50).collect::<String>()
879                        );
880                        sqlx::query(statement)
881                            .execute(&mut *tx)
882                            .await
883                            .map_err(|error| {
884                                let message = format!(
885                                    "Failed to execute statement {} in migration {}: {error}\nStatement: {}",
886                                    idx + 1, migration.version, statement
887                                );
888                                anyhow::Error::new(error).context(message)
889                            })?;
890                    }
891                }
892
893                sqlx::query(&format!(
894                    "INSERT INTO {}._duroxide_migrations (version, name) VALUES ($1, $2)",
895                    self.schema_name
896                ))
897                .bind(migration.version)
898                .bind(&migration.name)
899                .execute(&mut *tx)
900                .await?;
901                Ok(())
902            }
903            .await;
904
905        Self::finish_ddl(tx, result).await?;
906
907        tracing::info!(
908            "Applied migration {}: {}",
909            migration.version,
910            migration.name
911        );
912
913        Ok(())
914    }
915}
916
917#[cfg(test)]
918mod tests {
919    use super::*;
920
921    #[tokio::test]
922    async fn migration_connection_is_reused_after_successful_unlock() {
923        dotenvy::dotenv().ok();
924        let Ok(url) = std::env::var("DATABASE_URL") else {
925            eprintln!("DATABASE_URL not set; skipping migration connection database test");
926            return;
927        };
928        let pool = sqlx::postgres::PgPoolOptions::new()
929            .min_connections(1)
930            .max_connections(1)
931            .connect(&url)
932            .await
933            .unwrap();
934        let mut control = sqlx::PgConnection::connect(&url).await.unwrap();
935        let schema = format!("reuse_migration_{}", uuid::Uuid::new_v4().simple());
936        let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
937        let original_pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
938            .fetch_one(&pool)
939            .await
940            .unwrap();
941        let mut results = Vec::new();
942        for notifications in [false, false, true] {
943            runner
944                .migrate_with_notifications(notifications)
945                .await
946                .unwrap();
947            let pid: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
948                .fetch_one(&pool)
949                .await
950                .unwrap();
951            let unlocked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)")
952                .bind(runner.advisory_lock_key())
953                .fetch_one(&mut control)
954                .await
955                .unwrap();
956            results.push((pid, unlocked));
957        }
958        pool.close().await;
959        sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
960            .execute(&mut control)
961            .await
962            .unwrap();
963        for (pid, unlocked) in results {
964            assert_eq!(
965                pid, original_pid,
966                "migration success must not force a new connection"
967            );
968            assert!(
969                unlocked,
970                "the reused connection must not retain the migration lock"
971            );
972        }
973    }
974
975    #[tokio::test]
976    async fn migration_connection_is_discarded_when_unlock_is_not_confirmed() {
977        dotenvy::dotenv().ok();
978        let Ok(url) = std::env::var("DATABASE_URL") else {
979            eprintln!("DATABASE_URL not set; skipping migration unlock database test");
980            return;
981        };
982        let pool = sqlx::postgres::PgPoolOptions::new()
983            .min_connections(1)
984            .max_connections(1)
985            .connect(&url)
986            .await
987            .unwrap();
988        let mut control = sqlx::PgConnection::connect(&url).await.unwrap();
989        let schema = format!("lost_migration_lock_{}", uuid::Uuid::new_v4().simple());
990        let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
991        sqlx::query(&format!("CREATE SCHEMA {schema}"))
992            .execute(&mut control)
993            .await
994            .unwrap();
995        runner.ensure_migration_table(&mut control).await.unwrap();
996        let versions: Vec<_> = MigrationRunner::load_migrations()
997            .unwrap()
998            .iter()
999            .map(|m| m.version)
1000            .collect();
1001        let last = versions.last().unwrap();
1002        sqlx::Executor::execute(&mut control, format!(
1003            "CREATE FUNCTION {schema}.release_lock_early() RETURNS TRIGGER LANGUAGE plpgsql AS $$
1004             BEGIN PERFORM pg_advisory_unlock_all(); RETURN NEW; END $$;
1005             CREATE TRIGGER release_lock_early AFTER INSERT ON {schema}._duroxide_migrations
1006             FOR EACH ROW WHEN (NEW.version = {last}) EXECUTE FUNCTION {schema}.release_lock_early();"
1007        ).as_str()).await.unwrap();
1008        let before: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
1009            .fetch_one(&pool)
1010            .await
1011            .unwrap();
1012        let error = runner
1013            .migrate()
1014            .await
1015            .expect_err("an unconfirmed unlock is not success");
1016        let after: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
1017            .fetch_one(&pool)
1018            .await
1019            .unwrap();
1020        let applied = runner.get_applied_versions(&mut control).await.unwrap();
1021        let unlocked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)")
1022            .bind(runner.advisory_lock_key())
1023            .fetch_one(&mut control)
1024            .await
1025            .unwrap();
1026        pool.close().await;
1027        sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
1028            .execute(&mut control)
1029            .await
1030            .unwrap();
1031        assert!(
1032            error
1033                .to_string()
1034                .contains("Migration advisory lock was not held"),
1035            "{error:#}"
1036        );
1037        assert_ne!(
1038            after, before,
1039            "failed unlock must not return the connection to the pool"
1040        );
1041        assert_eq!(
1042            applied, versions,
1043            "a cleanup error must not rewrite committed migration records"
1044        );
1045        assert!(unlocked);
1046    }
1047
1048    #[tokio::test]
1049    async fn migration_connection_is_discarded_when_lock_acquisition_is_cancelled() {
1050        dotenvy::dotenv().ok();
1051        let Ok(url) = std::env::var("DATABASE_URL") else {
1052            eprintln!("DATABASE_URL not set; skipping migration cancellation database test");
1053            return;
1054        };
1055        let pool = sqlx::postgres::PgPoolOptions::new()
1056            .min_connections(1)
1057            .max_connections(1)
1058            .connect(&url)
1059            .await
1060            .unwrap();
1061        let mut control = sqlx::PgConnection::connect(&url).await.unwrap();
1062        let schema = format!("cancel_migration_{}", uuid::Uuid::new_v4().simple());
1063        let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
1064        let key = runner.advisory_lock_key();
1065        let before: i32 = sqlx::query_scalar("SELECT pg_backend_pid()")
1066            .fetch_one(&pool)
1067            .await
1068            .unwrap();
1069        sqlx::query("SELECT pg_advisory_lock($1)")
1070            .bind(key)
1071            .execute(&mut control)
1072            .await
1073            .unwrap();
1074        let migration = tokio::spawn(async move { runner.migrate().await });
1075        let waiting = tokio::time::timeout(Duration::from_secs(3), async {
1076            loop {
1077                let blocked: bool = sqlx::query_scalar(
1078                    "SELECT EXISTS(SELECT 1 FROM pg_stat_activity WHERE pid = $1 AND wait_event = 'advisory')",
1079                ).bind(before).fetch_one(&mut control).await.unwrap();
1080                if blocked {
1081                    break;
1082                }
1083                tokio::time::sleep(Duration::from_millis(10)).await;
1084            }
1085        }).await;
1086        migration.abort();
1087        assert!(migration.await.unwrap_err().is_cancelled());
1088        sqlx::query("SELECT pg_advisory_unlock($1)")
1089            .bind(key)
1090            .execute(&mut control)
1091            .await
1092            .unwrap();
1093        let after = tokio::time::timeout(
1094            Duration::from_secs(3),
1095            sqlx::query_scalar::<_, i32>("SELECT pg_backend_pid()").fetch_one(&pool),
1096        )
1097        .await
1098        .expect("cancellation must release the pool slot")
1099        .unwrap();
1100        let exited = tokio::time::timeout(Duration::from_secs(3), async {
1101            loop {
1102                let gone: bool = sqlx::query_scalar(
1103                    "SELECT NOT EXISTS(SELECT 1 FROM pg_stat_activity WHERE pid = $1)",
1104                )
1105                .bind(before)
1106                .fetch_one(&mut control)
1107                .await
1108                .unwrap();
1109                if gone {
1110                    break;
1111                }
1112                tokio::time::sleep(Duration::from_millis(10)).await;
1113            }
1114        })
1115        .await;
1116        let absent: bool = sqlx::query_scalar("SELECT to_regnamespace($1) IS NULL")
1117            .bind(&schema)
1118            .fetch_one(&mut control)
1119            .await
1120            .unwrap();
1121        let unlocked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock($1)")
1122            .bind(key)
1123            .fetch_one(&mut control)
1124            .await
1125            .unwrap();
1126        pool.close().await;
1127        sqlx::query(&format!("DROP SCHEMA IF EXISTS {schema} CASCADE"))
1128            .execute(&mut control)
1129            .await
1130            .unwrap();
1131        waiting.expect("migration must reach the advisory-lock wait");
1132        exited.expect("the cancelled session must exit rather than keep its advisory lock");
1133        assert_ne!(after, before);
1134        assert!(
1135            absent,
1136            "cancellation before acquiring the lock must not apply DDL"
1137        );
1138        assert!(
1139            unlocked,
1140            "no cancelled session may retain the migration lock"
1141        );
1142    }
1143
1144    #[tokio::test]
1145    async fn migration_statement_display_preserves_database_message_and_source() {
1146        dotenvy::dotenv().ok();
1147        let Ok(url) = std::env::var("DATABASE_URL") else {
1148            eprintln!("DATABASE_URL not set; skipping migration error database test");
1149            return;
1150        };
1151        let pool = sqlx::postgres::PgPoolOptions::new()
1152            .max_connections(1)
1153            .connect(&url)
1154            .await
1155            .unwrap();
1156        let schema = format!("migration_error_{}", uuid::Uuid::new_v4().simple());
1157        let runner = MigrationRunner::new(Arc::new(pool.clone()), schema.clone());
1158        let mut connection = pool.acquire().await.unwrap();
1159        sqlx::query(&format!("CREATE SCHEMA {schema}"))
1160            .execute(&mut *connection)
1161            .await
1162            .unwrap();
1163        runner
1164            .ensure_migration_table(&mut connection)
1165            .await
1166            .unwrap();
1167        let valid = Migration {
1168            version: 1,
1169            name: "0001_error_fixture.sql".to_string(),
1170            sql: "CREATE TABLE history_probe (id INTEGER PRIMARY KEY, valid BOOLEAN);
1171                  INSERT INTO history_probe VALUES (7, false);
1172                  CREATE FUNCTION validate_history_probe() RETURNS VOID LANGUAGE plpgsql AS $$
1173                  DECLARE bad_id INTEGER;
1174                  BEGIN
1175                      SELECT id INTO bad_id FROM history_probe WHERE NOT valid LIMIT 1;
1176                      IF FOUND THEN
1177                          RAISE EXCEPTION 'Malformed history: instance=damaged-history execution_id=1 event_id=%', bad_id
1178                              USING ERRCODE = '22023';
1179                      END IF;
1180                  END $$;".to_string(),
1181        };
1182        runner
1183            .apply_migration(&mut connection, &valid)
1184            .await
1185            .unwrap();
1186        let snapshot = format!(
1187            "SELECT jsonb_build_object(
1188                'ledger', (SELECT jsonb_agg(to_jsonb(m) ORDER BY version) FROM {schema}._duroxide_migrations m),
1189                'history', (SELECT jsonb_agg(to_jsonb(h) ORDER BY id) FROM {schema}.history_probe h),
1190                'function', pg_get_functiondef('{schema}.validate_history_probe()'::regprocedure))"
1191        );
1192        let before: serde_json::Value = sqlx::query_scalar(&snapshot)
1193            .fetch_one(&mut *connection)
1194            .await
1195            .unwrap();
1196        let invalid = Migration {
1197            version: 2,
1198            name: "0002_validate_history.sql".to_string(),
1199            sql: "INSERT INTO history_probe VALUES (8, true);
1200                  ALTER FUNCTION validate_history_probe() STABLE;
1201                  SELECT validate_history_probe();"
1202                .to_string(),
1203        };
1204        let error = runner
1205            .apply_migration(&mut connection, &invalid)
1206            .await
1207            .unwrap_err();
1208        let after: serde_json::Value = sqlx::query_scalar(&snapshot)
1209            .fetch_one(&mut *connection)
1210            .await
1211            .unwrap();
1212        sqlx::query(&format!("UPDATE {schema}.history_probe SET valid = true"))
1213            .execute(&mut *connection)
1214            .await
1215            .unwrap();
1216        runner
1217            .apply_migration(&mut connection, &invalid)
1218            .await
1219            .unwrap();
1220        let versions = runner.get_applied_versions(&mut connection).await.unwrap();
1221        sqlx::query(&format!("DROP SCHEMA {schema} CASCADE"))
1222            .execute(&mut *connection)
1223            .await
1224            .unwrap();
1225        drop(connection);
1226        pool.close().await;
1227        assert_eq!(
1228            after, before,
1229            "failed migration must preserve its ledger, function, and history"
1230        );
1231        assert_eq!(versions, vec![1, 2]);
1232        let database_error = error
1233            .downcast_ref::<sqlx::Error>()
1234            .and_then(sqlx::Error::as_database_error)
1235            .expect("retain the database source");
1236        assert_eq!(database_error.code().as_deref(), Some("22023"));
1237        let display = error.to_string();
1238        for expected in [
1239            "Failed to execute statement 3 in migration 2",
1240            "Malformed history: instance=damaged-history execution_id=1 event_id=7",
1241            "Statement: SELECT validate_history_probe();",
1242        ] {
1243            assert!(
1244                display.contains(expected),
1245                "missing {expected:?} in Display: {display}"
1246            );
1247        }
1248    }
1249
1250    #[tokio::test]
1251    async fn ddl_retry_logs_sqlstate_and_full_error_context() {
1252        #[derive(Clone, Default)]
1253        struct Capture(Arc<std::sync::Mutex<Vec<u8>>>);
1254
1255        impl std::io::Write for Capture {
1256            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
1257                self.0.lock().unwrap().extend_from_slice(bytes);
1258                Ok(bytes.len())
1259            }
1260
1261            fn flush(&mut self) -> std::io::Result<()> {
1262                Ok(())
1263            }
1264        }
1265
1266        dotenvy::dotenv().ok();
1267        let Ok(url) = std::env::var("DATABASE_URL") else {
1268            eprintln!("DATABASE_URL not set; skipping DDL logging database test");
1269            return;
1270        };
1271        let pool = sqlx::postgres::PgPoolOptions::new()
1272            .max_connections(1)
1273            .connect(&url)
1274            .await
1275            .unwrap();
1276        let runner = MigrationRunner::new(Arc::new(pool.clone()), "diagnostic_test".to_string());
1277        let captured = Capture::default();
1278        let writer = captured.clone();
1279        let subscriber = tracing_subscriber::fmt()
1280            .without_time()
1281            .with_ansi(false)
1282            .with_env_filter("off,duroxide_pg::migrations=warn")
1283            .with_writer(move || writer.clone())
1284            .finish();
1285        let _guard = tracing::subscriber::set_default(subscriber);
1286        for (code, message) in [
1287            ("40P01", "simulated migration deadlock"),
1288            ("55P03", "simulated migration lock timeout"),
1289        ] {
1290            let error = sqlx::query(&format!(
1291                "DO $$ BEGIN RAISE EXCEPTION '{message}' USING ERRCODE = '{code}'; END $$"
1292            ))
1293            .execute(&pool)
1294            .await
1295            .unwrap_err();
1296            let error = anyhow::Error::new(error).context("outer migration statement context");
1297            assert!(
1298                runner
1299                    .retry_ddl(
1300                        &error,
1301                        Instant::now() + Duration::from_secs(5),
1302                        "test migration"
1303                    )
1304                    .await
1305            );
1306            let output = String::from_utf8(captured.0.lock().unwrap().clone()).unwrap();
1307            assert!(
1308                output.contains("sqlstate=") && output.contains(code),
1309                "{output}"
1310            );
1311            assert!(
1312                output.contains("outer migration statement context") && output.contains(message),
1313                "{output}"
1314            );
1315        }
1316        pool.close().await;
1317    }
1318
1319    #[test]
1320    fn embedded_migration_versions_are_unique_and_increasing() {
1321        let migrations = MigrationRunner::load_migrations().expect("load embedded migrations");
1322        assert!(!migrations.is_empty(), "expected embedded SQL migrations");
1323        for pair in migrations.windows(2) {
1324            assert!(
1325                pair[0].version < pair[1].version,
1326                "embedded migrations must have unique, increasing versions: {} then {}",
1327                pair[0].name,
1328                pair[1].name,
1329            );
1330        }
1331    }
1332
1333    #[test]
1334    fn migration_search_path_pins_pg_temp_last() {
1335        // The security property: pg_temp must be present and last, so temporary
1336        // objects cannot shadow the unqualified references a migration relies on
1337        // the search_path to resolve.
1338        let stmt = MigrationRunner::migration_search_path_stmt("duroxide");
1339        assert_eq!(stmt, "SET LOCAL search_path TO duroxide, pg_temp");
1340    }
1341}