diff --git a/sqlpage/migrations/README.md b/sqlpage/migrations/README.md index b263393c..9d2765fc 100644 --- a/sqlpage/migrations/README.md +++ b/sqlpage/migrations/README.md @@ -21,7 +21,13 @@ that is greater than the previous one. Use commands like `ALTER TABLE` to update the schema declaratively instead of modifying the existing `CREATE TABLE` statements. -If you try to edit an existing migration, SQLPage will not run it again, will detect +If you try to edit an existing migration, SQLPage will not run it again, it will detect that the migration has already executed. Also, if the migration is different than the one that was executed, SQLPage will throw an error as the database structure must match. + +## Creating migrations on the command line + +You can create a migration directly with sqlpage by running the command `sqlpage create-migration [migration_name]` + +For example if you run `sqlpage create-migration "Example Migration 1"` on the command line, you will find a new file under the `sqlpage/migrations` folder called `[timestamp]_example_migration_1.sql` where timestamp is the current time when you ran the command. ## Running migrations diff --git a/src/app_config.rs b/src/app_config.rs index 584d32a2..5b04e49a 100644 --- a/src/app_config.rs +++ b/src/app_config.rs @@ -22,6 +22,20 @@ pub struct Cli { /// The path to the configuration file. #[clap(short = 'c', long)] pub config_file: Option, + + /// Subcommands for additional functionality. + #[clap(subcommand)] + pub command: Option, +} + +/// Enum for subcommands. +#[derive(Parser)] +pub enum Commands { + /// Create a new migration file. + CreateMigration { + /// Name of the migration. + migration_name: String, + }, } #[cfg(not(feature = "lambda-web"))] @@ -686,6 +700,7 @@ mod test { web_root: Some(PathBuf::from(".")), config_dir: None, config_file: None, + command: None, }; let config = AppConfig::from_cli(&cli).unwrap(); @@ -726,6 +741,7 @@ mod test { web_root: None, config_dir: None, config_file: Some(config_file_path.clone()), + command: None, }; let config = AppConfig::from_cli(&cli).unwrap(); @@ -744,6 +760,7 @@ mod test { web_root: Some(cli_web_dir.clone()), config_dir: None, config_file: Some(config_file_path), + command: None, }; let config = AppConfig::from_cli(&cli_with_web_root).unwrap(); @@ -773,6 +790,7 @@ mod test { web_root: None, config_dir: None, config_file: None, + command: None, }; let config = AppConfig::from_cli(&cli).unwrap(); diff --git a/src/main.rs b/src/main.rs index da1f83ba..ff16b378 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,4 @@ +use clap::Parser; use sqlpage::{ app_config, webserver::{self, Database}, @@ -15,9 +16,25 @@ async fn main() { async fn start() -> anyhow::Result<()> { let app_config = app_config::load_from_cli()?; + let cli = app_config::Cli::parse(); + + if let Some(command) = cli.command { + match command { + app_config::Commands::CreateMigration { migration_name } => { + // Pass configuration_directory from app_config + create_migration_file( + &migration_name, + app_config.configuration_directory.to_str().unwrap(), + )?; + return Ok(()); + } + } + } + let db = Database::init(&app_config).await?; webserver::database::migrations::apply(&app_config, &db).await?; let state = AppState::init_with_db(&app_config, db).await?; + log::debug!("Starting server..."); webserver::http::run_server(&app_config, state).await?; log::info!("Server stopped gracefully. Goodbye!"); @@ -41,3 +58,52 @@ fn init_logging() { Err(e) => log::error!("Error loading .env file: {e}"), } } + +fn create_migration_file( + migration_name: &str, + configuration_directory: &str, +) -> anyhow::Result<()> { + use chrono::Utc; + use std::fs; + use std::path::Path; + + let timestamp = Utc::now().format("%Y%m%d%H%M%S").to_string(); + let snake_case_name = migration_name + .replace(|c: char| !c.is_alphanumeric(), "_") + .to_lowercase(); + let file_name = format!("{}_{}.sql", timestamp, snake_case_name); + let migrations_dir = Path::new(configuration_directory).join("migrations"); + + if !migrations_dir.exists() { + fs::create_dir_all(&migrations_dir)?; + } + + let mut unique_file_name = file_name.clone(); + let mut counter = 1; + + while migrations_dir.join(&unique_file_name).exists() { + unique_file_name = format!("{}_{}_{}.sql", timestamp, snake_case_name, counter); + counter += 1; + } + + let file_path = migrations_dir.join(unique_file_name); + fs::write(&file_path, "-- Write your migration here\n")?; + + // the following code cleans up the display path to show where the migration was created + // relative to the current working directory, and then outputs the path to the migration + let file_path_canon = file_path.canonicalize().unwrap_or(file_path.clone()); + let cwd_canon = std::env::current_dir()? + .canonicalize() + .unwrap_or(std::env::current_dir()?); + let rel_path = match file_path_canon.strip_prefix(&cwd_canon) { + Ok(p) => p, + Err(_) => file_path_canon.as_path(), + }; + let mut display_path_str = rel_path.display().to_string(); + if display_path_str.starts_with("\\\\?\\") { + display_path_str = display_path_str.trim_start_matches("\\\\?\\").to_string(); + } + display_path_str = display_path_str.replace('\\', "/"); + println!("Migration file created: {}", display_path_str); + Ok(()) +}