db_conn.base.rs 75.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/*  medal                                                                                                            *\
 *  Copyright (C) 2020  Bundesweite Informatikwettbewerbe                                                            *
 *                                                                                                                   *
 *  This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero        *
 *  General Public License as published  by the Free Software Foundation, either version 3 of the License, or (at    *
 *  your option) any later version.                                                                                  *
 *                                                                                                                   *
 *  This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the       *
 *  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public      *
 *  License for more details.                                                                                        *
 *                                                                                                                   *
 *  You should have received a copy of the GNU Affero General Public License along with this program.  If not, see   *
\*  <http://www.gnu.org/licenses/>.                                                                                  */

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
impl MedalObject<Connection> for Participation {
    fn save(&mut self, conn: &Connection) {
        let query = "INSERT INTO participation (contest, session, start_date)
                     VALUES ($1, $2, $3)";
        conn.execute(query, &[&self.contest, &self.user, &self.start]).unwrap();
    }
}

impl MedalObject<Connection> for Group {
    fn save(&mut self, conn: &Connection) {
        match self.get_id() {
            Some(_id) => unimplemented!(),
            None => {
                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());
            }
        }
    }
}

impl MedalObject<Connection> for Task {
    fn save(&mut self, conn: &Connection) {
        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)
45
            .map(|id| {
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
                self.set_id(id);
            })
            .unwrap_or(()); // Err means no entry yet and is expected result

        let id = match self.get_id() {
            Some(id) => {
                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();
                id
            }
            None => {
                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()
            }
        };
        self.set_id(id);
    }
}

impl MedalObject<Connection> for Taskgroup {
    fn save(&mut self, conn: &Connection) {
        if let Some(first_task) = self.tasks.get(0) {
            let query = "SELECT taskgroup.id
                         FROM taskgroup
                         JOIN task
                         ON task.taskgroup = taskgroup.id
                         WHERE contest = $1
                         AND task.location = $2";
            conn.query_map_one(query, &[&self.contest, &first_task.location], |row| row.get(0))
                .unwrap_or(None)
80
                .map(|id| {
81
82
83
84
85
86
87
88
                    self.set_id(id);
                })
                .unwrap_or(()); // Err means no entry yet and is expected result
        }

        let id = match self.get_id() {
            Some(id) => {
                let query = "UPDATE taskgroup
89
90
91
                             SET contest = $1, name = $2, active = $3, positionalnumber = $4
                             WHERE id = $5";
                conn.execute(query, &[&self.contest, &self.name, &self.active, &self.positionalnumber, &id]).unwrap();
92
93
94
                id
            }
            None => {
95
96
97
                let query = "INSERT INTO taskgroup (contest, name, active, positionalnumber)
                             VALUES ($1, $2, $3, $4)";
                conn.execute(query, &[&self.contest, &self.name, &self.active, &self.positionalnumber]).unwrap();
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
                conn.get_last_id().unwrap()
            }
        };
        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) {
        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)
117
            .map(|id| {
118
119
120
121
122
123
124
                self.set_id(id);
            })
            .unwrap_or(()); // Err means no entry yet and is expected result

        let id = match self.get_id() {
            Some(id) => {
                let query = "UPDATE contest
125
126
                             SET location = $2,filename = $3, name = $4, duration = $5, public = $6, start_date = $7,
                                 end_date = $8, min_grade = $9, max_grade = $10, positionalnumber = $11,
127
                                 requires_login = $12, secret = $13, message = $14
128
                             WHERE id = $1";
129
                conn.execute(query,
130
131
                             &[&id,
                               &self.location,
132
133
134
135
136
137
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
                               &self.end,
138
139
                               &self.min_grade,
                               &self.max_grade,
140
                               &self.positionalnumber,
141
                               &self.requires_login,
142
143
                               &self.secret,
                               &self.message])
144
145
146
147
                    .unwrap();
                id
            }
            None => {
148
                let query = "INSERT INTO contest (location, filename, name, duration, public, start_date, end_date,
149
150
                                                  min_grade, max_grade, positionalnumber, requires_login, secret, message)
                             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)";
151
152
153
154
155
156
157
                conn.execute(query,
                             &[&self.location,
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
158
159
                               &self.end,
                               &self.min_grade,
160
                               &self.max_grade,
161
162
                               &self.positionalnumber,
                               &self.requires_login,
163
164
                               &self.secret,
                               &self.message])
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
                    .unwrap();
                conn.get_last_id().unwrap()
            }
        };
        self.set_id(id);
        for mut taskgroup in &mut self.taskgroups {
            taskgroup.contest = id;
            taskgroup.save(conn);
        }
    }
}

impl MedalConnection for Connection {
    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();

