2020-05-02 10:45:50 -07:00
|
|
|
use log::debug;
|
2020-05-01 19:41:29 -07:00
|
|
|
use serenity::prelude::TypeMapKey;
|
|
|
|
use sqlx::{
|
|
|
|
sqlite::{SqliteConnection, SqlitePool},
|
2020-05-01 22:04:51 -07:00
|
|
|
Error, Pool,
|
2020-05-01 19:41:29 -07:00
|
|
|
};
|
|
|
|
use std::env;
|
|
|
|
|
|
|
|
type DbPool = Pool<SqliteConnection>;
|
|
|
|
|
|
|
|
pub(crate) struct DbConnPool {
|
|
|
|
pool: DbPool,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DbConnPool {
|
2020-05-01 22:04:51 -07:00
|
|
|
pub async fn new() -> Result<Self, Error> {
|
|
|
|
Ok(Self {
|
|
|
|
pool: init_pool().await?,
|
|
|
|
})
|
2020-05-01 19:41:29 -07:00
|
|
|
}
|
2020-05-01 22:04:51 -07:00
|
|
|
|
|
|
|
pub async fn get_heck(&self) -> Result<i32, Error> {
|
2020-05-01 19:41:29 -07:00
|
|
|
sqlx::query!("UPDATE Heck SET count = count + 1")
|
|
|
|
.execute(&self.pool)
|
2020-05-01 22:04:51 -07:00
|
|
|
.await?;
|
2020-05-01 19:41:29 -07:00
|
|
|
|
2020-05-01 22:04:51 -07:00
|
|
|
Ok(sqlx::query!("SELECT count FROM Heck")
|
2020-05-01 19:41:29 -07:00
|
|
|
.fetch_one(&self.pool)
|
2020-05-01 22:04:51 -07:00
|
|
|
.await?
|
|
|
|
.count)
|
2020-05-01 19:41:29 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TypeMapKey for DbConnPool {
|
|
|
|
type Value = Self;
|
|
|
|
}
|
|
|
|
|
2020-05-01 22:04:51 -07:00
|
|
|
async fn init_pool() -> Result<DbPool, Error> {
|
2020-05-01 19:41:29 -07:00
|
|
|
let pool = SqlitePool::builder()
|
|
|
|
.build(&env::var("DATABASE_URL").unwrap())
|
2020-05-01 22:04:51 -07:00
|
|
|
.await?;
|
2020-05-01 19:41:29 -07:00
|
|
|
|
|
|
|
sqlx::query!(
|
|
|
|
"CREATE TABLE IF NOT EXISTS Heck (id INTEGER PRIMARY KEY NOT NULL, count INTEGER NOT NULL)"
|
|
|
|
)
|
|
|
|
.execute(&pool)
|
2020-05-01 22:04:51 -07:00
|
|
|
.await?;
|
2020-05-01 19:41:29 -07:00
|
|
|
|
2020-05-02 10:45:50 -07:00
|
|
|
debug!("Table Heck exists or was created");
|
|
|
|
|
2020-05-01 19:41:29 -07:00
|
|
|
if sqlx::query!("SELECT count FROM Heck")
|
|
|
|
.fetch_all(&pool)
|
2020-05-01 22:04:51 -07:00
|
|
|
.await?
|
2020-05-01 19:41:29 -07:00
|
|
|
.is_empty()
|
|
|
|
{
|
2020-05-02 10:45:50 -07:00
|
|
|
debug!("No entries in Heck, inserting default one");
|
2020-05-01 19:41:29 -07:00
|
|
|
sqlx::query!("INSERT INTO Heck VALUES (1, 0)")
|
|
|
|
.execute(&pool)
|
2020-05-01 22:04:51 -07:00
|
|
|
.await?;
|
2020-05-01 19:41:29 -07:00
|
|
|
}
|
|
|
|
|
2020-05-01 22:04:51 -07:00
|
|
|
Ok(pool)
|
2020-05-01 19:41:29 -07:00
|
|
|
}
|