summaryrefslogtreecommitdiffstats
path: root/rust/src/editing_crud.rs
blob: 8da3cabdd7783b25c347992244fad475ee933674 (plain)
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use crate::database_models::*;
use crate::database_schema::*;
use crate::entity_crud::ExpandFlags;
use crate::errors::*;
use crate::identifiers::{self, FatcatId};
use crate::server::DbConn;
use diesel::prelude::*;
use fatcat_openapi::models::*;
use std::str::FromStr;
use uuid::Uuid;

/*
 * The object types with accessors defined here:
 *
 * - editor
 * - editgroup
 * - editgroup_annotation
 *
 * Generic verbs/actions look like:
 *
 * - db_get (single)
 * - db_get_range (group; by timestamp, with limits)
 * - db_create (single)
 * - db_update (single)
 * - db_expand (single)
 *
 */

pub trait EditorCrud {
    fn db_get(conn: &DbConn, editor_id: FatcatId) -> Result<EditorRow>;
    fn db_create(&self, conn: &DbConn) -> Result<EditorRow>;
    fn db_update_username(&self, conn: &DbConn, editor_id: FatcatId) -> Result<EditorRow>;
}
impl EditorCrud for Editor {
    fn db_get(conn: &DbConn, editor_id: FatcatId) -> Result<EditorRow> {
        let editor: EditorRow = match editor::table.find(editor_id.to_uuid()).get_result(conn) {
            Ok(ed) => ed,
            Err(diesel::result::Error::NotFound) => {
                return Err(
                    FatcatError::NotFound("editor".to_string(), editor_id.to_string()).into(),
                );
            }
            other => other?,
        };
        Ok(editor)
    }

    fn db_create(&self, conn: &DbConn) -> Result<EditorRow> {
        identifiers::check_username(&self.username)?;
        let is_admin = self.is_admin.unwrap_or(false);
        let is_bot = self.is_bot.unwrap_or(false);
        let row: EditorRow = diesel::insert_into(editor::table)
            .values((
                editor::username.eq(&self.username),
                editor::is_admin.eq(is_admin),
                editor::is_bot.eq(is_bot),
            ))
            .get_result(conn)?;
        Ok(row)
    }

    fn db_update_username(&self, conn: &DbConn, editor_id: FatcatId) -> Result<EditorRow> {
        identifiers::check_username(&self.username)?;
        diesel::update(editor::table.find(editor_id.to_uuid()))
            .set(editor::username.eq(&self.username))
            .execute(conn)?;
        let editor: EditorRow = editor::table.find(editor_id.to_uuid()).get_result(conn)?;
        Ok(editor)
    }
}

