Skip to content

Commit

Permalink
refactor: move migrations into State::new()
Browse files Browse the repository at this point in the history
  • Loading branch information
AlphaKeks committed Jun 25, 2024
1 parent 683b76b commit 4eee1ba
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 21 deletions.
20 changes: 0 additions & 20 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ use std::backtrace::Backtrace;
use std::panic;

use anyhow::Context;
use sqlx::{Connection, MySqlConnection};
use tracing::Instrument;

mod logging;
Expand All @@ -32,29 +31,10 @@ async fn main() -> anyhow::Result<()> {

let _guard = logging::init().context("initialize logging")?;
let runtime_span = tracing::info_span!("runtime::startup");

let api_config = runtime_span
.in_scope(cs2kz_api::Config::new)
.context("load config")?;

let mut connection = MySqlConnection::connect(api_config.database_url.as_str())
.instrument(runtime_span.clone())
.await
.context("connect to database")?;

// Run database migrations.
//
// If this fails, e.g. because the migration files have changed since they last have been
// applied, the API will fail to startup, so the migrations can be fixed.
sqlx::migrate!("./database/migrations")
.run(&mut connection)
.instrument(runtime_span.clone())
.await
.context("run migrations")?;

// Don't wanna keep around a dead connection!
drop(connection);

let old_panic_hook = panic::take_hook();

// If anything anywhere ever panics, we want to log it.
Expand Down
8 changes: 7 additions & 1 deletion src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use std::convert::Infallible;
use std::sync::Arc;

use anyhow::Context;
use axum::async_trait;
use axum::extract::FromRequestParts;
use axum::http::request;
Expand Down Expand Up @@ -61,7 +62,7 @@ impl State {
};

/// Creates a new [`State`].
pub async fn new(api_config: crate::Config) -> Result<Self> {
pub async fn new(api_config: crate::Config) -> anyhow::Result<Self> {
tracing::debug!(?api_config, "initializing application state");
tracing::debug! {
url = %api_config.database_url,
Expand All @@ -77,6 +78,11 @@ impl State {
.connect(config.database_url.as_str())
.await?;

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

let http_client = reqwest::Client::new();
let jwt_state = JwtState::new(&config).map(Arc::new)?;

Expand Down

0 comments on commit 4eee1ba

Please sign in to comment.