db_conn_sqlite_new.rs 92.4 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
#![cfg(feature = "rusqlite")]
29
30
31

extern crate rusqlite;

32
use config;
33
34
35
36
use rusqlite::Connection;
use time;
use time::Duration;

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

41
42
fn gen_tosql_vector() -> Vec<&'static dyn rusqlite::types::ToSql> { Vec::new() }

43
44
45
46
47
48
49
50
trait Queryable {
    fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn rusqlite::types::ToSql], f: F)
                           -> rusqlite::Result<Option<T>>
        where F: FnOnce(&rusqlite::Row) -> T;
    fn query_map_many<T, F>(&self, sql: &str, params: &[&dyn rusqlite::types::ToSql], f: F) -> rusqlite::Result<Vec<T>>
        where F: FnMut(&rusqlite::Row) -> T;
    fn exists(&self, sql: &str, params: &[&dyn rusqlite::types::ToSql]) -> bool;
    fn get_last_id(&self) -> Option<i32>;
51
52

    fn reconnect_concrete(&config::Config) -> Self;
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
}

impl Queryable for Connection {
    fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn rusqlite::types::ToSql], f: F)
                           -> rusqlite::Result<Option<T>>
        where F: FnOnce(&rusqlite::Row) -> T {
        let mut stmt = self.prepare(sql)?;
        let mut rows = stmt.query(params)?;
        match rows.next() {
            None => Ok(None),
            Some(Err(e)) => Err(e),
            Some(Ok(row)) => Ok(Some(f(&row))),
        }
    }

    fn query_map_many<T, F>(&self, sql: &str, params: &[&dyn rusqlite::types::ToSql], f: F) -> rusqlite::Result<Vec<T>>
        where F: FnMut(&rusqlite::Row) -> T {
        let mut stmt = self.prepare(sql)?;
        let rows = stmt.query_map(params, f)?;
        Ok(rows.map(|x| x.unwrap()).collect())
    }

    fn exists(&self, sql: &str, params: &[&dyn rusqlite::types::ToSql]) -> bool {
        let mut stmt = self.prepare(sql).unwrap();
        stmt.exists(params).unwrap()
    }

    fn get_last_id(&self) -> Option<i32> { self.query_row("SELECT last_insert_rowid()", &[], |row| row.get(0)).ok() }
81
82
83
84

    fn reconnect_concrete(config: &config::Config) -> Self {
        rusqlite::Connection::open(config.database_file.clone().unwrap()).unwrap()
    }
85
86
}

87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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 OR REPLACE INTO grade (taskgroup, session, grade, validated)
                     VALUES (?1, ?2, ?3, ?4)";
116

117
118
119
        conn.execute(query, &[&self.taskgroup, &self.user, &self.grade, &self.validated]).unwrap();
    }
}
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*  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/>.                                                                                  */

134
135
136
137
138
139
140
141
142
143
144
145
146
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 => {
147
148
149
150
                let query = "INSERT INTO usergroup (name, groupcode, tag, admin, group_created)
                             VALUES (?1, ?2, ?3, ?4, ?5)";
                let now = time::get_time();
                conn.execute(query, &[&self.name, &self.groupcode, &self.tag, &self.admin, &now]).unwrap();
151
152
153
154
155
156
157
158
159
160
161
162
163
164
                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)
165
            .map(|id| {
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
                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)
200
                .map(|id| {
201
202
203
204
205
206
207
208
                    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
209
210
211
                             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();
212
213
214
                id
            }
            None => {
215
216
217
                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();
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
                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)
237
            .map(|id| {
238
239
240
241
242
243
244
                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
245
246
                             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,
247
                                 requires_login = ?12, requires_contest = ?13, secret = ?14, message = ?15
248
                             WHERE id = ?1";
249
                conn.execute(query,
250
251
                             &[&id,
                               &self.location,
252
253
254
255
256
257
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
                               &self.end,
258
259
                               &self.min_grade,
                               &self.max_grade,
260
                               &self.positionalnumber,
261
                               &self.requires_login,
262
                               &self.requires_contest,
263
264
                               &self.secret,
                               &self.message])
265
266
267
268
                    .unwrap();
                id
            }
            None => {
269
                let query = "INSERT INTO contest (location, filename, name, duration, public, start_date, end_date,
270
271
272
                                                  min_grade, max_grade, positionalnumber, requires_login,
                                                  requires_contest, secret, message)
                             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)";
273
274
275
276
277
278
279
                conn.execute(query,
                             &[&self.location,
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
280
281
                               &self.end,
                               &self.min_grade,
282
                               &self.max_grade,
283
284
                               &self.positionalnumber,
                               &self.requires_login,
285
                               &self.requires_contest,
286
287
                               &self.secret,
                               &self.message])
288
289
290
291
292
293
294
295
296
297
298
299
                    .unwrap();
                conn.get_last_id().unwrap()
            }
        };
        self.set_id(id);
        for mut taskgroup in &mut self.taskgroups {
            taskgroup.contest = id;
            taskgroup.save(conn);
        }
    }
}

