1#![cfg_attr(
4 all(feature = "postgres", feature = "sqlite"),
5 doc = include_str!("../README.md")
6)]
7#."
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
40pub const MIGRATION_LINE_MAIN: &str = "main";
42
43pub 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#[derive(Clone, Copy, Debug)]
60#[non_exhaustive]
61pub struct Migration {
62 pub down_sql: &'static str,
64 pub name: &'static str,
66 pub up_sql: &'static str,
68 pub version: i64,
70}
71
72#[derive(Clone, Copy, Debug, Eq, PartialEq)]
74pub enum Direction {
75 Down,
77 Up,
79}
80
81#[derive(Clone, Copy, Debug, Default)]
83pub struct MigrateOpts {
84 dry_run: bool,
86 max_steps: Option<usize>,
88 target_version: Option<i64>,
90}
91
92impl MigrateOpts {
93 #[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 #[must_use]
105 pub const fn dry_run(&self) -> bool {
106 self.dry_run
107 }
108
109 #[must_use]
111 pub const fn max_steps(&self) -> Option<usize> {
112 self.max_steps
113 }
114
115 #[must_use]
117 pub const fn target_version(&self) -> Option<i64> {
118 self.target_version
119 }
120
121 #[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 #[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 #[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#[derive(Clone, Debug)]
147#[non_exhaustive]
148pub struct MigrateVersion {
149 pub duration: Duration,
151 pub name: &'static str,
153 pub sql: String,
155 pub version: i64,
157}
158
159#[derive(Clone, Debug)]
161#[non_exhaustive]
162pub struct MigrateResult {
163 pub direction: Direction,
165 pub versions: Vec<MigrateVersion>,
167}
168
169#[derive(Clone, Debug, Default, Eq, PartialEq)]
174#[non_exhaustive]
175pub struct ValidateResult {
176 pub unapplied: Vec<i64>,
178}
179
180impl ValidateResult {
181 #[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#[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#[derive(Debug, Error)]
217#[non_exhaustive]
218pub enum Error {
219 #[error(transparent)]
221 Database(#[from] sqlx::Error),
222
223 #[error(
226 "found non-main migration lines; version {version:03} is irreversible without losing migration information"
227 )]
228 OtherMigrationLines {
229 version: i64,
231 },
232
233 #[error("version {version} is not in target list of valid migrations to apply")]
236 TargetNotSelected {
237 version: i64,
239 },
240
241 #[error("version {version} is not a River migration")]
243 UnknownVersion {
244 version: i64,
246 },
247}
248
249#[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 #[must_use]
261 pub fn all_versions() -> &'static [Migration] {
262 &POSTGRES_MIGRATIONS
263 }
264
265 #[must_use]
267 pub fn new(pool: PgPool) -> Self {
268 Self {
269 pool,
270 schema: SchemaName::current(),
271 }
272 }
273
274 #[must_use]
277 pub fn with_schema(mut self, schema: SchemaName) -> Self {
278 self.schema = schema;
279 self
280 }
281
282 #[must_use]
284 pub const fn schema(&self) -> &SchemaName {
285 &self.schema
286 }
287
288 pub async fn existing_versions(&self) -> Result<Vec<i64>, Error> {
294 let table = self.schema.qualify("river_migration");
295 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 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 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 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 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 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
485async 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 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 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 let target_was_pending = opts
527 .target_version
528 .is_some_and(|target| selected.iter().any(|migration| migration.version == target));
529
530 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 if direction == Direction::Down {
548 selected.pop();
549 }
550 }
551 None if direction == Direction::Down => {
552 return Err(Error::TargetNotSelected { version: target });
553 }
554 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 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 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 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 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 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 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}