        let query = "SELECT name FROM migrations WHERE name = $1";
        self.exists(query, &[&name])
    }

    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> {
203
204
        let query = "SELECT id, csrf_token, last_login, last_activity, permanent_login, username, password, salt,
                            logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname, street,
205
                            zip, city, nation, grade, sex, is_admin, is_teacher, managed_by, oauth_provider, oauth_foreign_id
206
207
208
209
210
211
212
213
214
215
216
                     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),
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
                                                                             salt: row.get(7),
                                                                             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),
                                                                             sex: row.get(19),

232
233
234
                                                                             is_admin: row.get(20),
                                                                             is_teacher: row.get(21),
                                                                             managed_by: row.get(22),
235

236
237
                                                                             oauth_provider: row.get(23),
                                                                             oauth_foreign_id: row.get(24) })
238
239
                          .ok()??;

240
        let duration = Duration::hours(12);
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
        let now = time::get_time();

        if let Some(last_activity) = session.last_activity {
            if now - last_activity < duration {
                let query = "UPDATE session
                             SET last_activity = $1
                             WHERE id = $2";
                self.execute(query, &[&now, &session.id]).unwrap();
                return Some(session);
            } else {
                // Session timed out
                // Should remove session token from session
                return None;
            }
        }
        // last_activity undefined
        // TODO: What should happen here?
        None
    }
    fn save_session(&self, session: SessionUser) {
261
262
263
264
265
266
267
268
269
270
271
272
        self.execute("UPDATE session
                      SET username = $1,
                          password = $2,
                          salt = $3,
                          logincode = $4,
                          firstname = $5,
                          lastname = $6,
                          street = $7,
                          zip = $8,
                          city = $9,
                          grade = $10,
                          sex = $11,
273
274
                          is_admin = $12,
                          is_teacher = $13,
275
276
277
278
                          permanent_login = $14,
                          email = $15,
                          email_unconfirmed = $16
                      WHERE id = $17",
279
280
281
282
283
284
285
286
287
288
                     &[&session.username,
                       &session.password,
                       &session.salt,
                       &session.logincode,
                       &session.firstname,
                       &session.lastname,
                       &session.street,
                       &session.zip,
                       &session.city,
                       &session.grade,
289
                       &session.sex,
290
                       &session.is_admin,
291
                       &session.is_teacher,
292
                       &session.permanent_login,
293
294
                       &session.email,
                       &session.email_unconfirmed,
295
296
297
298
299
300
301
                       &session.id])
            .unwrap();
    }
    fn new_session(&self, session_token: &str) -> SessionUser {
        let csrf_token = helpers::make_csrf_token();

        let now = time::get_time();
302
        let query = "INSERT INTO session (session_token, csrf_token, last_activity, permanent_login, grade, sex,
303
                                          is_teacher)
304
305
                     VALUES ($1, $2, $3, $4, $5, $6, $7)";
        self.execute(query, &[&session_token, &csrf_token, &now, &false, &0, &None::<i32>, &false]).unwrap();
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324

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

        SessionUser::minimal(id, session_token.to_owned(), csrf_token)
    }
    fn get_session_or_new(&self, key: &str) -> SessionUser {
        let query = "UPDATE session
                     SET session_token = $1
                     WHERE session_token = $2";
        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(query, &[&Option::<String>::None, &key]).unwrap();
                                                 self.new_session(&key)
                                             })
    }

    fn get_user_by_id(&self, user_id: i32) -> Option<SessionUser> {
        let query = "SELECT session_token, csrf_token, last_login, last_activity, permanent_login, username, password,
325
                            salt, logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname,
326
                            street, zip, city, nation, grade, sex, is_admin, is_teacher, managed_by, oauth_provider,
327
                            oauth_foreign_id
328
329
330
331
332
333
334
335
336
337
338
                     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),
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
                                                                   salt: row.get(7),
                                                                   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),
                                                                   sex: row.get(19),

354
355
356
                                                                   is_admin: row.get(20),
                                                                   is_teacher: row.get(21),
                                                                   managed_by: row.get(22),
357

358
359
                                                                   oauth_provider: row.get(23),
                                                                   oauth_foreign_id: row.get(24) })
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
            .ok()?
    }

    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)),
        };

        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))),
            _ => Some((session, None)),
        }
    }

    //TODO: use session
    fn login(&self, _session: Option<&str>, username: &str, password: &str) -> Result<String, ()> {
        let query = "SELECT id, password, salt
                     FROM session
                     WHERE username = $1";
        self.query_map_one(query, &[&username], |row| {
                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
                if helpers::verify_password(&password,
398
399
                                            &salt.ok_or_else(|| println!("salt from database empty"))?,
                                            &password_hash.ok_or_else(|| println!("password from database empty"))?)
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
                {
                    // TODO: fail more pleasantly
                    // Login okay, update session now!

                    let session_token = helpers::make_session_token();
                    let csrf_token = helpers::make_csrf_token();
                    let now = time::get_time();

                    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();

                    Ok(session_token)
                } else {
                    Err(())
                }
            })
            .map_err(|_| ())?
            .ok_or(())?
    }

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

                let session_token = helpers::make_session_token();
                let csrf_token = helpers::make_csrf_token();
                let now = time::get_time();

                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();

                session_token
            })
            .map_err(|_| ())?
            .ok_or(())
    }

    //TODO: use session
