db_conn_postgres.rs 58.9 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
#![cfg(feature = "postgres")]

16
17
extern crate postgres;

18
19
20
use postgres::Connection;
use time;
use time::Duration;
21
22
23

use db_conn::{MedalConnection, MedalObject};
use db_objects::*;
24
use helpers;
25

26
trait Queryable {
Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
27
28
    fn query_map_one<T, F>(&self, sql: &str, params: &[&dyn postgres::types::ToSql], f: F)
                           -> postgres::Result<Option<T>>
29
        where F: FnOnce(postgres::rows::Row<'_>) -> T;
30
31
    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;
32
    fn exists(&self, sql: &str, params: &[&dyn postgres::types::ToSql]) -> bool;
33
    fn get_last_id(&self) -> Option<i32>;
34
35
36
}

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

42
43
        Ok(rows.iter().next().map(f))
    }
44

45
46
47
48
49
    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())
    }

50
51
52
53
54
    fn exists(&self, sql: &str, params: &[&dyn postgres::types::ToSql]) -> bool {
        let stmt = self.prepare(sql).unwrap();
        !stmt.query(params).unwrap().is_empty()
    }

55
56
57
58
59
60
    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
                                                                  })
    }
61
    // Empty line intended
62
63
}

64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
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();
    }
}
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
                             SET contest = $1, name = $2, positionalnumber = $3
                             WHERE id = $4";
                conn.execute(query, &[&self.contest, &self.name, &self.positionalnumber, &id]).unwrap();
                id
            }
            None => {
                let query = "INSERT INTO taskgroup (contest, name, positionalnumber)
                             VALUES ($1, $2, $3)";
                conn.execute(query, &[&self.contest, &self.name, &self.positionalnumber]).unwrap();
                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
210
                             SET location = $1,filename = $2, name = $3, duration = $4, public = $5, start_date = $6,
211
212
                                 end_date = $7, min_grade = $8, max_grade = $9, positionalnumber = $10
                             WHERE id = $11";
213
214
215
216
217
218
219
220
                conn.execute(query,
                             &[&self.location,
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
                               &self.end,
221
222
                               &self.min_grade,
                               &self.max_grade,
223
                               &self.positionalnumber,
224
225
226
227
228
                               &id])
                    .unwrap();
                id
            }
            None => {
229
                let query = "INSERT INTO contest (location, filename, name, duration, public, start_date, end_date,
230
231
                                                  min_grade, max_grade, positionalnumber)
                             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)";
232
233
234
235
236
237
238
                conn.execute(query,
                             &[&self.location,
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
239
240
                               &self.end,
                               &self.min_grade,
241
242
                               &self.max_grade,
                               &self.positionalnumber])
243
244
245
246
247
248
249
250
251
252
253
254
                    .unwrap();
                conn.get_last_id().unwrap()
            }
        };
        self.set_id(id);
        for mut taskgroup in &mut self.taskgroups {
            taskgroup.contest = id;
            taskgroup.save(conn);
        }
    }
}

