db_conn_postgres.rs 71.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *                                                                             *
 *        WARNING                                                              *
 *                                                                             *
 * This file is auto generated by ./generate_connectors.sh                     *
 *                                                                             *
 * Do not edit this file directly. Instead edit one of the corresponding       *
 * .header.rs oder .base.rs files.                                             *
 *                                                                             *
 *                                                                             *
 *                                                                             *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */

14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*  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/>.                                                                                  */

28
29
#![cfg(feature = "postgres")]

30
31
extern crate postgres;

32
33
34
use postgres::Connection;
use time;
use time::Duration;
35
36
37

use db_conn::{MedalConnection, MedalObject};
use db_objects::*;
38
use helpers;
39

40
trait Queryable {
Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
41
42
    fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F)
                           -> postgres::Result<Option<T>>
43
        where F: FnOnce(postgres::rows::Row<'_>) -> T;
44
45
    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;
46
    fn exists(&self, sql: &str, params: &[&dyn postgres::types::ToSql]) -> bool;
47
    fn get_last_id(&self) -> Option<i32>;
48
49
50
}

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

56
57
        Ok(rows.iter().next().map(f))
    }
58

59
60
61
62
63
    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())
    }

64
65
66
67
68
    fn exists(&self, sql: &str, params: &[&dyn postgres::types::ToSql]) -> bool {
        let stmt = self.prepare(sql).unwrap();
        !stmt.query(params).unwrap().is_empty()
    }

69
70
71
72
73
74
    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
                                                                  })
    }
75
    // Empty line intended
76
77
}

78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
impl MedalObject<Connection> for Submission {
    fn save(&mut self, conn: &Connection) {
        match self.get_id() {
            Some(_id) => unimplemented!(),
            None => {
                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());
            }
        }
    }
}

impl MedalObject<Connection> for Grade {
    fn save(&mut self, conn: &Connection) {
        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();
    }
}
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*  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/>.                                                                                  */

125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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)
            .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) => {
                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)
                .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) => {
                let query = "UPDATE taskgroup
201
202
203
                             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();
204
205
206
                id
            }
            None => {
207
208
209
                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();
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
                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)
            .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) => {
                let query = "UPDATE contest
238
239
240
241
                             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,
                                 requires_login = $12, secret = $13
                             WHERE id = $1";
242
                conn.execute(query,
243
244
                             &[&id,
                               &self.location,
245
246
247
248
249
250
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
                               &self.end,
251
252
                               &self.min_grade,
                               &self.max_grade,
253
                               &self.positionalnumber,
254
255
                               &self.requires_login,
                               &self.secret])
256
257
258
259
                    .unwrap();
                id
            }
            None => {
260
                let query = "INSERT INTO contest (location, filename, name, duration, public, start_date, end_date,
261
262
                                                  min_grade, max_grade, positionalnumber, requires_login, secret)
                             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)";
263
264
265
266
267
268
269
                conn.execute(query,
                             &[&self.location,
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
270
271
                               &self.end,
                               &self.min_grade,
272
                               &self.max_grade,
273
274
275
                               &self.positionalnumber,
                               &self.requires_login,
                               &self.secret])
276
277
278
279
280
281
282
283
284
285
286
287
                    .unwrap();
                conn.get_last_id().unwrap()
            }
        };
        self.set_id(id);
        for mut taskgroup in &mut self.taskgroups {
            taskgroup.contest = id;
            taskgroup.save(conn);
        }
    }
}

288
impl MedalConnection for Connection {
289
290
291
292
293
294
    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();

295
296
        let query = "SELECT name FROM migrations WHERE name = $1";
        self.exists(query, &[&name])
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
    }

    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> {
314
315
        let query = "SELECT id, csrf_token, last_login, last_activity, permanent_login, username, password, salt,
                            logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname, street,
316
                            zip, city, nation, grade, sex, is_admin, is_teacher, managed_by, oauth_provider, oauth_foreign_id
317
318
                     FROM session
                     WHERE session_token = $1";
319
320
321
322
323
324
325
326
327
        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),
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
                                                                             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),

343
344
345
                                                                             is_admin: row.get(20),
                                                                             is_teacher: row.get(21),
                                                                             managed_by: row.get(22),
346

