2020-09-26 22:49:16 -07:00
|
|
|
use log::info;
|
2020-09-06 08:19:53 -07:00
|
|
|
use sqlx::migrate::{Migrate, MigrateDatabase, Migrator};
|
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-08-28 17:48:01 +02:00
|
|
|
use std::path::Path;
|
|
|
|
|
|
2020-09-28 21:05:42 -07:00
|
|
|
const MIGRATION_FOLDER: &str = "migrations";
|
2020-07-23 22:46:33 +02:00
|
|
|
|
|
|
|
|
pub async fn connect() -> Result<PgPool, sqlx::Error> {
|
|
|
|
|
info!("Initializing database connection");
|
|
|
|
|
let database_url = dotenv::var("DATABASE_URL").expect("`DATABASE_URL` not in .env");
|
|
|
|
|
let pool = PgPoolOptions::new()
|
2021-06-16 09:05:35 -07:00
|
|
|
.min_connections(
|
|
|
|
|
dotenv::var("DATABASE_MIN_CONNECTIONS")
|
|
|
|
|
.ok()
|
|
|
|
|
.map(|x| x.parse::<u32>().ok())
|
|
|
|
|
.flatten()
|
|
|
|
|
.unwrap_or(16),
|
|
|
|
|
)
|
|
|
|
|
.max_connections(
|
|
|
|
|
dotenv::var("DATABASE_MAX_CONNECTIONS")
|
|
|
|
|
.ok()
|
|
|
|
|
.map(|x| x.parse::<u32>().ok())
|
|
|
|
|
.flatten()
|
|
|
|
|
.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> {
|
|
|
|
|
let uri = &*dotenv::var("DATABASE_URL").expect("`DATABASE_URL` not in .env");
|
|
|
|
|
if !Postgres::database_exists(uri).await? {
|
|
|
|
|
info!("Creating database...");
|
|
|
|
|
Postgres::create_database(uri).await?;
|
|
|
|
|
}
|
|
|
|
|
info!("Applying migrations...");
|
|
|
|
|
run_migrations(uri).await?;
|
|
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn run_migrations(uri: &str) -> Result<(), sqlx::Error> {
|
|
|
|
|
let migrator = Migrator::new(Path::new(MIGRATION_FOLDER)).await?;
|
2020-09-06 08:19:53 -07:00
|
|
|
let mut conn: PgConnection = PgConnection::connect(uri).await?;
|
2020-08-28 17:48:01 +02:00
|
|
|
|
|
|
|
|
conn.ensure_migrations_table().await?;
|
|
|
|
|
|
|
|
|
|
let (version, dirty) = conn.version().await?.unwrap_or((0, false));
|
|
|
|
|
|
|
|
|
|
if dirty {
|
|
|
|
|
panic!("The database is dirty ! Please check your database status.");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for migration in migrator.iter() {
|
|
|
|
|
if migration.version > version {
|
2020-10-01 00:07:52 -05:00
|
|
|
let _elapsed = conn.apply(migration).await?;
|
2020-08-28 17:48:01 +02:00
|
|
|
} else {
|
|
|
|
|
conn.validate(migration).await?;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Ok(())
|
2020-09-06 08:19:53 -07:00
|
|
|
}
|