aboutsummaryrefslogtreecommitdiff
path: root/src/db/models.rs
blob: f7bbf8eb70f588b16b09825bdfdad363cdd56445 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use chrono::naive::NaiveDateTime;
use diesel::{
    prelude::*,
    Identifiable,
    Insertable,
    Queryable,
};
use diesel_async::{AsyncPgConnection, RunQueryDsl};
use sha1::Digest;

use crate::{
    db::schema::*,
    Error,
    Result,
};

#[derive(Queryable, Identifiable, PartialEq, Debug, Clone)]
#[diesel(table_name = memes)]
pub struct Meme {
    pub id:          i32,
    pub title:       String,
    pub content:     Option<String>,
    pub image_id:    Option<i32>,
    pub audio_id:    Option<i32>,
    pub metadata_id: i32,
}

impl Meme {
    pub async fn image(&self, conn: &mut AsyncPgConnection) -> Option<Result<Image>> {
        self.image_id
            .map(|x: i32| images::table.filter(images::id.eq(x))
                .first(conn)
                .await
                .map_err(Error::from))
    }

    pub async fn audio(&self, conn: &mut AsyncPgConnection) -> Option<Result<Audio>> {
        self.audio_id
            .map(|x: i32| audio::table.filter(audio::id.eq(x))
                .first(conn)
                .await
                .map_err(Error::from))
    }

    pub async fn find(conn: &mut AsyncPgConnection, id: i32) -> Result<Meme> {
        memes::table.find(id)
            .get_result(conn)
            .await
            .map_err(Error::from)
    }
}

#[derive(Insertable, PartialEq, Debug, Clone)]
#[diesel(table_name = memes)]
pub struct NewMeme {
    pub title:       String,
    pub content:     Option<String>,
    pub image_id:    Option<i32>,
    pub audio_id:    Option<i32>,
    pub metadata_id: i32,
}

impl NewMeme {
    pub async fn save(mut self, conn: &mut AsyncPgConnection, by_user: u64) -> Result<Meme> {
        let metadata = Metadata::create(conn, by_user)?;

        self.metadata_id = metadata.id;

        diesel::insert_into(memes::table)
            .values(&self)
            .get_result::<Meme>(conn)
            .await
            .map_err(Error::from)
    }
}

#[derive(Queryable, Identifiable, PartialEq, Debug)]
#[diesel(table_name = audio)]
pub struct Audio {
    pub id:          i32,
    pub data:        Vec<u8>,
    pub metadata_id: i32,
    pub data_hash:   Vec<u8>,
}

impl Audio {
    pub fn create(conn: &mut AsyncPgConnection, data: Vec<u8>, by_user: u64) -> Result<i32> {
        let mut data_hash = ::sha1::Sha1::new();
        data_hash.update(&data);
        let data_hash = data_hash.finalize().to_vec();

        let id = audio::table
            .select(audio::id)
            .filter(audio::data_hash.eq(&data_hash))
            .get_results::<i32>(conn)
            .await?;

        if let Some(id) = id.first() {
            return Ok(*id);
        }

        let metadata = Metadata::create(conn, by_user)?;

        let new_audio = NewAudio {
            data,
            data_hash,
            metadata_id: metadata.id,
        };

        diesel::insert_into(audio::table)
            .values(&new_audio)
            .returning(audio::id)
            .get_result(conn)
            .await
            .map_err(Error::from)
    }
}

#[derive(Insertable, PartialEq, Debug)]
#[diesel(table_name = audio)]
pub struct NewAudio {
    pub data:        Vec<u8>,
    pub metadata_id: i32,
    pub data_hash:   Vec<u8>,
}

#[derive(Queryable, Identifiable, PartialEq, Debug)]
#[diesel(table_name = images)]
pub struct Image {
    pub id:          i32,
    pub data:        Vec<u8>,
    pub metadata_id: i32,
    pub data_hash:   Vec<u8>,
    pub filename:    String,
}

impl Image {
    pub fn create(
        conn: &mut AsyncPgConnection,
        filename: &str,
        data: Vec<u8>,
        by_user: u64,
    ) -> Result<i32> {
        let mut data_hash = ::sha1::Sha1::new();
        data_hash.update(&data);
        let data_hash = data_hash.finalize().to_vec();

        let id = images::table
            .select(images::id)
            .filter(images::data_hash.eq(&data_hash))
            .get_results::<i32>(conn)
            .await?;

        if let Some(id) = id.first() {
            return Ok(*id);
        }

        let metadata = Metadata::create(conn, by_user)?;

        let new_image = NewImage {
            data,
            data_hash,
            filename: filename.to_owned(),
            metadata_id: metadata.id,
        };

        diesel::insert_into(images::table)
            .values(&new_image)
            .returning(images::id)
            .get_result(conn)
            .await
            .map_err(Error::from)
    }
}

