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
use crate::{salmo_contex::SalmoContext, migration_data::committed::{Commit, CommittedFile}, backend::{MigrationWithStatus, MigrationStatus}};
use anyhow::anyhow;

pub fn commit_migration(ctx: &SalmoContext, migration_id: &str) -> anyhow::Result<Commit> {
  let migrations = ctx.migrations()?;
  let migration = migrations.db[migration_id].clone();
  let commits = ctx.commits()?;
  let mut backends = ctx.environments.iter().map(|e| e.backend()).collect::<anyhow::Result<Vec<_>>>()?;
  let status = backends.iter_mut().map(|b| {
      Ok(b.migration_status(&commits, &[migration.clone()])?.into_iter().next().unwrap())
  }).collect::<anyhow::Result<Vec<MigrationWithStatus>>>()?;

  if !status.iter().all(|m| matches!(m.status, MigrationStatus::Tried { up_to_date: _ })) {
      return Err(anyhow!("Migration `{}` has not been tried in an environment. Commit aborted.", migration_id))
  }

  if !status.iter().all(|m| match m.status {
      MigrationStatus::Tried { up_to_date } => up_to_date,
      _ => false
  } ) {
      return Err(anyhow!("Migration `{}` was changed after last being tried. Retry it in order to commit. Commit aborted.", migration_id))
  }

  let commit = CommittedFile::add_commit(ctx, migration_id)?;

  for (mut backend, m) in backends.into_iter().zip(status) {
    backend.execute_migrations(&[MigrationWithStatus {
        migration: m.migration.clone(),
        status: MigrationStatus::Committed { tried: true }
    }])?;
    backend.untry_migrations(&[m])?;
  }

  Ok(commit)
}