starfish_api/db/
pool.rs

1use async_trait::async_trait;
2use sea_orm::{ConnectOptions, DbConn};
3use sea_orm_rocket::{rocket::figment::Figment, Config, Database};
4use starfish_core::sea_orm;
5use std::env;
6use std::time::Duration;
7
8#[derive(Database, Debug)]
9#[database("starfish")]
10pub struct Db(RocketDbPool);
11
12#[derive(Debug)]
13pub struct RocketDbPool {
14    pub conn: DbConn,
15}
16
17#[async_trait]
18impl sea_orm_rocket::Pool for RocketDbPool {
19    type Error = sea_orm::DbErr;
20
21    type Connection = DbConn;
22
23    async fn init(figment: &Figment) -> Result<Self, Self::Error> {
24        let config = figment.extract::<Config>().unwrap();
25        // Extract `DATABASE_URL` defined in environment variable (if any)
26        // Otherwise, use `DATABASE_URL`defined in `Rocket.toml`
27        let mut options: ConnectOptions = env::var("DATABASE_URL")
28            .map(Into::into)
29            .unwrap_or_else(|_| config.url.into());
30        options = dbg!(options);
31        options
32            .max_connections(config.max_connections as u32)
33            .min_connections(config.min_connections.unwrap_or_default())
34            .connect_timeout(Duration::from_secs(config.connect_timeout));
35        if let Some(idle_timeout) = config.idle_timeout {
36            options.idle_timeout(Duration::from_secs(idle_timeout));
37        }
38        let conn = sea_orm::Database::connect(options).await?;
39
40        Ok(RocketDbPool { conn })
41    }
42
43    fn borrow(&self) -> &Self::Connection {
44        &self.conn
45    }
46}