db_conn_postgres.rs 47.6 KB
Newer Older
1
2
#![cfg(feature = "postgres")]

3
4
extern crate postgres;

5
6
7
use postgres::Connection;
use time;
use time::Duration;
8
9
10

use db_conn::{MedalConnection, MedalObject};
use db_objects::*;
11
use helpers;
12

13
trait Queryable {
Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
14
15
    fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F)
                           -> postgres::Result<Option<T>>
16
        where F: FnOnce(postgres::rows::Row<'_>) -> T;
17
18
    fn query_map_many<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F) -> postgres::Result<Vec<T>>
        where F: FnMut(postgres::rows::Row<'_>) -> T;
19
    fn exists(&self, sql: &str, params: &[&dyn postgres::types::ToSql]) -> bool;
20
    fn get_last_id(&self) -> Option<i32>;
21
22
23
}

impl Queryable for Connection {
Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
24
25
    fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F)
                           -> postgres::Result<Option<T>>
26
27
        where F: FnOnce(postgres::rows::Row<'_>) -> T {
        let rows = self.query(sql, params)?;
28

29
30
        Ok(rows.iter().next().map(f))
    }
31

32
33
34
35
36
    fn query_map_many<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F) -> postgres::Result<Vec<T>>
        where F: FnMut(postgres::rows::Row<'_>) -> T {
        Ok(self.query(sql, params)?.iter().map(f).collect())
    }

37
38
39
40
41
    fn exists(&self, sql: &str, params: &[&dyn postgres::types::ToSql]) -> bool {
        let stmt = self.prepare(sql).unwrap();
        !stmt.query(params).unwrap().is_empty()
    }

42
43
44
45
46
47
    fn get_last_id(&self) -> Option<i32> {
        self.query("SELECT lastval()", &[]).unwrap().iter().next().map(|row| {
                                                                      let r: i64 = row.get(0);
                                                                      r as i32
                                                                  })
    }
48
    // Empty line intended
49
50
51
}

impl MedalConnection for Connection {
52
53
54
55
56
57
    fn dbtype(&self) -> &'static str { "postgres" }

    fn migration_already_applied(&self, name: &str) -> bool {
        let create_string = "CREATE TABLE IF NOT EXISTS migrations (name TEXT PRIMARY KEY);";
        self.execute(create_string, &[]).unwrap();

58
59
        let query = "SELECT name FROM migrations WHERE name = $1";
        self.exists(query, &[&name])
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
    }

    fn apply_migration(&mut self, name: &str, contents: &str) {
        print!("Applying migration `{}` … ", name);

        let tx = self.transaction().unwrap();

        tx.batch_execute(&contents).unwrap();
        tx.execute("INSERT INTO migrations (name) VALUES ($1)", &[&name]).unwrap();

        tx.commit().unwrap();

        println!("OK.");
    }

    // fn get_session<T: ToSql>(&self, key: T, keyname: &str) -> Option<SessionUser> {
    fn get_session(&self, key: &str) -> Option<SessionUser> {
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
        let query = "SELECT id, csrf_token, last_login, last_activity, permanent_login, username, password, logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname, street, zip, city, nation, grade, is_teacher, managed_by, oauth_provider, oauth_foreign_id, salt FROM session WHERE session_token = $1";
        let session = self.query_map_one(query, &[&key], |row| SessionUser { id: row.get(0),
                                                                             session_token: Some(key.to_string()),
                                                                             csrf_token: row.get(1),
                                                                             last_login: row.get(2),
                                                                             last_activity: row.get(3),
                                                                             permanent_login: row.get(4),

                                                                             username: row.get(5),
                                                                             password: row.get(6),
                                                                             salt: row.get(22),
                                                                             logincode: row.get(7),
                                                                             email: row.get(8),
                                                                             email_unconfirmed: row.get(9),
                                                                             email_confirmationcode: row.get(10),

                                                                             firstname: row.get(11),
                                                                             lastname: row.get(12),
                                                                             street: row.get(13),
                                                                             zip: row.get(14),
                                                                             city: row.get(15),
                                                                             nation: row.get(16),
                                                                             grade: row.get(17),

                                                                             is_teacher: row.get(18),
                                                                             managed_by: row.get(19),

                                                                             oauth_provider: row.get(20),
                                                                             oauth_foreign_id: row.get(21) })
                          .ok()??;
107
108
109

        let duration = if session.permanent_login { Duration::days(90) } else { Duration::minutes(90) };
        let now = time::get_time();
110

111
112
113
114
        if let Some(last_activity) = session.last_activity {
            if now - last_activity < duration {
                self.execute("UPDATE session SET last_activity = $1 WHERE id = $2", &[&now, &session.id]).unwrap();
                return Some(session);
115
            } else {
116
117
118
119
                // Session timed out
                // Should remove session token from session
                return None;
            }
120
        }
121
122
123
        // last_activity undefined
        // TODO: What should happen here?
        None
124
125
126
127
128
129
130
131
132
133
134
135
    }
    fn save_session(&self, session: SessionUser) {
        self.execute("UPDATE session SET
                      username = $1,
                      password = $2,
                      salt = $3,
                      logincode = $4,
                      firstname = $5,
                      lastname = $6,
                      street = $7,
                      zip = $8,
                      city = $9,
136
137
138
                      grade = $10,
                      is_teacher = $11
                      WHERE id = $12",
139
140
141
142
143
144
145
146
147
148
                     &[&session.username,
                       &session.password,
                       &session.salt,
                       &session.logincode,
                       &session.firstname,
                       &session.lastname,
                       &session.street,
                       &session.zip,
                       &session.city,
                       &session.grade,
149
                       &session.is_teacher,
150
151
152
153
                       &session.id])
            .unwrap();
    }
    fn new_session(&self, session_token: &str) -> SessionUser {
154
        let csrf_token = helpers::make_csrf_token();
155
156

        let now = time::get_time();
Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
157
158
        self.execute(
            "INSERT INTO session (session_token, csrf_token, last_activity, permanent_login, grade, is_teacher)
159
                      VALUES ($1, $2, $3, FALSE, 0, FALSE)",
Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
160
161
162
            &[&session_token, &csrf_token, &now],
        )
        .unwrap();
163

164
165
        let id = self.get_last_id().expect("Expected to get last row id");

166
        SessionUser::minimal(id as i32, session_token.to_owned(), csrf_token)
167
168
    }
    fn get_session_or_new(&self, key: &str) -> SessionUser {
169
170
171
172
        self.get_session(&key).ensure_alive().unwrap_or_else(|| {
                                                 // TODO: Factor this out in own function
                                                 // TODO: Should a new session key be generated every time?
                                                 self.execute(
173
                    "UPDATE session SET session_token = $1 WHERE session_token = $2",
174
175
176
                    &[&Option::<String>::None, &key]).unwrap();
                                                 self.new_session(&key)
                                             })
177
178
179
    }

