tern-core 3.1.6

Core interfaces and types for `tern` migration tooling.
Documentation
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! A migration runner for a context.
//!
//! The [`Runner`] type accepts any [`MigrationContext`] and exposes the methods
//! needed for tasks related to database migrations.
//!
//! Each method also exists as a (sub)command of the `App`, available with the
//! feature flag "cli" enabled.
use crate::error::{DatabaseError as _, Error, TernResult};
use crate::migration::{
    AppliedMigration, Migration, MigrationContext, MigrationId,
};

use chrono::{DateTime, Utc};
use display_json::{DebugAsJson, DisplayAsJsonPretty};
use serde::Serialize;
use std::collections::HashSet;
use std::fmt::Write;

/// Run operations on a set of migrations for the chosen context.
pub struct Runner<C: MigrationContext> {
    context: C,
}

impl<C> Runner<C>
where
    C: MigrationContext,
{
    /// Create a new `Runner` with default arguments from a context.
    pub fn new(context: C) -> Self {
        Self { context }
    }

    /// `CREATE IF NOT EXISTS` the history table.
    pub async fn init_history(&mut self) -> TernResult<()> {
        self.context.check_history_table().await
    }

    /// `DROP` the history table.
    pub async fn drop_history(&mut self) -> TernResult<()> {
        self.context.drop_history_table().await
    }

    // Find applied migrations that are not in the source directory.
    async fn validate_source(&mut self) -> TernResult<()> {
        self.context.check_history_table().await?;
        let applied: HashSet<MigrationId> = self
            .context
            .previously_applied()
            .await?
            .into_iter()
            .map(MigrationId::from)
            .collect();
        let source: HashSet<MigrationId> = self
            .context
            .migration_set(None)
            .migration_ids()
            .into_iter()
            .collect();

        check_migrations_in_sync(applied, source)
    }

    // Check that the target migration version (for some operation) is valid.
    fn validate_target(
        &self,
        last_applied: Option<i64>,
        target_version: Option<i64>,
    ) -> TernResult<()> {
        let Some(source) = self.context.migration_set(None).max() else {
            return Ok(());
        };
        if let Some(target) = target_version {
            match last_applied {
                Some(applied) if target < applied => {
                    Err(Error::Invalid(format!(
                        "target version V{target} earlier than latest applied version V{applied}",
                    )))?
                },
                _ if target > source => Err(Error::Invalid(format!(
                    "target version V{target} does not exist, latest version found was V{source}",
                )))?,
                _ => Ok(()),
            }
        } else {
            Ok(())
        }
    }

    /// Apply unapplied migrations up to and including the specified version.
    pub async fn run_apply(
        &mut self,
        target_version: Option<i64>,
        dryrun: bool,
    ) -> TernResult<Report> {
        self.validate_source().await?;
        let last_applied = self.context.latest_version().await?;
        self.validate_target(last_applied, target_version)?;

        let unapplied = self.context.migration_set(last_applied);

        let mut results = Vec::new();
        for migration in &unapplied.migrations {
            let id = migration.migration_id();
            let ver = migration.version();

            // Reached the target version, break the loop.
            if matches!(target_version, Some(end) if ver > end) {
                break;
            }

            let result = if dryrun {
                // Build each query, which possibly includes dynamic ones.
                let query = migration
                    .build(&mut self.context)
                    .await
                    .with_report(&results)?;

                MigrationResult::from_unapplied(migration.as_ref(), query.sql())
            } else {
                log::trace!("applying migration {id}");

                self.context
                    .apply(migration.as_ref())
                    .await
                    .tern_migration_result(migration.as_ref())
                    .with_report(&results)
                    .map(|v| {
                        MigrationResult::from_applied(
                            &v,
                            Some(migration.no_tx()),
                        )
                    })?
            };

            results.push(result);
        }

        Ok(Report::new(results))
    }

    /// Apply all unapplied migrations.
    #[deprecated(since = "3.1.0", note = "use `run_apply_all`")]
    pub async fn apply_all(&mut self) -> TernResult<Report> {
        self.run_apply(None, false).await
    }

    /// Apply all unapplied migrations.
    pub async fn run_apply_all(&mut self, dryrun: bool) -> TernResult<Report> {
        self.run_apply(None, dryrun).await
    }

    /// List the migrations that have already been applied.
    pub async fn list_applied(&mut self) -> TernResult<Report> {
        self.validate_source().await?;

        let applied = self
            .context
            .previously_applied()
            .await?
            .iter()
            .map(|m| MigrationResult::from_applied(m, None))
            .collect::<Vec<_>>();
        let report = Report::new(applied);

        Ok(report)
    }

    #[deprecated(
        since = "3.1.0",
        note = "no valid use case for `start_version`"
    )]
    pub async fn soft_apply(
        &mut self,
        start_version: Option<i64>,
        target_version: Option<i64>,
    ) -> TernResult<Report> {
        if start_version.is_some() {
            return Err(Error::Invalid(
                "no valid `start_version` other than the first unapplied, use `run_soft_apply`"
                    .into(),
            ));
        }
        self.run_soft_apply(target_version, false).await
    }

    /// Run a "soft apply" of the migrations up to and including the specified
    /// version.
    ///
    /// This means that the migration will be saved in the history table, but
    /// will not have its query applied.  This is useful in the case where you
    /// want to change migration tables, apply a patch to the current one,
    /// migrate from a different migration tool, etc.
    pub async fn run_soft_apply(
        &mut self,
        target_version: Option<i64>,
        dryrun: bool,
    ) -> TernResult<Report> {
        self.validate_source().await?;
        let last_applied = self.context.latest_version().await?;
        self.validate_target(last_applied, target_version)?;

        let unapplied = self.context.migration_set(last_applied);

        let mut results = Vec::new();
        for migration in &unapplied.migrations {
            let id = migration.migration_id();
            let ver = migration.version();

            // Reached the last version, break the loop.
            if matches!(target_version, Some(end) if ver > end) {
                break;
            }

            // Build each query, which possibly includes dynamic ones.
            let query = migration
                .build(&mut self.context)
                .await
                .with_report(&results)?;
            let mut content = String::from("-- SOFT APPLIED:\n\n");
            writeln!(content, "{query}")?;

            let applied = migration.to_applied(0, Utc::now(), &content);
            let result = MigrationResult::from_soft_applied(&applied, dryrun);

            if !dryrun {
                log::trace!("soft applying migration {id}");
                self.context
                    .insert_applied(&applied)
                    .await
                    .with_report(&results)?;
            }

            results.push(result);
        }
        let report = Report::new(results);

        Ok(report)
    }
}