347
348
                                                                             oauth_provider: row.get(23),
                                                                             oauth_foreign_id: row.get(24) })
349
                          .ok()??;
350
351
352

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

354
355
        if let Some(last_activity) = session.last_activity {
            if now - last_activity < duration {
356
357
358
359
                let query = "UPDATE session
                             SET last_activity = $1
                             WHERE id = $2";
                self.execute(query, &[&now, &session.id]).unwrap();
360
                return Some(session);
361
            } else {
362
363
364
365
                // Session timed out
                // Should remove session token from session
                return None;
            }
366
        }
367
368
369
        // last_activity undefined
        // TODO: What should happen here?
        None
370
371
    }
    fn save_session(&self, session: SessionUser) {
372
373
374
375
376
377
378
379
380
381
382
383
        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,
384
385
386
387
                          is_admin = $12,
                          is_teacher = $13,
                          permanent_login = $14
                      WHERE id = $15",
388
389
390
391
392
393
394
395
396
397
                     &[&session.username,
                       &session.password,
                       &session.salt,
                       &session.logincode,
                       &session.firstname,
                       &session.lastname,
                       &session.street,
                       &session.zip,
                       &session.city,
                       &session.grade,
398
                       &session.sex,
399
                       &session.is_admin,
400
                       &session.is_teacher,
401
                       &session.permanent_login,
402
403
404
405
                       &session.id])
            .unwrap();
    }
    fn new_session(&self, session_token: &str) -> SessionUser {
406
        let csrf_token = helpers::make_csrf_token();
407
408

        let now = time::get_time();
409
        let query = "INSERT INTO session (session_token, csrf_token, last_activity, permanent_login, grade, sex,
410
                                          is_teacher)
411
412
                     VALUES ($1, $2, $3, $4, $5, $6, $7)";
        self.execute(query, &[&session_token, &csrf_token, &now, &false, &0, &None::<i32>, &false]).unwrap();
413

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

416
        SessionUser::minimal(id, session_token.to_owned(), csrf_token)
417
418
    }
    fn get_session_or_new(&self, key: &str) -> SessionUser {
419
420
421
        let query = "UPDATE session
                     SET session_token = $1
                     WHERE session_token = $2";
422
423
424
        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?
425
                                                 self.execute(query, &[&Option::<String>::None, &key]).unwrap();
426
427
                                                 self.new_session(&key)
                                             })
428
429
430
    }

    fn get_user_by_id(&self, user_id: i32) -> Option<SessionUser> {
431
        let query = "SELECT session_token, csrf_token, last_login, last_activity, permanent_login, username, password,
432
                            salt, logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname,
433
                            street, zip, city, nation, grade, sex, is_admin, is_teacher, managed_by, oauth_provider,
434
                            oauth_foreign_id
435
436
                     FROM session
                     WHERE id = $1";
437
438
439
440
441
442
443
444
445
        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),
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
                                                                   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),

461
462
463
                                                                   is_admin: row.get(20),
                                                                   is_teacher: row.get(21),
                                                                   managed_by: row.get(22),
464

465
466
                                                                   oauth_provider: row.get(23),
                                                                   oauth_foreign_id: row.get(24) })
467
            .ok()?
468
469
470
471
472
473
474
475
476
477
    }

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

478
479
480
        let query = "SELECT name, groupcode, tag, admin
                     FROM usergroup
                     WHERE id = $1";
481
482
483
484
485
486
487
488
489
        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))),
490
491
492
493
494
495
            _ => Some((session, None)),
        }
    }

    //TODO: use session
    fn login(&self, _session: Option<&str>, username: &str, password: &str) -> Result<String, ()> {
496
497
498
499
        let query = "SELECT id, password, salt
                     FROM session
                     WHERE username = $1";
        self.query_map_one(query, &[&username], |row| {
500
501
502
503
                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
504
                if helpers::verify_password(&password,
505
506
                                            &salt.ok_or_else(|| println!("salt from database empty"))?,
                                            &password_hash.ok_or_else(|| println!("password from database empty"))?)
507
508
509
510
                {
                    // TODO: fail more pleasantly
                    // Login okay, update session now!

511
512
                    let session_token = helpers::make_session_token();
                    let csrf_token = helpers::make_csrf_token();
513
514
                    let now = time::get_time();

515
516
517
                    let query = "UPDATE session
                                 SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3
                                 WHERE id = $4";
518
                    self.execute(query, &[&session_token, &csrf_token, &now, &id]).unwrap();
519
520
521
522
523

                    Ok(session_token)
                } else {
                    Err(())
                }
524
525
526
            })
            .map_err(|_| ())?
            .ok_or(())?
527
528
529
530
    }

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

