discord-kurante/src/util/db.rs

93 lines
2.0 KiB
Rust
Raw Normal View History

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