Skip to main content

riverqueue_migrate/
lib.rs

1// The README's example uses both backends, so it's the crate documentation
2// (and its example runs as a doctest) when both are enabled, as on docs.rs.
3#![cfg_attr(
4    all(feature = "postgres", feature = "sqlite"),
5    doc = include_str!("../README.md")
6)]
7#![cfg_attr(
8    not(all(feature = "postgres", feature = "sqlite")),
9    doc = "River's PostgreSQL and SQLite migrations for Rust. The full crate documentation, \
10           from the README, builds with both the `postgres` and `sqlite` features, as on \
11           [docs.rs](https://docs.rs/riverqueue-migrate)."
12)]
13#![cfg_attr(docsrs, feature(doc_cfg))]
14#![forbid(unsafe_code)]
15#![warn(missing_docs)]
16
17#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
18compile_error!("riverqueue-migrate requires at least one database feature: `postgres` or `sqlite`");
19
20use std::time::Duration;
21#[cfg(feature = "postgres")]
22use std::time::Instant;
23
24#[cfg(feature = "postgres")]
25use sqlx::{PgPool, Row};
26use thiserror::Error;
27
28mod schema;
29#[cfg(feature = "sqlite")]
30mod sqlite;
31
32pub use schema::{SCHEMA_MAX_LEN, SchemaName, SchemaNameError};
33
34#[cfg(feature = "sqlite")]
35pub use sqlite::{SQLITE_MIGRATIONS, SqliteMigrator};
36
37#[cfg(feature = "postgres")]
38const TEMPLATE_SCHEMA: &str = "/* TEMPLATE: schema */";
39
40/// River's main migration line.
41pub const MIGRATION_LINE_MAIN: &str = "main";
42
43/// Latest migration version bundled with this release.
44pub const MIGRATION_VERSION_LATEST: i64 = 8;
45
46#[cfg(feature = "postgres")]
47macro_rules! migration {
48    ($version:literal, $name:literal, $file:literal) => {
49        Migration {
50            down_sql: include_str!(concat!("../migrations/main/", $file, ".down.sql")),
51            name: $name,
52            up_sql: include_str!(concat!("../migrations/main/", $file, ".up.sql")),
53            version: $version,
54        }
55    };
56}
57
58/// One canonical River migration.
59#[derive(Clone, Copy, Debug)]
60#[non_exhaustive]
61pub struct Migration {
62    /// Down migration SQL.
63    pub down_sql: &'static str,
64    /// Human-readable migration name.
65    pub name: &'static str,
66    /// Up migration SQL.
67    pub up_sql: &'static str,
68    /// Monotonically increasing version.
69    pub version: i64,
70}
71
72/// Migration direction.
73#[derive(Clone, Copy, Debug, Eq, PartialEq)]
74pub enum Direction {
75    /// Revert applied migrations.
76    Down,
77    /// Apply outstanding migrations.
78    Up,
79}
80
81/// Controls a migration operation.
82#[derive(Clone, Copy, Debug, Default)]
83pub struct MigrateOpts {
84    /// Report SQL without applying it.
85    dry_run: bool,
86    /// Maximum number of steps. Down migrations default to one step.
87    max_steps: Option<usize>,
88    /// Target schema version. Down excludes the target; `-1` removes River.
89    target_version: Option<i64>,
90}
91
92impl MigrateOpts {
93    /// Creates migration options with no target, step limit, or dry run.
94    #[must_use]
95    pub const fn new() -> Self {
96        Self {
97            dry_run: false,
98            max_steps: None,
99            target_version: None,
100        }
101    }
102
103    /// Returns whether SQL is reported without being applied.
104    #[must_use]
105    pub const fn dry_run(&self) -> bool {
106        self.dry_run
107    }
108
109    /// Returns the maximum number of migration steps.
110    #[must_use]
111    pub const fn max_steps(&self) -> Option<usize> {
112        self.max_steps
113    }
114
115    /// Returns the requested target version.
116    #[must_use]
117    pub const fn target_version(&self) -> Option<i64> {
118        self.target_version
119    }
120
121    /// Reports selected SQL without applying it.
122    #[must_use]
123    pub const fn with_dry_run(mut self, dry_run: bool) -> Self {
124        self.dry_run = dry_run;
125        self
126    }
127
128    /// Limits the number of migration steps.
129    #[must_use]
130    pub const fn with_max_steps(mut self, maximum: usize) -> Self {
131        self.max_steps = Some(maximum);
132        self
133    }
134
135    /// Migrates toward a target schema version. `-1` removes River. An up
136    /// migration whose target is already applied does nothing, even if later
137    /// versions are pending.
138    #[must_use]
139    pub const fn with_target_version(mut self, version: i64) -> Self {
140        self.target_version = Some(version);
141        self
142    }
143}
144
145/// One migration selected or applied by an operation.
146#[derive(Clone, Debug)]
147#[non_exhaustive]
148pub struct MigrateVersion {
149    /// Database execution time, or zero for a dry run.
150    pub duration: Duration,
151    /// Human-readable migration name.
152    pub name: &'static str,
153    /// Rendered SQL.
154    pub sql: String,
155    /// Migration version.
156    pub version: i64,
157}
158
159/// Result of a migration operation.
160#[derive(Clone, Debug)]
161#[non_exhaustive]
162pub struct MigrateResult {
163    /// Direction requested.
164    pub direction: Direction,
165    /// Versions applied or selected.
166    pub versions: Vec<MigrateVersion>,
167}
168
169/// Result of checking whether required migrations are applied.
170///
171/// Its `Display` output describes the unapplied versions, for reporting a
172/// failed validation.
173#[derive(Clone, Debug, Default, Eq, PartialEq)]
174#[non_exhaustive]
175pub struct ValidateResult {
176    /// Required versions that aren't applied, in ascending order.
177    pub unapplied: Vec<i64>,
178}
179
180impl ValidateResult {
181    /// Returns whether every required migration is applied.
182    #[must_use]
183    pub fn is_valid(&self) -> bool {
184        self.unapplied.is_empty()
185    }
186}
187
188impl std::fmt::Display for ValidateResult {
189    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190        if self.is_valid() {
191            formatter.write_str("all required migrations are applied")
192        } else {
193            write!(formatter, "unapplied migrations: {:?}", self.unapplied)
194        }
195    }
196}
197
198/// Canonical PostgreSQL migration bundle.
199#[cfg(feature = "postgres")]
200pub const POSTGRES_MIGRATIONS: [Migration; 8] = [
201    migration!(1, "create_river_migration", "001_create_river_migration"),
202    migration!(2, "initial_schema", "002_initial_schema"),
203    migration!(3, "river_job_tags_non_null", "003_river_job_tags_non_null"),
204    migration!(4, "pending_and_more", "004_pending_and_more"),
205    migration!(5, "migration_unique_client", "005_migration_unique_client"),
206    migration!(6, "bulk_unique", "006_bulk_unique"),
207    migration!(
208        7,
209        "notification_outbox_sqlite_jsonb_and_sql_cleanup",
210        "007_notification_outbox_sqlite_jsonb_and_sql_cleanup"
211    ),
212    migration!(8, "job_id_autoincrement", "008_job_id_autoincrement"),
213];
214
215/// River migration failure.
216#[derive(Debug, Error)]
217#[non_exhaustive]
218pub enum Error {
219    /// A database operation failed.
220    #[error(transparent)]
221    Database(#[from] sqlx::Error),
222
223    /// Migrating down past `version` would delete the migration records of
224    /// other migration lines, which the down migration can't restore.
225    #[error(
226        "found non-main migration lines; version {version:03} is irreversible without losing migration information"
227    )]
228    OtherMigrationLines {
229        /// The migration that would be reverted.
230        version: i64,
231    },
232
233    /// A down migration's target isn't among the applied versions it can
234    /// revert to within its step limit.
235    #[error("version {version} is not in target list of valid migrations to apply")]
236    TargetNotSelected {
237        /// The requested target version.
238        version: i64,
239    },
240
241    /// A target version isn't one of River's migrations.
242    #[error("version {version} is not a River migration")]
243    UnknownVersion {
244        /// The requested target version.
245        version: i64,
246    },
247}
248
249/// Applies and validates River's PostgreSQL migration history.
250#[cfg(feature = "postgres")]
251#[derive(Clone, Debug)]
252pub struct PostgresMigrator {
253    pool: PgPool,
254    schema: SchemaName,
255}
256
257#[cfg(feature = "postgres")]
258impl PostgresMigrator {
259    /// Returns every migration bundled with this crate.
260    #[must_use]
261    pub fn all_versions() -> &'static [Migration] {
262        &POSTGRES_MIGRATIONS
263    }
264
265    /// Creates a migrator for PostgreSQL's current schema.
266    #[must_use]
267    pub fn new(pool: PgPool) -> Self {
268        Self {
269            pool,
270            schema: SchemaName::current(),
271        }
272    }
273
274    /// Returns the migrator with `schema` migrated instead of the
275    /// connection's current schema.
276    #[must_use]
277    pub fn with_schema(mut self, schema: SchemaName) -> Self {
278        self.schema = schema;
279        self
280    }
281
282    /// Returns the schema this migrator migrates.
283    #[must_use]
284    pub const fn schema(&self) -> &SchemaName {
285        &self.schema
286    }
287
288    /// Returns applied main-line versions in ascending order.
289    ///
290    /// # Errors
291    ///
292    /// Returns [`Error::Database`] when the query fails.
293    pub async fn existing_versions(&self) -> Result<Vec<i64>, Error> {
294        let table = self.schema.qualify("river_migration");
295        // Pass the quoted, qualified name through unchanged like Go's
296        // `TableExists`, so a mixed-case schema is not folded to lowercase.
297        let exists: bool = sqlx::query_scalar("SELECT to_regclass($1) IS NOT NULL")
298            .bind(&table)
299            .fetch_one(&self.pool)
300            .await?;
301        if !exists {
302            return Ok(Vec::new());
303        }
304
305        let has_line: bool = sqlx::query_scalar(
306            "SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = coalesce($1, current_schema()) AND table_name = 'river_migration' AND column_name = 'line')",
307        )
308        .bind(self.schema.as_deref())
309        .fetch_one(&self.pool)
310        .await?;
311        let sql = if has_line {
312            format!("SELECT version FROM {table} WHERE line = $1 ORDER BY version")
313        } else {
314            format!("SELECT version FROM {table} ORDER BY version")
315        };
316        let rows = if has_line {
317            sqlx::query(sqlx::AssertSqlSafe(sql))
318                .bind(MIGRATION_LINE_MAIN)
319                .fetch_all(&self.pool)
320                .await?
321        } else {
322            sqlx::query(sqlx::AssertSqlSafe(sql))
323                .fetch_all(&self.pool)
324                .await?
325        };
326        Ok(rows.iter().map(|row| row.get("version")).collect())
327    }
328
329    /// Applies all outstanding up migrations and returns their versions.
330    ///
331    /// # Errors
332    ///
333    /// Returns [`Error::Database`] when a migration fails.
334    ///
335    /// # Cancel safety
336    ///
337    /// Each migration and its record in `river_migration` commit together in
338    /// their own transaction, on a task of their own. Dropping the future
339    /// stops migrating once the migration in progress finishes: it and
340    /// every migration before it stay applied, and migrating again
341    /// continues from there.
342    pub async fn migrate_up(&self) -> Result<Vec<i64>, Error> {
343        Ok(self
344            .migrate(Direction::Up, MigrateOpts::default())
345            .await?
346            .versions
347            .into_iter()
348            .map(|version| version.version)
349            .collect())
350    }
351
352    /// Applies up or down migrations with target, step, and dry-run controls.
353    ///
354    /// Each migration runs in its own transaction, so a failure leaves the
355    /// migrations before it applied.
356    ///
357    /// # Errors
358    ///
359    /// Returns [`Error::UnknownVersion`] when the target version doesn't exist,
360    /// [`Error::TargetNotSelected`] when a down target isn't applied or is
361    /// beyond the step limit, and [`Error::Database`] when a migration fails.
362    ///
363    /// # Cancel safety
364    ///
365    /// Each migration and its record in `river_migration` commit together in
366    /// their own transaction, on a task of their own. Dropping the future
367    /// stops migrating once the migration in progress finishes: it and
368    /// every migration before it stay applied, and migrating again
369    /// continues from there.
370    pub async fn migrate(
371        &self,
372        direction: Direction,
373        opts: MigrateOpts,
374    ) -> Result<MigrateResult, Error> {
375        validate_target(&POSTGRES_MIGRATIONS, opts.target_version, true)?;
376        let applied = self.existing_versions().await?;
377        let selected = select_migrations(&POSTGRES_MIGRATIONS, direction, opts, &applied)?;
378
379        let mut versions = Vec::with_capacity(selected.len());
380        for migration in selected {
381            let sql = self.render(match direction {
382                Direction::Down => migration.down_sql,
383                Direction::Up => migration.up_sql,
384            });
385            let mut duration = Duration::ZERO;
386            if !opts.dry_run {
387                let started_at = Instant::now();
388                // Each migration runs to completion on its own task, so
389                // dropping this future never abandons one partway.
390                let migrator = self.clone();
391                let task_sql = sql.clone();
392                run_to_completion(
393                    async move { migrator.apply(direction, migration, &task_sql).await },
394                )
395                .await?;
396                duration = started_at.elapsed();
397            }
398            versions.push(MigrateVersion {
399                duration,
400                name: migration.name,
401                sql,
402                version: migration.version,
403            });
404        }
405        Ok(MigrateResult {
406            direction,
407            versions,
408        })
409    }
410
411    /// Checks that every migration through an optional target is applied.
412    ///
413    /// # Errors
414    ///
415    /// Returns [`Error::UnknownVersion`] when the target version doesn't exist and
416    /// [`Error::Database`] when reading the applied versions fails.
417    pub async fn validate(&self, target_version: Option<i64>) -> Result<ValidateResult, Error> {
418        validate_target(&POSTGRES_MIGRATIONS, target_version, false)?;
419        let applied = self.existing_versions().await?;
420        Ok(validate_migrations(
421            &POSTGRES_MIGRATIONS,
422            target_version,
423            &applied,
424        ))
425    }
426
427    async fn apply(
428        &self,
429        direction: Direction,
430        migration: Migration,
431        sql: &str,
432    ) -> Result<(), Error> {
433        let mut transaction = self.pool.begin().await?;
434        // The only dynamic fragment is a validated and quoted schema name.
435        sqlx::raw_sql(sqlx::AssertSqlSafe(sql))
436            .execute(&mut *transaction)
437            .await?;
438        let table = self.schema.qualify("river_migration");
439        match direction {
440            Direction::Down if migration.version == 1 => {}
441            Direction::Down if migration.version <= 5 => {
442                sqlx::query(sqlx::AssertSqlSafe(format!(
443                    "DELETE FROM {table} WHERE version = $1"
444                )))
445                .bind(migration.version)
446                .execute(&mut *transaction)
447                .await?;
448            }
449            Direction::Down => {
450                sqlx::query(sqlx::AssertSqlSafe(format!(
451                    "DELETE FROM {table} WHERE line = $1 AND version = $2"
452                )))
453                .bind(MIGRATION_LINE_MAIN)
454                .bind(migration.version)
455                .execute(&mut *transaction)
456                .await?;
457            }
458            Direction::Up if migration.version >= 5 => {
459                sqlx::query(sqlx::AssertSqlSafe(format!(
460                    "INSERT INTO {table} (line, version) VALUES ($1, $2)"
461                )))
462                .bind(MIGRATION_LINE_MAIN)
463                .bind(migration.version)
464                .execute(&mut *transaction)
465                .await?;
466            }
467            Direction::Up => {
468                sqlx::query(sqlx::AssertSqlSafe(format!(
469                    "INSERT INTO {table} (version) VALUES ($1)"
470                )))
471                .bind(migration.version)
472                .execute(&mut *transaction)
473                .await?;
474            }
475        }
476        transaction.commit().await?;
477        Ok(())
478    }
479
480    fn render(&self, sql: &str) -> String {
481        sql.replace(TEMPLATE_SCHEMA, &self.schema.migration_prefix())
482    }
483}
484
485/// Runs a migration step on its own task and waits for it, so the step
486/// finishes even when the caller stops waiting.
487async fn run_to_completion(
488    step: impl std::future::Future<Output = Result<(), Error>> + Send + 'static,
489) -> Result<(), Error> {
490    match tokio::spawn(step).await {
491        Ok(result) => result,
492        Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
493        // The runtime is shutting down and cancelled the task.
494        Err(error) => Err(Error::Database(sqlx::Error::Io(std::io::Error::other(
495            format!("migration task failed: {error}"),
496        )))),
497    }
498}
499
500fn select_migrations(
501    migrations: &'static [Migration],
502    direction: Direction,
503    opts: MigrateOpts,
504    applied: &[i64],
505) -> Result<Vec<Migration>, Error> {
506    // Versions recorded by a newer River release are ignored like Go: up
507    // migrations apply only unapplied known versions, and down migrations
508    // revert only applied known versions.
509    let mut selected = match direction {
510        Direction::Up => migrations
511            .iter()
512            .filter(|migration| !applied.contains(&migration.version))
513            .copied()
514            .collect::<Vec<_>>(),
515        Direction::Down => migrations
516            .iter()
517            .rev()
518            .filter(|migration| applied.contains(&migration.version))
519            .copied()
520            .collect::<Vec<_>>(),
521    };
522
523    // An up migration whose target is already applied does nothing, even
524    // when later versions are pending. Check before the step limit trims
525    // the list, which can also drop a pending target.
526    let target_was_pending = opts
527        .target_version
528        .is_some_and(|target| selected.iter().any(|migration| migration.version == target));
529
530    // Go limits steps before locating the target, so a target outside the
531    // step window is not reached.
532    let maximum = opts
533        .max_steps
534        .or_else(|| (direction == Direction::Down && opts.target_version.is_none()).then_some(1));
535    if let Some(maximum) = maximum {
536        selected.truncate(maximum);
537    }
538
539    if let Some(target) = opts.target_version.filter(|target| *target != -1) {
540        match selected
541            .iter()
542            .position(|migration| migration.version == target)
543        {
544            Some(index) => {
545                selected.truncate(index + 1);
546                // A down target is the version that remains applied.
547                if direction == Direction::Down {
548                    selected.pop();
549                }
550            }
551            None if direction == Direction::Down => {
552                return Err(Error::TargetNotSelected { version: target });
553            }
554            // A pending up target beyond the step limit keeps the trimmed
555            // list; an applied one is a no-op.
556            None if target_was_pending => {}
557            None => selected.clear(),
558        }
559    }
560    Ok(selected)
561}
562
563fn validate_migrations(
564    migrations: &[Migration],
565    target_version: Option<i64>,
566    applied: &[i64],
567) -> ValidateResult {
568    let missing = migrations
569        .iter()
570        .filter(|migration| target_version.is_none_or(|target| migration.version <= target))
571        .filter(|migration| !applied.contains(&migration.version))
572        .map(|migration| migration.version)
573        .collect::<Vec<_>>();
574    ValidateResult { unapplied: missing }
575}
576
577fn validate_target(
578    migrations: &[Migration],
579    target_version: Option<i64>,
580    allow_empty: bool,
581) -> Result<(), Error> {
582    if let Some(target) = target_version
583        && !(allow_empty && target == -1)
584        && !migrations
585            .iter()
586            .any(|migration| migration.version == target)
587    {
588        return Err(Error::UnknownVersion { version: target });
589    }
590    Ok(())
591}
592
593#[cfg(test)]
594mod tests {
595    use super::{Direction, Error, MigrateOpts, Migration, select_migrations};
596
597    const MIGRATIONS: [Migration; 7] = {
598        const fn migration(version: i64) -> Migration {
599            Migration {
600                down_sql: "",
601                name: "test",
602                up_sql: "",
603                version,
604            }
605        }
606        [
607            migration(1),
608            migration(2),
609            migration(3),
610            migration(4),
611            migration(5),
612            migration(6),
613            migration(7),
614        ]
615    };
616
617    fn versions(
618        direction: Direction,
619        opts: MigrateOpts,
620        applied: &[i64],
621    ) -> Result<Vec<i64>, Error> {
622        select_migrations(&MIGRATIONS, direction, opts, applied).map(|selected| {
623            selected
624                .into_iter()
625                .map(|migration| migration.version)
626                .collect()
627        })
628    }
629
630    #[test]
631    fn applied_up_targets_are_no_ops() {
632        // Like Go, even with a gap below the target or later versions
633        // pending, with or without a step limit.
634        assert_eq!(
635            versions(
636                Direction::Up,
637                MigrateOpts::new().with_target_version(3),
638                &[1, 3]
639            )
640            .unwrap(),
641            Vec::<i64>::new()
642        );
643        assert_eq!(
644            versions(
645                Direction::Up,
646                MigrateOpts::new().with_target_version(3).with_max_steps(1),
647                &[1, 2, 3]
648            )
649            .unwrap(),
650            Vec::<i64>::new()
651        );
652    }
653
654    #[test]
655    fn selection_matches_go_target_and_step_semantics() {
656        let all = [1, 2, 3, 4, 5, 6, 7];
657
658        // Down defaults to one step, and a target is the version left applied.
659        assert_eq!(
660            versions(Direction::Down, MigrateOpts::new(), &all).unwrap(),
661            [7]
662        );
663        assert_eq!(
664            versions(
665                Direction::Down,
666                MigrateOpts::new().with_target_version(4),
667                &all
668            )
669            .unwrap(),
670            [7, 6, 5]
671        );
672        assert_eq!(
673            versions(
674                Direction::Down,
675                MigrateOpts::new().with_target_version(4),
676                &[1, 2, 3, 4]
677            )
678            .unwrap(),
679            Vec::<i64>::new()
680        );
681        assert_eq!(
682            versions(
683                Direction::Down,
684                MigrateOpts::new().with_target_version(-1),
685                &all
686            )
687            .unwrap(),
688            [7, 6, 5, 4, 3, 2, 1]
689        );
690
691        // Steps limit the list before the target is located, like Go.
692        assert_eq!(
693            versions(
694                Direction::Down,
695                MigrateOpts::new().with_target_version(5).with_max_steps(3),
696                &all
697            )
698            .unwrap(),
699            [7, 6]
700        );
701        assert!(matches!(
702            versions(
703                Direction::Down,
704                MigrateOpts::new().with_target_version(5).with_max_steps(2),
705                &all
706            ),
707            Err(Error::TargetNotSelected { version: 5 })
708        ));
709
710        // A down target that is not applied is an error rather than a no-op.
711        assert!(matches!(
712            versions(
713                Direction::Down,
714                MigrateOpts::new().with_target_version(5),
715                &[1, 2, 3]
716            ),
717            Err(Error::TargetNotSelected { version: 5 })
718        ));
719
720        // Up targets stop at the target and are no-ops once applied.
721        assert_eq!(
722            versions(
723                Direction::Up,
724                MigrateOpts::new().with_target_version(5),
725                &[1, 2]
726            )
727            .unwrap(),
728            [3, 4, 5]
729        );
730        assert_eq!(
731            versions(
732                Direction::Up,
733                MigrateOpts::new().with_target_version(2),
734                &[1, 2, 3]
735            )
736            .unwrap(),
737            Vec::<i64>::new()
738        );
739        assert_eq!(
740            versions(
741                Direction::Up,
742                MigrateOpts::new().with_target_version(6).with_max_steps(2),
743                &[1]
744            )
745            .unwrap(),
746            [2, 3]
747        );
748
749        // Versions recorded by a newer release are ignored.
750        assert_eq!(
751            versions(Direction::Up, MigrateOpts::new(), &[1, 2, 3, 99]).unwrap(),
752            [4, 5, 6, 7]
753        );
754        assert_eq!(
755            versions(
756                Direction::Down,
757                MigrateOpts::new(),
758                &[1, 2, 3, 4, 5, 6, 7, 8]
759            )
760            .unwrap(),
761            [7]
762        );
763    }
764}