tern_core/migration.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
//! This module contains types and traits related to the migration files.
//!
//! * [`Migration`] is the abstract representation of what is built from a
//! migration file.
//! * [`QueryBuilder`] is the recipe for building the query for a migration.
//! * [`MigrationSource`] is the ability to produce the set of migrations, a
//! [`MigrationSet`], for a particular context in order to be ran in that
//! context.
//! * [`MigrationContext`] is the core type. It has an associated [`Executor`]
//! and it can produce the migrations from source. Combined, it has the full
//! functionality of the migration tool.
//!
//! Generally these don't need to be implemented. Their corresponding derive
//! macros can be used instead.
use chrono::{DateTime, Utc};
use futures_core::{future::BoxFuture, Future};
use std::{fmt::Write, time::Instant};
use crate::error::{DatabaseError as _, TernResult};
/// The context in which a migration run occurs.
pub trait MigrationContext
where
Self: MigrationSource<Ctx = Self> + Send + Sync + 'static,
{
/// The name of the table in the database that tracks the history of this
/// migration set.
///
/// It defaults to `_tern_migrations` in the default schema for the
/// database driver if using the derive macro for this trait.
const HISTORY_TABLE: &str;
/// The type for executing queries in a migration run.
type Exec: Executor;
/// A reference to the underlying `Executor`.
fn executor(&mut self) -> &mut Self::Exec;
/// For a migration that is capable of building its query in this migration
/// context, this builds the query, applies the migration, then updates the
/// schema history table after.
fn apply<'migration, 'conn: 'migration, M>(
&'conn mut self,
migration: &'migration M,
) -> BoxFuture<'migration, TernResult<AppliedMigration>>
where
M: Migration<Ctx = Self> + Send + Sync + ?Sized,
{
Box::pin(async move {
let start = Instant::now();
let query = M::build(migration, self).await?;
let executor = self.executor();
if migration.no_tx() {
executor
.apply_no_tx(&query)
.await
.void_tern_migration_result(migration.version())?;
} else {
executor
.apply_tx(&query)
.await
.void_tern_migration_result(migration.version())?;
}
let applied_at = Utc::now();
let duration_ms = start.elapsed().as_millis() as i64;
let applied = migration.to_applied(duration_ms, applied_at);
executor
.insert_applied_migration(Self::HISTORY_TABLE, &applied)
.await?;
Ok(applied)
})
}
/// Gets the version of the most recently applied migration.
fn latest_version(&mut self) -> BoxFuture<'_, TernResult<Option<i64>>> {
Box::pin(async move {
let executor = self.executor();
let latest = executor
.get_all_applied(Self::HISTORY_TABLE)
.await?
.into_iter()
.fold(None, |acc, m| match acc {
None => Some(m.version),
Some(v) if m.version > v => Some(m.version),
_ => acc,
});
Ok(latest)
})
}
/// Get all previously applied migrations.
fn previously_applied(&mut self) -> BoxFuture<'_, TernResult<Vec<AppliedMigration>>> {
Box::pin(async move {
let executor = self.executor();
let applied = executor.get_all_applied(Self::HISTORY_TABLE).await?;
Ok(applied)
})
}
/// Check that the history table exists and create it if not.
fn check_history_table(&mut self) -> BoxFuture<'_, TernResult<()>> {
Box::pin(async move {
let executor = self.executor();
executor
.create_history_if_not_exists(Self::HISTORY_TABLE)
.await?;
Ok(())
})
}
/// Drop the history table if requested.
fn drop_history_table(&mut self) -> BoxFuture<'_, TernResult<()>> {
Box::pin(async move {
let executor = self.executor();
executor.drop_history(Self::HISTORY_TABLE).await?;
Ok(())
})
}
/// Upsert applied migrations.
fn upsert_applied<'migration, 'conn: 'migration>(
&'conn mut self,
applied: &'migration AppliedMigration,
) -> BoxFuture<'migration, TernResult<()>> {
Box::pin(async move {
self.executor()
.upsert_applied_migration(Self::HISTORY_TABLE, applied)
.await?;
Ok(())
})
}
}
/// The "executor" type for the database backend ultimately responsible for
/// issuing migration and schema history queries.
pub trait Executor
where
Self: Send + Sync + 'static,
{
/// The type of value that can produce queries for the history table of this
/// migration set.
type Queries: QueryRepository;
/// Apply the `Query` for the migration in a transaction.
fn apply_tx(&mut self, query: &Query) -> impl Future<Output = TernResult<()>> + Send;
/// Apply the `Query` for the migration _not_ in a transaction.
fn apply_no_tx(&mut self, query: &Query) -> impl Future<Output = TernResult<()>> + Send;
/// `CREATE IF NOT EXISTS` the history table.
fn create_history_if_not_exists(
&mut self,
history_table: &str,
) -> impl Future<Output = TernResult<()>> + Send;
/// `DROP` the history table.
fn drop_history(&mut self, history_table: &str) -> impl Future<Output = TernResult<()>> + Send;
/// Get the complete history of applied migrations.
fn get_all_applied(
&mut self,
history_table: &str,
) -> impl Future<Output = TernResult<Vec<AppliedMigration>>> + Send;
/// Insert an applied migration into the history table.
fn insert_applied_migration(
&mut self,
history_table: &str,
applied: &AppliedMigration,
) -> impl Future<Output = TernResult<()>> + Send;
/// Update or insert an applied migration.
fn upsert_applied_migration(
&mut self,
history_table: &str,
applied: &AppliedMigration,
) -> impl Future<Output = TernResult<()>> + Send;
}
/// A type that has a library of "administrative" queries that are needed during
/// a migration run.
pub trait QueryRepository {
/// The query that creates the schema history table or does nothing if it
/// already exists.
fn create_history_if_not_exists_query(history_table: &str) -> Query;
/// The query that drops the history table if requested.
fn drop_history_query(history_table: &str) -> Query;
/// The query to update the schema history table with an applied migration.
fn insert_into_history_query(history_table: &str, applied: &AppliedMigration) -> Query;
/// The query to return all rows from the schema history table.
fn select_star_from_history_query(history_table: &str) -> Query;
/// Query to insert or update a record in the history table.
fn upsert_history_query(history_table: &str, applied: &AppliedMigration) -> Query;
}
/// A single migration in a migration set.
pub trait Migration
where
Self: Send + Sync,
{
/// A migration context that is sufficient to build this migration.
type Ctx: MigrationContext;
/// Get the `MigrationId` for this migration.
fn migration_id(&self) -> MigrationId;
/// The raw file content of the migration source file.
fn content(&self) -> String;
/// Whether this migration should not be applied in a database transaction.
fn no_tx(&self) -> bool;
/// Produce a future resolving to the migration query when `await`ed.
fn build<'a>(&'a self, ctx: &'a mut Self::Ctx) -> BoxFuture<'a, TernResult<Query>>;
/// The migration version.
fn version(&self) -> i64 {
self.migration_id().version()
}
/// Convert this migration to an [`AppliedMigration`] assuming that it was
/// successfully applied.
fn to_applied(&self, duration_ms: i64, applied_at: DateTime<Utc>) -> AppliedMigration {
AppliedMigration::new(self.migration_id(), self.content(), duration_ms, applied_at)
}
}
/// A type that is used to collect a [`MigrationSet`] -- migrations that are not
/// applied yet -- which is used as the input to runner commands.
pub trait MigrationSource {
/// A migration context needed to collect migration sets.
type Ctx: MigrationContext;
/// The set of migrations since the last apply.
fn migration_set(&self, latest_version: Option<i64>) -> MigrationSet<Self::Ctx>;
}
/// The `Migration`s derived from the files in the source directory that need to
/// be applied.
pub struct MigrationSet<Ctx: ?Sized> {
pub migrations: Vec<Box<dyn Migration<Ctx = Ctx>>>,
}
impl<Ctx> MigrationSet<Ctx>
where
Ctx: MigrationContext,
{
pub fn new<T>(vs: T) -> MigrationSet<Ctx>
where
T: Into<Vec<Box<dyn Migration<Ctx = Ctx>>>>,
{
let mut migrations = vs.into();
migrations.sort_by_key(|m| m.version());
MigrationSet { migrations }
}
/// Number of migrations in the set.
pub fn len(&self) -> usize {
self.migrations.len()
}
/// Versions present in this migration set.
pub fn versions(&self) -> Vec<i64> {
self.migrations
.iter()
.map(|m| m.version())
.collect::<Vec<_>>()
}
/// The latest version in the set.
pub fn max(&self) -> Option<i64> {
self.versions().iter().max().copied()
}
/// The set is empty for the requested operation.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
/// A helper trait for [`Migration`].
///
/// With the derive macros, the user's responsibility is to implement this for
/// a Rust migration, and the proc macro uses it to build an implementation of
/// [`Migration`].
pub trait QueryBuilder {
/// The context for running a migration this query is built for.
///
/// It should have all the abilities described in `MigrationContext` but in
/// addition can expose other behavior that is needed for a specific query.
type Ctx: MigrationContext;
/// Asyncronously produce the migration query.
fn build(&self, ctx: &mut Self::Ctx) -> impl Future<Output = TernResult<Query>> + Send;
}
/// A SQL query.
pub struct Query(String);
impl Query {
pub fn new(sql: String) -> Self {
Self(sql)
}
pub fn sql(&self) -> &str {
&self.0
}
/// Split a query comprised of multiple statements.
///
/// For queries having `no_tx = true`, a migration comprised of multiple,
/// separate SQL statements needs to be broken up so that the statements can
/// run indepedently. Otherwise, many backends will run the collection of
/// statements in a transaction automatically, which breaches the `no_tx`
/// contract.
pub fn split_statements(&self) -> TernResult<Vec<String>> {
let mut statements = Vec::new();
self.sql()
.lines()
.try_fold(String::new(), |mut buf, line| {
let line = line.trim();
writeln!(buf, "{line}")?;
// If a line ends with `;` and is not a comment, this is the
// last line of the statement. So push to `statements` and
// reset the buffer for parsing the next statement.
if line.ends_with(";") && !line.starts_with("--") {
statements.push(buf);
Ok::<String, std::fmt::Error>(String::new())
} else {
Ok(buf)
}
})?;
Ok(statements)
}
}
/// Name/version derived from the migration source filename.
#[derive(Debug, Clone)]
pub struct MigrationId {
/// Version parsed from the migration filename.
version: i64,
/// Description parsed from the migration filename.
description: String,
}
impl MigrationId {
pub fn new(version: i64, description: String) -> Self {
Self {
version,
description,
}
}
pub fn version(&self) -> i64 {
self.version
}
pub fn description(&self) -> String {
self.description.clone()
}
}
impl std::fmt::Display for MigrationId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "V{}__{}", self.version, self.description)
}
}
/// An `AppliedMigration` is the information about a migration that completed
/// successfully and it is also a row in the schema history table.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "sqlx", derive(sqlx::FromRow))]
pub struct AppliedMigration {
/// The migration version.
pub version: i64,
/// The description of the migration.
pub description: String,
/// An encoding of the migration file when it was applied.
pub content: String,
/// How long the migration took to run.
pub duration_ms: i64,
/// When the applied migration was inserted.
pub applied_at: DateTime<Utc>,
}
impl AppliedMigration {
pub fn new(
id: MigrationId,
content: String,
duration_ms: i64,
applied_at: DateTime<Utc>,
) -> Self {
Self {
version: id.version,
description: id.description,
content,
duration_ms,
applied_at,
}
}
}