447
448
    fn login_foreign(&self, _session: Option<&str>, provider_id: &str, foreign_id: &str,
                     (is_teacher, is_admin, firstname, lastname, sex): (bool, bool, &str, &str, Option<i32>))
449
                     -> Result<(String, Option<time::Timespec>), ()>
450
451
452
453
454
    {
        let session_token = helpers::make_session_token();
        let csrf_token = helpers::make_csrf_token();
        let now = time::get_time();

455
        let query = "SELECT id, last_activity
456
                     FROM session
457
458
                     WHERE oauth_foreign_id = $1
                           AND oauth_provider = $2";
459
460
461
462
        match self.query_map_one(query, &[&foreign_id, &provider_id], |row| -> (i32, time::Timespec) {
                      (row.get(0), row.get(1))
                  }) {
            Ok(Some((id, last_activity))) => {
463
                let query = "UPDATE session
464
                             SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3,
465
466
                                 is_teacher = $4, is_admin = $5,  firstname = $6, lastname = $7, sex = $8
                             WHERE id = $9";
467
468
469
470
471
472
473
474
475
476
477
                self.execute(query,
                             &[&session_token,
                               &csrf_token,
                               &now,
                               &is_teacher,
                               &is_admin,
                               &firstname,
                               &lastname,
                               &sex,
                               &id])
                    .unwrap();
478

479
                Ok((session_token, Some(last_activity)))
480
481
482
483
            }
            // Add!
            _ => {
                let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity,
484
                                                  permanent_login, grade, sex, is_teacher, is_admin, oauth_foreign_id,
485
                                                  oauth_provider, firstname, lastname)
486
                             VALUES ($1, $2, $3, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)";
487
488
489
490
491
                self.execute(query,
                             &[&session_token,
                               &csrf_token,
                               &now,
                               &false,
492
                               &(if is_teacher { 255 } else { 0 }),
493
                               &sex,
494
                               &is_teacher,
495
                               &is_admin,
496
                               &foreign_id,
497
                               &provider_id,
498
499
500
501
                               &firstname,
                               &lastname])
                    .unwrap();

502
                Ok((session_token, None))
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
            }
        }
    }

    //TODO: use session
    fn create_user_with_groupcode(&self, _session: Option<&str>, groupcode: &str) -> Result<String, ()> {
        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(())?;

        // 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();

        let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity, permanent_login,
522
                                          logincode, grade, sex, is_teacher, managed_by)
523
                     VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)";
524
525
526
527
528
529
530
531
532
533
534
535
        self.execute(query,
                     &[&session_token,
                       &csrf_token,
                       &now,
                       &now,
                       &false,
                       &login_code,
                       &0,
                       &None::<i32>,
                       &false,
                       &group_id])
            .unwrap();
536
537
538
539
540
541
542
543
544
545
546
547

        Ok(session_token)
    }

    fn create_group_with_users(&self, mut group: Group) {
        // 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

548
            let query = "INSERT INTO session (firstname, lastname, csrf_token, permanent_login, logincode, grade, sex,
549
                                              is_teacher, managed_by)
550
                         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)";
551
552
553
554
555
556
557
            self.execute(query,
                         &[&user.firstname,
                           &user.lastname,
                           &csrf_token,
                           &false,
                           &login_code,
                           &user.grade,
558
                           &None::<i32>,
559
560
561
562
563
564
565
566
567
568
569
570
571
                           &false,
                           &group.id])
                .unwrap();
        }
    }

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

Robert Czechowski's avatar
Robert Czechowski committed
572
573
    fn signup(&self, session_token: &str, username: &str, email: &str, password_hash: String, salt: &str)
              -> SignupResult {
574
575
576
        let mut session_user = self.get_session_or_new(&session_token);

        if session_user.is_logged_in() {
Robert Czechowski's avatar
Robert Czechowski committed
577
            return SignupResult::UserLoggedIn;
578
579
580
        }

        if let Ok(None) = self.query_map_one("SELECT username FROM session WHERE username = $1",
Robert Czechowski's avatar
Robert Czechowski committed
581
582
583
584
                                             &[&username],
                                             |row| -> Option<String> { row.get(0) })
        {
        } else {
585
            //This username already exists!
Robert Czechowski's avatar
Robert Czechowski committed
586
            return SignupResult::UsernameTaken;
587
588
        }
        if let Ok(None) = self.query_map_one("SELECT email, email_unconfirmed FROM session WHERE email = $1 OR email_unconfirmed = $1",
Robert Czechowski's avatar
Robert Czechowski committed
589
590
591
592
                                             &[&email],
                                             |row| -> (Option<String>, Option<String>) { (row.get(0), row.get(1)) })
        {
        } else {
593
            //This email already exists!
Robert Czechowski's avatar
Robert Czechowski committed
594
            return SignupResult::EmailTaken;
595
596
597
598
599
600
601
602
603
604
605
        }

        session_user.username = Some(username.to_string());
        session_user.email_unconfirmed = Some(email.to_string());
        session_user.password = Some(password_hash);
        session_user.salt = Some(salt.to_string());

        self.save_session(session_user);
        SignupResult::SignedUp
    }

