tetratto_core/database/
polls.rs

1use oiseau::cache::Cache;
2use crate::model::communities::Poll;
3use crate::model::moderation::AuditLogEntry;
4use crate::model::{Error, Result, auth::User, permissions::FinePermission};
5use crate::{auto_method, DataManager};
6
7use oiseau::PostgresRow;
8
9use oiseau::{execute, get, query_rows, params};
10
11impl DataManager {
12    /// Get a [`Poll`] from an SQL row.
13    pub(crate) fn get_poll_from_row(x: &PostgresRow) -> Poll {
14        Poll {
15            id: get!(x->0(i64)) as usize,
16            owner: get!(x->1(i64)) as usize,
17            created: get!(x->2(i64)) as usize,
18            expires: get!(x->3(i32)) as usize,
19            option_a: get!(x->4(String)),
20            option_b: get!(x->5(String)),
21            option_c: get!(x->6(String)),
22            option_d: get!(x->7(String)),
23            votes_a: get!(x->8(i32)) as usize,
24            votes_b: get!(x->9(i32)) as usize,
25            votes_c: get!(x->10(i32)) as usize,
26            votes_d: get!(x->11(i32)) as usize,
27        }
28    }
29
30    auto_method!(get_poll_by_id()@get_poll_from_row -> "SELECT * FROM polls WHERE id = $1" --name="poll" --returns=Poll --cache-key-tmpl="atto.poll:{}");
31
32    /// Get all polls by their owner.
33    ///
34    /// # Arguments
35    /// * `owner` - the ID of the owner of the polls
36    pub async fn get_polls_by_owner_all(&self, owner: usize) -> Result<Vec<Poll>> {
37        let conn = match self.0.connect().await {
38            Ok(c) => c,
39            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
40        };
41
42        let res = query_rows!(
43            &conn,
44            "SELECT * FROM polls WHERE owner = $1 ORDER BY created DESC",
45            &[&(owner as i64)],
46            |x| { Self::get_poll_from_row(x) }
47        );
48
49        if res.is_err() {
50            return Err(Error::GeneralNotFound("poll".to_string()));
51        }
52
53        Ok(res.unwrap())
54    }
55
56    /// Create a new poll in the database.
57    ///
58    /// # Arguments
59    /// * `data` - a mock [`Poll`] object to insert
60    pub async fn create_poll(&self, data: Poll) -> Result<usize> {
61        // check values
62        if data.option_a.len() < 2 {
63            return Err(Error::DataTooShort("option A".to_string()));
64        } else if data.option_a.len() > 128 {
65            return Err(Error::DataTooLong("option A".to_string()));
66        }
67
68        if data.option_b.len() < 2 {
69            return Err(Error::DataTooShort("option B".to_string()));
70        } else if data.option_b.len() > 128 {
71            return Err(Error::DataTooLong("option B".to_string()));
72        }
73
74        if data.option_c.len() > 128 {
75            return Err(Error::DataTooLong("option C".to_string()));
76        }
77
78        if data.option_d.len() > 128 {
79            return Err(Error::DataTooLong("option D".to_string()));
80        }
81
82        // ...
83        let conn = match self.0.connect().await {
84            Ok(c) => c,
85            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
86        };
87
88        let res = execute!(
89            &conn,
90            "INSERT INTO polls VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)",
91            params![
92                &(data.id as i64),
93                &(data.owner as i64),
94                &(data.created as i64),
95                &(data.expires as i32),
96                &data.option_a,
97                &data.option_b,
98                &data.option_c,
99                &data.option_d,
100                &(data.votes_a as i32),
101                &(data.votes_b as i32),
102                &(data.votes_c as i32),
103                &(data.votes_d as i32),
104            ]
105        );
106
107        if let Err(e) = res {
108            return Err(Error::DatabaseError(e.to_string()));
109        }
110
111        Ok(data.id)
112    }
113
114    pub async fn delete_poll(&self, id: usize, user: &User) -> Result<()> {
115        let y = self.get_poll_by_id(id).await?;
116
117        if user.id != y.owner {
118            if !user.permissions.check(FinePermission::MANAGE_POSTS) {
119                return Err(Error::NotAllowed);
120            } else {
121                self.create_audit_log_entry(AuditLogEntry::new(
122                    user.id,
123                    format!("invoked `delete_poll` with x value `{id}`"),
124                ))
125                .await?
126            }
127        }
128        let conn = match self.0.connect().await {
129            Ok(c) => c,
130            Err(e) => return Err(Error::DatabaseConnection(e.to_string())),
131        };
132
133        let res = execute!(&conn, "DELETE FROM polls WHERE id = $1", &[&(id as i64)]);
134
135        if let Err(e) = res {
136            return Err(Error::DatabaseError(e.to_string()));
137        }
138
139        self.0.1.remove(format!("atto.poll:{}", id)).await;
140
141        // remove votes
142        let res = execute!(
143            &conn,
144            "DELETE FROM pollvotes WHERE poll_id = $1",
145            &[&(id as i64)]
146        );
147
148        if let Err(e) = res {
149            return Err(Error::DatabaseError(e.to_string()));
150        }
151
152        // ...
153        Ok(())
154    }
155
156    pub async fn cache_clear_poll(&self, poll: &Poll) {
157        self.0.1.remove(format!("atto.poll:{}", poll.id)).await;
158    }
159
160    auto_method!(incr_votes_a_count()@get_poll_by_id -> "UPDATE polls SET votes_a = votes_a + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --incr);
161    auto_method!(decr_votes_a_count()@get_poll_by_id -> "UPDATE polls SET votes_a = votes_a - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --decr=votes_a);
162
163    auto_method!(incr_votes_b_count()@get_poll_by_id -> "UPDATE polls SET votes_b = votes_b + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --incr);
164    auto_method!(decr_votes_b_count()@get_poll_by_id -> "UPDATE polls SET votes_b = votes_b - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --decr=votes_b);
165
166    auto_method!(incr_votes_c_count()@get_poll_by_id -> "UPDATE polls SET votes_c = votes_d + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --incr);
167    auto_method!(decr_votes_c_count()@get_poll_by_id -> "UPDATE polls SET votes_c = votes_d - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --decr=votes_c);
168
169    auto_method!(incr_votes_d_count()@get_poll_by_id -> "UPDATE polls SET votes_d = votes_d + 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --incr);
170    auto_method!(decr_votes_d_count()@get_poll_by_id -> "UPDATE polls SET votes_d = votes_d - 1 WHERE id = $1" --cache-key-tmpl=cache_clear_poll --decr=votes_d);
171}