gunnhildr/src/db/mod.rs

56 lines
1.7 KiB
Rust
Raw Normal View History

2024-12-06 20:51:45 +01:00
#![allow(unused)]
2024-12-06 18:08:24 +01:00
use log::{info, warn};
2024-12-06 20:51:45 +01:00
use sqlx::{migrate::MigrateDatabase, PgPool, Postgres, Sqlite, SqlitePool};
2024-12-06 18:08:24 +01:00
#[derive(Clone)]
pub enum DataBase {
Sqlite(sqlx::Pool<Sqlite>),
2024-12-06 20:51:45 +01:00
Postgres(sqlx::Pool<Postgres>),
2024-12-06 18:08:24 +01:00
}
impl DataBase {
pub async fn sqlite() -> Self {
if !sqlx::Sqlite::database_exists("sqlite:gunnhildr.db")
.await
.expect("failed to connect to db")
{
warn!("No SQLite database found, if this is the first time you are starting Gunnhildr, you can safely ignore this.");
sqlx::Sqlite::create_database("sqlite:gunnhildr.db")
.await
.expect("failed to create SQLite Database");
info!("Created new SQLite Database");
}
let pool = SqlitePool::connect("sqlite:gunnhildr.db").await.unwrap();
2024-12-06 18:08:24 +01:00
sqlx::migrate!("migrations/sqlite")
.run(&pool)
.await
.expect("Failed to apply migration!");
info!("Applied migrations.");
2024-12-06 18:08:24 +01:00
Self::Sqlite(pool)
}
2024-12-06 20:51:45 +01:00
pub async fn postgres(url: &str) -> Self {
if !sqlx::Postgres::database_exists(url)
.await
.expect("failed to connect to db")
{
warn!("No Postgres database found, if this is the first time you are starting Gunnhildr, you can safely ignore this.");
sqlx::Postgres::create_database(url)
.await
.expect("failed to create Postgres Database!");
info!("Created new Postgres Database");
}
let pool = PgPool::connect("url").await.unwrap();
sqlx::migrate!("migrations/postgres")
.run(&pool)
.await
.expect("Failed to apply migration!");
Self::Postgres(pool)
}
2024-12-06 18:08:24 +01:00
}