606
607
608
609
610
611
612
613
614
615
    fn load_submission(&self, session: &SessionUser, task: i32, subtask: Option<&str>) -> Option<Submission> {
        match subtask {
            None => {
                let query = "SELECT id, grade, validated, nonvalidated_grade, value, date, needs_validation
                             FROM submission
                             WHERE task = $1
                             AND session = $2
                             ORDER BY id DESC
                             LIMIT 1";
                self.query_map_one(query, &[&task, &session.id], |row| Submission { id: Some(row.get(0)),
Robert Czechowski's avatar
Robert Czechowski committed
616
                                                                                    task,
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
                                                                                    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) => {
                let query = "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";
                self.query_map_one(query, &[&task, &session.id, &subtask_id], |row| {
                        Submission { id: Some(row.get(0)),
Robert Czechowski's avatar
Robert Czechowski committed
637
                                     task,
638
639
640
641
642
643
644
645
646
647
648
649
650
                                     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()?
            }
        }
    }
651
652
653
654
655
656
657
658
    fn get_all_submissions(&self, session_id: i32, task: i32, subtask: Option<&str>) -> Vec<Submission> {
        match subtask {
            None => {
                let query = "SELECT id, grade, validated, nonvalidated_grade, value, date, needs_validation
                             FROM submission
                             WHERE task = $1
                             AND session = $2";
                self.query_map_many(query, &[&task, &session_id], |row| Submission { id: Some(row.get(0)),
Robert Czechowski's avatar
Robert Czechowski committed
659
                                                                                     task,
660
661
662
663
664
665
666
                                                                                     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),
667
668
669
                                                                                     needs_validation: row.get(6) })
                    .unwrap()
            }
670
            _ => unimplemented!(),
671
672
        }
    }
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
    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 {
        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| Grade { taskgroup: row.get(0),
                                                                           user: row.get(1),
                                                                           grade: None,
                                                                           validated: false })
                    .unwrap()
                    .unwrap() // should this unwrap?
            })
    }

    fn get_contest_groups_grades(&self, session_id: i32, contest_id: i32)
                                 -> (Vec<String>, Vec<(Group, Vec<(UserInfo, Vec<Grade>)>)>) {
        let query = "SELECT id, name
                     FROM taskgroup
                     WHERE contest = $1
714
715
                     AND active = $2
                     ORDER BY positionalnumber";
716
        let tasknames: Vec<(i32, String)> =
717
            self.query_map_many(query, &[&contest_id, &true], |row| (row.get(0), row.get(1))).unwrap();
718
719
720
721
722
723
724
725
726
727

        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 query = "SELECT grade.taskgroup, grade.session, grade.grade, grade.validated, usergroup.id, usergroup.name,
                            usergroup.groupcode, usergroup.tag, student.id, student.username, student.logincode,
728
                            student.firstname, student.lastname, student.grade AS sgrade
729
730
731
732
733
734
                     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
735
                     AND taskgroup.active = $3
736
737
                     ORDER BY usergroup.id, sgrade, student.lastname, student.firstname, student.id,
                              taskgroup.positionalnumber";
738
        let gradeinfo =
739
            self.query_map_many(query, &[&session_id, &contest_id, &true], |row| {
740
741
742
743
744
745
746
747
748
749
750
                    (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),
751
                                lastname: row.get(12),
Robert Czechowski's avatar
Robert Czechowski committed
752
                                grade: row.get(13) })
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
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
                })
                .unwrap();
        let mut gradeinfo_iter = gradeinfo.iter();

        if let Some(t /*Ok((grade, mut group, mut userinfo))*/) = gradeinfo_iter.next() {
            let (grade, mut group, mut userinfo) = t.clone();

            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;

            for ggu in gradeinfo_iter {
                let (g, gr, ui) = ggu;
                if gr.id != group.id {
                    users.push((userinfo, grades));
                    userinfo = ui.clone();
                    grades = vec![Default::default(); n_tasks];

                    groups.push((group, users));
                    group = gr.clone();
                    users = Vec::new();
                } else if ui.id != userinfo.id {
                    users.push((userinfo, grades));
                    userinfo = ui.clone();
                    grades = vec![Default::default(); n_tasks];
                }
                let index = g.taskgroup;
                grades[taskindex[&index]] = *g;
            }
            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> {
        let query = "SELECT id, name
                     FROM taskgroup
                     WHERE contest = $1
797
798
                     AND active = $2
                     ORDER BY positionalnumber";
799
        let tasknames: Vec<(i32, String)> =
800
            self.query_map_many(query, &[&contest_id, &true], |row| (row.get(0), row.get(1))).unwrap();
801
802
803
804
805
806
807
808
809
810
811
812
813
        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 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
814
815
                     AND taskgroup.active = $3
                     ORDER BY taskgroup.positionalnumber";
816
        let gradeinfo =
817
            self.query_map_many(query, &[&session_token, &contest_id, &true], |row| Grade { taskgroup: row.get(0),
Robert Czechowski's avatar
Robert Czechowski committed
818
819
820
                                                                                            user: row.get(1),
                                                                                            grade: row.get(2),
                                                                                            validated: row.get(3) })
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
                .unwrap();
        let gradeinfo_iter = gradeinfo.iter();

        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 {
        let query = "SELECT grade.taskgroup, grade.session, grade.grade, grade.validated
                     FROM grade
                     JOIN session ON session.id = grade.session
                     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()
    }

848
    /* Warning: This function makes no use of rusts type safety. Handle with care when changeing */
849
850
    fn export_contest_results_to_file(&self, contest_id: i32, taskgroups: &[(i32, String)], filename: &str) {
        use std::fs::OpenOptions;
851
        let file = OpenOptions::new().write(true).create(true).truncate(true).open(filename).unwrap();
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
        let mut headers = vec!["id",
                               "username",
                               "logincode",
                               "oauth_foreign_id",
                               "oauth_provider",
                               "firstname",
                               "lastname",
                               "grade",
                               "sex",
                               "is_teacher",
                               "group_id",
                               "group_name",
                               "group_tag",
                               "teacher_id",
                               "teacher_firstname",
                               "teacher_lastname",
                               "teacher_oauth_foreign_id",
                               "teacher_oauth_provider",
                               "contest_id",
                               "start_date"];
872
873
874

        let mut select_part = String::new();
        let mut join_part = String::new();
875
876
877

        let mut join_params = gen_tosql_vector();

878
        join_params.push(&contest_id);
879
880

        for (n, (id, name)) in taskgroups.iter().enumerate() {
881
882
883
884
885
            select_part.push_str(&format!(",\n g{}.grade ", n));
            join_part.push_str(&format!("\n LEFT JOIN grade AS g{} ON session.id = g{}.session AND g{}.taskgroup = ${} ", n, n, n, n + 2));
            join_params.push(id);
            headers.push(&name);
        }
886

887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
        let query = format!("SELECT session.id,
                                    session.username,
                                    session.logincode,
                                    session.oauth_foreign_id,
                                    session.oauth_provider,
                                    session.firstname,
                                    session.lastname,
                                    session.grade,
                                    session.sex,
                                    session.is_teacher,
                                    session.managed_by,
                                    usergroup.name,
                                    usergroup.tag,
                                    teacher.id,
                                    teacher.firstname,
                                    teacher.lastname,
                                    teacher.oauth_foreign_id,
                                    teacher.oauth_provider,
                                    participation.contest,
                                    participation.start_date
                                    {}
                             FROM participation
                             JOIN session ON participation.session = session.id
                             {}
                             LEFT JOIN usergroup ON session.managed_by = usergroup.id
                             LEFT JOIN session AS teacher ON usergroup.admin = teacher.id
913
914
                             WHERE participation.contest = $1",
                            select_part, join_part);
915
916

        use csv::Writer;
917
        let mut wtr = Writer::from_writer(file);
918
919
        wtr.serialize(&headers).unwrap();
        wtr.flush().unwrap();
920

921
922
        let file = wtr.into_inner().unwrap();
        let mut wtr = Writer::from_writer(file);
923
924
925
926
927
928

        self.query_map_many(&query, join_params.as_slice(), |row| {
                let mut points = Vec::new();
                for i in 20..20 + taskgroups.len() {
                    points.push(row.get::<_, Option<i32>>(i));
                }
929
930
                // Serialized as several tuples because Serde only supports tuples up to a certain length
                // (16 according to https://docs.serde.rs/serde/trait.Deserialize.html)
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
                wtr.serialize(((row.get::<_, i32>(0),
                                row.get::<_, Option<String>>(1),
                                row.get::<_, Option<String>>(2),
                                row.get::<_, Option<String>>(3),
                                row.get::<_, Option<String>>(4),
                                row.get::<_, Option<String>>(5),
                                row.get::<_, Option<String>>(6),
                                row.get::<_, i32>(7),
                                row.get::<_, Option<i32>>(8),
                                row.get::<_, bool>(9)),
                               (row.get::<_, Option<i32>>(10),
                                row.get::<_, Option<String>>(11),
                                row.get::<_, Option<String>>(12),
                                row.get::<_, Option<i32>>(13),
                                row.get::<_, Option<String>>(14),
                                row.get::<_, Option<String>>(15),
                                row.get::<_, Option<String>>(16),
                                row.get::<_, Option<String>>(17)),
                               row.get::<_, Option<i32>>(18),
950
951
                               row.get::<_, Option<self::time::Timespec>>(19)
                                  .map(|ts| self::time::strftime("%FT%T%z", &self::time::at(ts)).unwrap()),
952
953
954
955
                               points))
                   .unwrap();
            })
            .unwrap();
956
        wtr.flush().unwrap();
957
958
    }

959
    fn get_contest_list(&self) -> Vec<Contest> {
960
        let query = "SELECT id, location, filename, name, duration, public, start_date, end_date, min_grade, max_grade,
961
                            positionalnumber, requires_login, secret, message
962
                     FROM contest
963
                     ORDER BY positionalnumber";
964
965
966
967
968
969
970
971
972
973
        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),
                                                        min_grade: row.get(8),
                                                        max_grade: row.get(9),
974
                                                        positionalnumber: row.get(10),
975
976
                                                        requires_login: row.get(11),
                                                        secret: row.get(12),
977
                                                        message: row.get(13),
978
979
980
981
982
                                                        taskgroups: Vec::new() })
            .unwrap()
    }

    fn get_contest_by_id(&self, contest_id: i32) -> Contest {
983
        let query = "SELECT location, filename, name, duration, public, start_date, end_date, min_grade, max_grade,
984
                            requires_login, secret, message
985
986
987
988
989
990
991
992
993
994
995
996
                     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),
                                                                  min_grade: row.get(7),
                                                                  max_grade: row.get(8),