255
impl MedalConnection for Connection {
256
257
258
259
260
261
    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();

262
263
        let query = "SELECT name FROM migrations WHERE name = $1";
        self.exists(query, &[&name])
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    }

    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> {
281
282
        let query = "SELECT id, csrf_token, last_login, last_activity, permanent_login, username, password, logincode,
                            email, email_unconfirmed, email_confirmationcode, firstname, lastname, street, zip, city,
283
                            nation, grade, sex, is_teacher, managed_by, oauth_provider, oauth_foreign_id, salt
284
285
                     FROM session
                     WHERE session_token = $1";
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
        let session = self.query_map_one(query, &[&key], |row| SessionUser { id: row.get(0),
                                                                             session_token: Some(key.to_string()),
                                                                             csrf_token: row.get(1),
                                                                             last_login: row.get(2),
                                                                             last_activity: row.get(3),
                                                                             permanent_login: row.get(4),

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

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

310
311
                                                                             is_teacher: row.get(19),
                                                                             managed_by: row.get(20),
312

313
314
                                                                             oauth_provider: row.get(21),
                                                                             oauth_foreign_id: row.get(22) })
315
                          .ok()??;
316
317
318

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

320
321
        if let Some(last_activity) = session.last_activity {
            if now - last_activity < duration {
322
323
324
325
                let query = "UPDATE session
                             SET last_activity = $1
                             WHERE id = $2";
                self.execute(query, &[&now, &session.id]).unwrap();
326
                return Some(session);
327
            } else {
328
329
330
331
                // Session timed out
                // Should remove session token from session
                return None;
            }
332
        }
333
334
335
        // last_activity undefined
        // TODO: What should happen here?
        None
336
337
    }
    fn save_session(&self, session: SessionUser) {
338
339
340
341
342
343
344
345
346
347
348
349
350
351
        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,
                          is_teacher = $12
                      WHERE id = $13",
352
353
354
355
356
357
358
359
360
361
                     &[&session.username,
                       &session.password,
                       &session.salt,
                       &session.logincode,
                       &session.firstname,
                       &session.lastname,
                       &session.street,
                       &session.zip,
                       &session.city,
                       &session.grade,
362
                       &session.sex,
363
                       &session.is_teacher,
364
365
366
367
                       &session.id])
            .unwrap();
    }
    fn new_session(&self, session_token: &str) -> SessionUser {
368
        let csrf_token = helpers::make_csrf_token();
369
370

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

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

378
        SessionUser::minimal(id, session_token.to_owned(), csrf_token)
379
380
    }
    fn get_session_or_new(&self, key: &str) -> SessionUser {
381
382
383
        let query = "UPDATE session
                     SET session_token = $1
                     WHERE session_token = $2";
384
385
386
        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?
387
                                                 self.execute(query, &[&Option::<String>::None, &key]).unwrap();
388
389
                                                 self.new_session(&key)
                                             })
390
391
392
    }

    fn get_user_by_id(&self, user_id: i32) -> Option<SessionUser> {
393
394
        let query = "SELECT session_token, csrf_token, last_login, last_activity, permanent_login, username, password,
                            logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname, street,
395
396
                            zip, city, nation, grade, sex, is_teacher, managed_by, oauth_provider, oauth_foreign_id,
                            salt
397
398
                     FROM session
                     WHERE id = $1";
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
        self.query_map_one(query, &[&user_id], |row| SessionUser { id: user_id,
                                                                   session_token: row.get(0),
                                                                   csrf_token: row.get(1),
                                                                   last_login: row.get(2),
                                                                   last_activity: row.get(3),
                                                                   permanent_login: row.get(4),

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

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

423
424
                                                                   is_teacher: row.get(19),
                                                                   managed_by: row.get(20),
425

426
427
                                                                   oauth_provider: row.get(21),
                                                                   oauth_foreign_id: row.get(22) })
428
            .ok()?
429
430
431
432
433
434
435
436
437
438
    }

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

439
440
441
        let query = "SELECT name, groupcode, tag, admin
                     FROM usergroup
                     WHERE id = $1";
442
443
444
445
446
447
448
449
450
        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))),
451
452
453
454
455
456
            _ => Some((session, None)),
        }
    }

    //TODO: use session
    fn login(&self, _session: Option<&str>, username: &str, password: &str) -> Result<String, ()> {
457
458
459
460
        let query = "SELECT id, password, salt
                     FROM session
                     WHERE username = $1";
        self.query_map_one(query, &[&username], |row| {
461
462
463
464
                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
465
466
467
                if helpers::verify_password(&password,
                                            &salt.expect("salt from database empty"),
                                            &password_hash.expect("password from database empty"))
468
469
470
471
                {
                    // TODO: fail more pleasantly
                    // Login okay, update session now!

472
473
                    let session_token = helpers::make_session_token();
                    let csrf_token = helpers::make_csrf_token();
474
475
                    let now = time::get_time();

476
477
478
                    let query = "UPDATE session
                                 SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3
                                 WHERE id = $4";
479
                    self.execute(query, &[&session_token, &csrf_token, &now, &id]).unwrap();
480
481
482
483
484

                    Ok(session_token)
                } else {
                    Err(())
                }
485
486
487
            })
            .map_err(|_| ())?
            .ok_or(())?
488
489
490
491
    }

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

499
500
                let session_token = helpers::make_session_token();
                let csrf_token = helpers::make_csrf_token();
501
502
                let now = time::get_time();

503
504
505
                let query = "UPDATE session
                             SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3
                             WHERE id = $4";
506
                self.execute(query, &[&session_token, &csrf_token, &now, &id]).unwrap();
