summaryrefslogtreecommitdiffstats
path: root/src/state.rs
blob: 771647d0d1dd14c2e281f837ae3b451fbb311f88 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use std::fmt::Debug;

use axum::extract::FromRef;
use sqlx::PgPool;

use crate::Error;

#[derive(Debug, Clone, FromRef)]
pub struct AppState {
    pub pool: PgPool,
}

impl AppState {
    pub async fn new(uri: String) -> Result<Self, Error> {
        tracing::debug!("Attempting to connect to database...");

        let pool = sqlx::postgres::PgPoolOptions::new()
            .max_connections(10)
            .connect(&uri)
            .await?;

        tracing::info!("Connected to database: {uri}");

        sqlx::migrate!().run(&pool).await?;

        Ok(Self { pool })
    }
}