Skip to content

Commit 4eee1ba

Browse files
committed
refactor: move migrations into State::new()
1 parent 683b76b commit 4eee1ba

File tree

2 files changed

+7
-21
lines changed

2 files changed

+7
-21
lines changed

src/main.rs

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ use std::backtrace::Backtrace;
1717
use std::panic;
1818

1919
use anyhow::Context;
20-
use sqlx::{Connection, MySqlConnection};
2120
use tracing::Instrument;
2221

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

3332
let _guard = logging::init().context("initialize logging")?;
3433
let runtime_span = tracing::info_span!("runtime::startup");
35-
3634
let api_config = runtime_span
3735
.in_scope(cs2kz_api::Config::new)
3836
.context("load config")?;
3937

40-
let mut connection = MySqlConnection::connect(api_config.database_url.as_str())
41-
.instrument(runtime_span.clone())
42-
.await
43-
.context("connect to database")?;
44-
45-
// Run database migrations.
46-
//
47-
// If this fails, e.g. because the migration files have changed since they last have been
48-
// applied, the API will fail to startup, so the migrations can be fixed.
49-
sqlx::migrate!("./database/migrations")
50-
.run(&mut connection)
51-
.instrument(runtime_span.clone())
52-
.await
53-
.context("run migrations")?;
54-
55-
// Don't wanna keep around a dead connection!
56-
drop(connection);
57-
5838
let old_panic_hook = panic::take_hook();
5939

6040
// If anything anywhere ever panics, we want to log it.

src/state.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
use std::convert::Infallible;
1010
use std::sync::Arc;
1111

12+
use anyhow::Context;
1213
use axum::async_trait;
1314
use axum::extract::FromRequestParts;
1415
use axum::http::request;
@@ -61,7 +62,7 @@ impl State {
6162
};
6263

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

81+
sqlx::migrate!("./database/migrations")
82+
.run(&database)
83+
.await
84+
.context("run migrations")?;
85+
8086
let http_client = reqwest::Client::new();
8187
let jwt_state = JwtState::new(&config).map(Arc::new)?;
8288

0 commit comments

Comments
 (0)