    fn get_user_by_id(&self, user_id: i32) -> Option<SessionUser> {
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
        let query = "SELECT session_token, csrf_token, last_login, last_activity, permanent_login, username, password, logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname, street, zip, city, nation, grade, is_teacher, managed_by, oauth_provider, oauth_foreign_id, salt FROM session WHERE id = $1";
        self.query_map_one(query, &[&user_id], |row| SessionUser { id: user_id,
                                                                   session_token: row.get(0),
                                                                   csrf_token: row.get(1),
                                                                   last_login: row.get(2),
                                                                   last_activity: row.get(3),
                                                                   permanent_login: row.get(4),

                                                                   username: row.get(5),
                                                                   password: row.get(6),
                                                                   salt: row.get(22),
                                                                   logincode: row.get(7),
                                                                   email: row.get(8),
                                                                   email_unconfirmed: row.get(9),
                                                                   email_confirmationcode: row.get(10),

                                                                   firstname: row.get(11),
                                                                   lastname: row.get(12),
                                                                   street: row.get(13),
                                                                   zip: row.get(14),
                                                                   city: row.get(15),
                                                                   nation: row.get(16),
                                                                   grade: row.get(17),

                                                                   is_teacher: row.get(18),
                                                                   managed_by: row.get(19),

                                                                   oauth_provider: row.get(20),
                                                                   oauth_foreign_id: row.get(21) })
209
            .ok()?
210
211
212
213
214
215
216
217
218
219
    }

    fn get_user_and_group_by_id(&self, user_id: i32) -> Option<(SessionUser, Option<Group>)> {
        let session = self.get_user_by_id(user_id)?;

        let group_id = match session.managed_by {
            Some(id) => id,
            None => return Some((session, None)),
        };

220
221
222
223
224
225
226
227
228
229
        let query = "SELECT name, groupcode, tag, admin FROM usergroup WHERE id = $1";
        let res = self.query_map_one(query, &[&group_id], |row| Group { id: Some(group_id),
                                                                        name: row.get(0),
                                                                        groupcode: row.get(1),
                                                                        tag: row.get(2),
                                                                        admin: row.get(3),
                                                                        members: Vec::new() })
                      .ok()?;
        match res {
            Some(group) => Some((session, Some(group))),
230
231
232
233
234
235
            _ => Some((session, None)),
        }
    }

    //TODO: use session
    fn login(&self, _session: Option<&str>, username: &str, password: &str) -> Result<String, ()> {
236
237
238
239
240
        let query = "SELECT id, password, salt FROM session WHERE username = $1";
        self.query_map_one(
            query,
            &[&username],
            |row| {
241
242
243
244
                let (id, password_hash, salt): (i32, Option<String>, Option<String>) =
                    (row.get(0), row.get(1), row.get(2));

                //password_hash ist das, was in der Datenbank steht
245
246
247
                if helpers::verify_password(&password,
                                            &salt.expect("salt from database empty"),
                                            &password_hash.expect("password from database empty"))
248
249
250
251
                {
                    // TODO: fail more pleasantly
                    // Login okay, update session now!

252
253
                    let session_token = helpers::make_session_token();
                    let csrf_token = helpers::make_csrf_token();
254
255
                    let now = time::get_time();

256
257
                    let query = "UPDATE session SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3 WHERE id = $4";
                    self.execute(query, &[&session_token, &csrf_token, &now, &id]).unwrap();
258
259
260
261
262

                    Ok(session_token)
                } else {
                    Err(())
                }
263
            }).map_err(|_| ())?.ok_or(())?
264
265
266
267
    }