538
539
                let session_token = helpers::make_session_token();
                let csrf_token = helpers::make_csrf_token();
540
541
                let now = time::get_time();

542
543
544
                let query = "UPDATE session
                             SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3
                             WHERE id = $4";
545
                self.execute(query, &[&session_token, &csrf_token, &now, &id]).unwrap();
546

547
                session_token
548
549
550
            })
            .map_err(|_| ())?
            .ok_or(())
551
552
553
    }

    //TODO: use session
554
555
    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>))
556
557
                     -> Result<String, ()>
    {
558
559
        let session_token = helpers::make_session_token();
        let csrf_token = helpers::make_csrf_token();
560
561
        let now = time::get_time();

562
563
        let query = "SELECT id
                     FROM session
564
565
566
                     WHERE oauth_foreign_id = $1
                           AND oauth_provider = $2";
        match self.query_map_one(query, &[&foreign_id, &provider_id], |row| -> i32 { row.get(0) }) {
567
            Ok(Some(id)) => {
568
                let query = "UPDATE session
569
                             SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3,
570
571
                                 is_teacher = $4, is_admin = $5,  firstname = $6, lastname = $7, sex = $8
                             WHERE id = $9";
572
                self.execute(query, &[&session_token, &csrf_token, &now, &is_teacher, &is_admin, &firstname, &lastname, &sex, &id]).unwrap();
573
574
575
576
577

                Ok(session_token)
            }
            // Add!
            _ => {
578
                let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity,
579
                                                  permanent_login, grade, sex, is_teacher, is_admin, oauth_foreign_id,
580
                                                  oauth_provider, firstname, lastname)
581
                             VALUES ($1, $2, $3, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)";
582
583
584
585
586
                self.execute(query,
                             &[&session_token,
                               &csrf_token,
                               &now,
                               &false,
587
                               &(if is_teacher { 255 } else { 0 }),
588
                               &sex,
589
                               &is_teacher,
590
                               &is_admin,
591
                               &foreign_id,
592
                               &provider_id,
593
594
595
                               &firstname,
                               &lastname])
                    .unwrap();
596
597
598
599
600
601
602
603

                Ok(session_token)
            }
        }
    }

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

610
611
612
        // Login okay, create session!
        let session_token = helpers::make_session_token();
        let csrf_token = helpers::make_csrf_token();
613
        let login_code = helpers::make_login_code(); // TODO: check for collisions
614
        let now = time::get_time();
615

616
        let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity, permanent_login,
617
                                          logincode, grade, sex, is_teacher, managed_by)
618
                     VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)";
619
620
621
622
623
624
625
626
627
628
629
630
        self.execute(query,
                     &[&session_token,
                       &csrf_token,
                       &now,
                       &now,
                       &false,
                       &login_code,
                       &0,
                       &None::<i32>,
                       &false,
                       &group_id])
            .unwrap();
631

632
        Ok(session_token)
633
634
    }

Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
635
    fn create_group_with_users(&self, mut group: Group) {
636
637
638
639
640
641
        // 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
642

643
            let query = "INSERT INTO session (firstname, lastname, csrf_token, permanent_login, logincode, grade, sex,
644
                                              is_teacher, managed_by)
645
                         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)";
646
647
648
649
650
651
652
            self.execute(query,
                         &[&user.firstname,
                           &user.lastname,
                           &csrf_token,
                           &false,
                           &login_code,
                           &user.grade,
653
                           &None::<i32>,
654
655
656
                           &false,
                           &group.id])
                .unwrap();
657
        }
658
659
    }

660
    fn logout(&self, session: &str) {
661
662
663
        let query = "UPDATE session
                     SET session_token = NULL
                     WHERE session_token = $1";
664
        self.execute(query, &[&session]).unwrap();
665
666
667
668
    }

    fn load_submission(&self, session: &SessionUser, task: i32, subtask: Option<&str>) -> Option<Submission> {
        match subtask {
669
670
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
            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)),
                                                                                    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) => {
                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)),
                                     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()?
            }
