Skip to main content

duroxide_pg/
migrations.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use anyhow::Result;
5use include_dir::{include_dir, Dir};
6use sqlx::Connection;
7use sqlx::PgPool;
8use std::sync::Arc;
9
10static MIGRATIONS: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
11
12/// Migration metadata
13#[derive(Debug)]
14struct Migration {
15    version: i64,
16    name: String,
17    sql: String,
18}
19
20/// Migration runner that handles schema-qualified migrations
21pub struct MigrationRunner {
22    pool: Arc<PgPool>,
23    schema_name: String,
24}
25
26impl MigrationRunner {
27    /// Create a new migration runner
28    pub fn new(pool: Arc<PgPool>, schema_name: String) -> Self {
29        Self { pool, schema_name }
30    }
31
32    fn advisory_lock_key(&self) -> i64 {
33        // Stable 64-bit FNV-1a hash over (namespace + schema name).
34        // This avoids using Rust's DefaultHasher (randomized per-process).
35        const OFFSET: u64 = 0xcbf29ce484222325;
36        const PRIME: u64 = 0x100000001b3;
37
38        let mut hash = OFFSET;
39        for b in b"duroxide_pg:migrations:" {
40            hash ^= *b as u64;
41            hash = hash.wrapping_mul(PRIME);
42        }
43        for b in self.schema_name.as_bytes() {
44            hash ^= *b as u64;
45            hash = hash.wrapping_mul(PRIME);
46        }
47
48        hash as i64
49    }
50
51    async fn lock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
52        let key = self.advisory_lock_key();
53        // Session lock (not xact lock) so it spans multiple transactions.
54        // We explicitly unlock at the end.
55        sqlx::query("SELECT pg_advisory_lock($1)")
56            .bind(key)
57            .execute(&mut *conn)
58            .await?;
59        Ok(())
60    }
61
62    async fn unlock_for_migrations(&self, conn: &mut sqlx::postgres::PgConnection) {
63        let key = self.advisory_lock_key();
64        // Best-effort unlock.
65        let _ = sqlx::query("SELECT pg_advisory_unlock($1)")
66            .bind(key)
67            .execute(&mut *conn)
68            .await;
69    }
70
71    /// Run all pending migrations
72    pub async fn migrate(&self) -> Result<()> {
73        let mut conn = self.pool.acquire().await?;
74        let conn = &mut *conn;
75        self.lock_for_migrations(conn).await?;
76
77        // Reject unknown migrations while holding the advisory lock so that an
78        // older binary cannot rewrite a schema that is ahead of its code.
79        // Short-circuit: do NOT run migrate_inner if unknown migrations are
80        // detected.
81        let result = match self.check_no_unknown_migrations(conn).await {
82            Ok(()) => self.migrate_inner(conn).await,
83            Err(e) => Err(e),
84        };
85        self.unlock_for_migrations(conn).await;
86
87        result
88    }
89
90    /// Verify that the migration tracking table exists and that every embedded
91    /// migration has already been applied. Does not take the migration
92    /// advisory lock and does not create or modify any database objects.
93    ///
94    /// Returns an error if the `_duroxide_migrations` table is missing in
95    /// `schema_name` or if any bundled migration version is absent from it.
96    ///
97    /// Intended for processes that must not perform DDL (e.g. application
98    /// backends, where a separately privileged worker is responsible for
99    /// applying schema changes).
100    pub async fn verify(&self) -> Result<()> {
101        let mut conn = self.pool.acquire().await?;
102        let conn = &mut *conn;
103
104        // Check that the tracking table exists in the target schema.
105        let table_exists: bool = sqlx::query_scalar(
106            "SELECT EXISTS(SELECT 1 FROM information_schema.tables \
107             WHERE table_schema = $1 AND table_name = '_duroxide_migrations')",
108        )
109        .bind(&self.schema_name)
110        .fetch_one(&mut *conn)
111        .await?;
112
113        if !table_exists {
114            anyhow::bail!(
115                "duroxide migrations not initialized: schema {:?} does not \
116                 contain _duroxide_migrations. Construct a provider with \
117                 MigrationPolicy::ApplyAll (the default) from a process with \
118                 DDL privileges before using MigrationPolicy::VerifyOnly.",
119                self.schema_name
120            );
121        }
122
123        // Reject schemas that have migrations the running binary does not
124        // recognize (schema is ahead of the code).
125        self.check_no_unknown_migrations(conn).await?;
126
127        let migrations = self.load_migrations()?;
128        let applied: std::collections::HashSet<i64> =
129            self.get_applied_versions(conn).await?.into_iter().collect();
130
131        let mut missing: Vec<i64> = migrations
132            .iter()
133            .map(|m| m.version)
134            .filter(|v| !applied.contains(v))
135            .collect();
136        missing.sort_unstable();
137
138        if !missing.is_empty() {
139            anyhow::bail!(
140                "duroxide migrations not up to date in schema {:?}: missing \
141                 versions {:?}. Run migrations from a provider configured with \
142                 MigrationPolicy::ApplyAll before constructing VerifyOnly \
143                 providers.",
144                self.schema_name,
145                missing,
146            );
147        }
148
149        if !self.check_tables_exist(conn).await.unwrap_or(false) {
150            anyhow::bail!(
151                "duroxide migrations recorded as complete in schema {:?}, but \
152                 core tables are missing. The schema may be corrupted; run \
153                 migrations from a provider configured with \
154                 MigrationPolicy::ApplyAll before constructing VerifyOnly \
155                 providers.",
156                self.schema_name,
157            );
158        }
159
160        Ok(())
161    }
162
163    /// Check that the database has no migrations the running binary does not
164    /// recognize. Used by both `migrate()` (to refuse running DDL against a
165    /// schema ahead of the code) and `verify()` (to refuse claiming
166    /// successful verification of an unknown schema).
167    ///
168    /// Returns `Ok(())` if the tracking table does not yet exist: under
169    /// `ApplyAll` it will be created by `migrate_inner`, and under
170    /// `VerifyOnly` the missing table is reported separately before this is
171    /// called.
172    async fn check_no_unknown_migrations(
173        &self,
174        conn: &mut sqlx::postgres::PgConnection,
175    ) -> Result<()> {
176        let tracking_exists: bool = sqlx::query_scalar(
177            "SELECT EXISTS(SELECT 1 FROM information_schema.tables \
178             WHERE table_schema = $1 AND table_name = '_duroxide_migrations')",
179        )
180        .bind(&self.schema_name)
181        .fetch_one(&mut *conn)
182        .await?;
183
184        if !tracking_exists {
185            return Ok(());
186        }
187
188        let applied = self.get_applied_versions(conn).await?;
189        let expected: std::collections::HashSet<i64> = self
190            .load_migrations()?
191            .into_iter()
192            .map(|m| m.version)
193            .collect();
194
195        let mut unknown: Vec<i64> = applied
196            .into_iter()
197            .filter(|v| !expected.contains(v))
198            .collect();
199        unknown.sort_unstable();
200
201        if !unknown.is_empty() {
202            anyhow::bail!(
203                "schema {:?} has migrations not recognized by this version of \
204                 the code: {:?}. The database schema is ahead of the code. \
205                 Update the code to a compatible version.",
206                self.schema_name,
207                unknown,
208            );
209        }
210
211        Ok(())
212    }
213
214    async fn migrate_inner(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
215        // Ensure schema exists
216        if self.schema_name != "public" {
217            sqlx::query(&format!("CREATE SCHEMA IF NOT EXISTS {}", self.schema_name))
218                .execute(&mut *conn)
219                .await?;
220        }
221
222        // Load migrations from filesystem
223        let migrations = self.load_migrations()?;
224
225        tracing::debug!(
226            "Loaded {} migrations for schema {}",
227            migrations.len(),
228            self.schema_name
229        );
230
231        // Ensure migration tracking table exists (in the schema)
232        self.ensure_migration_table(conn).await?;
233
234        // Get applied migrations
235        let applied_versions = self.get_applied_versions(conn).await?;
236
237        tracing::debug!("Applied migrations: {:?}", applied_versions);
238
239        // Check if key tables exist - if not, we need to re-run migrations even if marked as applied
240        // This handles the case where cleanup dropped tables but not the migration tracking table
241        let tables_exist = self.check_tables_exist(conn).await.unwrap_or(false);
242
243        // Apply pending migrations (or re-apply if tables don't exist)
244        for migration in migrations {
245            let should_apply = if !applied_versions.contains(&migration.version) {
246                true // New migration
247            } else if !tables_exist {
248                // Migration was applied but tables don't exist - re-apply
249                tracing::warn!(
250                    "Migration {} is marked as applied but tables don't exist, re-applying",
251                    migration.version
252                );
253                // Remove the old migration record so we can re-apply
254                sqlx::query(&format!(
255                    "DELETE FROM {}._duroxide_migrations WHERE version = $1",
256                    self.schema_name
257                ))
258                .bind(migration.version)
259                .execute(&mut *conn)
260                .await?;
261                true
262            } else {
263                false // Already applied and tables exist
264            };
265
266            if should_apply {
267                tracing::debug!(
268                    "Applying migration {}: {}",
269                    migration.version,
270                    migration.name
271                );
272                self.apply_migration(conn, &migration).await?;
273            } else {
274                tracing::debug!(
275                    "Skipping migration {}: {} (already applied)",
276                    migration.version,
277                    migration.name
278                );
279            }
280        }
281
282        Ok(())
283    }
284
285    /// Load migrations from the embedded migrations directory
286    fn load_migrations(&self) -> Result<Vec<Migration>> {
287        let mut migrations = Vec::new();
288
289        // Get all files from embedded directory
290        let mut files: Vec<_> = MIGRATIONS
291            .files()
292            .filter(|file| file.path().extension().and_then(|ext| ext.to_str()) == Some("sql"))
293            .collect();
294
295        // Sort by path to ensure consistent ordering
296        files.sort_by_key(|f| f.path());
297
298        for file in files {
299            let file_name = file
300                .path()
301                .file_name()
302                .and_then(|n| n.to_str())
303                .ok_or_else(|| anyhow::anyhow!("Invalid filename in migrations"))?;
304
305            let sql = file
306                .contents_utf8()
307                .ok_or_else(|| anyhow::anyhow!("Migration file is not valid UTF-8: {file_name}"))?
308                .to_string();
309
310            let version = self.parse_version(file_name)?;
311            let name = file_name.to_string();
312
313            migrations.push(Migration { version, name, sql });
314        }
315
316        Ok(migrations)
317    }
318
319    /// Parse version number from migration filename (e.g., "0001_initial.sql" -> 1)
320    fn parse_version(&self, filename: &str) -> Result<i64> {
321        let version_str = filename
322            .split('_')
323            .next()
324            .ok_or_else(|| anyhow::anyhow!("Invalid migration filename: {filename}"))?;
325
326        version_str
327            .parse::<i64>()
328            .map_err(|e| anyhow::anyhow!("Invalid migration version {version_str}: {e}"))
329    }
330
331    /// Ensure migration tracking table exists
332    async fn ensure_migration_table(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<()> {
333        // Create migration table in the target schema
334        sqlx::query(&format!(
335            r#"
336            CREATE TABLE IF NOT EXISTS {}._duroxide_migrations (
337                version BIGINT PRIMARY KEY,
338                name TEXT NOT NULL,
339                applied_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
340            )
341            "#,
342            self.schema_name
343        ))
344        .execute(&mut *conn)
345        .await?;
346
347        Ok(())
348    }
349
350    /// Check if key tables exist
351    async fn check_tables_exist(&self, conn: &mut sqlx::postgres::PgConnection) -> Result<bool> {
352        // Check if instances table exists (as a proxy for all tables)
353        let exists: bool = sqlx::query_scalar(
354            "SELECT EXISTS(SELECT 1 FROM information_schema.tables WHERE table_schema = $1 AND table_name = 'instances')",
355        )
356        .bind(&self.schema_name)
357        .fetch_one(&mut *conn)
358        .await?;
359
360        Ok(exists)
361    }
362
363    /// Get list of applied migration versions
364    async fn get_applied_versions(
365        &self,
366        conn: &mut sqlx::postgres::PgConnection,
367    ) -> Result<Vec<i64>> {
368        let versions: Vec<i64> = sqlx::query_scalar(&format!(
369            "SELECT version FROM {}._duroxide_migrations ORDER BY version",
370            self.schema_name
371        ))
372        .fetch_all(&mut *conn)
373        .await?;
374
375        Ok(versions)
376    }
377
378    /// Split SQL into statements, respecting dollar-quoted strings ($$...$$)
379    /// This handles stored procedures and other constructs that use dollar-quoting
380    fn split_sql_statements(sql: &str) -> Vec<String> {
381        let mut statements = Vec::new();
382        let mut current_statement = String::new();
383        let chars: Vec<char> = sql.chars().collect();
384        let mut i = 0;
385        let mut in_dollar_quote = false;
386        let mut dollar_tag: Option<String> = None;
387
388        while i < chars.len() {
389            let ch = chars[i];
390
391            if !in_dollar_quote {
392                // Check for start of dollar-quoted string
393                if ch == '$' {
394                    let mut tag = String::new();
395                    tag.push(ch);
396                    i += 1;
397
398                    // Collect the tag (e.g., $$, $tag$, $function$)
399                    while i < chars.len() {
400                        let next_ch = chars[i];
401                        if next_ch == '$' {
402                            tag.push(next_ch);
403                            dollar_tag = Some(tag.clone());
404                            in_dollar_quote = true;
405                            current_statement.push_str(&tag);
406                            i += 1;
407                            break;
408                        } else if next_ch.is_alphanumeric() || next_ch == '_' {
409                            tag.push(next_ch);
410                            i += 1;
411                        } else {
412                            // Not a dollar quote, just a $ character
413                            current_statement.push(ch);
414                            break;
415                        }
416                    }
417                } else if ch == ';' {
418                    // End of statement (only if not in dollar quote)
419                    current_statement.push(ch);
420                    let trimmed = current_statement.trim().to_string();
421                    if !trimmed.is_empty() {
422                        statements.push(trimmed);
423                    }
424                    current_statement.clear();
425                    i += 1;
426                } else {
427                    current_statement.push(ch);
428                    i += 1;
429                }
430            } else {
431                // Inside dollar-quoted string
432                current_statement.push(ch);
433
434                // Check for end of dollar-quoted string
435                if ch == '$' {
436                    let tag = dollar_tag.as_ref().unwrap();
437                    let mut matches = true;
438
439                    // Check if the following characters match the closing tag
440                    for (j, tag_char) in tag.chars().enumerate() {
441                        if j == 0 {
442                            continue; // Skip first $ (we already matched it)
443                        }
444                        if i + j >= chars.len() || chars[i + j] != tag_char {
445                            matches = false;
446                            break;
447                        }
448                    }
449
450                    if matches {
451                        // Found closing tag - consume remaining tag characters
452                        for _ in 0..(tag.len() - 1) {
453                            if i + 1 < chars.len() {
454                                current_statement.push(chars[i + 1]);
455                                i += 1;
456                            }
457                        }
458                        in_dollar_quote = false;
459                        dollar_tag = None;
460                    }
461                }
462                i += 1;
463            }
464        }
465
466        // Add remaining statement if any
467        let trimmed = current_statement.trim().to_string();
468        if !trimmed.is_empty() {
469            statements.push(trimmed);
470        }
471
472        statements
473    }
474
475    /// Build the `SET LOCAL search_path` statement used while applying a migration.
476    ///
477    /// `pg_temp` is pinned last so it sits at the lowest priority instead of its
478    /// implicit highest-priority position, preventing a temporary object from
479    /// shadowing the unqualified references a migration resolves via the
480    /// `search_path`. This is defense-in-depth (CVE-2018-1058); `pg_catalog` is left
481    /// unlisted so PostgreSQL keeps it implicitly first.
482    ///
483    /// `schema_name` is validated at provider construction
484    /// (`^[A-Za-z_][A-Za-z0-9_]*$`), so direct interpolation here is safe.
485    fn migration_search_path_stmt(schema_name: &str) -> String {
486        format!("SET LOCAL search_path TO {schema_name}, pg_temp")
487    }
488
489    /// Apply a single migration
490    async fn apply_migration(
491        &self,
492        conn: &mut sqlx::postgres::PgConnection,
493        migration: &Migration,
494    ) -> Result<()> {
495        // Start transaction
496        let mut tx = conn.begin().await?;
497
498        // Set search_path for this transaction.
499        //
500        // `pg_temp` is pinned explicitly at the lowest priority. Without it,
501        // `pg_temp` keeps its implicit highest-priority position, which would let a
502        // temporary object shadow the unqualified references this migration relies on
503        // the search_path to resolve. This is defense-in-depth (CVE-2018-1058
504        // guidance); see `migration_search_path_stmt` for the threat model.
505        sqlx::query(&Self::migration_search_path_stmt(&self.schema_name))
506            .execute(&mut *tx)
507            .await?;
508
509        // Remove comment lines and split SQL into individual statements
510        let sql = migration.sql.trim();
511        let cleaned_sql: String = sql
512            .lines()
513            .map(|line| {
514                // Remove full-line comments
515                if let Some(idx) = line.find("--") {
516                    // Check if -- is inside a string (simple check)
517                    let before = &line[..idx];
518                    if before.matches('\'').count() % 2 == 0 {
519                        // Even number of quotes means -- is not in a string
520                        line[..idx].trim()
521                    } else {
522                        line
523                    }
524                } else {
525                    line
526                }
527            })
528            .filter(|line| !line.is_empty())
529            .collect::<Vec<_>>()
530            .join("\n");
531
532        // Split by semicolon, but respect dollar-quoted strings ($$...$$)
533        let statements = Self::split_sql_statements(&cleaned_sql);
534
535        tracing::debug!(
536            "Executing {} statements for migration {}",
537            statements.len(),
538            migration.version
539        );
540
541        for (idx, statement) in statements.iter().enumerate() {
542            if !statement.trim().is_empty() {
543                tracing::debug!(
544                    "Executing statement {} of {}: {}...",
545                    idx + 1,
546                    statements.len(),
547                    &statement.chars().take(50).collect::<String>()
548                );
549                sqlx::query(statement)
550                    .execute(&mut *tx)
551                    .await
552                    .map_err(|e| {
553                        anyhow::anyhow!(
554                            "Failed to execute statement {} in migration {}: {}\nStatement: {}",
555                            idx + 1,
556                            migration.version,
557                            e,
558                            statement
559                        )
560                    })?;
561            }
562        }
563
564        // Record migration as applied
565        sqlx::query(&format!(
566            "INSERT INTO {}._duroxide_migrations (version, name) VALUES ($1, $2)",
567            self.schema_name
568        ))
569        .bind(migration.version)
570        .bind(&migration.name)
571        .execute(&mut *tx)
572        .await?;
573
574        // Commit transaction
575        tx.commit().await?;
576
577        tracing::info!(
578            "Applied migration {}: {}",
579            migration.version,
580            migration.name
581        );
582
583        Ok(())
584    }
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590
591    #[test]
592    fn migration_search_path_pins_pg_temp_last() {
593        // The security property: pg_temp must be present and last, so temporary
594        // objects cannot shadow the unqualified references a migration relies on
595        // the search_path to resolve.
596        let stmt = MigrationRunner::migration_search_path_stmt("duroxide");
597        assert_eq!(stmt, "SET LOCAL search_path TO duroxide, pg_temp");
598    }
599}