300
impl MedalConnection for Connection {
301
302
    fn reconnect(config: &config::Config) -> Self { Self::reconnect_concrete(config) }

303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
    fn dbtype(&self) -> &'static str { "sqlite_v2" }

    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.execute_batch(&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> {
328
329
        let query = "SELECT id, csrf_token, last_login, last_activity, account_created, username, password,
                            salt, logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname, street,
330
                            zip, city, nation, grade, sex, is_admin, is_teacher, managed_by, oauth_provider, oauth_foreign_id
331
332
333
334
335
336
337
                     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),
338
                                                                             account_created: row.get(4),
339
340
341

                                                                             username: row.get(5),
                                                                             password: row.get(6),
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
                                                                             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),

357
358
359
                                                                             is_admin: row.get(20),
                                                                             is_teacher: row.get(21),
                                                                             managed_by: row.get(22),
360

361
362
                                                                             oauth_provider: row.get(23),
                                                                             oauth_foreign_id: row.get(24) })
363
364
                          .ok()??;

365
        let duration = Duration::hours(12);
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
        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) {
386
387
388
389
390
391
392
393
394
395
396
397
        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,
398
399
                          is_admin = ?12,
                          is_teacher = ?13,
400
                          managed_by = ?14,
401
402
403
                          email = ?15,
                          email_unconfirmed = ?16
                      WHERE id = ?17",
404
405
406
407
408
409
410
411
412
413
                     &[&session.username,
                       &session.password,
                       &session.salt,
                       &session.logincode,
                       &session.firstname,
                       &session.lastname,
                       &session.street,
                       &session.zip,
                       &session.city,
                       &session.grade,
414
                       &session.sex,
415
                       &session.is_admin,
416
                       &session.is_teacher,
417
                       &session.managed_by,
418
419
                       &session.email,
                       &session.email_unconfirmed,
420
421
422
423
424
425
426
                       &session.id])
            .unwrap();
    }
    fn new_session(&self, session_token: &str) -> SessionUser {
        let csrf_token = helpers::make_csrf_token();

        let now = time::get_time();
427
        let query = "INSERT INTO session (session_token, csrf_token, last_activity, account_created, grade, sex,
428
                                          is_teacher)
429
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)";
Robert Czechowski's avatar
Robert Czechowski committed
430
431
        self.execute(query, &[&session_token, &csrf_token, &now, &None::<time::Timespec>, &0, &None::<i32>, &false])
            .unwrap();
432
433
434
435
436

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

        SessionUser::minimal(id, session_token.to_owned(), csrf_token)
    }
Robert Czechowski's avatar
Robert Czechowski committed
437
438
    fn session_set_activity_dates(&self, session_id: i32, account_created: Option<time::Timespec>,
                                  last_login: Option<time::Timespec>, last_activity: Option<time::Timespec>) {
439
440
441
442
443
        let query = "UPDATE session
                     SET account_created = ?2, last_login = ?3, last_activity = ?4
                     WHERE id = ?1";
        self.execute(query, &[&session_id, &account_created, &last_login, &last_activity]).unwrap();
    }
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
    fn get_session_or_new(&self, key: &str) -> Result<SessionUser, ()> {
        fn disable_old_session_and_create_new(conn: &Connection, key: &str) -> Result<SessionUser, ()> {
            let query = "UPDATE session
                         SET session_token = ?1
                         WHERE session_token = ?2";
            // TODO: Should a new session key be generated every time?
            conn.execute(query, &[&Option::<String>::None, &key]).map_err(|_| ())?;
            Ok(conn.new_session(&key))
        }

        if let Some(session) = self.get_session(&key).ensure_alive() {
            Ok(session)
        } else {
            disable_old_session_and_create_new(self, key)
        }
459
460
461
    }

    fn get_user_by_id(&self, user_id: i32) -> Option<SessionUser> {
462
        let query = "SELECT session_token, csrf_token, last_login, last_activity, account_created, username, password,
463
                            salt, logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname,
464
                            street, zip, city, nation, grade, sex, is_admin, is_teacher, managed_by, oauth_provider,
465
                            oauth_foreign_id
466
467
468
469
470
471
472
                     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),