507

508
                session_token
509
510
511
            })
            .map_err(|_| ())?
            .ok_or(())
512
513
514
    }

    //TODO: use session
515
516
    fn login_foreign(&self, _session: Option<&str>, provider_id: &str, foreign_id: &str, is_teacher: bool,
                     firstname: &str, lastname: &str)
517
518
                     -> Result<String, ()>
    {
519
520
        let session_token = helpers::make_session_token();
        let csrf_token = helpers::make_csrf_token();
521
522
        let now = time::get_time();

523
524
        let query = "SELECT id
                     FROM session
525
526
527
                     WHERE oauth_foreign_id = $1
                           AND oauth_provider = $2";
        match self.query_map_one(query, &[&foreign_id, &provider_id], |row| -> i32 { row.get(0) }) {
528
            Ok(Some(id)) => {
529
530
531
                let query = "UPDATE session
                             SET session_token = $1, csrf_token = $2, last_login = $3, last_activity = $3
                             WHERE id = $4";
532
                self.execute(query, &[&session_token, &csrf_token, &now, &id]).unwrap();
533
534
535
536
537

                Ok(session_token)
            }
            // Add!
            _ => {
538
                let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity,
539
                                                  permanent_login, grade, sex, is_teacher, oauth_foreign_id,
540
                                                  oauth_provider, firstname, lastname)
541
                             VALUES ($1, $2, $3, $3, $4, $5, $6, $7, $8, $9, $10, $11)";
542
543
544
545
546
                self.execute(query,
                             &[&session_token,
                               &csrf_token,
                               &now,
                               &false,
547
                               &(if is_teacher { 255 } else { 0 }),
548
                               &None::<i32>,
549
550
                               &is_teacher,
                               &foreign_id,
551
                               &provider_id,
552
553
554
                               &firstname,
                               &lastname])
                    .unwrap();
555
556
557
558
559
560
561
562

                Ok(session_token)
            }
        }
    }

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

569
570
571
        // Login okay, create session!
        let session_token = helpers::make_session_token();
        let csrf_token = helpers::make_csrf_token();
572
        let login_code = helpers::make_login_code(); // TODO: check for collisions
573
        let now = time::get_time();
574

575
        let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity, permanent_login,
576
                                          logincode, grade, sex, is_teacher, managed_by)
577
                     VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)";
578
579
580
581
582
583
584
585
586
587
588
589
        self.execute(query,
                     &[&session_token,
                       &csrf_token,
                       &now,
                       &now,
                       &false,
                       &login_code,
                       &0,
                       &None::<i32>,
                       &false,
                       &group_id])
            .unwrap();
590

591
        Ok(session_token)
592
593
    }

Robert Czechowski's avatar
rustfmt    
Robert Czechowski committed
594
    fn create_group_with_users(&self, mut group: Group) {
595
596
597
598
599
600
        // 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
601

602
            let query = "INSERT INTO session (firstname, lastname, csrf_token, permanent_login, logincode, grade, sex,
603
                                              is_teacher, managed_by)
604
                         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)";
605
606
607
608
609
610
611
            self.execute(query,
                         &[&user.firstname,
                           &user.lastname,
                           &csrf_token,
                           &false,
                           &login_code,
                           &user.grade,
612
                           &None::<i32>,
613
614
615
                           &false,
                           &group.id])
                .unwrap();
616
        }
617
618
    }

619
    fn logout(&self, session: &str) {
620
621
622
        let query = "UPDATE session
                     SET session_token = NULL
                     WHERE session_token = $1";
623
        self.execute(query, &[&session]).unwrap();
624
625
626
627
    }

    fn load_submission(&self, session: &SessionUser, task: i32, subtask: Option<&str>) -> Option<Submission> {
        match subtask {
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
            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()?
            }
669
670
671
672
673
674
675
676
677
678
679
680
681
        }
    }
    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 {
682
683
684
685
686
687
        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";
688
689
690
691
692
693
694
        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
695
696
697
                         FROM submission
                         JOIN task ON task.id = submission.task
                         WHERE submission.id = $1";
698
699
700
701
702
703
704
                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?
            })
705
706
707
708
    }

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

716
717
718
719
720
721
722
        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);
        }