710
711
        }
    }
712
713
714
715
716
717
718
719
    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)),
720
721
722
723
724
725
726
727
                                                                                    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),
728
729
730
                                                                                     needs_validation: row.get(6) })
                    .unwrap()
            }
731
            _ => unimplemented!()
732
733
        }
    }
734
735
736
737
738
739
740
741
742
743
744
    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 {
745
746
747
748
749
750
        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";
751
752
753
754
755
756
757
        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
758
759
760
                         FROM submission
                         JOIN task ON task.id = submission.task
                         WHERE submission.id = $1";
761
762
763
764
765
766
767
                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?
            })
768
769
770
771
    }

    fn get_contest_groups_grades(&self, session_id: i32, contest_id: i32)
                                 -> (Vec<String>, Vec<(Group, Vec<(UserInfo, Vec<Grade>)>)>) {
772
773
774
        let query = "SELECT id, name
                     FROM taskgroup
                     WHERE contest = $1
775
776
                     AND active = $2
                     ORDER BY positionalnumber";
777
        let tasknames: Vec<(i32, String)> =
778
            self.query_map_many(query, &[&contest_id, &true], |row| (row.get(0), row.get(1))).unwrap();
779

780
781
782
783
784
785
786
        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);
        }

787
788
        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,
789
                            student.firstname, student.lastname, student.grade AS sgrade
790
791
792
793
794
795
                     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
796
                     AND taskgroup.active = $3
797
798
                     ORDER BY usergroup.id, sgrade, student.lastname, student.firstname, student.id,
                              taskgroup.positionalnumber";
799
        let gradeinfo =
800
            self.query_map_many(query, &[&session_id, &contest_id, &true], |row| {
801
802
803
804
805
806
807
808
809
810
811
                    (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),
812
                                lastname: row.get(12),
Robert Czechowski's avatar
Robert Czechowski committed
813
                                grade: row.get(13) })
814
815
816
                })
                .unwrap();
        let mut gradeinfo_iter = gradeinfo.iter();
817
818

        if let Some(t /*Ok((grade, mut group, mut userinfo))*/) = gradeinfo_iter.next() {
819
            let (grade, mut group, mut userinfo) = t.clone();
820
821
822
823
824
825

            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;
826
            grades[taskindex[&index]] = grade;
827
828

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

835
836
                    groups.push((group, users));
                    group = gr.clone();
837
838
                    users = Vec::new();
                } else if ui.id != userinfo.id {
839
840
                    users.push((userinfo, grades));
                    userinfo = ui.clone();
841
                    grades = vec![Default::default(); n_tasks];
842
                }
843
                let index = g.taskgroup;
844
                grades[taskindex[&index]] = *g;
845
            }
846
847
            users.push((userinfo, grades));
            groups.push((group, users));
848
849
850
851
852
853
854

            (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> {
855
856
857
        let query = "SELECT id, name
                     FROM taskgroup
                     WHERE contest = $1
858
859
                     AND active = $2
                     ORDER BY positionalnumber";
860
        let tasknames: Vec<(i32, String)> =
861
            self.query_map_many(query, &[&contest_id, &true], |row| (row.get(0), row.get(1))).unwrap();
862
863
864
865
866
867
868
        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);
        }

869
870
871
872
873
874
        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
875
876
                     AND taskgroup.active = $3
                     ORDER BY taskgroup.positionalnumber";
877
        let gradeinfo =
878
            self.query_map_many(query, &[&session_token, &contest_id, &true], |row| Grade { taskgroup: row.get(0),
Robert Czechowski's avatar
Robert Czechowski committed
879
880
881
                                                                                            user: row.get(1),
                                                                                            grade: row.get(2),
                                                                                            validated: row.get(3) })
882
883
                .unwrap();
        let gradeinfo_iter = gradeinfo.iter();
