From 5548e3723466b3dae17deec61b4b92b280a49e5f Mon Sep 17 00:00:00 2001 From: Milim Date: Fri, 6 Dec 2024 18:08:24 +0100 Subject: [PATCH] basic SQLite database setup --- .gitignore | 3 +++ Cargo.toml | 2 +- src/config.rs | 2 +- src/db/mod.rs | 31 +++++++++++++++++++++++++++++++ src/main.rs | 15 +++++++++++---- 5 files changed, 47 insertions(+), 6 deletions(-) create mode 100644 src/db/mod.rs diff --git a/.gitignore b/.gitignore index ea8c4bf..d9811f6 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ /target +gunnhildr.db +gunnhildr.db-shm +gunnhildr.db-wal \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 30d497e..2fbb05f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,5 +9,5 @@ env_logger = "0.11.5" figment = {version="0.10.19", features=["env"]} log = "0.4.22" serde = {version="1.0.215", features=["derive"]} -sqlx = {version="0.8.2", features=["runtime-tokio"]} +sqlx = {version="0.8.2", features=["runtime-tokio","postgres", "sqlite"]} tokio = "1.42.0" diff --git a/src/config.rs b/src/config.rs index 88637bd..4e74963 100644 --- a/src/config.rs +++ b/src/config.rs @@ -5,7 +5,7 @@ use figment::{ use serde::{Deserialize, Serialize}; use std::net::{IpAddr, Ipv4Addr}; -#[derive(Deserialize, Serialize)] +#[derive(Deserialize, Serialize, Clone, Copy)] pub struct Config { pub binding_ip: IpAddr, pub port: u16, diff --git a/src/db/mod.rs b/src/db/mod.rs new file mode 100644 index 0000000..6c120ee --- /dev/null +++ b/src/db/mod.rs @@ -0,0 +1,31 @@ +use log::{info, warn}; +use sqlx::{migrate::MigrateDatabase, Sqlite, SqlitePool}; + +#[derive(Clone)] +pub enum DataBase { + Sqlite(sqlx::Pool), + //Postgres(sqlx::Pool), +} + +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(); + sqlx::migrate!("migrations/sqlite") + .run(&pool) + .await + .expect("Failed to apply migration!"); + + Self::Sqlite(pool) + } +} diff --git a/src/main.rs b/src/main.rs index 5a8fc1e..e95217b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,18 +2,25 @@ use actix_web::{get, App, HttpServer}; use log::info; mod config; +mod db; #[actix_web::main] async fn main() -> Result<(), std::io::Error> { env_logger::init(); let config = config::parse_config(); + let db = db::DataBase::sqlite().await; info!("Server starting..."); - HttpServer::new(|| App::new().service(hello)) - .bind((config.binding_ip, config.port))? - .run() - .await + HttpServer::new(move || { + App::new() + .app_data(config) + .app_data(db.clone()) + .service(hello) + }) + .bind((config.binding_ip, config.port))? + .run() + .await } #[get("/hello")]