723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
        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,
                            student.firstname, student.lastname
                     FROM grade
                     JOIN taskgroup ON grade.taskgroup = taskgroup.id
                     JOIN session AS student ON grade.session = student.id
                     JOIN usergroup ON student.managed_by = usergroup.id
                     WHERE usergroup.admin = $1
                     AND taskgroup.contest = $2
                     ORDER BY usergroup.id, student.id, taskgroup.id ASC";
        let gradeinfo =
            self.query_map_many(query, &[&session_id, &contest_id], |row| {
                    (Grade { taskgroup: row.get(0), user: row.get(1), grade: row.get(2), validated: row.get(3) },
                     Group { id: Some(row.get(4)),
                             name: row.get(5),
                             groupcode: row.get(6),
                             tag: row.get(7),
                             admin: session_id,
                             members: Vec::new() },
                     UserInfo { id: row.get(8),
                                username: row.get(9),
                                logincode: row.get(10),
                                firstname: row.get(11),
                                lastname: row.get(12) })
                })
                .unwrap();
        let mut gradeinfo_iter = gradeinfo.iter();
750
751

        if let Some(t /*Ok((grade, mut group, mut userinfo))*/) = gradeinfo_iter.next() {
752
            let (grade, mut group, mut userinfo) = t.clone();
753
754
755
756
757
758

            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;
759
            grades[taskindex[&index]] = grade;
760
761

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

768
769
                    groups.push((group, users));
                    group = gr.clone();
770
771
                    users = Vec::new();
                } else if ui.id != userinfo.id {
772
773
                    users.push((userinfo, grades));
                    userinfo = ui.clone();
774
                    grades = vec![Default::default(); n_tasks];
775
                }
776
                let index = g.taskgroup;
777
                grades[taskindex[&index]] = *g;
778
            }
779
780
            users.push((userinfo, grades));
            groups.push((group, users));
781
782
783
784
785
786
787

            (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> {
788
789
790
791
        let query = "SELECT id, name
                     FROM taskgroup
                     WHERE contest = $1
                     ORDER BY id ASC";
792
793
        let tasknames: Vec<(i32, String)> =
            self.query_map_many(query, &[&contest_id], |row| (row.get(0), row.get(1))).unwrap();
794
795
796
797
798
799
800
        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);
        }

801
802
803
804
805
806
807
808
809
810
811
812
813
814
        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
                     ORDER BY taskgroup.id ASC";
        let gradeinfo =
            self.query_map_many(query, &[&session_token, &contest_id], |row| Grade { taskgroup: row.get(0),
                                                                                     user: row.get(1),
                                                                                     grade: row.get(2),
                                                                                     validated: row.get(3) })
                .unwrap();
        let gradeinfo_iter = gradeinfo.iter();
815
816
817
818
819

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

        for g in gradeinfo_iter {
            let index = g.taskgroup;
820
            grades[taskindex[&index]] = *g;
821
822
823
824
825
826
        }

        grades
    }

    fn get_taskgroup_user_grade(&self, session_token: &str, taskgroup_id: i32) -> Grade {
827
        let query = "SELECT grade.taskgroup, grade.session, grade.grade, grade.validated
828
829
830
831
                     FROM grade
                     JOIN session ON session.id = grade.session
                     WHERE session.session_token = $1
                     AND grade.taskgroup = $2";
832
833
834
835
836
837
        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()
838
839
840
    }

    fn get_contest_list(&self) -> Vec<Contest> {
841
842
        let query = "SELECT id, location, filename, name, duration, public, start_date, end_date, min_grade, max_grade,
                            positionalnumber
843
                     FROM contest
844
                     ORDER BY positionalnumber";
845
846
847
848
849
850
851
852
        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),
853
854
                                                        min_grade: row.get(8),
                                                        max_grade: row.get(9),
855
                                                        positionalnumber: row.get(10),
856
857
                                                        taskgroups: Vec::new() })
            .unwrap()
858
859
860
    }

    fn get_contest_by_id(&self, contest_id: i32) -> Contest {
861
        let query = "SELECT location, filename, name, duration, public, start_date, end_date, min_grade, max_grade
862
863
                     FROM contest
                     WHERE id = $1";
864
865
866
867
868
869
870
871
        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),
872
873
                                                                  min_grade: row.get(7),
                                                                  max_grade: row.get(8),
874
                                                                  positionalnumber: None,