997
                                                                  positionalnumber: None,
998
999
                                                                  requires_login: row.get(9),
                                                                  secret: row.get(10),
1000
                                                                  message: row.get(11),
1001
1002
1003
1004
1005
1006
1007
                                                                  taskgroups: Vec::new() })
            .unwrap()
            .unwrap() // TODO: Should return Option?
    }

    fn get_contest_by_id_complete(&self, contest_id: i32) -> Contest {
        let query = "SELECT contest.location, contest.filename, contest.name, contest.duration, contest.public,
1008
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade,
1009
1010
1011
                            contest.requires_login, contest.secret, contest.message,
                            taskgroup.id, taskgroup.name,
                            task.id, task.location, task.stars
1012
1013
1014
1015
                     FROM contest
                     JOIN taskgroup ON contest.id = taskgroup.contest
                     JOIN task ON taskgroup.id = task.taskgroup
                     WHERE contest.id = $1
1016
                     AND taskgroup.active = $2
1017
1018
                     ORDER BY taskgroup.positionalnumber";
        let taskgroupcontest =
1019
            self.query_map_many(query, &[&contest_id, &true], |row| {
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
                    (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),
                               min_grade: row.get(7),
                               max_grade: row.get(8),
1030
                               positionalnumber: None,
1031
1032
                               requires_login: row.get(9),
                               secret: row.get(10),
1033
                               message: row.get(11),
1034
                               taskgroups: Vec::new() },
1035
                     Taskgroup { id: Some(row.get(12)),
1036
                                 contest: contest_id,
1037
                                 name: row.get(13),
1038
                                 active: true,
1039
1040
                                 positionalnumber: None,
                                 tasks: Vec::new() },
1041
                     Task { id: Some(row.get(14)), taskgroup: row.get(12), location: row.get(15), stars: row.get(16) })
1042
1043
1044
1045
                })
                .unwrap();
        let mut taskgroupcontest_iter = taskgroupcontest.into_iter();