#[derive(Insertable, PartialEq, Debug)]
#[diesel(table_name = images)]
pub struct NewImage {
    pub data:        Vec<u8>,
    pub metadata_id: i32,
    pub data_hash:   Vec<u8>,
    pub filename:    String,
}

#[derive(Queryable, Identifiable, PartialEq, Debug, Clone)]
#[diesel(table_name = metadata)]
pub struct Metadata {
    pub id:         i32,
    pub created:    NaiveDateTime,
    pub created_by: i64,
}

impl Metadata {
    pub fn create(conn: &mut AsyncPgConnection, by_user: u64) -> Result<Metadata> {
        diesel::insert_into(metadata::table)
            .values(&NewMetadata {
                created_by: by_user as i64,
            })
            .get_result::<Metadata>(conn)
            .await
            .map_err(Error::from)
    }

    pub fn find(conn: &mut AsyncPgConnection, id: i32) -> Result<Metadata> {
        metadata::table.find(id).get_result::<Metadata>(conn).await.map_err(Error::from)
    }
}

#[derive(Insertable, PartialEq, Debug)]
#[diesel(table_name = metadata)]
pub struct NewMetadata {
    pub created_by: i64,
}

#[derive(Queryable, Identifiable, PartialEq, Debug)]
#[diesel(table_name = audit_records)]
pub struct AuditRecord {
    pub id:          i32,
    pub updated:     NaiveDateTime,
    pub updated_by:  i64,
    pub metadata_id: i32,
}

impl AuditRecord {
    pub fn create(conn: &mut AsyncPgConnection, metadata: i32, by_user: u64) -> Result<AuditRecord> {
        diesel::insert_into(audit_records::table)
            .values(&NewAuditRecord {
                updated_by:  by_user as i64,
                metadata_id: metadata,
            })
            .get_result::<AuditRecord>(conn)
            .await
            .map_err(Error::from)
    }
}

#[derive(Insertable, PartialEq, Debug)]
#[diesel(table_name = audit_records)]
pub struct NewAuditRecord {
    pub updated_by:  i64,
    pub metadata_id: i32,
}

#[derive(Queryable, Identifiable, PartialEq, Debug)]
#[diesel(table_name = tombstones)]
pub struct Tombstone {
    pub id:          i32,
    pub deleted:     NaiveDateTime,
    pub deleted_by:  i64,
    pub metadata_id: i32,
    pub meme_id:     i32,
}

#[derive(Insertable, PartialEq, Debug)]
#[diesel(table_name = tombstones)]
pub struct NewTombstone {
    pub deleted_by:  i64,
    pub metadata_id: i32,
    pub meme_id:     i32,
}

#[derive(Queryable, Identifiable, PartialEq, Debug)]
#[diesel(table_name = invocation_records)]
pub struct InvocationRecord {
    pub id:         i32,
    pub user_id:    i64,
    pub message_id: i64,
    pub meme_id:    i32,
    pub time:       NaiveDateTime,
    pub random:     bool,
}

#[derive(Insertable, PartialEq, Debug)]
#[diesel(table_name = invocation_records)]
pub struct NewInvocationRecord {
    pub user_id:    i64,
    pub message_id: i64,
    pub meme_id:    i32,
    pub random:     bool,
}

impl InvocationRecord {
    pub fn create(
        conn: &mut AsyncPgConnection,
        user_id: u64,
        message_id: u64,
        meme_id: i32,
        random: bool,
    ) -> Result<Self> {
        diesel::insert_into(invocation_records::table)
            .values(&NewInvocationRecord {
                user_id: user_id as i64,
                message_id: message_id as i64,
                meme_id,
                random,
            })
            .get_result::<InvocationRecord>(conn)
            .await
            .map_err(Error::from)
    }

    pub fn last(conn: &mut AsyncPgConnection) -> Result<Self> {
        invocation_records::table
            .order(invocation_records::time.desc())
            .first(conn)
            .await
            .map_err(Error::from)
    }

    pub fn last_n(conn: &mut AsyncPgConnection, n: usize) -> Result<Vec<Self>> {
        invocation_records::table
            .order(invocation_records::time.desc())
            .limit(n as i64)
            .load(conn)
            .await
            .map_err(Error::from)
    }
}