875
                                                                  taskgroups: Vec::new() })
876
877
878
879
880
            .unwrap()
            .unwrap() // TODO: Should return Option?
    }

    fn get_contest_by_id_complete(&self, contest_id: i32) -> Contest {
881
        let query = "SELECT contest.location, contest.filename, contest.name, contest.duration, contest.public,
882
883
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade, taskgroup.id,
                            taskgroup.name, task.id, task.location, task.stars
884
885
886
887
                     FROM contest
                     JOIN taskgroup ON contest.id = taskgroup.contest
                     JOIN task ON taskgroup.id = task.taskgroup
                     WHERE contest.id = $1
888
                     ORDER BY taskgroup.positionalnumber";
889
890
891
892
893
894
895
896
897
898
        let taskgroupcontest =
            self.query_map_many(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),
899
900
                               min_grade: row.get(7),
                               max_grade: row.get(8),
901
                               positionalnumber: None,
902
                               taskgroups: Vec::new() },
903
                     Taskgroup { id: Some(row.get(9)),
904
                                 contest: contest_id,
905
                                 name: row.get(10),
906
907
                                 positionalnumber: None,
                                 tasks: Vec::new() },
908
                     Task { id: Some(row.get(11)), taskgroup: row.get(9), location: row.get(12), stars: row.get(13) })
909
910
911
                })
                .unwrap();
        let mut taskgroupcontest_iter = taskgroupcontest.into_iter();
912
913
914
915

        let (mut contest, mut taskgroup, task) = taskgroupcontest_iter.next().unwrap();
        taskgroup.tasks.push(task);
        for tgc in taskgroupcontest_iter {
916
917
918
919
            let (_, tg, t) = tgc;
            if tg.id != taskgroup.id {
                contest.taskgroups.push(taskgroup);
                taskgroup = tg;
920
            }
921
            taskgroup.tasks.push(t);
922
923
924
925
926
927
        }
        contest.taskgroups.push(taskgroup);
        contest
    }

    fn get_contest_by_id_partial(&self, contest_id: i32) -> Contest {
928
        let query = "SELECT contest.location, contest.filename, contest.name, contest.duration, contest.public,
929
930
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade, taskgroup.id,
                            taskgroup.name
931
932
933
                     FROM contest
                     JOIN taskgroup ON contest.id = taskgroup.contest
                     WHERE contest.id = $1";
934
935
936
937
938
939
940
941
942
        let taskgroupcontest = self.query_map_many(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),
943
944
                                                  min_grade: row.get(7),
                                                  max_grade: row.get(8),
945
                                                  positionalnumber: None,
946
                                                  taskgroups: Vec::new() },
947
                                        Taskgroup { id: Some(row.get(9)),
948
                                                    contest: contest_id,
949
                                                    name: row.get(10),
950
951
952
953
                                                    positionalnumber: None,
                                                    tasks: Vec::new() })
                                   })
                                   .unwrap();
954
        let mut taskgroupcontest_iter = taskgroupcontest.into_iter();
955
956
957
958

        let (mut contest, taskgroup) = taskgroupcontest_iter.next().unwrap();
        contest.taskgroups.push(taskgroup);
        for tgc in taskgroupcontest_iter {
959
960
            let (_, tg) = tgc;
            contest.taskgroups.push(tg);
961
962
963
964
965
        }
        contest
    }

    fn get_participation(&self, session: &str, contest_id: i32) -> Option<Participation> {
966
967
968
969
970
        let query = "SELECT session, start_date
                     FROM participation
                     JOIN session ON session.id = session
                     WHERE session.session_token = $1
                     AND contest = $2";
971
972
973
974
        self.query_map_one(query, &[&session, &contest_id], |row| Participation { contest: contest_id,
                                                                                  user: row.get(0),
                                                                                  start: row.get(1) })
            .ok()?
975
976
    }
    fn new_participation(&self, session: &str, contest_id: i32) -> Result<Participation, ()> {
977
978
979
980
981
        let query = "SELECT session, start_date
                     FROM participation
                     JOIN session ON session.id = session
                     WHERE session.session_token = $1
                     AND contest = $2";
982
983
        match self.query_map_one(query, &[&session, &contest_id], |_| {}).map_err(|_| ())? {
            Some(()) => Err(()),
984
985
986
            None => {
                let now = time::get_time();
                self.execute(
987
                             "INSERT INTO participation (contest, session, start_date)
988
                     SELECT $1, id, $2 FROM session WHERE session_token = $3",
989
990
991
                             &[&contest_id, &now, &session],
                )
                    .unwrap();
992
993
994
995
996
997

                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 {
998
999
1000
        let query = "SELECT location, stars, taskgroup
                     FROM task
                     WHERE id = $1";
1001
1002
1003
1004
        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) })
1005
1006
1007
1008
            .unwrap()
            .unwrap()
    }
    fn get_task_by_id_complete(&self, task_id: i32) -> (Task, Taskgroup, Contest) {
1009
1010
        let query = "SELECT task.location, task.stars, taskgroup.id, taskgroup.name, contest.id, contest.location,
                            contest.filename, contest.name, contest.duration, contest.public, contest.start_date,
1011
                            contest.end_date, contest.min_grade, contest.max_grade
1012
1013
1014
1015
                     FROM contest
                     JOIN taskgroup ON taskgroup.contest = contest.id
                     JOIN task ON task.taskgroup = taskgroup.id
                     WHERE task.id = $1";
1016
1017
        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) },