1046
1047
1048
1049
1050
1051
1052
1053
1054
        if let Some((mut contest, mut taskgroup, task)) = taskgroupcontest_iter.next() {
            taskgroup.tasks.push(task);
            for tgc in taskgroupcontest_iter {
                let (_, tg, t) = tgc;
                if tg.id != taskgroup.id {
                    contest.taskgroups.push(taskgroup);
                    taskgroup = tg;
                }
                taskgroup.tasks.push(t);
1055
            }
1056
1057
1058
1059
1060
1061
            contest.taskgroups.push(taskgroup);
            contest
        } else {
            // If the contest has no tasks, we fall back to the function, that does not try to gather the task
            // information
            self.get_contest_by_id(contest_id)
1062
1063
1064
1065
1066
        }
    }

    fn get_contest_by_id_partial(&self, contest_id: i32) -> Contest {
        let query = "SELECT contest.location, contest.filename, contest.name, contest.duration, contest.public,
1067
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade,
1068
1069
                            contest.requires_login, contest.secret, contest.message,
                            taskgroup.id, taskgroup.name
1070
1071
                     FROM contest
                     JOIN taskgroup ON contest.id = taskgroup.contest
1072
1073
1074
                     WHERE contest.id = $1
                     AND taskgroup.active = $2";
        let taskgroupcontest = self.query_map_many(query, &[&contest_id, &true], |row| {
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
                                       (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),
                                                  min_grade: row.get(7),
                                                  max_grade: row.get(8),
1085
                                                  positionalnumber: None,
1086
1087
                                                  requires_login: row.get(9),
                                                  secret: row.get(10),
1088
                                                  message: row.get(11),
1089
                                                  taskgroups: Vec::new() },
1090
                                        Taskgroup { id: Some(row.get(12)),
1091
                                                    contest: contest_id,
1092
                                                    name: row.get(13),
1093
                                                    active: true,
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
                                                    positionalnumber: None,
                                                    tasks: Vec::new() })
                                   })
                                   .unwrap();
        let mut taskgroupcontest_iter = taskgroupcontest.into_iter();

        let (mut contest, taskgroup) = taskgroupcontest_iter.next().unwrap();
        contest.taskgroups.push(taskgroup);
        for tgc in taskgroupcontest_iter {
            let (_, tg) = tgc;
            contest.taskgroups.push(tg);
        }
        contest
    }

