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 {
|
2020-05-02 20:56:04 -07:00
|
|
|
pub pool: DbPool,
|
2020-05-01 19:41:29 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
2020-05-02 20:56:04 -07:00
|
|
|
// Heck table
|
2020-05-01 19:41:29 -07:00
|
|
|
sqlx::query!(
|
2020-05-02 20:56:04 -07:00
|
|
|
"CREATE TABLE IF NOT EXISTS Heck (
|
|
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE,
|
|
|
|
count INTEGER NOT NULL
|
|
|
|
)"
|
2020-05-01 19:41:29 -07:00
|
|
|
)
|
|
|
|
.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-02 20:56:04 -07: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-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-02 20:56:04 -07:00
|
|
|
sqlx::query!("INSERT INTO Heck (count) VALUES (0)")
|
2020-05-01 19:41:29 -07:00
|
|
|
.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
|
|
|
}
|