    //TODO: use session
    fn login_with_code(&self, _session: Option<&str>, logincode: &str) -> Result<String, ()> {
268
269
270
271
272
        let query = "SELECT id FROM session WHERE logincode = $1";
        self.query_map_one(
            query,
            &[&logincode],
            |row| {
273
274
275
                // Login okay, update session now!
                let id: i32 = row.get(0);

276
277
                let session_token = helpers::make_session_token();
                let csrf_token = helpers::make_csrf_token();
278
279
                let now = time::get_time();

280
281
                let query = "UPDATE session SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3 WHERE id = $4";
                self.execute(query, &[&session_token, &csrf_token, &now, &id]).unwrap();
282

283
284
                session_token
            }).map_err(|_| ())?.ok_or(())
285
286
287
    }

    //TODO: use session
288
289
    fn login_foreign(&self, _session: Option<&str>, foreign_id: &str, is_teacher: bool, firstname: &str,
                     lastname: &str)
290
291
                     -> Result<String, ()>
    {
292
293
        let session_token = helpers::make_session_token();
        let csrf_token = helpers::make_csrf_token();
294
295
        let now = time::get_time();

296
297
298
299
300
        let query = "SELECT id FROM session WHERE oauth_foreign_id = $1";
        match self.query_map_one(query, &[&foreign_id], |row| -> i32 { row.get(0) }) {
            Ok(Some(id)) => {
                let query = "UPDATE session SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3 WHERE id = $4";
                self.execute(query, &[&session_token, &csrf_token, &now, &id]).unwrap();
301
302
303
304
305

                Ok(session_token)
            }
            // Add!
            _ => {
306
307
308
309
310
311
312
313
314
315
316
317
                let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity, permanent_login, grade, is_teacher, oauth_foreign_id, firstname, lastname) VALUES ($1, $2, $3, $3, $4, $5, $6, $7, $8, $9)";
                self.execute(query,
                             &[&session_token,
                               &csrf_token,
                               &now,
                               &false,
                               &0,
                               &is_teacher,
                               &foreign_id,
                               &firstname,
                               &lastname])
                    .unwrap();
318
319
320
321
322
323
324
325

                Ok(session_token)
            }
        }
    }

    //TODO: use session
    fn create_user_with_groupcode(&self, _session: Option<&str>, groupcode: &str) -> Result<String, ()> {
326
327
328
        let query = "SELECT id FROM usergroup WHERE groupcode = $1";
        let group_id =
            self.query_map_one(query, &[&groupcode], |row| -> i32 { row.get(0) }).map_err(|_| ())?.ok_or(())?;
329

330
331
332
333
334
        // Login okay, create session!
        let session_token = helpers::make_session_token();
        let csrf_token = helpers::make_csrf_token();
        let login_code = helpers::make_login_code(); // todo: check for collisions
        let now = time::get_time();
335

336
337
        let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity, permanent_login, logincode, grade, is_teacher, managed_by) VALUES ($1, $2, $3, $3, $4, $5, $6, $7, $8)";
        self.execute(query, &[&session_token, &csrf_token, &now, &false, &login_code, &0, &false, &group_id]).unwrap();
338

339
        Ok(session_token)
340
341
    }

Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
342
    fn create_group_with_users(&self, mut group: Group) {
343
344
345
346
347
348
        // Generate group ID:
        group.save(self);

        for user in group.members {
            let csrf_token = helpers::make_csrf_token();
            let login_code = helpers::make_login_code(); // TODO: check for collisions
Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
349

350
351
352
353
354
355
356
357
358
359
360
            let query = "INSERT INTO session (firstname, lastname, csrf_token, permanent_login, logincode, grade, is_teacher, managed_by) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)";
            self.execute(query,
                         &[&user.firstname,
                           &user.lastname,
                           &csrf_token,
                           &false,
                           &login_code,
                           &user.grade,
                           &false,
                           &group.id])
                .unwrap();
361
        }
362
363
    }

