Skip to content

Added create-migration command line instruction #943

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion sqlpage/migrations/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
18 changes: 18 additions & 0 deletions src/app_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,20 @@ pub struct Cli {
/// The path to the configuration file.
#[clap(short = 'c', long)]
pub config_file: Option<PathBuf>,

/// Subcommands for additional functionality.
#[clap(subcommand)]
pub command: Option<Commands>,
}

/// 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"))]
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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();
Expand All @@ -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();
Expand Down Expand Up @@ -773,6 +790,7 @@ mod test {
web_root: None,
config_dir: None,
config_file: None,
command: None,
};

let config = AppConfig::from_cli(&cli).unwrap();
Expand Down
66 changes: 66 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use clap::Parser;
use sqlpage::{
app_config,
webserver::{self, Database},
Expand All @@ -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!");
Expand All @@ -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(())
}