p4bl0t/src/db/mod.rs

74 lines
1.8 KiB
Rust

#![allow(clippy::cast_possible_wrap, clippy::cast_sign_loss)]
use std::env;
use poise::serenity_prelude::{ChannelId, GuildId};
use sqlx::SqlitePool;
use tracing::error;
pub type Result<T> = ::std::result::Result<T, sqlx::Error>;
pub struct Database {
pool: SqlitePool,
}
impl Database {
pub async fn new() -> Result<Self> {
Ok(Self {
pool: SqlitePool::connect(
&env::var("DATABASE_URL")
.expect("Missing enviroment variable DATABASE_URL"),
)
.await?,
})
}
pub async fn get_logging_channel(
&self,
guild_id: GuildId,
) -> Result<Vec<u64>> {
let guild_id = guild_id.0 as i64;
let channels = sqlx::query!(
r#"
SELECT channel_id
FROM guild_log_channels
WHERE guild_id = ?1
"#,
guild_id
)
.fetch_all(&self.pool)
.await
.map_err(|e| {
error!("Error getting logging channels for guild {guild_id}: {e:?}");
e
})?;
Ok(channels.iter().map(|id| id.channel_id as u64).collect())
}
pub async fn set_logging_channel(
&self,
guild_id: GuildId,
channel_id: ChannelId,
) -> Result<()> {
let guild_id = guild_id.0 as i64;
let channel_id = channel_id.0 as i64;
let mut conn = self.pool.acquire().await?;
sqlx::query!(
r#"
INSERT INTO guild_log_channels (guild_id, channel_id)
VALUES ( ?1, ?2 )
"#,
guild_id,
channel_id
)
.execute(&mut *conn)
.await
.map_err(|e| {
error!("Error setting channel {channel_id} as logger for guild {guild_id}: {e:?}");
e
})
.map(|_| ())
}
}