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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
#![warn(missing_docs, unreachable_pub, rust_2018_idioms)]
#![forbid(unsafe_code)]
mod diff;
mod dyn_migration;
mod error;
mod state;
pub use dyn_migration::{MigrationCtxProvider, MigrationRunMode};
pub use error::*;
use async_trait::async_trait;
use dyn_migration::{CtxRegistry, DynMigration, DynMigrationScriptCtx, MigrationDirection};
use itertools::Itertools;
use migrate_state::{StateGuard, StateLock};
use state::State;
use std::fmt;
use tracing::{info, info_span, instrument};
use tracing_futures::Instrument;
#[async_trait]
pub trait Migration: Send + 'static {
type Ctx: Send + 'static;
async fn up(&mut self, ctx: &mut Self::Ctx) -> Result<(), DynError>;
async fn down(&mut self, ctx: &mut Self::Ctx) -> Result<(), DynError>;
}
pub struct PlanBuilder {
ctx_registry: CtxRegistry,
migrations: Vec<DynMigration>,
state_lock: Box<dyn StateLock>,
force_lock: bool,
}
impl PlanBuilder {
pub fn ctx_provider(&mut self, provider: impl MigrationCtxProvider) -> &mut Self {
self.ctx_registry.insert(provider);
self
}
pub fn migration(
&mut self,
name: impl Into<String>,
migration: impl Migration + 'static,
) -> &mut Self {
self.migrations
.push(DynMigration::new(name.into(), migration));
self
}
pub fn force_lock(&mut self, val: bool) -> &mut Self {
self.force_lock = val;
self
}
pub fn display(&self) -> MigrationsDisplayBuilder<'_> {
MigrationsDisplayBuilder(self)
}
#[instrument(skip(self), err)]
pub async fn build(self, kind: &MigrationsSelection<'_>) -> Result<Plan, PlanBuildError> {
info!("Aсquiring the state lock (this may take a moment)...");
let mut state_guard = self
.state_lock
.lock(self.force_lock)
.await
.map_err(PlanBuildErrorKind::StateLock)?;
let state_client = state_guard.client();
let mut state = State::decode(
&state_client
.fetch()
.await
.map_err(PlanBuildErrorKind::StateFetch)?,
)?;
let mut diff = diff::diff(self.migrations, &mut state.applied_migrations)?;
let (left_completed, left_pending, kind) = match kind {
MigrationsSelection::Up { inclusive_bound } => {
let left_pending = match inclusive_bound {
Some(bound) => {
let idx = Self::find_migration(&diff.pending, bound)?;
diff.pending.split_off(idx + 1)
}
None => vec![],
};
(diff.completed, left_pending, PlanKind::Up(diff.pending))
}
MigrationsSelection::Down { inclusive_bound } => {
let idx = Self::find_migration(&diff.completed, inclusive_bound)?;
let kind = PlanKind::Down(diff.completed.split_off(idx));
(diff.completed, diff.pending, kind)
}
};
Ok(Plan {
ctx_registry: self.ctx_registry,
state: StateCtx {
guard: Some(state_guard),
pruned: diff.pruned,
state,
},
left_completed,
left_pending,
kind,
})
}
fn find_migration(migs: &[DynMigration], bound: &str) -> Result<usize, PlanBuildError> {
migs.iter().position(|it| it.name == bound).ok_or_else(|| {
PlanBuildErrorKind::UnknownMigration {
name: bound.to_owned(),
available: migs.iter().map(|it| it.name.clone()).collect(),
}
.into()
})
}
}
#[derive(Debug)]
pub enum MigrationsSelection<'a> {
Up {
inclusive_bound: Option<&'a str>,
},
Down {
inclusive_bound: &'a str,
},
}
pub struct Plan {
ctx_registry: CtxRegistry,
state: StateCtx,
#[allow(unused)]
left_completed: Vec<DynMigration>,
#[allow(unused)]
left_pending: Vec<DynMigration>,
kind: PlanKind,
}
impl Plan {
pub fn builder(state_lock: impl StateLock + 'static) -> PlanBuilder {
PlanBuilder {
ctx_registry: CtxRegistry::new(),
migrations: Vec::new(),
state_lock: Box::new(state_lock),
force_lock: false,
}
}
pub fn display(&self) -> PlanDisplayBuilder<'_> {
PlanDisplayBuilder { plan: self }
}
#[instrument(skip(self))]
pub async fn exec(mut self, run_mode: MigrationRunMode) -> Result<(), PlanExecError> {
let mut errors = vec![];
let mut guard = self.state.guard.take().unwrap();
info!("Executing migrations...");
if let Err(err) = self.try_exec(run_mode).await {
errors.push(err);
}
info!("Saving new migration state data...");
if let Err(err) = guard.client().update(self.state.state.encode()).await {
errors.push(PlanExecErrorKind::UpdateState(err));
}
info!("Releasing the state lock (this may take a moment)...");
if let Err(err) = guard.unlock().await {
errors.push(PlanExecErrorKind::UnlockState(err));
}
if errors.is_empty() {
Ok(())
} else {
Err(PlanExecError { errors })
}
}
async fn try_exec(&mut self, run_mode: MigrationRunMode) -> Result<(), PlanExecErrorKind> {
let mut ctx = DynMigrationScriptCtx {
ctx_registry: &mut self.ctx_registry,
run_mode,
direction: self.kind.to_migration_direction(),
};
match &mut self.kind {
PlanKind::Up(migrations) => {
for migration in migrations {
let state_entry = state::MigrationMeta {
name: migration.name.clone(),
};
self.state.state.applied_migrations.push(state_entry);
let span = info_span!("migrate-up");
Self::exec_migration(&mut ctx, migration)
.instrument(span)
.await?;
}
}
PlanKind::Down(migrations) => {
for migration in migrations.iter_mut().rev() {
let removed = self.state.state.applied_migrations.pop();
assert_eq!(removed.unwrap().name, migration.name);
let span = info_span!("migrate-down");
Self::exec_migration(&mut ctx, migration)
.instrument(span)
.await?;
}
}
}
Ok(())
}
async fn exec_migration(
ctx: &mut DynMigrationScriptCtx<'_>,
migration: &mut DynMigration,
) -> Result<(), PlanExecErrorKind> {
info!(
migration = migration.name.as_str(),
direction = %ctx.direction,
"Executing migration",
);
match migration.script.exec(ctx).await {
Err(PlanExecErrorKind::CtxLacksNoCommitMode) => {
info!("Migration lacks support for no-commit mode, skipping it...");
Ok(())
}
result => result,
}
}
}
pub struct MigrationsDisplayBuilder<'a>(&'a PlanBuilder);
impl MigrationsDisplayBuilder<'_> {
pub fn build(&self) -> impl '_ + fmt::Display {
MigrationsDisplay(self)
}
}
struct MigrationsDisplay<'a>(&'a MigrationsDisplayBuilder<'a>);
impl fmt::Display for MigrationsDisplay<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let format = &(self.0)
.0
.migrations
.iter()
.enumerate()
.format_with("\n", |(i, mig), f| {
f(&format_args!("{}. {}", i + 1, mig.name))
});
write!(f, "{}", format)
}
}
pub struct PlanDisplayBuilder<'p> {
plan: &'p Plan,
}
impl PlanDisplayBuilder<'_> {
pub fn build(&self) -> impl '_ + fmt::Display {
PlanDisplay(self)
}
}
struct PlanDisplay<'p>(&'p PlanDisplayBuilder<'p>);
impl fmt::Display for PlanDisplay<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let plan = self.0.plan;
let (migrations, touched) = match &plan.kind {
PlanKind::Up(migrations) => (migrations, "applied (up)"),
PlanKind::Down(migrations) => (migrations, "rolled back (down)"),
};
if migrations.is_empty() {
writeln!(f, "No migrations are planned to be {}", touched)?;
} else {
let migrations = plan
.kind
.migrations_in_exec_order()
.format_with("\n", |mig, f| f(&format_args!("- {}", mig.name)));
writeln!(
f,
"The following migrations are planned to be {}:\n{}",
touched, migrations
)?;
}
if !plan.state.pruned.is_empty() {
let pruned = plan
.state
.pruned
.iter()
.format_with("\n", |mig, f| f(&format_args!("- {}", mig.name)));
writeln!(
f,
"\n\nThe following migrations are planned to be pruned: {}",
pruned
)?;
}
Ok(())
}
}
enum PlanKind {
Up(Vec<DynMigration>),
Down(Vec<DynMigration>),
}
impl PlanKind {
fn to_migration_direction(&self) -> MigrationDirection {
match self {
PlanKind::Up(_) => MigrationDirection::Up,
PlanKind::Down(_) => MigrationDirection::Down,
}
}
fn migrations_in_exec_order(&self) -> impl Iterator<Item = &DynMigration> {
match self {
PlanKind::Up(migrations) => Box::new(migrations.iter()) as Box<dyn Iterator<Item = _>>,
PlanKind::Down(migrations) => Box::new(migrations.iter().rev()),
}
}
}
struct StateCtx {
guard: Option<Box<dyn StateGuard>>,
pruned: Vec<state::MigrationMeta>,
state: state::State,
}