Skip to content

Commit

Permalink
add a migrate command to migrate the db
Browse files Browse the repository at this point in the history
  • Loading branch information
imor committed Sep 24, 2024
1 parent 88d2870 commit eef5e05
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
25 changes: 23 additions & 2 deletions api/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,39 @@
use std::env;

use anyhow::anyhow;
use api::{
configuration::get_configuration,
startup::Application,
telemetry::{get_subscriber, init_subscriber},
};
use tracing::info;
use tracing_log::log::error;

#[actix_web::main]
pub async fn main() -> anyhow::Result<()> {
let subscriber = get_subscriber("api".into(), "info".into(), std::io::stdout);
init_subscriber(subscriber);
let configuration = get_configuration().expect("Failed to read configuration.");
info!("{configuration}");
let application = Application::build(configuration.clone()).await?;
application.run_until_stopped().await?;
let mut args = env::args();

if args.len() == 2 {
let command = args.nth(1).unwrap();
if command == "migrate" {
Application::migrate_database(configuration).await?;
} else {
let message = "invalid command line arguments";
error!("{message}");
return Err(anyhow!(message));
}
} else if args.len() == 1 {
let application = Application::build(configuration.clone()).await?;
application.run_until_stopped().await?;
} else {
let message = "invalid command line arguments";
error!("{message}");
return Err(anyhow!(message));
}

Ok(())
}
8 changes: 8 additions & 0 deletions api/src/startup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ impl Application {
Ok(Self { port, server })
}

pub async fn migrate_database(configuration: Settings) -> Result<(), anyhow::Error> {
let connection_pool = get_connection_pool(&configuration.database);

sqlx::migrate!("./migrations").run(&connection_pool).await?;

Ok(())
}

pub fn port(&self) -> u16 {
self.port
}
Expand Down

0 comments on commit eef5e05

Please sign in to comment.