diff options
Diffstat (limited to 'src/db')
| -rw-r--r-- | src/db/mod.rs | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/src/db/mod.rs b/src/db/mod.rs new file mode 100644 index 0000000..1a60ce3 --- /dev/null +++ b/src/db/mod.rs @@ -0,0 +1,54 @@ +use miette::Diagnostic; +use thiserror::Error; + +pub struct Migration { + pub filename: String, + pub directory: String, + pub script_contents: String, +} + +const DB_MIGRATION_DIR: &str = "./src/db/"; + +/// To prevent accidental error coersion in other modules, std::io::Error gets cast as Migration Error here +#[derive(Debug, Diagnostic, Error)] +pub enum MigrationError { + #[error("IO error")] + IOMigrationError(#[from] std::io::Error), +} + +type Result<T> = std::result::Result<T, MigrationError>; + +/// Reads the filesystem for sql files in the DB migration directory +fn get_script_filenames() -> Result<Vec<String>> { + let results = std::fs::read_dir(DB_MIGRATION_DIR)?; + + Ok(results + .flat_map(|entry| entry.unwrap().file_name().into_string()) + .filter(|s| s.ends_with(".sql")) + .collect()) +} + +/// Gets SQL files from the DB migration directory to provide instructions for setting up the database +pub fn get_migration_scripts() -> Result<Vec<Migration>> { + let files = get_script_filenames()?; + let mut migrations = vec![]; + + for file in files { + let filename = String::from(DB_MIGRATION_DIR) + &file; + tracing::event!( + tracing::Level::TRACE, + filename = filename, + "Found migration script." + ); + + let contents = std::fs::read_to_string(filename)?; + + migrations.push(Migration { + filename: file, + directory: DB_MIGRATION_DIR.into(), + script_contents: contents, + }); + } + + Ok(migrations) +} |