/// A formatted version of a collection of migrations.
#[derive(Clone, Serialize, DebugAsJson, DisplayAsJsonPretty, Default)]
pub struct Report {
    migrations: Vec<MigrationResult>,
}

impl Report {
    pub fn new(migrations: Vec<MigrationResult>) -> Self {
        Self { migrations }
    }

    pub fn count(&self) -> usize {
        self.migrations.len()
    }

    /// Return the vector of results.
    pub fn results(&self) -> Vec<MigrationResult> {
        self.migrations.clone()
    }

    /// Return an iterator of the migration results.
    pub fn iter_results(&self) -> impl Iterator<Item = MigrationResult> {
        self.migrations.clone().into_iter()
    }
}

/// A formatted version of a migration that is the return type for `Runner`
/// actions.
#[derive(Clone, Serialize, DebugAsJson, DisplayAsJsonPretty)]
#[allow(dead_code)]
pub struct MigrationResult {
    dryrun: bool,
    version: i64,
    state: MigrationState,
    applied_at: Option<DateTime<Utc>>,
    description: String,
    content: String,
    transactional: Transactional,
    duration_ms: RunDuration,
}

impl MigrationResult {
    pub(crate) fn from_applied(
        applied: &AppliedMigration,
        no_tx: Option<bool>,
    ) -> Self {
        Self {
            dryrun: false,
            version: applied.version,
            state: MigrationState::Applied,
            applied_at: Some(applied.applied_at),
            description: applied.description.clone(),
            content: applied.content.clone(),
            transactional: no_tx.map(Transactional::from_boolean).unwrap_or(
                Transactional::Other("Previously applied".to_string()),
            ),
            duration_ms: RunDuration::Duration(applied.duration_ms),
        }
    }

    pub(crate) fn from_soft_applied(
        applied: &AppliedMigration,
        dryrun: bool,
    ) -> Self {
        Self {
            dryrun,
            version: applied.version,
            state: MigrationState::SoftApplied,
            applied_at: Some(applied.applied_at),
            description: applied.description.clone(),
            content: applied.content.clone(),
            transactional: Transactional::Other("Soft applied".to_string()),
            duration_ms: RunDuration::Duration(applied.duration_ms),
        }
    }

