migratrom 0.2.0

Declarative, self-verifying database migrations (core engine).
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
//! Migration orchestration: locking, checksum verification, ordering, and the
//! per-migration transaction strategy.

use std::sync::Arc;

use sha2::{Digest, Sha256};

use crate::checksum::verify_checksum;
use crate::db::{with_transaction, Db};
use crate::error::{MigratromError, Result};
use crate::graph::plan_order;
use crate::logger::{ConsoleLogger, MigrationLogger};
use crate::sql::SqlDialect;
use crate::types::{ApplyResult, Migration, Operation};

use super::executor::{run_operation, OpOutcome};
use super::history::{
    ensure_history_table, read_applied_ids, read_applied_records, record_migration,
    DEFAULT_HISTORY_TABLE,
};

/// Options controlling an apply run.
pub struct ApplyOptions {
    /// History table name; defaults to [`DEFAULT_HISTORY_TABLE`].
    pub history_table: Option<String>,
    /// Plan and run prechecks read-only, executing and recording nothing.
    pub dry_run: bool,
    /// Serialize applies via an advisory lock when the dialect supports it.
    pub advisory_lock: bool,
    /// Progress logger; defaults to [`ConsoleLogger`].
    pub logger: Option<Arc<dyn MigrationLogger>>,
}

impl Default for ApplyOptions {
    fn default() -> Self {
        Self {
            history_table: None,
            dry_run: false,
            advisory_lock: true,
            logger: None,
        }
    }
}

/// Apply pending migrations in dependency order and record them in history.
///
/// Already-applied migrations are skipped but their bodies are checksum-verified.
/// Each pending migration runs in a single transaction unless it contains an
/// [`Operation::outside_transaction`] operation, in which case transactional
/// segments and the outside op run separately.
pub async fn apply_migrations(
    migrations: &[Migration],
    db: &dyn Db,
    dialect: &dyn SqlDialect,
    options: &ApplyOptions,
) -> Result<ApplyResult> {
    let history_table = options
        .history_table
        .clone()
        .unwrap_or_else(|| DEFAULT_HISTORY_TABLE.to_string());

    if options.advisory_lock && dialect.capabilities().advisory_locks {
        let key = advisory_lock_key(&history_table);
        dialect.acquire_lock(db, key).await?;
        let result = apply_unlocked(migrations, db, dialect, options, &history_table).await;
        // Release even on failure, preserving the original error.
        let _ = dialect.release_lock(db, key).await;
        result
    } else {
        apply_unlocked(migrations, db, dialect, options, &history_table).await
    }
}

async fn apply_unlocked(
    migrations: &[Migration],
    db: &dyn Db,
    dialect: &dyn SqlDialect,
    options: &ApplyOptions,
    history_table: &str,
) -> Result<ApplyResult> {
    let logger: Arc<dyn MigrationLogger> = options
        .logger
        .clone()
        .unwrap_or_else(|| Arc::new(ConsoleLogger));

    ensure_history_table(db, history_table, dialect).await?;
    let applied_ids = read_applied_ids(db, history_table, dialect).await?;
    let stored = read_applied_records(db, history_table, dialect).await?;

    for m in migrations {
        if applied_ids.contains(&m.id) {
            if let Some(record) = stored.get(&m.id) {
                verify_checksum(&record.checksum, &m.operations, m.id)?;
            }
        }
    }

    let pending = plan_order(migrations, &applied_ids)?;
    let mut applied = Vec::new();
    let mut skipped_ops = Vec::new();

    for migration in &pending {
        logger.info(&format!("migration {}", migration.id));
        let result = apply_one(
            db,
            migration,
            dialect,
            history_table,
            logger.as_ref(),
            options.dry_run,
            &mut skipped_ops,
        )
        .await;
        match result {
            Ok(()) => {
                if !options.dry_run {
                    applied.push(migration.id);
                }
            }
            Err(cause) => {
                return Err(MigratromError::MigrationFailed {
                    id: migration.id,
                    cause: Box::new(cause),
                })
            }
        }
    }

    Ok(ApplyResult {
        applied,
        skipped_ops,
    })
}

