You've already forked AstralRinth
forked from didirus/AstralRinth
feat(migration): Added automatic migration (#54)
This commit is contained in:
@@ -1,5 +1,10 @@
|
||||
use log::info;
|
||||
use log::{info, debug};
|
||||
use sqlx::postgres::{PgPool, PgPoolOptions};
|
||||
use sqlx::migrate::{Migrator, Migrate, MigrateDatabase};
|
||||
use std::path::Path;
|
||||
use sqlx::{PgConnection, Connection, Postgres};
|
||||
|
||||
const MIGRATION_FOLDER: &'static str = "migrations";
|
||||
|
||||
pub async fn connect() -> Result<PgPool, sqlx::Error> {
|
||||
info!("Initializing database connection");
|
||||
@@ -12,3 +17,38 @@ pub async fn connect() -> Result<PgPool, sqlx::Error> {
|
||||
|
||||
Ok(pool)
|
||||
}
|
||||
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?;
|
||||
let mut conn : PgConnection = PgConnection::connect(uri).await?;
|
||||
|
||||
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 {
|
||||
let elapsed = conn.apply(migration).await?;
|
||||
} else {
|
||||
conn.validate(migration).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user