473
                                                                   account_created: row.get(4),
474
475
476

                                                                   username: row.get(5),
                                                                   password: row.get(6),
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
                                                                   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),

492
493
494
                                                                   is_admin: row.get(20),
                                                                   is_teacher: row.get(21),
                                                                   managed_by: row.get(22),
495

496
497
                                                                   oauth_provider: row.get(23),
                                                                   oauth_foreign_id: row.get(24) })
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
            .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,
536
537
                                            &salt.ok_or_else(|| println!("salt from database empty"))?,
                                            &password_hash.ok_or_else(|| println!("password from database empty"))?)
538
539
540
541
542
                {
                    // TODO: fail more pleasantly
                    // Login okay, update session now!

                    let session_token = helpers::make_session_token();
543
                    let csrf_token = helpers::make_csrf_token();
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
                    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, ()> {
562
563
564
565
        if logincode == "" {
            return Err(());
        }

566
567
568
        let query = "SELECT id
                     FROM session
                     WHERE logincode = ?1";
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
        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
589
590
    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>))
Robert Czechowski's avatar
Robert Czechowski committed
591
                     -> Result<(String, Option<time::Timespec>), ()> {
592
593
594
595
        let session_token = helpers::make_session_token();
        let csrf_token = helpers::make_csrf_token();
        let now = time::get_time();

596
        let query = "SELECT id, last_activity
597
                     FROM session
598
599
                     WHERE oauth_foreign_id = ?1
                           AND oauth_provider = ?2";
600
601
602
603
        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))) => {
604
                let query = "UPDATE session
605
                             SET session_token = ?1, csrf_token = ?2, last_login = ?3, last_activity = ?3,
606
607
                                 is_teacher = ?4, is_admin = ?5,  firstname = ?6, lastname = ?7, sex = ?8
                             WHERE id = ?9";
608
609
610
611
612
613
614
615
616
617
618
                self.execute(query,
                             &[&session_token,
                               &csrf_token,
                               &now,
                               &is_teacher,
                               &is_admin,
                               &firstname,
                               &lastname,
                               &sex,
                               &id])
                    .unwrap();
619

620
                Ok((session_token, Some(last_activity)))
621
622
623
624
            }
            // Add!
            _ => {
                let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity,
625
                                                  account_created, grade, sex, is_teacher, is_admin, oauth_foreign_id,
626
                                                  oauth_provider, firstname, lastname)
627
                             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)";
628
629
630
631
                self.execute(query,
                             &[&session_token,
                               &csrf_token,
                               &now,
632
633
                               &now,
                               &now,
634
                               &(if is_teacher { 255 } else { 0 }),
635
                               &sex,
636
                               &is_teacher,
637
                               &is_admin,
638
                               &foreign_id,
639
                               &provider_id,
640
641
642
643
                               &firstname,
                               &lastname])
                    .unwrap();

644
                Ok((session_token, None))
645
646
647
648
649
650
            }
        }
    }

    //TODO: use session
    fn create_user_with_groupcode(&self, _session: Option<&str>, groupcode: &str) -> Result<String, ()> {
651
652
653
654
        if groupcode == "" {
            return Err(());
        }

655
656
657
658
659
660
661
662
663
664
665
666
        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();

667
        let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity, account_created,
668
                                          logincode, grade, sex, is_teacher, managed_by)
669
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)";
670
671
672
673
674
        self.execute(query,
                     &[&session_token,
                       &csrf_token,
                       &now,
                       &now,
675
                       &now,
676
677
678
679
680
681
                       &login_code,
                       &0,
                       &None::<i32>,
                       &false,
                       &group_id])
            .unwrap();