1018
1019
1020
1021
1022
                 Taskgroup { id: Some(row.get(2)),
                             contest: row.get(4),
                             name: row.get(3),
                             positionalnumber: None,
                             tasks: Vec::new() },
1023
1024
1025
1026
1027
1028
1029
1030
                 Contest { id: Some(row.get(4)),
                           location: row.get(5),
                           filename: row.get(6),
                           name: row.get(7),
                           duration: row.get(8),
                           public: row.get(9),
                           start: row.get(10),
                           end: row.get(11),
1031
1032
                           min_grade: row.get(12),
                           max_grade: row.get(13),
1033
                           positionalnumber: None,
1034
1035
1036
1037
                           taskgroups: Vec::new() })
            })
            .unwrap()
            .unwrap()
1038
1039
1040
1041
    }

    fn get_submission_to_validate(&self, tasklocation: &str, subtask: Option<&str>) -> i32 {
        match subtask {
1042
            Some(st) => {
1043
1044
1045
1046
1047
1048
1049
                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";
1050
1051
1052
                self.query_map_one(query, &[&tasklocation, &st], |row| row.get(0)).unwrap().unwrap()
            }
            None => {
1053
1054
1055
1056
1057
1058
                let query = "SELECT id
                             FROM submission
                             JOIN task ON submission.task = task.id
                             WHERE task.location = $1
                             AND needs_validation = 1
                             LIMIT 1";
1059
1060
                self.query_map_one(query, &[&tasklocation], |row| row.get(0)).unwrap().unwrap()
            }
1061
1062
1063
1064
        }
    }

    fn find_next_submission_to_validate(&self, userid: i32, taskgroupid: i32) {
1065
1066
1067
1068
1069
1070
1071
        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";
1072
1073
        let (id, validated): (i32, bool) =
            self.query_map_one(query, &[&taskgroupid, &userid], |row| (row.get(0), row.get(1))).unwrap().unwrap();
1074
        if !validated {
1075
1076
1077
            let query = "UPDATE submission
                         SET needs_validation = 1
                         WHERE id = $1";
1078
            self.execute(query, &[&id]).unwrap();
1079
1080
1081
1082
1083
1084
        }
    }

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

    fn get_groups(&self, session_id: i32) -> Vec<Group> {
1085
1086
1087
        let query = "SELECT id, name, groupcode, tag
                     FROM usergroup
                     WHERE admin = $1";
1088
1089
1090
1091
1092
1093
        self.query_map_many(query, &[&session_id], |row| Group { id: Some(row.get(0)),
                                                                 name: row.get(1),
                                                                 groupcode: row.get(2),
                                                                 tag: row.get(3),
                                                                 admin: session_id,
                                                                 members: Vec::new() })
1094
1095
1096
1097
1098
1099
            .unwrap()
    }
    fn get_groups_complete(&self, _session_id: i32) -> Vec<Group> {
        unimplemented!();
    }
    fn get_group_complete(&self, group_id: i32) -> Option<Group> {
1100
1101
1102
        let query = "SELECT name, groupcode, tag, admin
                     FROM usergroup
                     WHERE id  = $1";
1103
1104
1105
1106
1107
1108
        let mut group = self.query_map_one(query, &[&group_id], |row| Group { id: Some(group_id),
                                                                              name: row.get(0),
                                                                              groupcode: row.get(1),
                                                                              tag: row.get(2),
                                                                              admin: row.get(3),
                                                                              members: Vec::new() })
1109
1110
1111
                            .unwrap()
                            .unwrap(); // TODO handle error

1112
1113
        let query = "SELECT id, session_token, csrf_token, last_login, last_activity, permanent_login, username,
                            password, logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname,
1114
                            street, zip, city, nation, grade, sex, is_teacher, oauth_provider, oauth_foreign_id, salt
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
                     FROM session
                     WHERE managed_by = $1";
        group.members = self.query_map_many(query, &[&group_id], |row| SessionUser { id: row.get(0),
                                                                                     session_token: row.get(1),
                                                                                     csrf_token: row.get(2),
                                                                                     last_login: row.get(3),
                                                                                     last_activity: row.get(4),
                                                                                     permanent_login: row.get(5),

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

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

1142
                                                                                     is_teacher: row.get(20),
1143
1144
                                                                                     managed_by: Some(group_id),

1145
1146
                                                                                     oauth_provider: row.get(21),
                                                                                     oauth_foreign_id: row.get(22) })
1147
                            .unwrap();
1148
1149
        Some(group)
    }