1109
1110
1111
1112
1113
1114
    fn get_participation(&self, session_id: i32, contest_id: i32) -> Option<Participation> {
        let query = "SELECT start_date
                     FROM participation
                     WHERE session = $1
                     AND contest = $2";
        self.query_map_one(query, &[&session_id, &contest_id], |row| Participation { contest: contest_id,
1115
1116
                                                                                     user: session_id,
                                                                                     start: row.get(0) })
1117
1118
1119
1120
            .ok()?
    }

    fn get_own_participation(&self, session: &str, contest_id: i32) -> Option<Participation> {
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
        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()?
    }
1131
1132
1133

    fn get_all_participations_complete(&self, session_id: i32) -> Vec<(Participation, Contest)> {
        let query = "SELECT participation.start_date, contest.id, location, filename, name, duration, public,
1134
                            contest.start_date, end_date, min_grade, max_grade, requires_login, secret, message
1135
1136
1137
1138
                     FROM participation
                     JOIN contest ON participation.contest = contest.id
                     WHERE participation.session = $1";
        self.query_map_many(query, &[&session_id], |row| {
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
                (Participation { contest: row.get(1), user: session_id, start: row.get(0) },
                 Contest { id: Some(row.get(1)),
                           location: row.get(2),
                           filename: row.get(3),
                           name: row.get(4),
                           duration: row.get(5),
                           public: row.get(6),
                           start: row.get(7),
                           end: row.get(8),
                           min_grade: row.get(9),
                           max_grade: row.get(10),
                           positionalnumber: None,
                           requires_login: row.get(11),
                           secret: row.get(12),
1153
                           message: row.get(13),
1154
1155
1156
                           taskgroups: Vec::new() })
            })
            .unwrap()
1157
1158
    }

1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
    fn new_participation(&self, session: &str, contest_id: i32) -> Result<Participation, ()> {
        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(()),
            None => {
                let now = time::get_time();
                self.execute(
                             "INSERT INTO participation (contest, session, start_date)
                     SELECT $1, id, $2 FROM session WHERE session_token = $3",
                             &[&contest_id, &now, &session],
                )
                    .unwrap();

1176
                Ok(self.get_own_participation(session, contest_id).unwrap()) // TODO: This errors if not logged in …
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
            }
        }
    }
    fn get_task_by_id(&self, task_id: i32) -> Task {
        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) })
            .unwrap()
            .unwrap()
    }
    fn get_task_by_id_complete(&self, task_id: i32) -> (Task, Taskgroup, Contest) {
1192
1193
        let query = "SELECT task.location, task.stars, taskgroup.id, taskgroup.name, taskgroup.active, contest.id,
                            contest.location, contest.filename, contest.name, contest.duration, contest.public,
1194
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade,
1195
                            contest.requires_login, contest.secret, contest.message
1196
1197
1198
1199
1200
1201
1202
                     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)),
1203
                             contest: row.get(5),
1204
                             name: row.get(3),
1205
                             active: row.get(4),
1206
1207
                             positionalnumber: None,
                             tasks: Vec::new() },
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
                 Contest { id: Some(row.get(5)),
                           location: row.get(6),
                           filename: row.get(7),
                           name: row.get(8),
                           duration: row.get(9),
                           public: row.get(10),
                           start: row.get(11),
                           end: row.get(12),
                           min_grade: row.get(13),
                           max_grade: row.get(14),
1218
                           positionalnumber: None,
1219
1220
                           requires_login: row.get(15),
                           secret: row.get(16),
1221
                           message: row.get(17),
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
                           taskgroups: Vec::new() })
            })
            .unwrap()
            .unwrap()
    }

    fn get_submission_to_validate(&self, tasklocation: &str, subtask: Option<&str>) -> i32 {
        match subtask {
            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()
            }
        }
    }

    fn find_next_submission_to_validate(&self, userid: i32, taskgroupid: i32) {
        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();
        if !validated {
            let query = "UPDATE submission
                         SET needs_validation = 1
                         WHERE id = $1";
            self.execute(query, &[&id]).unwrap();
        }
    }

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

    fn get_groups(&self, session_id: i32) -> Vec<Group> {
        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() })
            .unwrap()
    }
    fn get_groups_complete(&self, _session_id: i32) -> Vec<Group> {
        unimplemented!();
    }
    fn get_group_complete(&self, group_id: i32) -> Option<Group> {
        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() })
                            .unwrap()
                            .unwrap(); // TODO handle error

        let query = "SELECT id, session_token, csrf_token, last_login, last_activity, permanent_login, username,
                            password, logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname,