364
    fn logout(&self, session: &str) {
365
366
        let query = "UPDATE session SET session_token = NULL WHERE session_token = $1";
        self.execute(query, &[&session]).unwrap();
367
368
369
370
    }

    fn load_submission(&self, session: &SessionUser, task: i32, subtask: Option<&str>) -> Option<Submission> {
        match subtask {
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
            None => self.query_map_one("SELECT id, grade, validated, nonvalidated_grade, value, date, needs_validation FROM submission WHERE task = $1 AND session = $2 ORDER BY id DESC LIMIT 1", &[&task, &session.id], |row| {
                Submission {
                    id: Some(row.get(0)),
                    task: task,
                    session_user: session.id,
                    grade: row.get(1),
                    validated: row.get(2),
                    nonvalidated_grade: row.get(3 ),
                    subtask_identifier: None,
                    value: row.get(4),
                    date: row.get(5),
                    needs_validation: row.get(6),
                }
            }).ok()?,
            Some(subtask_id) => self.query_map_one("SELECT id, grade, validated, nonvalidated_grade, value, date, needs_validation FROM submission WHERE task = $1 AND session = $2 AND subtask_identifier = $3 ORDER BY id DESC LIMIT 1", &[&task, &session.id, &subtask_id], |row| {
                Submission {
                    id: Some(row.get(0)),
                    task: task,
                    session_user: session.id,
                    grade: row.get(1),
                    validated: row.get(2),
                    nonvalidated_grade: row.get(3),
                    subtask_identifier: Some(subtask_id.to_string()),
                    value: row.get(4),
                    date: row.get(5),
                    needs_validation: row.get(6),
                }
            }).ok()?,
399
400
401
402
403
404
405
406
407
408
409
410
411
        }
    }
    fn submit_submission(&self, mut submission: Submission) {
        submission.save(self);

        let mut grade = self.get_grade_by_submission(submission.id.unwrap());
        if grade.grade.is_none() || submission.grade > grade.grade.unwrap() {
            grade.grade = Some(submission.grade);
            grade.validated = false;
            grade.save(self);
        }
    }
    fn get_grade_by_submission(&self, submission_id: i32) -> Grade {
412
413
414
415
416
417
418
419
420
421
422
        let query = "SELECT grade.taskgroup, grade.session, grade.grade, grade.validated FROM grade JOIN task ON grade.taskgroup = task.taskgroup JOIN submission ON task.id = submission.task AND grade.session = submission.session WHERE submission.id = $1";
        self.query_map_one(query, &[&submission_id], |row| {
            Grade {
                taskgroup: row.get(0),
                user: row.get(1),
                grade: row.get(2),
                validated: row.get(3),
            }
        }).unwrap_or(None).unwrap_or_else(|| {
            let query = "SELECT task.taskgroup, submission.session FROM submission JOIN task ON task.id = submission.task WHERE submission.id = $1";
            self.query_map_one(query, &[&submission_id], |row| {
423
424
425
                Grade {
                    taskgroup: row.get(0),
                    user: row.get(1),
426
427
428
429
430
                    grade: None,
                    validated: false,
                }
            }).unwrap().unwrap() // should this unwrap?
        })
431
432
433
434
    }

    fn get_contest_groups_grades(&self, session_id: i32, contest_id: i32)
                                 -> (Vec<String>, Vec<(Group, Vec<(UserInfo, Vec<Grade>)>)>) {
435
436
437
438
        let query = "SELECT id, name FROM taskgroup WHERE contest = $1 ORDER BY id ASC";
        let tasknames: Vec<(i32, String)> =
            self.query_map_many(query, &[&contest_id], |row| (row.get(0), row.get(1))).unwrap();

439
440
441
442
443
444
445
        let mut taskindex: ::std::collections::BTreeMap<i32, usize> = ::std::collections::BTreeMap::new();

        let n_tasks = tasknames.len();
        for (index, (i, _)) in tasknames.iter().enumerate() {
            taskindex.insert(*i, index);
        }

446
        let stmt = self.prepare("SELECT grade.taskgroup, grade.session, grade.grade, grade.validated, usergroup.id, usergroup.name, usergroup.groupcode, usergroup.tag, student.id, student.username, student.logincode, student.firstname, student.lastname
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
                                     FROM grade
                                     JOIN taskgroup ON grade.taskgroup = taskgroup.id
                                     JOIN session AS student ON grade.session = student.id
                                     JOIN usergroup ON student.managed_by = usergroup.id
                                     WHERE usergroup.admin = $1 AND taskgroup.contest = $2
                                     ORDER BY usergroup.id, student.id, taskgroup.id ASC").unwrap();
        let res = stmt.query(&[&session_id, &contest_id]).unwrap();
        let mut gradeinfo_iter =
            res.iter().map(|row| {
                          (Grade { taskgroup: row.get(0), user: row.get(1), grade: row.get(2), validated: row.get(3) },
                           Group { id: Some(row.get(4)),
                                   name: row.get(5),
                                   groupcode: row.get(6),
                                   tag: row.get(7),
                                   admin: session_id,
                                   members: Vec::new() },
                           UserInfo { id: row.get(8),
                                      username: row.get(9),
                                      logincode: row.get(10),
                                      firstname: row.get(11),
                                      lastname: row.get(12) })
                      });

        if let Some(t /*Ok((grade, mut group, mut userinfo))*/) = gradeinfo_iter.next() {
471
            let (grade, group, userinfo) = t;
472
473
474
475
476
477
478
479
480
481
482
483
484

            let mut grades: Vec<Grade> = vec![Default::default(); n_tasks];
            let mut users: Vec<(UserInfo, Vec<Grade>)> = Vec::new();
            let mut groups: Vec<(Group, Vec<(UserInfo, Vec<Grade>)>)> = Vec::new();

            let index = grade.taskgroup;
            grades[taskindex[&index]] = grade;

            // TODO: does
            // https://stackoverflow.com/questions/29859892/mutating-an-item-inside-of-nested-loops
            // help to spare all these clones?

            for ggu in gradeinfo_iter {
485
486
487
488
489
490
491
492
493
494
                let (g, gr, ui) = ggu;
                if gr.id != group.id {
                    users.push((userinfo.clone(), grades));
                    grades = vec![Default::default(); n_tasks];

                    groups.push((group.clone(), users));
                    users = Vec::new();
                } else if ui.id != userinfo.id {
                    users.push((userinfo.clone(), grades));
                    grades = vec![Default::default(); n_tasks];
495
                }
496
497
                let index = g.taskgroup;
                grades[taskindex[&index]] = g;
498
499
500
501
502
503
504
505
506
507
            }
            users.push((userinfo, grades));
            groups.push((group, users));

            (tasknames.iter().map(|(_, name)| name.clone()).collect(), groups)
        } else {
            (Vec::new(), Vec::new()) // should those be default filled?
        }
    }
    fn get_contest_user_grades(&self, session_token: &str, contest_id: i32) -> Vec<Grade> {
508
509
510
        let query = "SELECT id, name FROM taskgroup WHERE contest = $1 ORDER BY id ASC";
        let tasknames: Vec<(i32, String)> =
            self.query_map_many(query, &[&contest_id], |row| (row.get(0), row.get(1))).unwrap();
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
        let mut taskindex: ::std::collections::BTreeMap<i32, usize> = ::std::collections::BTreeMap::new();

        let n_tasks = tasknames.len();
        for (index, (i, _)) in tasknames.iter().enumerate() {
            taskindex.insert(*i, index);
        }

        let res = self.query("SELECT grade.taskgroup, grade.session, grade.grade, grade.validated
                                     FROM grade
                                     JOIN taskgroup ON grade.taskgroup = taskgroup.id
                                     JOIN session ON session.id = grade.session
                                     WHERE session.session_token = $1 AND taskgroup.contest = $2
                                     ORDER BY taskgroup.id ASC",
                             &[&session_token, &contest_id])
                      .unwrap();
        let gradeinfo_iter =
            res.iter()
               .map(|row| Grade { taskgroup: row.get(0), user: row.get(1), grade: row.get(2), validated: row.get(3) });

        let mut grades: Vec<Grade> = vec![Default::default(); n_tasks];

        for g in gradeinfo_iter {
            let index = g.taskgroup;
            grades[taskindex[&index]] = g;
        }

        grades
    }

    fn get_taskgroup_user_grade(&self, session_token: &str, taskgroup_id: i32) -> Grade {
541
        let query = "SELECT grade.taskgroup, grade.session, grade.grade, grade.validated
542
543
                                     FROM grade
                                     JOIN session ON session.id = grade.session
544
545
546
547
548
549
550
                                     WHERE session.session_token = $1 AND grade.taskgroup = $2";
        self.query_map_one(query, &[&session_token, &taskgroup_id], |row| Grade { taskgroup: row.get(0),
                                                                                  user: row.get(1),
                                                                                  grade: row.get(2),
                                                                                  validated: row.get(3) })
            .unwrap_or(None)
            .unwrap_or_default()
551
552
553
    }

    fn get_contest_list(&self) -> Vec<Contest> {
554
555
556
557
558
559
560
561
562
563
564
        let query = "SELECT id, location, filename, name, duration, public, start_date, end_date FROM contest ORDER BY id";
        self.query_map_many(query, &[], |row| Contest { id: Some(row.get(0)),
                                                        location: row.get(1),
                                                        filename: row.get(2),
                                                        name: row.get(3),
                                                        duration: row.get(4),
                                                        public: row.get(5),
                                                        start: row.get(6),
                                                        end: row.get(7),
                                                        taskgroups: Vec::new() })
            .unwrap()
565
566
567
    }

    fn get_contest_by_id(&self, contest_id: i32) -> Contest {
568
569
570
571
572
573
574
575
576
577
578
        let query =
            "SELECT location, filename, name, duration, public, start_date, end_date FROM contest WHERE id = $1";
        self.query_map_one(query, &[&contest_id], |row| Contest { id: Some(contest_id),
                                                                  location: row.get(0),
                                                                  filename: row.get(1),
                                                                  name: row.get(2),
                                                                  duration: row.get(3),
                                                                  public: row.get(4),
                                                                  start: row.get(5),
                                                                  end: row.get(6),
                                                                  taskgroups: Vec::new() })
579
580
581
582
583
            .unwrap()
            .unwrap() // TODO: Should return Option?
    }

    fn get_contest_by_id_complete(&self, contest_id: i32) -> Contest {
584
585
586
        let query = "SELECT contest.location, contest.filename, contest.name, contest.duration, contest.public, contest.start_date, contest.end_date, taskgroup.id, taskgroup.name, task.id, task.location, task.stars FROM contest JOIN taskgroup ON contest.id = taskgroup.contest JOIN task ON taskgroup.id = task.taskgroup WHERE contest.id = $1 ORDER BY taskgroup.id";
        let res = self.query(query, &[&contest_id]).unwrap();

587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
        let mut taskgroupcontest_iter =
            res.iter().map(|row| {
                          (Contest { id: Some(contest_id),
                                     location: row.get(0),
                                     filename: row.get(1),
                                     name: row.get(2),
                                     duration: row.get(3),
                                     public: row.get(4),
                                     start: row.get(5),
                                     end: row.get(6),
                                     taskgroups: Vec::new() },
                           Taskgroup { id: Some(row.get(7)), contest: contest_id, name: row.get(8), tasks: Vec::new() },
                           Task { id: Some(row.get(9)),
                                  taskgroup: row.get(7),
                                  location: row.get(10),
                                  stars: row.get(11) })
                      });

        let (mut contest, mut taskgroup, task) = taskgroupcontest_iter.next().unwrap();
        taskgroup.tasks.push(task);
        for tgc in taskgroupcontest_iter {
608
609
610
611
            let (_, tg, t) = tgc;
            if tg.id != taskgroup.id {
                contest.taskgroups.push(taskgroup);
                taskgroup = tg;
612
            }
613
            taskgroup.tasks.push(t);
614
615
616
617
618
619
        }
        contest.taskgroups.push(taskgroup);
        contest
    }

    fn get_contest_by_id_partial(&self, contest_id: i32) -> Contest {
620
621
622
        let query = "SELECT contest.location, contest.filename, contest.name, contest.duration, contest.public, contest.start_date, contest.end_date, taskgroup.id, taskgroup.name FROM contest JOIN taskgroup ON contest.id = taskgroup.contest WHERE contest.id = $1";

        let res = self.query(query, &[&contest_id]).unwrap();
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
        let mut taskgroupcontest_iter =
            res.iter().map(|row| {
                          (Contest { id: Some(contest_id),
                                     location: row.get(0),
                                     filename: row.get(1),
                                     name: row.get(2),
                                     duration: row.get(3),
                                     public: row.get(4),
                                     start: row.get(5),
                                     end: row.get(6),
                                     taskgroups: Vec::new() },
                           Taskgroup { id: Some(row.get(7)), contest: contest_id, name: row.get(8), tasks: Vec::new() })
                      });

        let (mut contest, taskgroup) = taskgroupcontest_iter.next().unwrap();
        contest.taskgroups.push(taskgroup);
        for tgc in taskgroupcontest_iter {
640
641
            let (_, tg) = tgc;
            contest.taskgroups.push(tg);
642
643
644
645
646
        }
        contest
    }

    fn get_participation(&self, session: &str, contest_id: i32) -> Option<Participation> {
647
648
649
650
651
        let query = "SELECT session, start_date FROM participation JOIN session ON session.id = session WHERE session.session_token = $1 AND contest = $2";
        self.query_map_one(query, &[&session, &contest_id], |row| Participation { contest: contest_id,
                                                                                  user: row.get(0),
                                                                                  start: row.get(1) })
            .ok()?
652
653
    }
    fn new_participation(&self, session: &str, contest_id: i32) -> Result<Participation, ()> {
654
655
656
        let query = "SELECT session, start_date FROM participation JOIN session ON session.id = session WHERE session.session_token = $1 AND contest = $2";
        match self.query_map_one(query, &[&session, &contest_id], |_| {}).map_err(|_| ())? {
            Some(()) => Err(()),
657
658
659
            None => {
                let now = time::get_time();
                self.execute(
660
                             "INSERT INTO participation (contest, session, start_date)
661
                     SELECT $1, id, $2 FROM session WHERE session_token = $3",
662
663
664
                             &[&contest_id, &now, &session],
                )
                    .unwrap();
665
666
667
668
669
670

                Ok(self.get_participation(session, contest_id).unwrap()) // TODO: This errors if not logged in …
            }
        }
    }
    fn get_task_by_id(&self, task_id: i32) -> Task {
671
672
673
674
675
        let query = "SELECT location, stars, taskgroup FROM task WHERE id = $1";
        self.query_map_one(query, &[&task_id], |row| Task { id: Some(task_id),
                                                            taskgroup: row.get(2),
                                                            location: row.get(0),
                                                            stars: row.get(1) })
676
677
678
679
            .unwrap()
            .unwrap()
    }
    fn get_task_by_id_complete(&self, task_id: i32) -> (Task, Taskgroup, Contest) {
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
        let query = "SELECT task.location, task.stars, taskgroup.id, taskgroup.name, contest.id, contest.location, contest.filename, contest.name, contest.duration, contest.public, contest.start_date, contest.end_date FROM contest JOIN taskgroup ON taskgroup.contest = contest.id JOIN task ON task.taskgroup = taskgroup.id WHERE task.id = $1";
        self.query_map_one(query, &[&task_id], |row| {
                (Task { id: Some(task_id), taskgroup: row.get(2), location: row.get(0), stars: row.get(1) },
                 Taskgroup { id: Some(row.get(2)), contest: row.get(4), name: row.get(3), tasks: Vec::new() },
                 Contest { id: Some(row.get(4)),
                           location: row.get(5),
                           filename: row.get(6),
                           name: row.get(7),
                           duration: row.get(8),
                           public: row.get(9),
                           start: row.get(10),
                           end: row.get(11),
                           taskgroups: Vec::new() })
            })
            .unwrap()
            .unwrap()
696
697
698
699
    }

    fn get_submission_to_validate(&self, tasklocation: &str, subtask: Option<&str>) -> i32 {
        match subtask {
700
701
702
703
704
705
706
707
            Some(st) => {
                let query = "SELECT id FROM submission JOIN task ON submission.task = task.id WHERE task.location = $1  AND subtask_identifier = $2 AND needs_validation = 1 LIMIT 1";
                self.query_map_one(query, &[&tasklocation, &st], |row| row.get(0)).unwrap().unwrap()
            }
            None => {
                let query = "SELECT id FROM submission JOIN task ON submission.task = task.id WHERE task.location = $1 AND needs_validation = 1 LIMIT 1";
                self.query_map_one(query, &[&tasklocation], |row| row.get(0)).unwrap().unwrap()
            }
708
709
710
711
        }
    }

    fn find_next_submission_to_validate(&self, userid: i32, taskgroupid: i32) {
712
713
714
        let query = "SELECT id, validated FROM submission JOIN task ON submission.task = task.id WHERE task.taskgroup = $1 AND submission.session = $2 ORDER BY value DESC id DESC LIMIT 1";
        let (id, validated): (i32, bool) =
            self.query_map_one(query, &[&taskgroupid, &userid], |row| (row.get(0), row.get(1))).unwrap().unwrap();
715
        if !validated {
716
717
            let query = "UPDATE submission SET needs_validation = 1 WHERE id = $1";
            self.execute(query, &[&id]).unwrap();
718
719
720
721
722
723
        }
    }

    fn add_group(&self, group: &mut Group) { group.save(self); }

    fn get_groups(&self, session_id: i32) -> Vec<Group> {
724
725
726
727
728
729
730
        let query = "SELECT id, name, groupcode, tag FROM usergroup WHERE admin = $1";
        self.query_map_many(query, &[&session_id], |row| Group { id: Some(row.get(0)),
                                                                 name: row.get(1),
                                                                 groupcode: row.get(2),
                                                                 tag: row.get(3),
                                                                 admin: session_id,
                                                                 members: Vec::new() })
731
732
733
734
735
736
            .unwrap()
    }
    fn get_groups_complete(&self, _session_id: i32) -> Vec<Group> {
        unimplemented!();
    }
    fn get_group_complete(&self, group_id: i32) -> Option<Group> {
737
738
739
740
741
742
743
        let query = "SELECT name, groupcode, tag, admin FROM usergroup WHERE id  = $1";
        let mut group = self.query_map_one(query, &[&group_id], |row| Group { id: Some(group_id),
                                                                              name: row.get(0),
                                                                              groupcode: row.get(1),
                                                                              tag: row.get(2),
                                                                              admin: row.get(3),
                                                                              members: Vec::new() })
744
745
746
                            .unwrap()
                            .unwrap(); // TODO handle error

747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
        let query = "SELECT id, session_token, csrf_token, last_login, last_activity, permanent_login, username,
                            password, logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname,
                            street, zip, city, nation, grade, is_teacher, oauth_provider, oauth_foreign_id, salt
                     FROM session
                     WHERE managed_by = $1";
        group.members = self.query_map_many(query, &[&group_id], |row| SessionUser { id: row.get(0),
                                                                                     session_token: row.get(1),
                                                                                     csrf_token: row.get(2),
                                                                                     last_login: row.get(3),
                                                                                     last_activity: row.get(4),
                                                                                     permanent_login: row.get(5),

                                                                                     username: row.get(6),
                                                                                     password: row.get(7),
                                                                                     salt: row.get(22),
                                                                                     logincode: row.get(8),
                                                                                     email: row.get(9),
                                                                                     email_unconfirmed: row.get(10),
                                                                                     email_confirmationcode:
                                                                                         row.get(11),

                                                                                     firstname: row.get(12),
                                                                                     lastname: row.get(13),
                                                                                     street: row.get(14),
                                                                                     zip: row.get(15),
                                                                                     city: row.get(16),
                                                                                     nation: row.get(17),
                                                                                     grade: row.get(18),

                                                                                     is_teacher: row.get(19),
                                                                                     managed_by: Some(group_id),

                                                                                     oauth_provider: row.get(20),
                                                                                     oauth_foreign_id: row.get(21) })
                            .unwrap();
782
783
        Some(group)
    }
784

785
    fn reset_all_contest_visibilities(&self) { self.execute("UPDATE contest SET public = $1", &[&false]).unwrap(); }
786
787
788
789
}