1150

1151
1152
1153
1154
1155
1156
1157
1158
    fn get_debug_information(&self) -> String {
        let duration = Duration::minutes(60);
        let now = time::get_time();
        let then = now - duration;

        let query = "SELECT count(*)
                     FROM session
                     WHERE last_activity > $1;";
1159
        let n_asession: i64 = self.query_map_one(query, &[&then], |row| row.get(0)).unwrap().unwrap();
1160
1161
1162
1163

        let query = "SELECT count(*)
                     FROM participation
                     WHERE start_date > $1;";
1164
        let n_apart: i64 = self.query_map_one(query, &[&then], |row| row.get(0)).unwrap().unwrap();
1165
1166
1167

        let query = "SELECT count(*)
                     FROM session;";
1168
        let n_session: i64 = self.query_map_one(query, &[], |row| row.get(0)).unwrap().unwrap();
1169
1170
1171

        let query = "SELECT count(*)
                     FROM session
1172
1173
                     WHERE oauth_foreign_id IS NOT NULL OR logincode IS NOT NULL;";
        let n_user: i64 = self.query_map_one(query, &[], |row| row.get(0)).unwrap().unwrap();
1174
1175
1176

        let query = "SELECT count(*)
                     FROM session
1177
1178
                     WHERE oauth_foreign_id IS NOT NULL;";
        let n_pmsuser: i64 = self.query_map_one(query, &[], |row| row.get(0)).unwrap().unwrap();
1179
1180
1181
1182

        let query = "SELECT count(*)
                     FROM session
                     WHERE is_teacher = $1;";
1183
        let n_teacher: i64 = self.query_map_one(query, &[&true], |row| row.get(0)).unwrap().unwrap();
1184
1185
1186

        let query = "SELECT count(*)
                     FROM participation;";
1187
        let n_part: i64 = self.query_map_one(query, &[], |row| row.get(0)).unwrap().unwrap();
1188
1189
1190

        let query = "SELECT count(*)
                     FROM submission;";
1191
        let n_sub: i64 = self.query_map_one(query, &[], |row| row.get(0)).unwrap().unwrap();
1192

1193
1194
        format!(
                "{{
Robert Czechowski's avatar
Robert Czechowski committed
1195
  'timestamp': {},
1196
1197
1198
1199
1200
1201
1202
1203
  'active_sessions': {},
  'active_participations': {},
  'sessions': {},
  'users': {},
  'pms_users': {},
  'teachers': {},
  'participations': {},
  'submissions': {}
1204
1205
}}
",
Robert Czechowski's avatar
Robert Czechowski committed
1206
                now.sec, n_asession, n_apart, n_session, n_user, n_pmsuser, n_teacher, n_part, n_sub
1207
        )
1208
1209
    }

1210
    fn reset_all_contest_visibilities(&self) { self.execute("UPDATE contest SET public = $1", &[&false]).unwrap(); }
1211
}