    pub(crate) fn from_unapplied<M>(migration: &M, content: &str) -> Self
    where
        M: Migration + ?Sized,
    {
        Self {
            dryrun: true,
            version: migration.version(),
            state: MigrationState::Unapplied,
            applied_at: None,
            description: migration.migration_id().description(),
            content: content.into(),
            transactional: Transactional::from_boolean(migration.no_tx()),
            duration_ms: RunDuration::Unapplied,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Serialize)]
enum MigrationState {
    Applied,
    SoftApplied,
    Unapplied,
}

#[derive(Debug, Clone, Serialize)]
enum Transactional {
    NoTransaction,
    InTransaction,
    Other(String),
}

impl Transactional {
    fn from_boolean(v: bool) -> Self {
        if v {
            return Self::NoTransaction;
        };
        Self::InTransaction
    }
}

#[derive(Debug, Clone, Copy, Serialize)]
enum RunDuration {
    Duration(i64),
    Unapplied,
}

impl std::fmt::Display for Transactional {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NoTransaction => write!(f, "No Transaction"),
            Self::InTransaction => write!(f, "In Transaction"),
            Self::Other(s) => write!(f, "{s}"),
        }
    }
}

impl std::fmt::Display for MigrationState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Applied => write!(f, "Applied"),
            Self::SoftApplied => write!(f, "Soft Applied"),
            Self::Unapplied => write!(f, "Not Applied"),
        }
    }
}

impl std::fmt::Display for RunDuration {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Duration(ms) => write!(f, "{}ms", ms),
            Self::Unapplied => write!(f, "Not Applied"),
        }
    }
}

// Migrations that have been applied already but do not exist locally.
fn check_migrations_in_sync(
    applied: HashSet<MigrationId>,
    source: HashSet<MigrationId>,
) -> TernResult<()> {
    let source_not_found: Vec<&MigrationId> =
        applied.difference(&source).collect();

    if !source_not_found.is_empty() {
        return Err(Error::OutOfSync {
            at_issue: source_not_found.into_iter().cloned().collect(),
            msg: "version/name applied but missing in source".into(),
        });
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::Error;
    use super::MigrationId;

    use std::collections::HashSet;

    #[test]
    fn missing_source() {
        let source: HashSet<MigrationId> = vec![
            MigrationId::new(1, "first".into()),
            MigrationId::new(2, "second".into()),
            MigrationId::new(3, "fourth".into()),
        ]
        .into_iter()
        .collect();
        let applied: HashSet<MigrationId> = vec![
            MigrationId::new(1, "first".into()),
            MigrationId::new(2, "second".into()),
            MigrationId::new(3, "third".into()),
        ]
        .into_iter()
        .collect();
        let missing = vec![MigrationId::new(3, "third".into())];
        let result = super::check_migrations_in_sync(applied, source);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, Error::OutOfSync { at_issue, .. } if *at_issue == missing)
        );
    }

    #[test]
    fn fewer_in_source() {
        let source: HashSet<MigrationId> = vec![
            MigrationId::new(1, "first".into()),
            MigrationId::new(2, "second".into()),
            MigrationId::new(3, "third".into()),
        ]
        .into_iter()
        .collect();
        let applied: HashSet<MigrationId> = vec![
            MigrationId::new(1, "first".into()),
            MigrationId::new(2, "second".into()),
            MigrationId::new(3, "third".into()),
            MigrationId::new(4, "fourth".into()),
        ]
        .into_iter()
        .collect();
        let missing = vec![MigrationId::new(4, "fourth".into())];
        let result = super::check_migrations_in_sync(applied, source);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            matches!(err, Error::OutOfSync { at_issue, .. } if *at_issue == missing)
        );
    }

    #[test]
    fn mismatched_source() {
        let source: HashSet<MigrationId> = vec![
            MigrationId::new(1, "first".into()),
            MigrationId::new(2, "second".into()),
            MigrationId::new(3, "third".into()),
            MigrationId::new(4, "fifth".into()),
            MigrationId::new(5, "sixth".into()),
            MigrationId::new(6, "seventh".into()),
            MigrationId::new(7, "eighth".into()),
        ]
        .into_iter()
        .collect();
        let applied: HashSet<MigrationId> = vec![
            MigrationId::new(1, "first".into()),
            MigrationId::new(2, "second".into()),
            MigrationId::new(3, "third".into()),
            MigrationId::new(4, "fourth".into()),
            MigrationId::new(5, "fifth".into()),
        ]
        .into_iter()
        .collect();
        let divergence = vec![
            MigrationId::new(4, "fourth".into()),
            MigrationId::new(5, "fifth".into()),
        ];
        let result = super::check_migrations_in_sync(applied, source);
        assert!(result.is_err());
        let err = result.unwrap_err();
        let Error::OutOfSync { mut at_issue, .. } = err else {
            panic!("expected Error::OutOfSync");
        };
        at_issue.sort_by_key(|migration| migration.version());
        assert_eq!(divergence, at_issue);
    }
}