Set up global app state

This commit is contained in:
Joscha 2023-08-04 14:21:20 +02:00
parent 4028c3eea2
commit 037f076475
2 changed files with 22 additions and 8 deletions

42
src/state.rs Normal file
View file

@ -0,0 +1,42 @@
//! Globally accessible application state.
use axum::extract::FromRef;
use sqlx::{
sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteSynchronous},
SqlitePool,
};
// TODO Occasionally run PRAGMA optimize
// TODO Open db from path
async fn pool() -> sqlx::Result<SqlitePool> {
let options = SqliteConnectOptions::new()
// https://www.sqlite.org/pragma.html#pragma_journal_mode
.journal_mode(SqliteJournalMode::Wal)
// https://www.sqlite.org/pragma.html#pragma_synchronous
// NORMAL recommended when using WAL, can't cause corruption
.synchronous(SqliteSynchronous::Normal)
// https://www.sqlite.org/pragma.html#pragma_foreign_keys
.foreign_keys(true)
// https://www.sqlite.org/pragma.html#pragma_trusted_schema
// The docs recommend always turning this off
.pragma("trusted_schema", "false")
.create_if_missing(true)
.optimize_on_close(true, None);
let pool = SqlitePoolOptions::new().connect_with(options).await?;
sqlx::migrate!().run(&pool).await?;
Ok(pool)
}
#[derive(Clone, FromRef)]
pub struct AppState {
pub db: SqlitePool,
}
impl AppState {
pub async fn new() -> anyhow::Result<Self> {
Ok(Self { db: pool().await? })
}
}