impl MedalObject<Connection> for Task {
    fn save(&mut self, conn: &Connection) {
790
791
792
        let query = "SELECT id FROM task WHERE taskgroup = $1 AND location = $2";
        conn.query_map_one(query, &[&self.taskgroup, &self.location], |row| row.get(0))
            .unwrap_or(None)
793
794
795
796
797
798
799
800
            .and_then(|id| {
                self.set_id(id);
                Some(())
            })
            .unwrap_or(()); // Err means no entry yet and is expected result

        let id = match self.get_id() {
            Some(id) => {
801
802
                let query = "UPDATE task SET taskgroup = $1, location = $2, stars = $3 WHERE id = $4";
                conn.execute(query, &[&self.taskgroup, &self.location, &self.stars, &id]).unwrap();
803
804
805
                id
            }
            None => {
806
807
808
                let query = "INSERT INTO task (taskgroup, location, stars) VALUES ($1, $2, $3)";
                conn.execute(query, &[&self.taskgroup, &self.location, &self.stars]).unwrap();
                conn.get_last_id().unwrap()
809
810
811
812
813
814
815
816
            }
        };
        self.set_id(id);
    }
}

impl MedalObject<Connection> for Taskgroup {
    fn save(&mut self, conn: &Connection) {
817
818
819
        let query = "SELECT id FROM taskgroup WHERE contest = $1 AND name = $2";
        conn.query_map_one(query, &[&self.contest, &self.name], |row| row.get(0))
            .unwrap_or(None)
820
821
822
823
824
825
826
827
            .and_then(|id| {
                self.set_id(id);
                Some(())
            })
            .unwrap_or(()); // Err means no entry yet and is expected result

        let id = match self.get_id() {
            Some(id) => {
828
829
                let query = "UPDATE taskgroup SET contest = $1, name = $2 WHERE id = $3";
                conn.execute(query, &[&self.contest, &self.name, &id]).unwrap();
830
831
832
                id
            }
            None => {
833
834
835
                let query = "INSERT INTO taskgroup (contest, name) VALUES ($1, $2)";
                conn.execute(query, &[&self.contest, &self.name]).unwrap();
                conn.get_last_id().unwrap()
836
837
838
839
840
841
842
843
844
845
846
847
            }
        };
        self.set_id(id);
        for mut task in &mut self.tasks {
            task.taskgroup = id;
            task.save(conn);
        }
    }
}