884
885
886
887
888

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

        for g in gradeinfo_iter {
            let index = g.taskgroup;
889
            grades[taskindex[&index]] = *g;
890
891
892
893
894
895
        }

        grades
    }

    fn get_taskgroup_user_grade(&self, session_token: &str, taskgroup_id: i32) -> Grade {
896
        let query = "SELECT grade.taskgroup, grade.session, grade.grade, grade.validated
897
898
899
900
                     FROM grade
                     JOIN session ON session.id = grade.session
                     WHERE session.session_token = $1
                     AND grade.taskgroup = $2";
901
902
903
904
905
906
        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()
907
908
    }

909
910
911
912
913
914
915
916
917
    fn export_contest_results_to_file(&self, contest_id: i32, taskgroups_ids: &[i32], filename: &str) {
        let query = "COPY (
                         SELECT * from contest
                     )
                     TO '/tmp/output.csv'
                     WITH CSV DELIMITER ',' HEADER;";
        self.execute(query, &[]).unwrap();
    }

918
    fn get_contest_list(&self) -> Vec<Contest> {
919
        let query = "SELECT id, location, filename, name, duration, public, start_date, end_date, min_grade, max_grade,
920
                            positionalnumber, requires_login, secret
921
                     FROM contest
922
                     ORDER BY positionalnumber";
923
924
925
926
927
928
929
930
        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),
931
932
                                                        min_grade: row.get(8),
                                                        max_grade: row.get(9),
933
                                                        positionalnumber: row.get(10),
934
935
                                                        requires_login: row.get(11),
                                                        secret: row.get(12),
936
937
                                                        taskgroups: Vec::new() })
            .unwrap()
938
939
940
    }

    fn get_contest_by_id(&self, contest_id: i32) -> Contest {
941
942
        let query = "SELECT location, filename, name, duration, public, start_date, end_date, min_grade, max_grade,
                            requires_login, secret
943
944
                     FROM contest
                     WHERE id = $1";
945
946
947
948
949
950
951
952
        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),
953
954
                                                                  min_grade: row.get(7),
                                                                  max_grade: row.get(8),
955
                                                                  positionalnumber: None,
956
957
                                                                  requires_login: row.get(9),
                                                                  secret: row.get(10),
958
                                                                  taskgroups: Vec::new() })
959
960
961
962
963
            .unwrap()
            .unwrap() // TODO: Should return Option?
    }

    fn get_contest_by_id_complete(&self, contest_id: i32) -> Contest {
964
        let query = "SELECT contest.location, contest.filename, contest.name, contest.duration, contest.public,
965
966
967
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade,
                            contest.requires_login, contest.secret, taskgroup.id, taskgroup.name, task.id,
                            task.location, task.stars
968
969
970
971
                     FROM contest
                     JOIN taskgroup ON contest.id = taskgroup.contest
                     JOIN task ON taskgroup.id = task.taskgroup
                     WHERE contest.id = $1
972
                     AND taskgroup.active = $2
973
                     ORDER BY taskgroup.positionalnumber";
974
        let taskgroupcontest =
975
            self.query_map_many(query, &[&contest_id, &true], |row| {
976
977
978
979
980
981
982
983
                    (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),
984
985
                               min_grade: row.get(7),
                               max_grade: row.get(8),
986
                               positionalnumber: None,
987
988
                               requires_login: row.get(9),
                               secret: row.get(10),
989
                               taskgroups: Vec::new() },
990
                     Taskgroup { id: Some(row.get(11)),
991
                                 contest: contest_id,
992
                                 name: row.get(12),
993
                                 active: true,
994
995
                                 positionalnumber: None,
                                 tasks: Vec::new() },
996
                     Task { id: Some(row.get(13)), taskgroup: row.get(11), location: row.get(14), stars: row.get(15) })
997
998
999
                })
                .unwrap();
        let mut taskgroupcontest_iter = taskgroupcontest.into_iter();