pub trait EditgroupCrud {
    fn db_get(conn: &DbConn, editgroup_id: FatcatId) -> Result<EditgroupRow>;
    fn db_get_with_changelog(
        conn: &DbConn,
        editgroup_id: FatcatId,
    ) -> Result<(EditgroupRow, Option<ChangelogRow>)>;
    fn db_expand(&mut self, conn: &DbConn, expand: ExpandFlags) -> Result<()>;
    fn db_get_range_for_editor(
        conn: &DbConn,
        editor_id: FatcatId,
        limit: u64,
        since: Option<chrono::DateTime<chrono::Utc>>,
        before: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Vec<(EditgroupRow, Option<ChangelogRow>)>>;
    fn db_get_range_reviewable(
        conn: &DbConn,
        limit: u64,
        since: Option<chrono::DateTime<chrono::Utc>>,
        before: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Vec<EditgroupRow>>;
    fn db_create(&self, conn: &DbConn, autoaccept: bool) -> Result<EditgroupRow>;
    fn db_update(
        &self,
        conn: &DbConn,
        editgroup_id: FatcatId,
        submit: Option<bool>,
    ) -> Result<EditgroupRow>;
}

impl EditgroupCrud for Editgroup {
    /// This method does *not* expand the 'edits'; currently that's still done in the endpoint
    /// handler, but it probably should be done in this trait with a db_expand()
    fn db_get(conn: &DbConn, editgroup_id: FatcatId) -> Result<EditgroupRow> {
        // Note: at least for now, continue to fetch along with changelog to ensure is_accepted is
        // consistent.
        let (row, _): (EditgroupRow, Option<ChangelogRow>) =
            Self::db_get_with_changelog(conn, editgroup_id)?;
        Ok(row)
    }

    fn db_get_with_changelog(
        conn: &DbConn,
        editgroup_id: FatcatId,
    ) -> Result<(EditgroupRow, Option<ChangelogRow>)> {
        let (eg_row, cl_row): (EditgroupRow, Option<ChangelogRow>) = match editgroup::table
            .left_outer_join(changelog::table)
            .filter(editgroup::id.eq(editgroup_id.to_uuid()))
            .first(conn)
        {
            Ok(eg) => eg,
            Err(diesel::result::Error::NotFound) => {
                return Err(FatcatError::NotFound(
                    "editgroup".to_string(),
                    editgroup_id.to_string(),
                )
                .into());
            }
            other => other?,
        };

        ensure!(
            cl_row.is_some() == eg_row.is_accepted,
            "internal database consistency error on editgroup: {}",
            editgroup_id
        );
        Ok((eg_row, cl_row))
    }

    /// Note: this *still* doesn't expand the 'edits', at least yet. *Only* the direct editgroup
    /// 'GET' handler does that.
    fn db_expand(&mut self, conn: &DbConn, expand: ExpandFlags) -> Result<()> {
        if expand.editors {
            let editor_id = FatcatId::from_str(
                self.editor_id
                    .as_ref()
                    .expect("tried to expand bare Editgroup model"),
            )?;
            self.editor = Some(Editor::db_get(conn, editor_id)?.into_model());
        }
        Ok(())
    }

    fn db_get_range_for_editor(
        conn: &DbConn,
        editor_id: FatcatId,
        limit: u64,
        since: Option<chrono::DateTime<chrono::Utc>>,
        before: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Vec<(EditgroupRow, Option<ChangelogRow>)>> {
        let rows: Vec<(EditgroupRow, Option<ChangelogRow>)> = match (since, before) {
            (Some(since), None) => editgroup::table
                .left_outer_join(changelog::table)
                .filter(editgroup::editor_id.eq(editor_id.to_uuid()))
                .filter(editgroup::created.gt(since))
                .order_by(editgroup::created.asc())
                .limit(limit as i64)
                .get_results(conn)?,
            (_, Some(before)) => editgroup::table
                .left_outer_join(changelog::table)
                .filter(editgroup::editor_id.eq(editor_id.to_uuid()))
                .filter(editgroup::created.lt(before))
                .order_by(editgroup::created.desc())
                .limit(limit as i64)
                .get_results(conn)?,
            (None, None) => editgroup::table
                .left_outer_join(changelog::table)
                .filter(editgroup::editor_id.eq(editor_id.to_uuid()))
                .order_by(editgroup::created.desc())
                .limit(limit as i64)
                .get_results(conn)?,
        };
        Ok(rows)
    }

    fn db_get_range_reviewable(
        conn: &DbConn,
        limit: u64,
        since: Option<chrono::DateTime<chrono::Utc>>,
        before: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Vec<EditgroupRow>> {
        let rows: Vec<EditgroupRow> = match (since, before) {
            (Some(since), None) => editgroup::table
                .filter(editgroup::is_accepted.eq(false))
                .filter(editgroup::submitted.is_not_null())
                .filter(editgroup::submitted.gt(since))
                .order_by(editgroup::submitted.asc())
                .limit(limit as i64)
                .get_results(conn)?,
            (_, Some(before)) => editgroup::table
                .filter(editgroup::is_accepted.eq(false))
                .filter(editgroup::submitted.is_not_null())
                .filter(editgroup::submitted.lt(before))
                .order_by(editgroup::submitted.desc())
                .limit(limit as i64)
                .get_results(conn)?,
            (None, None) => editgroup::table
                .filter(editgroup::is_accepted.eq(false))
                .filter(editgroup::submitted.is_not_null())
                .order_by(editgroup::created.desc())
                .limit(limit as i64)
                .get_results(conn)?,
        };
        Ok(rows)
    }

    fn db_create(&self, conn: &DbConn, autoaccept: bool) -> Result<EditgroupRow> {
        let editor_id = self
            .editor_id
            .clone()
            .ok_or_else(|| FatcatError::BadRequest("missing editor_id".to_string()))?;
        let editor_id = FatcatId::from_str(&editor_id)?;
        let eg_row: EditgroupRow = diesel::insert_into(editgroup::table)
            .values((
                editgroup::editor_id.eq(editor_id.to_uuid()),
                editgroup::is_accepted.eq(autoaccept),
                editgroup::description.eq(&self.description),
                editgroup::extra_json.eq(&self.extra),
            ))
            .get_result(conn)?;
        Ok(eg_row)
    }

    fn db_update(
        &self,
        conn: &DbConn,
        editgroup_id: FatcatId,
        submit: Option<bool>,
    ) -> Result<EditgroupRow> {
        let row = Self::db_get(conn, editgroup_id)?;
        if row.is_accepted {
            // "can't update an accepted editgroup"
            Err(FatcatError::EditgroupAlreadyAccepted(
                editgroup_id.to_string(),
            ))?;
        }
        match submit {
            Some(true) => {
                // just a submit
                let row = diesel::update(editgroup::table.find(editgroup_id.to_uuid()))
                    .set(editgroup::submitted.eq(diesel::dsl::now))
                    .get_result(conn)?;
                Ok(row)
            }
            Some(false) => {
                // just a retraction
                let submitted: Option<chrono::NaiveDateTime> = None;
                let row = diesel::update(editgroup::table.find(editgroup_id.to_uuid()))
                    .set(editgroup::submitted.eq(submitted))
                    .get_result(conn)?;
                Ok(row)
            }
            None => {
                // full-on row update... though we only do extra and description
                let row = diesel::update(editgroup::table.find(editgroup_id.to_uuid()))
                    .set((
                        editgroup::description.eq(&self.description),
                        editgroup::extra_json.eq(&self.extra),
                    ))
                    .get_result(conn)?;
                Ok(row)
            }
        }
    }
}

pub trait EditgroupAnnotationCrud {
    fn db_get(conn: &DbConn, annotation_id: Uuid) -> Result<EditgroupAnnotationRow>;
    fn db_expand(&mut self, conn: &DbConn, expand: ExpandFlags) -> Result<()>;
    fn db_get_range_for_editor(
        conn: &DbConn,
        editor_id: FatcatId,
        limit: u64,
        since: Option<chrono::DateTime<chrono::Utc>>,
        before: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Vec<EditgroupAnnotationRow>>;
    fn db_get_range_for_editgroup(
        conn: &DbConn,
        editgroup_id: FatcatId,
        limit: u64,
        since: Option<chrono::DateTime<chrono::Utc>>,
        before: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Vec<EditgroupAnnotationRow>>;
    fn db_create(&self, conn: &DbConn) -> Result<EditgroupAnnotationRow>;
}

impl EditgroupAnnotationCrud for EditgroupAnnotation {
    fn db_get(conn: &DbConn, annotation_id: Uuid) -> Result<EditgroupAnnotationRow> {
        let row: EditgroupAnnotationRow = match editgroup_annotation::table
            .find(annotation_id)
            .get_result(conn)
        {
            Ok(ea) => ea,
            Err(diesel::result::Error::NotFound) => {
                return Err(FatcatError::NotFound(
                    "editgroup_annotation".to_string(),
                    annotation_id.to_string(),
                )
                .into());
            }
            other => other?,
        };
        Ok(row)
    }

    fn db_expand(&mut self, conn: &DbConn, expand: ExpandFlags) -> Result<()> {
        if expand.editors {
            let editor_id = FatcatId::from_str(
                self.editor_id
                    .as_ref()
                    .expect("tried to expand bare Editor model"),
            )?;
            self.editor = Some(Editor::db_get(conn, editor_id)?.into_model());
        }
        Ok(())
    }

    fn db_get_range_for_editor(
        conn: &DbConn,
        editor_id: FatcatId,
        limit: u64,
        since: Option<chrono::DateTime<chrono::Utc>>,
        before: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Vec<EditgroupAnnotationRow>> {
        let rows: Vec<EditgroupAnnotationRow> = match (since, before) {
            (Some(since), None) => editgroup_annotation::table
                .filter(editgroup_annotation::editor_id.eq(editor_id.to_uuid()))
                .filter(editgroup_annotation::created.gt(since))
                .order_by(editgroup_annotation::created.asc())
                .limit(limit as i64)
                .get_results(conn)?,
            (_, Some(before)) => editgroup_annotation::table
                .filter(editgroup_annotation::editor_id.eq(editor_id.to_uuid()))
                .filter(editgroup_annotation::created.lt(before))
                .order_by(editgroup_annotation::created.desc())
                .limit(limit as i64)
                .get_results(conn)?,
            (None, None) => editgroup_annotation::table
                .filter(editgroup_annotation::editor_id.eq(editor_id.to_uuid()))
                .order_by(editgroup_annotation::created.desc())
                .limit(limit as i64)
                .get_results(conn)?,
        };
        Ok(rows)
    }

    fn db_get_range_for_editgroup(
        conn: &DbConn,
        editgroup_id: FatcatId,
        limit: u64,
        since: Option<chrono::DateTime<chrono::Utc>>,
        before: Option<chrono::DateTime<chrono::Utc>>,
    ) -> Result<Vec<EditgroupAnnotationRow>> {
        let rows: Vec<EditgroupAnnotationRow> = match (since, before) {
            (Some(since), None) => editgroup_annotation::table
                .filter(editgroup_annotation::editgroup_id.eq(editgroup_id.to_uuid()))
                .filter(editgroup_annotation::created.gt(since))
                .order_by(editgroup_annotation::created.asc())
                .limit(limit as i64)
                .get_results(conn)?,
            (_, Some(before)) => editgroup_annotation::table
                .filter(editgroup_annotation::editgroup_id.eq(editgroup_id.to_uuid()))
                .filter(editgroup_annotation::created.lt(before))
                .order_by(editgroup_annotation::created.desc())
                .limit(limit as i64)
                .get_results(conn)?,
            (None, None) => editgroup_annotation::table
                .filter(editgroup_annotation::editgroup_id.eq(editgroup_id.to_uuid()))
                .order_by(editgroup_annotation::created.desc())
                .limit(limit as i64)
                .get_results(conn)?,
        };
        Ok(rows)
    }

    fn db_create(&self, conn: &DbConn) -> Result<EditgroupAnnotationRow> {
        let editor_id = self
            .editor_id
            .clone()
            .ok_or_else(|| FatcatError::BadRequest("missing editor_id".to_string()))?;
        let editor_id = FatcatId::from_str(&editor_id)?;
        let editgroup_id = self
            .editgroup_id
            .clone()
            .ok_or_else(|| FatcatError::BadRequest("missing editgroup_id".to_string()))?;
        let editgroup_id = FatcatId::from_str(&editgroup_id)?;
        let ed: EditgroupAnnotationRow = diesel::insert_into(editgroup_annotation::table)
            .values((
                editgroup_annotation::editor_id.eq(editor_id.to_uuid()),
                editgroup_annotation::editgroup_id.eq(editgroup_id.to_uuid()),
                editgroup_annotation::comment_markdown.eq(&self.comment_markdown),
                editgroup_annotation::extra_json.eq(&self.extra),
            ))
            .get_result(conn)?;
        Ok(ed)
    }
}