2020-09-26 22:49:16 -07:00
|
|
|
use log::info;
|
2022-02-05 23:08:30 -07:00
|
|
|
use sqlx::migrate::MigrateDatabase;
|
2020-07-23 22:46:33 +02:00
|
|
|
use sqlx::postgres::{PgPool, PgPoolOptions};
|
2020-09-06 08:19:53 -07:00
|
|
|
use sqlx::{Connection, PgConnection, Postgres};
|
2020-07-23 22:46:33 +02:00
|
|
|
|
|
|
|
|
pub async fn connect() -> Result<PgPool, sqlx::Error> {
|
|
|
|
|
info!("Initializing database connection");
|
2022-02-27 21:44:00 -07:00
|
|
|
let database_url =
|
|
|
|
|
dotenv::var("DATABASE_URL").expect("`DATABASE_URL` not in .env");
|
2020-07-23 22:46:33 +02:00
|
|
|
let pool = PgPoolOptions::new()
|
2021-06-16 09:05:35 -07:00
|
|
|
.min_connections(
|
|
|
|
|
dotenv::var("DATABASE_MIN_CONNECTIONS")
|
|
|
|
|
.ok()
|
2021-10-12 11:26:59 +08:00
|
|
|
.and_then(|x| x.parse().ok())
|
2021-06-16 09:05:35 -07:00
|
|
|
.unwrap_or(16),
|
|
|
|
|
)
|
|
|
|
|
.max_connections(
|
|
|
|
|
dotenv::var("DATABASE_MAX_CONNECTIONS")
|
|
|
|
|
.ok()
|
2021-10-12 11:26:59 +08:00
|
|
|
.and_then(|x| x.parse().ok())
|
2021-06-16 09:05:35 -07:00
|
|
|
.unwrap_or(16),
|
|
|
|
|
)
|
2020-07-23 22:46:33 +02:00
|
|
|
.connect(&database_url)
|
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
|
|
Ok(pool)
|
|
|
|
|
}
|
2020-08-28 17:48:01 +02:00
|
|
|
pub async fn check_for_migrations() -> Result<(), sqlx::Error> {
|
2021-10-12 11:26:59 +08:00
|
|
|
let uri = dotenv::var("DATABASE_URL").expect("`DATABASE_URL` not in .env");
|
|
|
|
|
let uri = uri.as_str();
|
2020-08-28 17:48:01 +02:00
|
|
|
if !Postgres::database_exists(uri).await? {
|
|
|
|
|
info!("Creating database...");
|
|
|
|
|
Postgres::create_database(uri).await?;
|
|
|
|
|
}
|
|
|
|
|
|
2022-02-05 23:08:30 -07:00
|
|
|
info!("Applying migrations...");
|
2020-08-28 17:48:01 +02:00
|
|
|
|
2020-09-06 08:19:53 -07:00
|
|
|
let mut conn: PgConnection = PgConnection::connect(uri).await?;
|
2022-02-05 23:08:30 -07:00
|
|
|
sqlx::migrate!()
|
|
|
|
|
.run(&mut conn)
|
|
|
|
|
.await
|
|
|
|
|
.expect("Error while running database migrations!");
|
2020-08-28 17:48:01 +02:00
|
|
|
|
|
|
|
|
Ok(())
|
2020-09-06 08:19:53 -07:00
|
|
|
}
|