libsalmo/migration_data/
migrations.rs

1use std::{path::{PathBuf, Path}, collections::HashMap, io::Error, fs::read_to_string};
2
3use log::trace;
4use sha2::{Sha256, Digest};
5
6#[derive(Debug, Clone, Hash, PartialEq, Eq)]
7pub struct Migration {
8  pub id: String,
9  pub path: PathBuf
10}
11
12impl Migration {
13  pub fn migrate_path(&self) -> PathBuf {
14    self.path.join("migrate.sql")
15  }
16
17  pub fn revert_path(&self) -> PathBuf {
18    self.path.join("revert.sql")
19  }
20
21  pub fn migrate_sql(&self) -> anyhow::Result<String> {
22    Ok(read_to_string(self.migrate_path())?)
23  }
24
25  pub fn revert_sql(&self) -> anyhow::Result<String> {
26    Ok(read_to_string(self.revert_path())?)
27  }
28
29  pub fn migrate_hash(&self) -> anyhow::Result<String> {
30    let contents = self.migrate_sql()?;
31    let mut hasher = Sha256::new();
32    hasher.update(contents);
33    Ok(hex::encode(hasher.finalize()))
34  }
35}
36
37pub struct MigrationRegistry {
38  pub db: HashMap<String, Migration>
39}
40
41impl MigrationRegistry {
42  pub fn load(dir: &Path) -> Result<Self, Error> {
43    trace!("loading registry of migrations in dir {:?}", dir);
44    let db: HashMap<String, Migration> = dir.read_dir()?.filter_map(|entry| {
45      let entry = entry.ok()?;
46      if entry.file_type().ok()?.is_dir() {
47        let id = entry.path().file_name()?.to_str()?.to_owned();
48        Some((id.clone(), Migration {
49          id,
50          path: entry.path()
51        }))
52      } else {
53        None
54      }
55    }).collect();
56    Ok(Self {
57      db
58    })
59  }
60}