use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};
use id_effect::{
Effect, HCons, HList, HNil, Layer, Selector, fail, hlist, need, sleep, succeed, suspend,
};
use crate::client::{SqlClient, SqlClientEnv, SqlClientService};
use crate::error::SqlError;
use crate::row::SqlRow;
use crate::transaction::{SqlTransaction, with_transaction};
use crate::value::SqlValue;
mod source;
mod split;
#[cfg(test)]
mod tests;
pub const DEFAULT_TABLE: &str = "_id_effect_migrations";
pub const DEFAULT_LOCK_KEY: i64 = 0x6964_6566_6d69_6772;
pub const DEFAULT_LOCK_TIMEOUT: Duration = Duration::from_secs(60);
const LOCK_POLL: Duration = Duration::from_millis(100);
const LOCK_SQL: &str = "SELECT pg_try_advisory_xact_lock($1) AS locked";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Migration {
version: i64,
description: String,
file: String,
sql: String,
checksum: Vec<u8>,
down: Option<(String, String)>,
}
impl Migration {
pub fn version(&self) -> i64 {
self.version
}
pub fn description(&self) -> &str {
&self.description
}
pub fn file(&self) -> &str {
&self.file
}
pub fn sql(&self) -> &str {
&self.sql
}
pub fn checksum(&self) -> &[u8] {
&self.checksum
}
pub fn checksum_hex(&self) -> String {
hex(&self.checksum)
}
pub fn down_file(&self) -> Option<&str> {
self.down.as_ref().map(|(file, _)| file.as_str())
}
pub fn down_sql(&self) -> Option<&str> {
self.down.as_ref().map(|(_, sql)| sql.as_str())
}
pub fn is_reversible(&self) -> bool {
self.down.is_some()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MigrateError {
Source(String),
ChecksumMismatch {
version: i64,
file: String,
},
Missing {
version: i64,
},
Pending {
versions: Vec<i64>,
},
Failed {
version: i64,
file: String,
error: SqlError,
},
LockTimeout {
key: i64,
timeout: Duration,
},
MissingDown {
version: i64,
file: String,
},
Sql(SqlError),
}
impl fmt::Display for MigrateError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MigrateError::Source(msg) => write!(f, "migration source: {msg}"),
MigrateError::ChecksumMismatch { version, file } => write!(
f,
"migration {version} ({file}) changed after it was applied: checksum mismatch"
),
MigrateError::Missing { version } => write!(
f,
"migration {version} is applied in the database but missing from the source"
),
MigrateError::Pending { versions } => {
let list: Vec<String> = versions.iter().map(i64::to_string).collect();
write!(
f,
"{} pending migration(s): {}",
versions.len(),
list.join(", ")
)
}
MigrateError::Failed { file, error, .. } => write!(f, "migration {file} failed: {error}"),
MigrateError::LockTimeout { key, timeout } => write!(
f,
"timed out after {timeout:?} waiting for the migration lock (advisory lock {key})"
),
MigrateError::MissingDown { file, .. } => write!(
f,
"migration {file} cannot be reverted: it has no down script (.down.sql)"
),
MigrateError::Sql(e) => write!(f, "migration bookkeeping failed: {e}"),
}
}
}
impl std::error::Error for MigrateError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
MigrateError::Failed { error, .. } | MigrateError::Sql(error) => Some(error),
_ => None,
}
}
}
impl From<SqlError> for MigrateError {
fn from(e: SqlError) -> Self {
MigrateError::Sql(e)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MigrationState {
Pending,
Applied,
Drifted,
Missing,
}
impl MigrationState {
pub fn is_applied(self) -> bool {
self != MigrationState::Pending
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MigrationStatus {
pub version: i64,
pub description: String,
pub state: MigrationState,
pub checksum: Vec<u8>,
pub applied_checksum: Option<Vec<u8>>,
pub applied_at: Option<jiff::Timestamp>,
pub reversible: bool,
}
impl MigrationStatus {
pub fn checksum_hex(&self) -> String {
hex(&self.checksum)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MigrationsApplied(pub Vec<i64>);
pub type MigratedEnv = HCons<MigrationsApplied, HNil>;
#[derive(Clone, Debug)]
struct AppliedRow {
version: i64,
description: String,
checksum: Vec<u8>,
applied_at: jiff::Timestamp,
}
#[derive(Clone, Debug)]
pub struct Migrator {
migrations: Arc<[Migration]>,
table: Arc<str>,
lock_key: i64,
lock_timeout: Duration,
}
impl Migrator {
fn new(migrations: Vec<Migration>) -> Self {
Self {
migrations: migrations.into(),
table: Arc::from(DEFAULT_TABLE),
lock_key: DEFAULT_LOCK_KEY,
lock_timeout: DEFAULT_LOCK_TIMEOUT,
}
}
pub fn from_dir(dir: impl AsRef<Path>) -> Result<Self, MigrateError> {
source::from_dir(dir.as_ref()).map(Self::new)
}
pub fn from_files<I, N, S>(files: I) -> Result<Self, MigrateError>
where
I: IntoIterator<Item = (N, S)>,
N: Into<String>,
S: Into<String>,
{
source::from_files(files.into_iter().map(|(n, s)| (n.into(), s.into()))).map(Self::new)
}
pub fn from_sqlx(migrator: &sqlx::migrate::Migrator) -> Result<Self, MigrateError> {
source::from_sqlx(migrator).map(Self::new)
}
pub fn with_table(mut self, table: impl Into<String>) -> Self {
let table = table.into();
assert!(
valid_table(&table),
"Migrator::with_table: `{table}` is not a [schema.]table name of ASCII letters, digits and _"
);
self.table = table.into();
self
}
pub fn with_lock_key(mut self, key: i64) -> Self {
self.lock_key = key;
self
}
pub fn with_lock_timeout(mut self, timeout: Duration) -> Self {
self.lock_timeout = timeout;
self
}
pub fn migrations(&self) -> &[Migration] {
&self.migrations
}
pub fn table(&self) -> &str {
&self.table
}
pub fn lock_key(&self) -> i64 {
self.lock_key
}
pub fn lock_timeout(&self) -> Duration {
self.lock_timeout
}
pub fn run_on(&self, client: Arc<dyn SqlClient>) -> Effect<Vec<i64>, MigrateError> {
let this = self.clone();
self.applied(Arc::clone(&client)).flat_map(move |applied| {
if let Err(e) = this.validate(&applied) {
return fail(e);
}
let pending = this.pending(&applied);
this.each(pending, move |this, m| {
this.apply_one(Arc::clone(&client), m)
})
})
}
pub fn status_on(
&self,
client: Arc<dyn SqlClient>,
) -> Effect<Vec<MigrationStatus>, MigrateError> {
let this = self.clone();
self
.applied(client)
.map(move |applied| this.statuses(&applied))
}
pub fn revert_on(&self, client: Arc<dyn SqlClient>, n: usize) -> Effect<Vec<i64>, MigrateError> {
let this = self.clone();
self.applied(Arc::clone(&client)).flat_map(move |applied| {
let targets = match this
.validate(&applied)
.and_then(|()| this.revert_targets(&applied, n))
{
Ok(targets) => targets,
Err(e) => return fail(e),
};
this.each(targets, move |this, t| {
this.revert_one(Arc::clone(&client), t)
})
})
}
pub fn check_on(&self, client: Arc<dyn SqlClient>) -> Effect<(), MigrateError> {
let this = self.clone();
self.applied(client).flat_map(move |applied| {
ready(this.validate(&applied).and_then(|()| {
let versions: Vec<i64> = this
.pending(&applied)
.iter()
.map(Migration::version)
.collect();
if versions.is_empty() {
Ok(())
} else {
Err(MigrateError::Pending { versions })
}
}))
})
}
pub fn run<R, I>(&self) -> Effect<Vec<i64>, MigrateError, R>
where
R: Selector<SqlClientService, I> + HList,
{
let this = self.clone();
need::<SqlClientService>().flat_map(move |c| this.run_on(Arc::clone(&c.0)).narrow())
}
pub fn status<R, I>(&self) -> Effect<Vec<MigrationStatus>, MigrateError, R>
where
R: Selector<SqlClientService, I> + HList,
{
let this = self.clone();
need::<SqlClientService>().flat_map(move |c| this.status_on(Arc::clone(&c.0)).narrow())
}
pub fn revert<R, I>(&self, n: usize) -> Effect<Vec<i64>, MigrateError, R>
where
R: Selector<SqlClientService, I> + HList,
{
let this = self.clone();
need::<SqlClientService>().flat_map(move |c| this.revert_on(Arc::clone(&c.0), n).narrow())
}
pub fn check<R, I>(&self) -> Effect<(), MigrateError, R>
where
R: Selector<SqlClientService, I> + HList,
{
let this = self.clone();
need::<SqlClientService>().flat_map(move |c| this.check_on(Arc::clone(&c.0)).narrow())
}
pub fn layer<E>(&self) -> Layer<MigratedEnv, E, SqlClientEnv>
where
E: From<MigrateError> + Send + 'static,
{
let this = self.clone();
Layer::effect(move || {
this
.run::<SqlClientEnv, _>()
.map(|applied| hlist![MigrationsApplied(applied)])
.map_err(E::from)
})
}
fn create_table_sql(&self) -> String {
format!(
"CREATE TABLE IF NOT EXISTS {} (version BIGINT PRIMARY KEY, description TEXT NOT NULL, \
checksum BYTEA NOT NULL, installed_on TIMESTAMPTZ NOT NULL DEFAULT now(), \
execution_ms BIGINT NOT NULL)",
self.table
)
}
fn select_applied_sql(&self) -> String {
format!(
"SELECT version, description, checksum, installed_on FROM {} ORDER BY version",
self.table
)
}
fn recorded_sql(&self) -> String {
format!("SELECT checksum FROM {} WHERE version = $1", self.table)
}
fn insert_sql(&self) -> String {
format!(
"INSERT INTO {} (version, description, checksum, execution_ms) VALUES ($1, $2, $3, $4)",
self.table
)
}
fn delete_sql(&self) -> String {
format!("DELETE FROM {} WHERE version = $1", self.table)
}
fn applied(&self, client: Arc<dyn SqlClient>) -> Effect<Vec<AppliedRow>, MigrateError> {
let (this, create, select) = (
self.clone(),
self.create_table_sql(),
self.select_applied_sql(),
);
with_transaction(Arc::clone(&client), move |tx| {
this.lock(&tx).flat_map(move |()| {
tx.execute(&create, &[])
.map(drop)
.map_err(MigrateError::from)
})
})
.flat_map(move |()| {
client
.query(&select, &[])
.map_err(MigrateError::from)
.flat_map(|rows| ready(rows.iter().map(applied_row).collect()))
})
}
fn lock(&self, tx: &Arc<dyn SqlTransaction>) -> Effect<(), MigrateError> {
let retries =
u32::try_from(self.lock_timeout.as_millis() / LOCK_POLL.as_millis()).unwrap_or(u32::MAX);
try_lock(Arc::clone(tx), self.lock_key, self.lock_timeout, retries)
}
fn recorded(
&self,
tx: &Arc<dyn SqlTransaction>,
version: i64,
) -> Effect<Option<Vec<u8>>, MigrateError> {
tx.query(&self.recorded_sql(), &[SqlValue::I64(version)])
.map_err(MigrateError::from)
.flat_map(|rows| {
ready(
rows
.first()
.map(|r| r.get::<Vec<u8>>("checksum"))
.transpose()
.map_err(MigrateError::from),
)
})
}
fn apply_one(
&self,
client: Arc<dyn SqlClient>,
m: Migration,
) -> Effect<Option<i64>, MigrateError> {
let this = self.clone();
with_transaction(client, move |tx| {
this.lock(&tx).flat_map(move |()| {
let insert = this.insert_sql();
this
.recorded(&tx, m.version)
.flat_map(move |recorded| match recorded {
Some(sum) if sum == m.checksum => succeed(None),
Some(_) => fail(MigrateError::ChecksumMismatch {
version: m.version,
file: m.file,
}),
None => {
let started = Instant::now();
script(&tx, &m.sql, m.version, &m.file).flat_map(move |()| {
let ms = i64::try_from(started.elapsed().as_millis()).unwrap_or(i64::MAX);
let row = [
SqlValue::I64(m.version),
SqlValue::Text(m.description),
SqlValue::Bytes(m.checksum),
SqlValue::I64(ms),
];
tx.execute(&insert, &row)
.map_err(MigrateError::from)
.map(move |_| Some(m.version))
})
}
})
})
})
}
fn revert_one(
&self,
client: Arc<dyn SqlClient>,
(version, file, sql): (i64, String, String),
) -> Effect<Option<i64>, MigrateError> {
let this = self.clone();
with_transaction(client, move |tx| {
this.lock(&tx).flat_map(move |()| {
let delete = this.delete_sql();
this
.recorded(&tx, version)
.flat_map(move |recorded| match recorded {
None => succeed(None),
Some(_) => script(&tx, &sql, version, &file).flat_map(move |()| {
tx.execute(&delete, &[SqlValue::I64(version)])
.map_err(MigrateError::from)
.map(move |_| Some(version))
}),
})
})
})
}
fn each<T, F>(&self, items: Vec<T>, step: F) -> Effect<Vec<i64>, MigrateError>
where
T: Send + 'static,
F: Fn(&Migrator, T) -> Effect<Option<i64>, MigrateError> + Send + Sync + 'static,
{
let (this, step) = (self.clone(), Arc::new(step));
items
.into_iter()
.fold(succeed(Vec::new()), move |done, item| {
let (this, step) = (this.clone(), Arc::clone(&step));
done.flat_map(move |mut out: Vec<i64>| {
step(&this, item).map(move |version| {
out.extend(version);
out
})
})
})
}
fn find(&self, version: i64) -> Option<&Migration> {
self.migrations.iter().find(|m| m.version == version)
}
fn validate(&self, applied: &[AppliedRow]) -> Result<(), MigrateError> {
for row in applied {
match self.find(row.version) {
None => {
return Err(MigrateError::Missing {
version: row.version,
});
}
Some(m) if m.checksum != row.checksum => {
return Err(MigrateError::ChecksumMismatch {
version: m.version,
file: m.file.clone(),
});
}
Some(_) => {}
}
}
Ok(())
}
fn pending(&self, applied: &[AppliedRow]) -> Vec<Migration> {
let done: BTreeSet<i64> = applied.iter().map(|row| row.version).collect();
self
.migrations
.iter()
.filter(|m| !done.contains(&m.version))
.cloned()
.collect()
}
fn revert_targets(
&self,
applied: &[AppliedRow],
n: usize,
) -> Result<Vec<(i64, String, String)>, MigrateError> {
applied
.iter()
.rev()
.take(n)
.map(|row| {
let m = self.find(row.version).ok_or(MigrateError::Missing {
version: row.version,
})?;
let (file, sql) = m.down.clone().ok_or_else(|| MigrateError::MissingDown {
version: m.version,
file: m.file.clone(),
})?;
Ok((m.version, file, sql))
})
.collect()
}
fn statuses(&self, applied: &[AppliedRow]) -> Vec<MigrationStatus> {
let mut all: BTreeMap<i64, MigrationStatus> = self
.migrations
.iter()
.map(|m| {
let status = MigrationStatus {
version: m.version,
description: m.description.clone(),
state: MigrationState::Pending,
checksum: m.checksum.clone(),
applied_checksum: None,
applied_at: None,
reversible: m.is_reversible(),
};
(m.version, status)
})
.collect();
for row in applied {
let status = all.entry(row.version).or_insert_with(|| MigrationStatus {
version: row.version,
description: row.description.clone(),
state: MigrationState::Missing,
checksum: row.checksum.clone(),
applied_checksum: None,
applied_at: None,
reversible: false,
});
if status.state == MigrationState::Pending {
status.state = if status.checksum == row.checksum {
MigrationState::Applied
} else {
MigrationState::Drifted
};
}
status.applied_checksum = Some(row.checksum.clone());
status.applied_at = Some(row.applied_at);
}
all.into_values().collect()
}
}
pub fn run<R, I>(dir: impl Into<PathBuf>) -> Effect<Vec<i64>, MigrateError, R>
where
R: Selector<SqlClientService, I> + HList,
{
let dir = dir.into();
suspend(move || match Migrator::from_dir(&dir) {
Ok(migrator) => migrator.run(),
Err(e) => fail(e),
})
}
pub fn layer<E>(dir: impl Into<PathBuf>) -> Layer<MigratedEnv, E, SqlClientEnv>
where
E: From<MigrateError> + Send + 'static,
{
let dir = dir.into();
Layer::effect(move || {
run::<SqlClientEnv, _>(dir.clone())
.map(|applied| hlist![MigrationsApplied(applied)])
.map_err(E::from)
})
}
fn ready<A: Send + 'static>(r: Result<A, MigrateError>) -> Effect<A, MigrateError> {
match r {
Ok(a) => succeed(a),
Err(e) => fail(e),
}
}
fn applied_row(row: &SqlRow) -> Result<AppliedRow, MigrateError> {
Ok(AppliedRow {
version: row.get("version")?,
description: row.get("description")?,
checksum: row.get("checksum")?,
applied_at: row.get("installed_on")?,
})
}
fn try_lock(
tx: Arc<dyn SqlTransaction>,
key: i64,
timeout: Duration,
retries: u32,
) -> Effect<(), MigrateError> {
tx.query(LOCK_SQL, &[SqlValue::I64(key)])
.map_err(MigrateError::from)
.flat_map(
move |rows| match rows.first().map(|r| r.get::<bool>("locked")).transpose() {
Err(e) => fail(e.into()),
Ok(Some(true)) => succeed(()),
Ok(_) if retries == 0 => fail(MigrateError::LockTimeout { key, timeout }),
Ok(_) => sleep(LOCK_POLL).flat_map(move |()| try_lock(tx, key, timeout, retries - 1)),
},
)
}
fn script(
tx: &Arc<dyn SqlTransaction>,
sql: &str,
version: i64,
file: &str,
) -> Effect<(), MigrateError> {
split::statements(sql)
.into_iter()
.fold(succeed(()), |done, stmt| {
let (tx, file) = (Arc::clone(tx), file.to_owned());
done.flat_map(move |()| {
tx.execute(&stmt, &[])
.map(drop)
.map_err(move |error| MigrateError::Failed {
version,
file,
error,
})
})
})
}
fn valid_table(name: &str) -> bool {
let parts: Vec<&str> = name.split('.').collect();
parts.len() <= 2
&& parts.iter().all(|part| {
part
.chars()
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& part.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
})
}
fn hex(bytes: &[u8]) -> String {
use std::fmt::Write;
bytes
.iter()
.fold(String::with_capacity(bytes.len() * 2), |mut s, b| {
let _ = write!(s, "{b:02x}");
s
})
}