From f5e7e0a36e4bdd72ececbef9e185fa32af4e8161 Mon Sep 17 00:00:00 2001 From: Milim Date: Fri, 6 Dec 2024 20:51:45 +0100 Subject: [PATCH] add postgress boilerplate --- src/db/mod.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/src/db/mod.rs b/src/db/mod.rs index 6c120ee..0c93318 100644 --- a/src/db/mod.rs +++ b/src/db/mod.rs @@ -1,10 +1,11 @@ +#![allow(unused)] use log::{info, warn}; -use sqlx::{migrate::MigrateDatabase, Sqlite, SqlitePool}; +use sqlx::{migrate::MigrateDatabase, PgPool, Postgres, Sqlite, SqlitePool}; #[derive(Clone)] pub enum DataBase { Sqlite(sqlx::Pool), - //Postgres(sqlx::Pool), + Postgres(sqlx::Pool), } impl DataBase { @@ -28,4 +29,25 @@ impl DataBase { Self::Sqlite(pool) } + + 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) + } }