682
683
684
685
686
687
688

        Ok(session_token)
    }

    fn create_group_with_users(&self, mut group: Group) {
        // Generate group ID:
        group.save(self);
689

690
        let now = time::get_time();
691
692
693
694
695

        for user in group.members {
            let csrf_token = helpers::make_csrf_token();
            let login_code = helpers::make_login_code(); // TODO: check for collisions

696
            let query = "INSERT INTO session (firstname, lastname, csrf_token, account_created, logincode, grade, sex,
697
                                              is_teacher, managed_by)
698
                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)";
699
700
701
702
            self.execute(query,
                         &[&user.firstname,
                           &user.lastname,
                           &csrf_token,
703
                           &now,
704
705
                           &login_code,
                           &user.grade,
706
                           &user.sex,
707
708
709
710
711
712
713
714
715
716
717
718
719
                           &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
720
721
    fn signup(&self, session_token: &str, username: &str, email: &str, password_hash: String, salt: &str)
              -> SignupResult {
722
        let mut session_user = self.get_session_or_new(&session_token).unwrap();
723
724

        if session_user.is_logged_in() {
Robert Czechowski's avatar
Robert Czechowski committed
725
            return SignupResult::UserLoggedIn;
726
727
728
        }

        if let Ok(None) = self.query_map_one("SELECT username FROM session WHERE username = ?1",
Robert Czechowski's avatar
Robert Czechowski committed
729
730
731
732
                                             &[&username],
                                             |row| -> Option<String> { row.get(0) })
        {
        } else {
733
            //This username already exists!
Robert Czechowski's avatar
Robert Czechowski committed
734
            return SignupResult::UsernameTaken;
735
736
        }
        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
737
738
739
740
                                             &[&email],
                                             |row| -> (Option<String>, Option<String>) { (row.get(0), row.get(1)) })
        {
        } else {
741
            //This email already exists!
Robert Czechowski's avatar
Robert Czechowski committed
742
            return SignupResult::EmailTaken;
743
744
745
746
747
748
749
750
751
752
753
        }

        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
    }

754
755
756
757
758
759
760
761
762
763
    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
764
                                                                                    task,
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
                                                                                    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
785
                                     task,
786
787
788
789
790
791
792
793
794
795
796
797
798
                                     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()?
            }
        }
    }
799
800
801
802
803
804
    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
805
806
                             AND session = ?2
                             ORDER BY date";
807
                self.query_map_many(query, &[&task, &session_id], |row| Submission { id: Some(row.get(0)),
Robert Czechowski's avatar
Robert Czechowski committed
808
                                                                                     task,
809
810
811
812
813
814
815
                                                                                     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),
816
817
818
                                                                                     needs_validation: row.get(6) })
                    .unwrap()
            }
819
            _ => unimplemented!(),
820
821
        }
    }
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
    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";
839
840
841
842
843
844
845
        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
846
847
848
                         FROM submission
                         JOIN task ON task.id = submission.task
                         WHERE submission.id = ?1";
849
850
851
852
853
854
855
                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?
            })
856
857
858
859
860
861
862
    }

    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
863
864
                     AND active = ?2
                     ORDER BY positionalnumber";
865
        let tasknames: Vec<(i32, String)> =
866
            self.query_map_many(query, &[&contest_id, &true], |row| (row.get(0), row.get(1))).unwrap();
867
868
869
870
871
872
873
874

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

875
876
        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,
877
                            student.firstname, student.lastname, student.grade AS sgrade
878
879
880
881
882
883
                     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
884
                     AND taskgroup.active = ?3
885
886
                     ORDER BY usergroup.id, sgrade, student.lastname, student.firstname, student.id,
                              taskgroup.positionalnumber";
887
        let gradeinfo =
888
            self.query_map_many(query, &[&session_id, &contest_id, &true], |row| {
889
890
891
892
893
894
895
896
897
898
899
                    (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),
900
                                lastname: row.get(12),
Robert Czechowski's avatar
Robert Czechowski committed
901
                                grade: row.get(13) })
902
903
                })
                .unwrap();
904
        let mut gradeinfo_iter = gradeinfo.iter();
905
906

        if let Some(t /*Ok((grade, mut group, mut userinfo))*/) = gradeinfo_iter.next() {
907
            let (grade, mut group, mut userinfo) = t.clone();
908
909
910
911
912
913

            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;
914
            grades[taskindex[&index]] = grade;
915
916

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

923
924
                    groups.push((group, users));
                    group = gr.clone();
925
926
                    users = Vec::new();
                } else if ui.id != userinfo.id {
927
928
                    users.push((userinfo, grades));
                    userinfo = ui.clone();
929
                    grades = vec![Default::default(); n_tasks];
930
                }
