#![cfg_attr(
all(feature = "postgres", feature = "sqlite"),
doc = include_str!("../README.md")
)]
#."
)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
#[cfg(not(any(feature = "postgres", feature = "sqlite")))]
compile_error!("riverqueue-migrate requires at least one database feature: `postgres` or `sqlite`");
use std::time::Duration;
#[cfg(feature = "postgres")]
use std::time::Instant;
#[cfg(feature = "postgres")]
use sqlx::{PgPool, Row};
use thiserror::Error;
mod schema;
#[cfg(feature = "sqlite")]
mod sqlite;
pub use schema::{SCHEMA_MAX_LEN, SchemaName, SchemaNameError};
#[cfg(feature = "sqlite")]
pub use sqlite::{SQLITE_MIGRATIONS, SqliteMigrator};
#[cfg(feature = "postgres")]
const TEMPLATE_SCHEMA: &str = "/* TEMPLATE: schema */";
pub const MIGRATION_LINE_MAIN: &str = "main";
pub const MIGRATION_VERSION_LATEST: i64 = 8;
#[cfg(feature = "postgres")]
macro_rules! migration {
($version:literal, $name:literal, $file:literal) => {
Migration {
down_sql: include_str!(concat!("../migrations/main/", $file, ".down.sql")),
name: $name,
up_sql: include_str!(concat!("../migrations/main/", $file, ".up.sql")),
version: $version,
}
};
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct Migration {
pub down_sql: &'static str,
pub name: &'static str,
pub up_sql: &'static str,
pub version: i64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Direction {
Down,
Up,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct MigrateOpts {
dry_run: bool,
max_steps: Option<usize>,
target_version: Option<i64>,
}
impl MigrateOpts {
#[must_use]
pub const fn new() -> Self {
Self {
dry_run: false,
max_steps: None,
target_version: None,
}
}
#[must_use]
pub const fn dry_run(&self) -> bool {
self.dry_run
}
#[must_use]
pub const fn max_steps(&self) -> Option<usize> {
self.max_steps
}
#[must_use]
pub const fn target_version(&self) -> Option<i64> {
self.target_version
}
#[must_use]
pub const fn with_dry_run(mut self, dry_run: bool) -> Self {
self.dry_run = dry_run;
self
}
#[must_use]
pub const fn with_max_steps(mut self, maximum: usize) -> Self {
self.max_steps = Some(maximum);
self
}
#[must_use]
pub const fn with_target_version(mut self, version: i64) -> Self {
self.target_version = Some(version);
self
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct MigrateVersion {
pub duration: Duration,
pub name: &'static str,
pub sql: String,
pub version: i64,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct MigrateResult {
pub direction: Direction,
pub versions: Vec<MigrateVersion>,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct ValidateResult {
pub unapplied: Vec<i64>,
}
impl ValidateResult {
#[must_use]
pub fn is_valid(&self) -> bool {
self.unapplied.is_empty()
}
}
impl std::fmt::Display for ValidateResult {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.is_valid() {
formatter.write_str("all required migrations are applied")
} else {
write!(formatter, "unapplied migrations: {:?}", self.unapplied)
}
}
}
#[cfg(feature = "postgres")]
pub const POSTGRES_MIGRATIONS: [Migration; 8] = [
migration!(1, "create_river_migration", "001_create_river_migration"),
migration!(2, "initial_schema", "002_initial_schema"),
migration!(3, "river_job_tags_non_null", "003_river_job_tags_non_null"),
migration!(4, "pending_and_more", "004_pending_and_more"),
migration!(5, "migration_unique_client", "005_migration_unique_client"),
migration!(6, "bulk_unique", "006_bulk_unique"),
migration!(
7,
"notification_outbox_sqlite_jsonb_and_sql_cleanup",
"007_notification_outbox_sqlite_jsonb_and_sql_cleanup"
),
migration!(8, "job_id_autoincrement", "008_job_id_autoincrement"),
];
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
#[error(transparent)]
Database(#[from] sqlx::Error),
#[error(
"found non-main migration lines; version {version:03} is irreversible without losing migration information"
)]
OtherMigrationLines {
version: i64,
},
#[error("version {version} is not in target list of valid migrations to apply")]
TargetNotSelected {
version: i64,
},
#[error("version {version} is not a River migration")]
UnknownVersion {
version: i64,
},
}
#[cfg(feature = "postgres")]
#[derive(Clone, Debug)]
pub struct PostgresMigrator {
pool: PgPool,
schema: SchemaName,
}
#[cfg(feature = "postgres")]
impl PostgresMigrator {
#[must_use]
pub fn all_versions() -> &'static [Migration] {
&POSTGRES_MIGRATIONS
}
#[must_use]
pub fn new(pool: PgPool) -> Self {
Self {
pool,
schema: SchemaName::current(),
}
}
#[must_use]
pub fn with_schema(mut self, schema: SchemaName) -> Self {
self.schema = schema;
self
}
#[must_use]
pub const fn schema(&self) -> &SchemaName {
&self.schema
}
pub async fn existing_versions(&self) -> Result<Vec<i64>, Error> {
let table = self.schema.qualify("river_migration");
let exists: bool = sqlx::query_scalar("SELECT to_regclass($1) IS NOT NULL")
.bind(&table)
.fetch_one(&self.pool)
.await?;
if !exists {
return Ok(Vec::new());
}
let has_line: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = coalesce($1, current_schema()) AND table_name = 'river_migration' AND column_name = 'line')",
)
.bind(self.schema.as_deref())
.fetch_one(&self.pool)
.await?;
let sql = if has_line {
format!("SELECT version FROM {table} WHERE line = $1 ORDER BY version")
} else {
format!("SELECT version FROM {table} ORDER BY version")
};
let rows = if has_line {
sqlx::query(sqlx::AssertSqlSafe(sql))
.bind(MIGRATION_LINE_MAIN)
.fetch_all(&self.pool)
.await?
} else {
sqlx::query(sqlx::AssertSqlSafe(sql))
.fetch_all(&self.pool)
.await?
};
Ok(rows.iter().map(|row| row.get("version")).collect())
}
pub async fn migrate_up(&self) -> Result<Vec<i64>, Error> {
Ok(self
.migrate(Direction::Up, MigrateOpts::default())
.await?
.versions
.into_iter()
.map(|version| version.version)
.collect())
}
pub async fn migrate(
&self,
direction: Direction,
opts: MigrateOpts,
) -> Result<MigrateResult, Error> {
validate_target(&POSTGRES_MIGRATIONS, opts.target_version, true)?;
let applied = self.existing_versions().await?;
let selected = select_migrations(&POSTGRES_MIGRATIONS, direction, opts, &applied)?;
let mut versions = Vec::with_capacity(selected.len());
for migration in selected {
let sql = self.render(match direction {
Direction::Down => migration.down_sql,
Direction::Up => migration.up_sql,
});
let mut duration = Duration::ZERO;
if !opts.dry_run {
let started_at = Instant::now();
let migrator = self.clone();
let task_sql = sql.clone();
run_to_completion(
async move { migrator.apply(direction, migration, &task_sql).await },
)
.await?;
duration = started_at.elapsed();
}
versions.push(MigrateVersion {
duration,
name: migration.name,
sql,
version: migration.version,
});
}
Ok(MigrateResult {
direction,
versions,
})
}
pub async fn validate(&self, target_version: Option<i64>) -> Result<ValidateResult, Error> {
validate_target(&POSTGRES_MIGRATIONS, target_version, false)?;
let applied = self.existing_versions().await?;
Ok(validate_migrations(
&POSTGRES_MIGRATIONS,
target_version,
&applied,
))
}
async fn apply(
&self,
direction: Direction,
migration: Migration,
sql: &str,
) -> Result<(), Error> {
let mut transaction = self.pool.begin().await?;
sqlx::raw_sql(sqlx::AssertSqlSafe(sql))
.execute(&mut *transaction)
.await?;
let table = self.schema.qualify("river_migration");
match direction {
Direction::Down if migration.version == 1 => {}
Direction::Down if migration.version <= 5 => {
sqlx::query(sqlx::AssertSqlSafe(format!(
"DELETE FROM {table} WHERE version = $1"
)))
.bind(migration.version)
.execute(&mut *transaction)
.await?;
}
Direction::Down => {
sqlx::query(sqlx::AssertSqlSafe(format!(
"DELETE FROM {table} WHERE line = $1 AND version = $2"
)))
.bind(MIGRATION_LINE_MAIN)
.bind(migration.version)
.execute(&mut *transaction)
.await?;
}
Direction::Up if migration.version >= 5 => {
sqlx::query(sqlx::AssertSqlSafe(format!(
"INSERT INTO {table} (line, version) VALUES ($1, $2)"
)))
.bind(MIGRATION_LINE_MAIN)
.bind(migration.version)
.execute(&mut *transaction)
.await?;
}
Direction::Up => {
sqlx::query(sqlx::AssertSqlSafe(format!(
"INSERT INTO {table} (version) VALUES ($1)"
)))
.bind(migration.version)
.execute(&mut *transaction)
.await?;
}
}
transaction.commit().await?;
Ok(())
}
fn render(&self, sql: &str) -> String {
sql.replace(TEMPLATE_SCHEMA, &self.schema.migration_prefix())
}
}
async fn run_to_completion(
step: impl std::future::Future<Output = Result<(), Error>> + Send + 'static,
) -> Result<(), Error> {
match tokio::spawn(step).await {
Ok(result) => result,
Err(error) if error.is_panic() => std::panic::resume_unwind(error.into_panic()),
Err(error) => Err(Error::Database(sqlx::Error::Io(std::io::Error::other(
format!("migration task failed: {error}"),
)))),
}
}
fn select_migrations(
migrations: &'static [Migration],
direction: Direction,
opts: MigrateOpts,
applied: &[i64],
) -> Result<Vec<Migration>, Error> {
let mut selected = match direction {
Direction::Up => migrations
.iter()
.filter(|migration| !applied.contains(&migration.version))
.copied()
.collect::<Vec<_>>(),
Direction::Down => migrations
.iter()
.rev()
.filter(|migration| applied.contains(&migration.version))
.copied()
.collect::<Vec<_>>(),
};
let target_was_pending = opts
.target_version
.is_some_and(|target| selected.iter().any(|migration| migration.version == target));
let maximum = opts
.max_steps
.or_else(|| (direction == Direction::Down && opts.target_version.is_none()).then_some(1));
if let Some(maximum) = maximum {
selected.truncate(maximum);
}
if let Some(target) = opts.target_version.filter(|target| *target != -1) {
match selected
.iter()
.position(|migration| migration.version == target)
{
Some(index) => {
selected.truncate(index + 1);
if direction == Direction::Down {
selected.pop();
}
}
None if direction == Direction::Down => {
return Err(Error::TargetNotSelected { version: target });
}
None if target_was_pending => {}
None => selected.clear(),
}
}
Ok(selected)
}
fn validate_migrations(
migrations: &[Migration],
target_version: Option<i64>,
applied: &[i64],
) -> ValidateResult {
let missing = migrations
.iter()
.filter(|migration| target_version.is_none_or(|target| migration.version <= target))
.filter(|migration| !applied.contains(&migration.version))
.map(|migration| migration.version)
.collect::<Vec<_>>();
ValidateResult { unapplied: missing }
}
fn validate_target(
migrations: &[Migration],
target_version: Option<i64>,
allow_empty: bool,
) -> Result<(), Error> {
if let Some(target) = target_version
&& !(allow_empty && target == -1)
&& !migrations
.iter()
.any(|migration| migration.version == target)
{
return Err(Error::UnknownVersion { version: target });
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{Direction, Error, MigrateOpts, Migration, select_migrations};
const MIGRATIONS: [Migration; 7] = {
const fn migration(version: i64) -> Migration {
Migration {
down_sql: "",
name: "test",
up_sql: "",
version,
}
}
[
migration(1),
migration(2),
migration(3),
migration(4),
migration(5),
migration(6),
migration(7),
]
};
fn versions(
direction: Direction,
opts: MigrateOpts,
applied: &[i64],
) -> Result<Vec<i64>, Error> {
select_migrations(&MIGRATIONS, direction, opts, applied).map(|selected| {
selected
.into_iter()
.map(|migration| migration.version)
.collect()
})
}
#[test]
fn applied_up_targets_are_no_ops() {
assert_eq!(
versions(
Direction::Up,
MigrateOpts::new().with_target_version(3),
&[1, 3]
)
.unwrap(),
Vec::<i64>::new()
);
assert_eq!(
versions(
Direction::Up,
MigrateOpts::new().with_target_version(3).with_max_steps(1),
&[1, 2, 3]
)
.unwrap(),
Vec::<i64>::new()
);
}
#[test]
fn selection_matches_go_target_and_step_semantics() {
let all = [1, 2, 3, 4, 5, 6, 7];
assert_eq!(
versions(Direction::Down, MigrateOpts::new(), &all).unwrap(),
[7]
);
assert_eq!(
versions(
Direction::Down,
MigrateOpts::new().with_target_version(4),
&all
)
.unwrap(),
[7, 6, 5]
);
assert_eq!(
versions(
Direction::Down,
MigrateOpts::new().with_target_version(4),
&[1, 2, 3, 4]
)
.unwrap(),
Vec::<i64>::new()
);
assert_eq!(
versions(
Direction::Down,
MigrateOpts::new().with_target_version(-1),
&all
)
.unwrap(),
[7, 6, 5, 4, 3, 2, 1]
);
assert_eq!(
versions(
Direction::Down,
MigrateOpts::new().with_target_version(5).with_max_steps(3),
&all
)
.unwrap(),
[7, 6]
);
assert!(matches!(
versions(
Direction::Down,
MigrateOpts::new().with_target_version(5).with_max_steps(2),
&all
),
Err(Error::TargetNotSelected { version: 5 })
));
assert!(matches!(
versions(
Direction::Down,
MigrateOpts::new().with_target_version(5),
&[1, 2, 3]
),
Err(Error::TargetNotSelected { version: 5 })
));
assert_eq!(
versions(
Direction::Up,
MigrateOpts::new().with_target_version(5),
&[1, 2]
)
.unwrap(),
[3, 4, 5]
);
assert_eq!(
versions(
Direction::Up,
MigrateOpts::new().with_target_version(2),
&[1, 2, 3]
)
.unwrap(),
Vec::<i64>::new()
);
assert_eq!(
versions(
Direction::Up,
MigrateOpts::new().with_target_version(6).with_max_steps(2),
&[1]
)
.unwrap(),
[2, 3]
);
assert_eq!(
versions(Direction::Up, MigrateOpts::new(), &[1, 2, 3, 99]).unwrap(),
[4, 5, 6, 7]
);
assert_eq!(
versions(
Direction::Down,
MigrateOpts::new(),
&[1, 2, 3, 4, 5, 6, 7, 8]
)
.unwrap(),
[7]
);
}
}