tern_core/
runner.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
use chrono::{DateTime, Utc};

use crate::error::{TernResult, ToMigrationResult as _};
use crate::migration::{AppliedMigration, Migration, MigrationContext};

/// Run migrations in the chosen context.
pub struct Runner<C: MigrationContext> {
    context: C,
}

impl<C> Runner<C>
where
    C: MigrationContext,
{
    pub fn new(context: C) -> Self {
        Self { context }
    }

    /// Apply all unapplied migrations.
    pub async fn apply_all(&mut self) -> TernResult<Report> {
        self.context.check_history_table().await?;
        let latest = self.context.latest_version().await?;
        let set = self.context.migration_set(latest);

        let mut results = Vec::new();
        for migration in &set.migrations {
            let id = migration.migration_id();
            log::info!("applying migration {id}");

            let result = self
                .context
                .apply(migration.as_ref())
                .await
                .to_migration_result(migration.as_ref());
            results.push(result);
        }
        let report = Report::new(results);

        Ok(report)
    }

    /// Return the migration set that would be applied without the `dryrun`.
    pub async fn dryrun(&mut self) -> TernResult<Report> {
        self.context.check_history_table().await?;
        let latest = self.context.latest_version().await?;
        let set = self.context.migration_set(latest);

        let mut unapplied = Vec::new();
        for migration in &set.migrations {
            unapplied.push(MigrationResult::from_unapplied(migration.as_ref()))
        }
        let report = Report::new(unapplied);

        Ok(report)
    }

    /// List the migrations that have already been applied.
    pub async fn list_applied(&mut self) -> TernResult<Report> {
        self.context.check_history_table().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)
    }

    /// `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
    }

    /// Run a "soft apply" for the supplied range of migration versions.  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, or migrate from a different migration tool
    /// to this one, etc.
    ///
    /// If `from_version` (resp. `to_version`) is `None`, this will soft apply
    /// starting at the first migration (resp. ending with the last migration).
    pub async fn soft_apply(
        &mut self,
        from_version: Option<i64>,
        to_version: Option<i64>,
    ) -> TernResult<Report> {
        self.context.check_history_table().await?;
        let all = self.context.migration_set(None);

        let mut results = Vec::new();
        for migration in &all.migrations {
            let id = migration.migration_id();
            log::info!("soft applying migration {id}");

            let ver = migration.version();

            // Skip if before `from_version`.
            if matches!(from_version, Some(v) if ver < v) {
                continue;
            }
            // Break if after `to_version`.
            if matches!(to_version, Some(v) if ver > v) {
                break;
            }

            let applied = migration.to_applied(0, Utc::now());
            self.context.upsert_applied(&applied).await?;
            let result = MigrationResult::from_soft_applied(&applied);
            results.push(result);
        }
        let report = Report::new(results);

        Ok(report)
    }
}

/// A formatted version of a collection of migrations.
#[derive(Debug, Clone)]
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()
    }
}

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

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

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

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

    pub(crate) fn from_failed<M>(migration: &M, message: String) -> Self
    where
        M: Migration + ?Sized,
    {
        Self {
            version: migration.version(),
            state: MigrationState::Failed,
            applied_at: None,
            description: migration.migration_id().description(),
            content: Self::truncate_content(&migration.content()),
            transactional: Transactional::from_boolean(migration.no_tx()),
            duration_ms: RunDuration::Unapplied,
            error_reason: MigrationErrors::Message(message),
        }
    }

    fn truncate_content(content: &str) -> String {
        let res = content.lines().take(10).collect::<Vec<_>>().join("\n") + "...";
        res.to_string()
    }
}

#[derive(Debug, Clone, Copy)]
enum MigrationState {
    Applied,
    SoftApplied,
    Unapplied,
    Failed,
}

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

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

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

#[derive(Debug, Clone)]
enum MigrationErrors {
    Message(String),
    None,
}

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::NotApplicable(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, "UNAPPLIED"),
            Self::Failed => write!(f, "FAILED"),
        }
    }
}

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, "UNAPPLIED"),
        }
    }
}

impl std::fmt::Display for MigrationErrors {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Message(e) => write!(f, "{}", e),
            Self::None => write!(f, "SUCCESS"),
        }
    }
}