931
932
                let index = g.taskgroup;
                grades[taskindex[&index]] = *g;
933
            }
934
935
            users.push((userinfo, grades));
            groups.push((group, users));
936
937
938
939
940
941
942
943
944
945

            (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
946
947
                     AND active = ?2
                     ORDER BY positionalnumber";
948
        let tasknames: Vec<(i32, String)> =
949
            self.query_map_many(query, &[&contest_id, &true], |row| (row.get(0), row.get(1))).unwrap();
950
951
952
953
954
955
956
        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);
        }

957
958
959
960
961
962
        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
963
964
                     AND taskgroup.active = ?3
                     ORDER BY taskgroup.positionalnumber";
965
        let gradeinfo =
966
            self.query_map_many(query, &[&session_token, &contest_id, &true], |row| Grade { taskgroup: row.get(0),
Robert Czechowski's avatar
Robert Czechowski committed
967
968
969
                                                                                            user: row.get(1),
                                                                                            grade: row.get(2),
                                                                                            validated: row.get(3) })
970
971
                .unwrap();
        let gradeinfo_iter = gradeinfo.iter();
972
973
974
975
976

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

        for g in gradeinfo_iter {
            let index = g.taskgroup;
977
            grades[taskindex[&index]] = *g;
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
        }

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

997
    /* Warning: This function makes no use of rusts typeb safety. Handle with care when changeing */
998
999
    fn export_contest_results_to_file(&self, contest_id: i32, taskgroups: &[(i32, String)], filename: &str) {
        use std::fs::OpenOptions;
1000
        let file = OpenOptions::new().write(true).create(true).truncate(true).open(filename).unwrap();
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
        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",
Robert Czechowski's avatar
Robert Czechowski committed
1018
                               "teacher_oauth_school_id",
1019
1020
1021
                               "teacher_oauth_provider",
                               "contest_id",
                               "start_date"];
1022
1023
1024

        let mut select_part = String::new();
        let mut join_part = String::new();
1025
1026
1027

        let mut join_params = gen_tosql_vector();

1028
        join_params.push(&contest_id);
1029
1030

        for (n, (id, name)) in taskgroups.iter().enumerate() {
1031
1032
1033
1034
1035
            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);
        }
1036

1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
        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
1063
1064
                             WHERE participation.contest = ?1",
                            select_part, join_part);
1065
1066

        use csv::Writer;
1067
        let mut wtr = Writer::from_writer(file);
1068
1069
        wtr.serialize(&headers).unwrap();
        wtr.flush().unwrap();
1070

1071
1072
        let file = wtr.into_inner().unwrap();
        let mut wtr = Writer::from_writer(file);
1073
1074
1075
1076
1077
1078

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

1080
                let teacher_oauth_and_school_id = row.get::<_, Option<String>>(16);
Robert Czechowski's avatar
Robert Czechowski committed
1081
                let (teacher_oauth_id, teacher_school_id) = if let Some(toasi) = teacher_oauth_and_school_id {
1082
1083
1084
1085
1086
1087
1088
1089
                    let mut v = toasi.split('/');
                    let oid: Option<String> = v.next().map(|s| s.to_owned());
                    let sid: Option<String> = v.next().map(|s| s.to_owned());
                    (oid, sid)
                } else {
                    (None, None)
                };

1090
1091
                // 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)
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
                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),
Robert Czechowski's avatar
Robert Czechowski committed
1108
1109
                                teacher_oauth_id,
                                teacher_school_id,
1110
1111
                                row.get::<_, Option<String>>(17)),
                               row.get::<_, Option<i32>>(18),
1112
1113
                               row.get::<_, Option<time::Timespec>>(19)
                                  .map(|ts| self::time::strftime("%FT%T%z", &time::at(ts)).unwrap()),
1114
1115
1116
1117
                               points))
                   .unwrap();
            })
            .unwrap();
1118
        wtr.flush().unwrap();
1119
1120
    }

1121
    fn get_contest_list(&self) -> Vec<Contest> {
1122
        let query = "SELECT id, location, filename, name, duration, public, start_date, end_date, min_grade, max_grade,
1123
                            positionalnumber, requires_login, requires_contest, secret, message
1124
                     FROM contest
1125
                     ORDER BY positionalnumber DESC";
1126
1127
1128
1129
1130
1131
1132
1133
        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),
