discord-kurante/src/util/db.rs

60 lines
1.2 KiB
Rust
Raw Normal View History

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 {
pool: DbPool,
}
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
sqlx::query!(
"CREATE TABLE IF NOT EXISTS Heck (id INTEGER PRIMARY KEY NOT NULL, count INTEGER NOT NULL)"
)
.execute(&pool)
2020-05-02 05:04:51 +00:00
.await?;
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()
{
sqlx::query!("INSERT INTO Heck VALUES (1, 0)")
.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
}