1000
1001
1002
1003

        let (mut contest, mut taskgroup, task) = taskgroupcontest_iter.next().unwrap();
        taskgroup.tasks.push(task);
        for tgc in taskgroupcontest_iter {
1004
1005
1006
1007
            let (_, tg, t) = tgc;
            if tg.id != taskgroup.id {
                contest.taskgroups.push(taskgroup);
                taskgroup = tg;
1008
            }
1009
            taskgroup.tasks.push(t);
1010
1011
1012
1013
1014
1015
        }
        contest.taskgroups.push(taskgroup);
        contest
    }

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

        let (mut contest, taskgroup) = taskgroupcontest_iter.next().unwrap();
        contest.taskgroups.push(taskgroup);
        for tgc in taskgroupcontest_iter {
1051
1052
            let (_, tg) = tgc;
            contest.taskgroups.push(tg);
1053
1054
1055
1056
1057
        }
        contest
    }

    fn get_participation(&self, session: &str, contest_id: i32) -> Option<Participation> {
1058
1059
1060
1061
1062
        let query = "SELECT session, start_date
                     FROM participation
                     JOIN session ON session.id = session
                     WHERE session.session_token = $1
                     AND contest = $2";
1063
1064
1065
1066
        self.query_map_one(query, &[&session, &contest_id], |row| Participation { contest: contest_id,
                                                                                  user: row.get(0),
                                                                                  start: row.get(1) })
            .ok()?
1067
    }
1068
1069
1070
1071
1072
1073
1074
1075

    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,
                            contest.start_date, end_date, min_grade, max_grade, requires_login, secret
                     FROM participation
                     JOIN contest ON participation.contest = contest.id
                     WHERE participation.session = $1";
        self.query_map_many(query, &[&session_id], |row| {
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
                                       ( 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),
                                                  taskgroups: Vec::new() },
                                        )
                                   })
                                   .unwrap()
1096
1097
    }

1098
    
1099
    fn new_participation(&self, session: &str, contest_id: i32) -> Result<Participation, ()> {
1100
1101
1102
1103
1104
        let query = "SELECT session, start_date
                     FROM participation
                     JOIN session ON session.id = session
                     WHERE session.session_token = $1
                     AND contest = $2";
1105
1106
        match self.query_map_one(query, &[&session, &contest_id], |_| {}).map_err(|_| ())? {
            Some(()) => Err(()),
1107
1108
1109
            None => {
                let now = time::get_time();
                self.execute(
1110
                             "INSERT INTO participation (contest, session, start_date)
1111
                     SELECT $1, id, $2 FROM session WHERE session_token = $3",
1112
1113
1114
                             &[&contest_id, &now, &session],
                )
                    .unwrap();
1115
1116
1117
1118
1119
1120

                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 {
1121
1122
1123
        let query = "SELECT location, stars, taskgroup
                     FROM task
                     WHERE id = $1";
1124
1125
1126
1127
        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) })
1128
1129
1130
1131
            .unwrap()
            .unwrap()
    }
    fn get_task_by_id_complete(&self, task_id: i32) -> (Task, Taskgroup, Contest) {
1132
1133
        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,
1134
1135
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade,
                            contest.requires_login, contest.secret
1136
1137
1138
1139
                     FROM contest
                     JOIN taskgroup ON taskgroup.contest = contest.id
                     JOIN task ON task.taskgroup = taskgroup.id
                     WHERE task.id = $1";
1140
1141
        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) },
1142
                 Taskgroup { id: Some(row.get(2)),
1143
                             contest: row.get(5),
1144
                             name: row.get(3),
1145
                             active: row.get(4),
1146
1147
                             positionalnumber: None,
                             tasks: Vec::new() },
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
                 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),
1158
                           positionalnumber: None,
1159
1160
                           requires_login: row.get(15),
                           secret: row.get(16),
1161
1162
1163
1164
                           taskgroups: Vec::new() })
            })
            .unwrap()
            .unwrap()
1165
1166
1167
1168
    }

    fn get_submission_to_validate(&self, tasklocation: &str, subtask: Option<&str>) -> i32 {
        match subtask {
1169
            Some(st) => {
1170
1171
1172
1173
1174
1175
1176
                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";
1177
1178
1179
                self.query_map_one(query, &[&tasklocation, &st], |row| row.get(0)).unwrap().unwrap()
            }
            None => {
1180
1181
1182
1183
1184
1185
                let query = "SELECT id
                             FROM submission
                             JOIN task ON submission.task = task.id
                             WHERE task.location = $1
                             AND needs_validation = 1
                             LIMIT 1";
1186
1187
                self.query_map_one(query, &[&tasklocation], |row| row.get(0)).unwrap().unwrap()
            }
1188
1189
1190
1191
        }
    }

    fn find_next_submission_to_validate(&self, userid: i32, taskgroupid: i32) {
1192
1193
1194
1195
1196
1197
1198
        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";