impl MedalObject<Connection> for Contest {
    fn save(&mut self, conn: &Connection) {
848
849
850
        let query = "SELECT id FROM contest WHERE location = $1 AND filename = $2";
        conn.query_map_one(query, &[&self.location, &self.filename], |row| row.get(0))
            .unwrap_or(None)
851
852
853
854
855
856
            .and_then(|id| {
                self.set_id(id);
                Some(())
            })
            .unwrap_or(()); // Err means no entry yet and is expected result

857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
        let id = match self.get_id() {
            Some(id) => {
                let query = "UPDATE contest SET location = $1,filename = $2, name = $3, duration = $4, public = $5, start_date = $6, end_date = $7 WHERE id = $8";
                conn.execute(query,
                             &[&self.location,
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
                               &self.end,
                               &id])
                    .unwrap();
                id
            }
            None => {
                let query = "INSERT INTO contest (location, filename, name, duration, public, start_date, end_date) VALUES ($1, $2, $3, $4, $5, $6, $7)";
                conn.execute(query,
                             &[&self.location,
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
                               &self.end])
                    .unwrap();
                conn.get_last_id().unwrap()
            }
        };
886
887
888
889
890
891
892
893
894
895
        self.set_id(id);
        for mut taskgroup in &mut self.taskgroups {
            taskgroup.contest = id;
            taskgroup.save(conn);
        }
    }
}

