discord-kurante/src/util/db.rs

65 lines
1.3 KiB
Rust

use serenity::prelude::TypeMapKey;
use sqlx::{
sqlite::{SqliteConnection, SqlitePool},
Pool,
};
use std::env;
type DbPool = Pool<SqliteConnection>;
pub(crate) struct DbConnPool {
pool: DbPool,
}
impl DbConnPool {
pub async fn new() -> Self {
Self {
pool: init_pool().await,
}
}
pub async fn get_heck(&self) -> i32 {
sqlx::query!("UPDATE Heck SET count = count + 1")
.execute(&self.pool)
.await
.unwrap();
sqlx::query!("SELECT count FROM Heck")
.fetch_one(&self.pool)
.await
.unwrap()
.count
}
}
impl TypeMapKey for DbConnPool {
type Value = Self;
}
async fn init_pool() -> DbPool {
let pool = SqlitePool::builder()
.build(&env::var("DATABASE_URL").unwrap())
.await
.unwrap();
sqlx::query!(
"CREATE TABLE IF NOT EXISTS Heck (id INTEGER PRIMARY KEY NOT NULL, count INTEGER NOT NULL)"
)
.execute(&pool)
.await
.unwrap();
if sqlx::query!("SELECT count FROM Heck")
.fetch_all(&pool)
.await
.unwrap()
.is_empty()
{
sqlx::query!("INSERT INTO Heck VALUES (1, 0)")
.execute(&pool)
.await
.unwrap();
}
pool
}