Last active: 10 months ago
Tokio once_cell global postgres sqlx rust
static DB: OnceCell<Pool<Postgres>> = OnceCell::const_new();
async fn access_db() -> &'static Pool<Postgres> {
let initer = || async {
let db_url = env::var("SPIO_DB").expect("db host url must be set");
let pool = PgPoolOptions::new()
.max_connections(20)
.acquire_timeout(Duration::from_secs(3))
.connect(&db_url)
.await;
match pool {
Ok(pool) => pool,
Err(err) => {
panic!("connect to postgres failed {}", err)
}
}
};
DB.get_or_init(initer).await
}