impl MedalObject<Connection> for Grade {
    fn save(&mut self, conn: &Connection) {
896
897
        let query = "INSERT INTO grade (taskgroup, session, grade, validated) VALUES ($1, $2, $3, $4) ON CONFLICT ON CONSTRAINT grade_pkey DO UPDATE SET grade = excluded.grade, validated = excluded.validated";
        conn.execute(query, &[&self.taskgroup, &self.user, &self.grade, &self.validated]).unwrap();
898
899
900
901
902
    }
}

impl MedalObject<Connection> for Participation {
    fn save(&mut self, conn: &Connection) {
903
904
        let query = "INSERT INTO participation (contest, session, start_date) VALUES ($1, $2, $3)";
        conn.execute(query, &[&self.contest, &self.user, &self.start]).unwrap();
905
906
907
908
909
910
911
912
    }
}

impl MedalObject<Connection> for Submission {
    fn save(&mut self, conn: &Connection) {
        match self.get_id() {
            Some(_id) => unimplemented!(),
            None => {
913
914
915
916
917
918
919
920
921
922
923
924
925
                let query = "INSERT INTO submission (task, session, grade, validated, nonvalidated_grade, subtask_identifier, value, date, needs_validation) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)";
                conn.execute(query,
                             &[&self.task,
                               &self.session_user,
                               &self.grade,
                               &self.validated,
                               &self.nonvalidated_grade,
                               &self.subtask_identifier,
                               &self.value,
                               &self.date,
                               &self.needs_validation])
                    .unwrap();
                self.set_id(conn.get_last_id().unwrap());
926
927
928
929
930
931
932
933
934
935
            }
        }
    }
}

impl MedalObject<Connection> for Group {
    fn save(&mut self, conn: &Connection) {
        match self.get_id() {
            Some(_id) => unimplemented!(),
            None => {
936
937
938
                let query = "INSERT INTO usergroup (name, groupcode, tag, admin) VALUES ($1, $2, $3, $4)";
                conn.execute(query, &[&self.name, &self.groupcode, &self.tag, &self.admin]).unwrap();
                self.set_id(conn.get_last_id().unwrap());
939
940
941
942
            }
        }
    }
}