async fn apply_one(
    db: &dyn Db,
    migration: &Migration,
    dialect: &dyn SqlDialect,
    history_table: &str,
    log: &dyn MigrationLogger,
    dry_run: bool,
    skipped_ops: &mut Vec<String>,
) -> Result<()> {
    let has_outside = migration.operations.iter().any(|o| o.outside_transaction);

    if dry_run {
        // Read-only: run prechecks, execute nothing, record nothing.
        for op in &migration.operations {
            if run_operation(db, op, log, true).await? == OpOutcome::Skipped {
                skipped_ops.push(op.id.clone());
            }
        }
        return Ok(());
    }

    if has_outside {
        return run_segmented(db, migration, dialect, history_table, log, skipped_ops).await;
    }

    with_transaction(db, || async {
        for op in &migration.operations {
            if run_operation(db, op, log, false).await? == OpOutcome::Skipped {
                skipped_ops.push(op.id.clone());
            }
        }
        record_migration(db, history_table, migration, dialect).await?;
        Ok::<(), MigratromError>(())
    })
    .await
}

/// Run a migration that contains outside-transaction operations: each
/// transactional segment runs in its own transaction, each outside op runs
/// standalone, and history is recorded with the final segment.
async fn run_segmented(
    db: &dyn Db,
    migration: &Migration,
    dialect: &dyn SqlDialect,
    history_table: &str,
    log: &dyn MigrationLogger,
    skipped_ops: &mut Vec<String>,
) -> Result<()> {
    let mut transactional: Vec<&Operation> = Vec::new();

    for op in &migration.operations {
        if op.outside_transaction {
            flush_segment(
                db,
                &transactional,
                false,
                dialect,
                history_table,
                migration,
                log,
                skipped_ops,
            )
            .await?;
            transactional.clear();
            if run_operation(db, op, log, false).await? == OpOutcome::Skipped {
                skipped_ops.push(op.id.clone());
            }
        } else {
            transactional.push(op);
        }
    }
    flush_segment(
        db,
        &transactional,
        true,
        dialect,
        history_table,
        migration,
        log,
        skipped_ops,
    )
    .await
}

#[allow(clippy::too_many_arguments)]
async fn flush_segment(
    db: &dyn Db,
    batch: &[&Operation],
    record: bool,
    dialect: &dyn SqlDialect,
    history_table: &str,
    migration: &Migration,
    log: &dyn MigrationLogger,
    skipped_ops: &mut Vec<String>,
) -> Result<()> {
    if batch.is_empty() {
        return Ok(());
    }
    with_transaction(db, || async {
        for op in batch {
            if run_operation(db, op, log, false).await? == OpOutcome::Skipped {
                skipped_ops.push(op.id.clone());
            }
        }
        if record {
            record_migration(db, history_table, migration, dialect).await?;
        }
        Ok::<(), MigratromError>(())
    })
    .await
}

