pikadick/database/
reddit_embed.rs

1use crate::database::Database;
2use anyhow::Context;
3use rusqlite::{
4    params,
5    OptionalExtension,
6    TransactionBehavior,
7};
8use serenity::model::prelude::GuildId;
9
10// Reddit Embed SQL
11const GET_REDDIT_EMBED_ENABLED_SQL: &str = include_str!("../../sql/get_reddit_embed_enabled.sql");
12const SET_REDDIT_EMBED_ENABLED_SQL: &str = include_str!("../../sql/set_reddit_embed_enabled.sql");
13
14impl Database {
15    /// Enable or disable reddit embeds.
16    ///
17    /// # Returns
18    /// Returns the old value
19    pub async fn set_reddit_embed_enabled(
20        &self,
21        guild_id: GuildId,
22        enabled: bool,
23    ) -> anyhow::Result<bool> {
24        self.access_db(move |db| {
25            let txn = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
26            let old_data = txn
27                .prepare_cached(GET_REDDIT_EMBED_ENABLED_SQL)?
28                .query_row([i64::from(guild_id)], |row| row.get(0))
29                .optional()?
30                .unwrap_or(false);
31            txn.prepare_cached(SET_REDDIT_EMBED_ENABLED_SQL)?
32                .execute(params![i64::from(guild_id), enabled])?;
33
34            txn.commit()
35                .context("failed to set reddit embed")
36                .map(|_| old_data)
37        })
38        .await?
39    }
40
41    /// Get the reddit embed setting.
42    pub async fn get_reddit_embed_enabled(&self, guild_id: GuildId) -> anyhow::Result<bool> {
43        self.access_db(move |db| {
44            db.prepare_cached(GET_REDDIT_EMBED_ENABLED_SQL)?
45                .query_row([i64::from(guild_id)], |row| row.get(0))
46                .optional()
47                .context("failed to read database")
48                .map(|v| v.unwrap_or(false))
49        })
50        .await?
51    }
52}