1302
                            street, zip, city, nation, grade, sex, is_admin, is_teacher, oauth_provider, oauth_foreign_id, salt
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
                     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),
1328
                                                                                     sex: row.get(19),
1329

1330
1331
                                                                                     is_admin: row.get(20),
                                                                                     is_teacher: row.get(21),
1332
1333
                                                                                     managed_by: Some(group_id),

1334
1335
                                                                                     oauth_provider: row.get(22),
                                                                                     oauth_foreign_id: row.get(23) })
1336
1337
1338
                            .unwrap();
        Some(group)
    }
1339

1340
    fn delete_user(&self, user_id: i32) {
1341
1342
1343
1344
        let query = "DELETE FROM session
                     WHERE id = $1";
        self.execute(query, &[&user_id]).unwrap();
    }
1345
    fn delete_group(&self, group_id: i32) {
1346
1347
1348
1349
        let query = "DELETE FROM usergroup
                     WHERE id = $1";
        self.execute(query, &[&group_id]).unwrap();
    }
1350
    fn delete_participation(&self, user_id: i32, contest_id: i32) {
1351
1352
        let query = "DELETE FROM submission
                     WHERE id IN (
1353
                         SELECT submission.id FROM submission
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
                         JOIN task ON submission.task = task.id
                         JOIN taskgroup ON task.taskgroup = taskgroup.id
                         WHERE taskgroup.contest = $1
                         AND submission.session = $2
                     )";
        self.execute(query, &[&contest_id, &user_id]).unwrap();

        let query = "DELETE FROM grade
                     WHERE taskgroup IN (
                         SELECT id FROM taskgroup
                         WHERE taskgroup.contest = $1
                     )
                     AND session = $2";
        self.execute(query, &[&contest_id, &user_id]).unwrap();
1368

1369
1370
1371
1372
1373
        let query = "DELETE FROM participation
                     WHERE contest = $1
                     AND session = $2";
        self.execute(query, &[&contest_id, &user_id]).unwrap();
    }
1374

1375
    fn get_search_users(&self,
1376
1377
                        (s_id, s_firstname, s_lastname, s_logincode, s_groupcode, s_pms_id): (Option<i32>,
                         Option<String>,
1378
1379
1380
1381
                         Option<String>,
                         Option<String>,
                         Option<String>,
                         Option<String>))
1382
                        -> Result<Vec<(i32, Option<String>, Option<String>)>, Vec<(i32, String, String)>>
1383
1384
1385
1386
1387
1388
    {
        if let Some(id) = s_id {
            let query = "SELECT id, firstname, lastname
                         FROM session
                         WHERE id = $1
                         LIMIT 30";
1389
            Ok(self.query_map_many(query, &[&id], |row| (row.get(0), row.get(1), row.get(2))).unwrap())
1390
1391
1392
1393
1394
        } else if let Some(logincode) = s_logincode {
            let query = "SELECT id, firstname, lastname
                         FROM session
                         WHERE logincode = $1
                         LIMIT 30";
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
            Ok(self.query_map_many(query, &[&logincode], |row| (row.get(0), row.get(1), row.get(2))).unwrap())
        } else if let Some(groupcode) = s_groupcode {
            let query = "SELECT id, name, tag
                         FROM usergroup
                         WHERE groupcode = $1
                         LIMIT 30";
            Err(self.query_map_many(query, &[&groupcode], |row| {
                        (row.get(0),
                         format!("Gruppe: {}", row.get::<_, String>(1)),
                         format!("(Marker: {})", row.get::<_, String>(2)))
                    })
                    .unwrap())
1407
1408
1409
1410
1411
        } else if let Some(pms_id) = s_pms_id {
            let query = "SELECT id, firstname, lastname
                         FROM session
                         WHERE oauth_foreign_id = $1
                         LIMIT 30";
1412
            Ok(self.query_map_many(query, &[&pms_id], |row| (row.get(0), row.get(1), row.get(2))).unwrap())
1413
1414
1415
1416
1417
1418
        } else if let (Some(firstname), Some(lastname)) = (s_firstname, s_lastname) {
            let query = "SELECT id, firstname, lastname
                         FROM session
                         WHERE firstname LIKE $1
                         AND lastname LIKE $2
                         LIMIT 30";
1419
1420
            Ok(