/// First eight SHA-256 bytes of the history-table name as a signed, big-endian
/// 64-bit advisory-lock key.
pub fn advisory_lock_key(history_table: &str) -> i64 {
    let digest = Sha256::digest(history_table.as_bytes());
    let mut bytes = [0u8; 8];
    bytes.copy_from_slice(&digest[..8]);
    i64::from_be_bytes(bytes)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::Row;
    use crate::sql::SqliteDialect;
    use crate::types::{Check, ExecuteStep};
    use async_trait::async_trait;
    use std::collections::{HashMap, VecDeque};
    use std::sync::Mutex;

    #[derive(Default)]
    struct FakeState {
        executed: Vec<String>,
        bool_results: HashMap<String, bool>,
        bool_seqs: HashMap<String, VecDeque<bool>>,
        depth: u32,
        snapshot: Vec<String>,
        rolled_back: bool,
    }

    #[derive(Default)]
    struct FakeDb {
        state: Mutex<FakeState>,
    }

    impl FakeDb {
        fn set_bool(&self, sql: &str, value: bool) {
            self.state
                .lock()
                .unwrap()
                .bool_results
                .insert(sql.to_string(), value);
        }
        fn set_bool_seq(&self, sql: &str, values: &[bool]) {
            self.state
                .lock()
                .unwrap()
                .bool_seqs
                .insert(sql.to_string(), values.iter().copied().collect());
        }
        fn executed(&self) -> Vec<String> {
            self.state.lock().unwrap().executed.clone()
        }
        fn rolled_back(&self) -> bool {
            self.state.lock().unwrap().rolled_back
        }
    }

    #[async_trait]
    impl Db for FakeDb {
        async fn query_bool(&self, sql: &str) -> Result<bool> {
            let mut state = self.state.lock().unwrap();
            if let Some(seq) = state.bool_seqs.get_mut(sql) {
                if let Some(v) = seq.pop_front() {
                    return Ok(v);
                }
            }
            Ok(state.bool_results.get(sql).copied().unwrap_or(false))
        }
        async fn execute(&self, sql: &str) -> Result<()> {
            self.state.lock().unwrap().executed.push(sql.to_string());
            Ok(())
        }
        async fn query_rows(&self, _sql: &str) -> Result<Vec<Box<dyn Row>>> {
            Ok(Vec::new())
        }
        async fn begin(&self) -> Result<()> {
            let mut state = self.state.lock().unwrap();
            if state.depth == 0 {
                state.snapshot = state.executed.clone();
                state.rolled_back = false;
            }
            state.depth += 1;
            Ok(())
        }
        async fn commit(&self) -> Result<()> {
            self.state.lock().unwrap().depth -= 1;
            Ok(())
        }
        async fn rollback(&self) -> Result<()> {
            let mut state = self.state.lock().unwrap();
            state.depth -= 1;
            if state.depth == 0 {
                state.executed = state.snapshot.clone();
                state.rolled_back = true;
            }
            Ok(())
        }
    }

    fn op(id: &str, pre: &str, exec: &str, post: &str) -> Operation {
        Operation {
            id: id.to_string(),
            label: id.to_string(),
            precheck: vec![Check::new("pre", pre)],
            execute: vec![ExecuteStep::new("do", exec)],
            postcheck: vec![Check::new("post", post)],
            outside_transaction: false,
        }
    }

    fn options() -> ApplyOptions {
        ApplyOptions {
            advisory_lock: false,
            ..Default::default()
        }
    }

    #[tokio::test]
    async fn applies_and_records_a_migration() {
        let db = FakeDb::default();
        db.set_bool("PRE", true);
        db.set_bool_seq("POST", &[false, true]); // skip-check false, then verify true
        let migration = Migration::new(1, None, vec![op("op.one", "PRE", "DO", "POST")]);

        let result = apply_migrations(&[migration], &db, &SqliteDialect, &options())
            .await
            .unwrap();

        assert_eq!(result.applied, vec![1]);
        assert!(result.skipped_ops.is_empty());
        assert!(db.executed().iter().any(|s| s == "DO"));
        assert!(db.executed().iter().any(|s| s.starts_with("INSERT INTO")));
    }

    #[tokio::test]
    async fn skips_already_satisfied_operation() {
        let db = FakeDb::default();
        db.set_bool("POST", true); // postcheck already passes => skip
        let migration = Migration::new(1, None, vec![op("op.one", "PRE", "DO", "POST")]);

        let result = apply_migrations(&[migration], &db, &SqliteDialect, &options())
            .await
            .unwrap();

        assert_eq!(result.applied, vec![1]);
        assert_eq!(result.skipped_ops, vec!["op.one".to_string()]);
        assert!(!db.executed().iter().any(|s| s == "DO"));
    }

    #[tokio::test]
    async fn dry_run_executes_and_records_nothing() {
        let db = FakeDb::default();
        db.set_bool("PRE", true);
        db.set_bool("POST", false);
        let migration = Migration::new(1, None, vec![op("op.one", "PRE", "DO", "POST")]);

        let result = apply_migrations(
            &[migration],
            &db,
            &SqliteDialect,
            &ApplyOptions {
                dry_run: true,
                advisory_lock: false,
                ..Default::default()
            },
        )
        .await
        .unwrap();

        assert!(result.applied.is_empty());
        assert!(!db.executed().iter().any(|s| s == "DO"));
        assert!(!db.executed().iter().any(|s| s.starts_with("INSERT INTO")));
    }

    #[tokio::test]
    async fn rolls_back_when_postcheck_fails() {
        let db = FakeDb::default();
        db.set_bool("PRE", true);
        db.set_bool("POST", false); // never verifies => postcheck failure
        let migration = Migration::new(1, None, vec![op("op.one", "PRE", "DO", "POST")]);

        let err = apply_migrations(&[migration], &db, &SqliteDialect, &options())
            .await
            .unwrap_err();

        assert!(matches!(err, MigratromError::MigrationFailed { id: 1, .. }));
        assert!(db.rolled_back());
        assert!(!db.executed().iter().any(|s| s == "DO"));
    }

    #[test]
    fn advisory_lock_key_is_stable() {
        // Matches the cross-language derivation: signed BE i64 of the first 8 hash bytes.
        assert_eq!(advisory_lock_key("a"), advisory_lock_key("a"));
        assert_ne!(advisory_lock_key("a"), advisory_lock_key("b"));
    }
}