1134
1135
                                                        min_grade: row.get(8),
                                                        max_grade: row.get(9),
1136
                                                        positionalnumber: row.get(10),
1137
                                                        requires_login: row.get(11),
1138
1139
1140
                                                        requires_contest: row.get(12),
                                                        secret: row.get(13),
                                                        message: row.get(14),
1141
1142
1143
1144
1145
                                                        taskgroups: Vec::new() })
            .unwrap()
    }

    fn get_contest_by_id(&self, contest_id: i32) -> Contest {
1146
        let query = "SELECT location, filename, name, duration, public, start_date, end_date, min_grade, max_grade,
1147
                            requires_login, requires_contest, secret, message
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
                     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),
1158
1159
                                                                  min_grade: row.get(7),
                                                                  max_grade: row.get(8),
1160
                                                                  positionalnumber: None,
1161
                                                                  requires_login: row.get(9),
1162
1163
1164
                                                                  requires_contest: row.get(10),
                                                                  secret: row.get(11),
                                                                  message: row.get(12),
1165
1166
1167
1168
1169
1170
1171
                                                                  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,
1172
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade,
1173
                            contest.requires_login, contest.requires_contest, contest.secret, contest.message,
1174
1175
                            taskgroup.id, taskgroup.name,
                            task.id, task.location, task.stars
1176
1177
1178
                     FROM contest
                     JOIN taskgroup ON contest.id = taskgroup.contest
                     JOIN task ON taskgroup.id = task.taskgroup
1179
                     WHERE contest.id = ?1
1180
                     AND taskgroup.active = ?2
1181
                     ORDER BY taskgroup.positionalnumber";
1182
        let taskgroupcontest =
1183
            self.query_map_many(query, &[&contest_id, &true], |row| {
1184
1185
1186
1187
1188
1189
1190
1191
                    (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),
1192
1193
                               min_grade: row.get(7),
                               max_grade: row.get(8),
1194
                               positionalnumber: None,
1195
                               requires_login: row.get(9),
1196
1197
1198
                               requires_contest: row.get(10),
                               secret: row.get(11),
                               message: row.get(12),
1199
                               taskgroups: Vec::new() },
1200
                     Taskgroup { id: Some(row.get(13)),
1201
                                 contest: contest_id,
1202
                                 name: row.get(14),
1203
                                 active: true,
1204
1205
                                 positionalnumber: None,
                                 tasks: Vec::new() },
1206
                     Task { id: Some(row.get(15)), taskgroup: row.get(13), location: row.get(16), stars: row.get(17) })
1207
1208
                })
                .unwrap();
1209
        let mut taskgroupcontest_iter = taskgroupcontest.into_iter();
1210

1211
1212
1213
1214
1215
1216
1217
1218
1219
        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);
1220
            }
1221
1222
1223
1224
1225
1226
            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)
1227
1228
1229
1230
1231
        }
    }

    fn get_contest_by_id_partial(&self, contest_id: i32) -> Contest {
        let query = "SELECT contest.location, contest.filename, contest.name, contest.duration, contest.public,
1232
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade,
1233
                            contest.requires_login, contest.requires_contest, contest.secret, contest.message,
1234
                            taskgroup.id, taskgroup.name
1235
1236
                     FROM contest
                     JOIN taskgroup ON contest.id = taskgroup.contest
1237
1238
1239
                     WHERE contest.id = ?1
                     AND taskgroup.active = ?2";
        let taskgroupcontest = self.query_map_many(query, &[&contest_id, &true], |row| {
1240
1241
1242
1243
1244
1245
1246
1247
                                       (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),
1248
1249
                                                  min_grade: row.get(7),
                                                  max_grade: row.get(8),
1250
                                                  positionalnumber: None,
1251
                                                  requires_login: row.get(9),
1252
1253
1254
                                                  requires_contest: row.get(10),
                                                  secret: row.get(11),
                                                  message: row.get(12),
1255
                                                  taskgroups: Vec::new() },
1256
                                        Taskgroup { id: Some(row.get(13)),
1257
                                                    contest: contest_id,
1258
                                                    name: row.get(14),
1259
                                                    active: true,
1260
1261
1262