db_conn_sqlite_new.rs 64.5 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
#![cfg(feature = "rusqlite")]
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

extern crate rusqlite;

use rusqlite::Connection;
use time;
use time::Duration;

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

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

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

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
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)";
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
        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
173
174
175
                             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();
176
177
178
                id
            }
            None => {
179
180
181
                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();
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
                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
211
212
213
                             SET location = ?2,filename = ?3, name = ?4, duration = ?5, public = ?6, start_date = ?7,
                                 end_date = ?8, min_grade = ?9, max_grade = ?10, positionalnumber = ?11,
                                 requires_login = ?12, secret = ?13
                             WHERE id = ?1";
214
                conn.execute(query,
215
216
                             &[&id,
                               &self.location,
217
218
219
220
221
222
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
                               &self.end,
223
224
                               &self.min_grade,
                               &self.max_grade,
225
                               &self.positionalnumber,
226
227
                               &self.requires_login,
                               &self.secret])
228
229
230
231
                    .unwrap();
                id
            }
            None => {
232
                let query = "INSERT INTO contest (location, filename, name, duration, public, start_date, end_date,
233
234
                                                  min_grade, max_grade, positionalnumber, requires_login, secret)
                             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)";
235
236
237
238
239
240
241
                conn.execute(query,
                             &[&self.location,
                               &self.filename,
                               &self.name,
                               &self.duration,
                               &self.public,
                               &self.start,
242
243
                               &self.end,
                               &self.min_grade,
244
                               &self.max_grade,
245
246
247
                               &self.positionalnumber,
                               &self.requires_login,
                               &self.secret])
248
249
250
251
252
253
254
255
256
257
258
259
                    .unwrap();
                conn.get_last_id().unwrap()
            }
        };
        self.set_id(id);
        for mut taskgroup in &mut self.taskgroups {
            taskgroup.contest = id;
            taskgroup.save(conn);
        }
    }
}

260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
impl MedalConnection for Connection {
    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> {
286
287
        let query = "SELECT id, csrf_token, last_login, last_activity, permanent_login, username, password, salt,
                            logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname, street,
288
                            zip, city, nation, grade, sex, is_admin, is_teacher, managed_by, oauth_provider, oauth_foreign_id
289
290
291
292
293
294
295
296
297
298
299
                     FROM session
                     WHERE session_token = ?1";
        let session = self.query_map_one(query, &[&key], |row| SessionUser { id: row.get(0),
                                                                             session_token: Some(key.to_string()),
                                                                             csrf_token: row.get(1),
                                                                             last_login: row.get(2),
                                                                             last_activity: row.get(3),
                                                                             permanent_login: row.get(4),

                                                                             username: row.get(5),
                                                                             password: row.get(6),
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
                                                                             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),

315
316
317
                                                                             is_admin: row.get(20),
                                                                             is_teacher: row.get(21),
                                                                             managed_by: row.get(22),
318

319
320
                                                                             oauth_provider: row.get(23),
                                                                             oauth_foreign_id: row.get(24) })
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
                          .ok()??;

        let duration = if session.permanent_login { Duration::days(90) } else { Duration::minutes(90) };
        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) {
344
345
346
347
348
349
350
351
352
353
354
355
        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,
356
357
358
359
                          is_admin = ?12,
                          is_teacher = ?13,
                          permanent_login = ?14
                      WHERE id = ?15",
360
361
362
363
364
365
366
367
368
369
                     &[&session.username,
                       &session.password,
                       &session.salt,
                       &session.logincode,
                       &session.firstname,
                       &session.lastname,
                       &session.street,
                       &session.zip,
                       &session.city,
                       &session.grade,
370
                       &session.sex,
371
                       &session.is_admin,
372
                       &session.is_teacher,
373
                       &session.permanent_login,
374
375
376
377
378
379
380
                       &session.id])
            .unwrap();
    }
    fn new_session(&self, session_token: &str) -> SessionUser {
        let csrf_token = helpers::make_csrf_token();

        let now = time::get_time();
381
        let query = "INSERT INTO session (session_token, csrf_token, last_activity, permanent_login, grade, sex,
382
                                          is_teacher)
383
384
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)";
        self.execute(query, &[&session_token, &csrf_token, &now, &false, &0, &None::<i32>, &false]).unwrap();
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403

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

        SessionUser::minimal(id, session_token.to_owned(), csrf_token)
    }
    fn get_session_or_new(&self, key: &str) -> SessionUser {
        let query = "UPDATE session
                     SET session_token = ?1
                     WHERE session_token = ?2";
        self.get_session(&key).ensure_alive().unwrap_or_else(|| {
                                                 // TODO: Factor this out in own function
                                                 // TODO: Should a new session key be generated every time?
                                                 self.execute(query, &[&Option::<String>::None, &key]).unwrap();
                                                 self.new_session(&key)
                                             })
    }

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

                                                                   username: row.get(5),
                                                                   password: row.get(6),
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
                                                                   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),

433
434
435
                                                                   is_admin: row.get(20),
                                                                   is_teacher: row.get(21),
                                                                   managed_by: row.get(22),
436

437
438
                                                                   oauth_provider: row.get(23),
                                                                   oauth_foreign_id: row.get(24) })
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
            .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,
477
478
                                            &salt.ok_or_else(|| println!("salt from database empty"))?,
                                            &password_hash.ok_or_else(|| println!("password from database empty"))?)
479
480
481
482
483
                {
                    // TODO: fail more pleasantly
                    // Login okay, update session now!

                    let session_token = helpers::make_session_token();
484
                    let csrf_token = helpers::make_csrf_token();
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
                    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, ()> {
503
504
505
        let query = "SELECT id
                     FROM session
                     WHERE logincode = ?1";
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
        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
526
527
    fn login_foreign(&self, _session: Option<&str>, provider_id: &str, foreign_id: &str, is_teacher: bool,
                     firstname: &str, lastname: &str)
528
529
530
531
532
533
534
535
                     -> Result<String, ()>
    {
        let session_token = helpers::make_session_token();
        let csrf_token = helpers::make_csrf_token();
        let now = time::get_time();

        let query = "SELECT id
                     FROM session
536
537
538
                     WHERE oauth_foreign_id = ?1
                           AND oauth_provider = ?2";
        match self.query_map_one(query, &[&foreign_id, &provider_id], |row| -> i32 { row.get(0) }) {
539
540
541
542
543
544
545
546
547
548
549
            Ok(Some(id)) => {
                let query = "UPDATE session
                             SET session_token = ?1, csrf_token = ?2, last_login = ?3, last_activity = ?3
                             WHERE id = ?4";
                self.execute(query, &[&session_token, &csrf_token, &now, &id]).unwrap();

                Ok(session_token)
            }
            // Add!
            _ => {
                let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity,
550
                                                  permanent_login, grade, sex, is_teacher, oauth_foreign_id,
551
                                                  oauth_provider, firstname, lastname)
552
                             VALUES (?1, ?2, ?3, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)";
553
554
555
556
557
                self.execute(query,
                             &[&session_token,
                               &csrf_token,
                               &now,
                               &false,
558
                               &(if is_teacher { 255 } else { 0 }),
559
                               &None::<i32>,
560
561
                               &is_teacher,
                               &foreign_id,
562
                               &provider_id,
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
                               &firstname,
                               &lastname])
                    .unwrap();

                Ok(session_token)
            }
        }
    }

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

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

        let query = "INSERT INTO session (session_token, csrf_token, last_login, last_activity, permanent_login,
587
                                          logincode, grade, sex, is_teacher, managed_by)
588
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)";
589
590
591
592
593
594
595
596
597
598
599
600
        self.execute(query,
                     &[&session_token,
                       &csrf_token,
                       &now,
                       &now,
                       &false,
                       &login_code,
                       &0,
                       &None::<i32>,
                       &false,
                       &group_id])
            .unwrap();
601
602
603
604
605
606
607
608
609
610
611
612

        Ok(session_token)
    }

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

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

613
            let query = "INSERT INTO session (firstname, lastname, csrf_token, permanent_login, logincode, grade, sex,
614
                                              is_teacher, managed_by)
615
                         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)";
616
617
618
619
620
621
622
            self.execute(query,
                         &[&user.firstname,
                           &user.lastname,
                           &csrf_token,
                           &false,
                           &login_code,
                           &user.grade,
623
                           &None::<i32>,
624
625
626
627
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
                           &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();
    }

    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)),
                                                                                    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()?
            }
        }
    }
    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";
699
700
701
702
703
704
705
        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
706
707
708
                         FROM submission
                         JOIN task ON task.id = submission.task
                         WHERE submission.id = ?1";
709
710
711
712
713
714
715
                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?
            })
716
717
718
719
720
721
722
    }

    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
723
724
                     AND active = ?2
                     ORDER BY positionalnumber";
725
        let tasknames: Vec<(i32, String)> =
726
            self.query_map_many(query, &[&contest_id, &true], |row| (row.get(0), row.get(1))).unwrap();
727
728
729
730
731
732
733
734

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

735
736
        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,
737
                            student.firstname, student.lastname, student.grade AS sgrade
738
739
740
741
742
743
                     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
744
                     AND taskgroup.active = ?3
745
746
                     ORDER BY usergroup.id, sgrade, student.lastname, student.firstname, student.id,
                              taskgroup.positionalnumber";
747
        let gradeinfo =
748
            self.query_map_many(query, &[&session_id, &contest_id, &true], |row| {
749
750
751
752
753
754
755
756
757
758
759
                    (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),
760
                                lastname: row.get(12),
Robert Czechowski's avatar
Robert Czechowski committed
761
                                grade: row.get(13) })
762
763
                })
                .unwrap();
764
        let mut gradeinfo_iter = gradeinfo.iter();
765
766

        if let Some(t /*Ok((grade, mut group, mut userinfo))*/) = gradeinfo_iter.next() {
767
            let (grade, mut group, mut userinfo) = t.clone();
768
769
770
771
772
773

            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;
774
            grades[taskindex[&index]] = grade;
775
776

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

783
784
                    groups.push((group, users));
                    group = gr.clone();
785
786
                    users = Vec::new();
                } else if ui.id != userinfo.id {
787
788
                    users.push((userinfo, grades));
                    userinfo = ui.clone();
789
                    grades = vec![Default::default(); n_tasks];
790
                }
791
792
                let index = g.taskgroup;
                grades[taskindex[&index]] = *g;
793
            }
794
795
            users.push((userinfo, grades));
            groups.push((group, users));
796
797
798
799
800
801
802
803
804
805

            (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
806
807
                     AND active = ?2
                     ORDER BY positionalnumber";
808
        let tasknames: Vec<(i32, String)> =
809
            self.query_map_many(query, &[&contest_id, &true], |row| (row.get(0), row.get(1))).unwrap();
810
811
812
813
814
815
816
        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);
        }

817
818
819
820
821
822
        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
823
824
                     AND taskgroup.active = ?3
                     ORDER BY taskgroup.positionalnumber";
825
        let gradeinfo =
826
            self.query_map_many(query, &[&session_token, &contest_id, &true], |row| Grade { taskgroup: row.get(0),
Robert Czechowski's avatar
Robert Czechowski committed
827
828
829
                                                                                            user: row.get(1),
                                                                                            grade: row.get(2),
                                                                                            validated: row.get(3) })
830
831
                .unwrap();
        let gradeinfo_iter = gradeinfo.iter();
832
833
834
835
836

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

        for g in gradeinfo_iter {
            let index = g.taskgroup;
837
            grades[taskindex[&index]] = *g;
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
        }

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

    fn get_contest_list(&self) -> Vec<Contest> {
858
        let query = "SELECT id, location, filename, name, duration, public, start_date, end_date, min_grade, max_grade,
859
                            positionalnumber, requires_login, secret
860
                     FROM contest
861
                     ORDER BY positionalnumber";
862
863
864
865
866
867
868
869
        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),
870
871
                                                        min_grade: row.get(8),
                                                        max_grade: row.get(9),
872
                                                        positionalnumber: row.get(10),
873
874
                                                        requires_login: row.get(11),
                                                        secret: row.get(12),
875
876
877
878
879
                                                        taskgroups: Vec::new() })
            .unwrap()
    }

    fn get_contest_by_id(&self, contest_id: i32) -> Contest {
880
881
        let query = "SELECT location, filename, name, duration, public, start_date, end_date, min_grade, max_grade,
                            requires_login, secret
882
883
884
885
886
887
888
889
890
891
                     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),
892
893
                                                                  min_grade: row.get(7),
                                                                  max_grade: row.get(8),
894
                                                                  positionalnumber: None,
895
896
                                                                  requires_login: row.get(9),
                                                                  secret: row.get(10),
897
898
899
900
901
902
903
                                                                  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,
904
905
906
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade,
                            contest.requires_login, contest.secret, taskgroup.id, taskgroup.name, task.id,
                            task.location, task.stars
907
908
909
                     FROM contest
                     JOIN taskgroup ON contest.id = taskgroup.contest
                     JOIN task ON taskgroup.id = task.taskgroup
910
                     WHERE contest.id = ?1
911
                     AND taskgroup.active = ?2
912
                     ORDER BY taskgroup.positionalnumber";
913
        let taskgroupcontest =
914
            self.query_map_many(query, &[&contest_id, &true], |row| {
915
916
917
918
919
920
921
922
                    (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),
923
924
                               min_grade: row.get(7),
                               max_grade: row.get(8),
925
                               positionalnumber: None,
926
927
                               requires_login: row.get(9),
                               secret: row.get(10),
928
                               taskgroups: Vec::new() },
929
                     Taskgroup { id: Some(row.get(11)),
930
                                 contest: contest_id,
931
                                 name: row.get(12),
932
                                 active: true,
933
934
                                 positionalnumber: None,
                                 tasks: Vec::new() },
935
                     Task { id: Some(row.get(13)), taskgroup: row.get(11), location: row.get(14), stars: row.get(15) })
936
937
                })
                .unwrap();
938
        let mut taskgroupcontest_iter = taskgroupcontest.into_iter();
939

940
        let (mut contest, mut taskgroup, task) = taskgroupcontest_iter.next().unwrap();
941
942
        taskgroup.tasks.push(task);
        for tgc in taskgroupcontest_iter {
943
944
945
946
            let (_, tg, t) = tgc;
            if tg.id != taskgroup.id {
                contest.taskgroups.push(taskgroup);
                taskgroup = tg;
947
            }
948
            taskgroup.tasks.push(t);
949
950
951
952
953
954
955
        }
        contest.taskgroups.push(taskgroup);
        contest
    }

    fn get_contest_by_id_partial(&self, contest_id: i32) -> Contest {
        let query = "SELECT contest.location, contest.filename, contest.name, contest.duration, contest.public,
956
957
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade,
                            contest.requires_login, contest_secret, taskgroup.id, taskgroup.name
958
959
                     FROM contest
                     JOIN taskgroup ON contest.id = taskgroup.contest
960
961
962
                     WHERE contest.id = ?1
                     AND taskgroup.active = ?2";
        let taskgroupcontest = self.query_map_many(query, &[&contest_id, &true], |row| {
963
964
965
966
967
968
969
970
                                       (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),
971
972
                                                  min_grade: row.get(7),
                                                  max_grade: row.get(8),
973
                                                  positionalnumber: None,
974
975
                                                  requires_login: row.get(9),
                                                  secret: row.get(10),
976
                                                  taskgroups: Vec::new() },
977
                                        Taskgroup { id: Some(row.get(11)),
978
                                                    contest: contest_id,
979
                                                    name: row.get(12),
980
                                                    active: true,
981
982
983
984
                                                    positionalnumber: None,
                                                    tasks: Vec::new() })
                                   })
                                   .unwrap();
985
        let mut taskgroupcontest_iter = taskgroupcontest.into_iter();
986

987
        let (mut contest, taskgroup) = taskgroupcontest_iter.next().unwrap();
988
989
        contest.taskgroups.push(taskgroup);
        for tgc in taskgroupcontest_iter {
990
991
            let (_, tg) = tgc;
            contest.taskgroups.push(tg);
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
        }
        contest
    }

    fn get_participation(&self, session: &str, contest_id: i32) -> Option<Participation> {
        let query = "SELECT session, start_date
                     FROM participation
                     JOIN session ON session.id = session
                     WHERE session.session_token = ?1
                     AND contest = ?2";
        self.query_map_one(query, &[&session, &contest_id], |row| Participation { contest: contest_id,
                                                                                  user: row.get(0),
                                                                                  start: row.get(1) })
            .ok()?
    }
    fn new_participation(&self, session: &str, contest_id: i32) -> Result<Participation, ()> {
        let query = "SELECT session, start_date
                     FROM participation
                     JOIN session ON session.id = session
                     WHERE session.session_token = ?1
                     AND contest = ?2";
        match self.query_map_one(query, &[&session, &contest_id], |_| {}).map_err(|_| ())? {
            Some(()) => Err(()),
            None => {
                let now = time::get_time();
                self.execute(
                             "INSERT INTO participation (contest, session, start_date)
                     SELECT ?1, id, ?2 FROM session WHERE session_token = ?3",
                             &[&contest_id, &now, &session],
                )
                    .unwrap();

                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 {
        let query = "SELECT location, stars, taskgroup
                     FROM task
                     WHERE id = ?1";
        self.query_map_one(query, &[&task_id], |row| Task { id: Some(task_id),
                                                            taskgroup: row.get(2),
                                                            location: row.get(0),
                                                            stars: row.get(1) })
            .unwrap()
            .unwrap()
    }
    fn get_task_by_id_complete(&self, task_id: i32) -> (Task, Taskgroup, Contest) {
1040
1041
        let query = "SELECT task.location, task.stars, taskgroup.id, taskgroup.name, taskgroup.active, contest.id,
                            contest.location, contest.filename, contest.name, contest.duration, contest.public,
1042
1043
                            contest.start_date, contest.end_date, contest.min_grade, contest.max_grade,
                            contest.requires_login, contest.secret
1044
1045
1046
1047
1048
1049
                     FROM contest
                     JOIN taskgroup ON taskgroup.contest = contest.id
                     JOIN task ON task.taskgroup = taskgroup.id
                     WHERE task.id = ?1";
        self.query_map_one(query, &[&task_id], |row| {
                (Task { id: Some(task_id), taskgroup: row.get(2), location: row.get(0), stars: row.get(1) },
1050
                 Taskgroup { id: Some(row.get(2)),
1051
                             contest: row.get(5),
1052
                             name: row.get(3),
1053
                             active: row.get(4),
1054
1055
                             positionalnumber: None,
                             tasks: Vec::new() },
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
                 Contest { id: Some(row.get(5)),
                           location: row.get(6),
                           filename: row.get(7),
                           name: row.get(8),
                           duration: row.get(9),
                           public: row.get(10),
                           start: row.get(11),
                           end: row.get(12),
                           min_grade: row.get(13),
                           max_grade: row.get(14),
1066
                           positionalnumber: None,
1067
1068
                           requires_login: row.get(15),
                           secret: row.get(16),
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
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
1140
1141
1142
1143
1144
1145
1146
1147
1148
                           taskgroups: Vec::new() })
            })
            .unwrap()
            .unwrap()
    }

    fn get_submission_to_validate(&self, tasklocation: &str, subtask: Option<&str>) -> i32 {
        match subtask {
            Some(st) => {
                let query = "SELECT id
                             FROM submission
                             JOIN task ON submission.task = task.id
                             WHERE task.location = ?1
                             AND subtask_identifier = ?2
                             AND needs_validation = 1
                             LIMIT 1";
                self.query_map_one(query, &[&tasklocation, &st], |row| row.get(0)).unwrap().unwrap()
            }
            None => {
                let query = "SELECT id
                             FROM submission
                             JOIN task ON submission.task = task.id
                             WHERE task.location = ?1
                             AND needs_validation = 1
                             LIMIT 1";
                self.query_map_one(query, &[&tasklocation], |row| row.get(0)).unwrap().unwrap()
            }
        }
    }

    fn find_next_submission_to_validate(&self, userid: i32, taskgroupid: i32) {
        let query = "SELECT id, validated
                     FROM submission
                     JOIN task ON submission.task = task.id
                     WHERE task.taskgroup = ?1
                     AND submission.session = ?2
                     ORDER BY value DESC id DESC
                     LIMIT 1";
        let (id, validated): (i32, bool) =
            self.query_map_one(query, &[&taskgroupid, &userid], |row| (row.get(0), row.get(1))).unwrap().unwrap();
        if !validated {
            let query = "UPDATE submission
                         SET needs_validation = 1
                         WHERE id = ?1";
            self.execute(query, &[&id]).unwrap();
        }
    }

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

    fn get_groups(&self, session_id: i32) -> Vec<Group> {
        let query = "SELECT id, name, groupcode, tag
                     FROM usergroup
                     WHERE admin = ?1";
        self.query_map_many(query, &[&session_id], |row| Group { id: Some(row.get(0)),
                                                                 name: row.get(1),
                                                                 groupcode: row.get(2),
                                                                 tag: row.get(3),
                                                                 admin: session_id,
                                                                 members: Vec::new() })
            .unwrap()
    }
    fn get_groups_complete(&self, _session_id: i32) -> Vec<Group> {
        unimplemented!();
    }
    fn get_group_complete(&self, group_id: i32) -> Option<Group> {
        let query = "SELECT name, groupcode, tag, admin
                     FROM usergroup
                     WHERE id  = ?1";
        let mut group = self.query_map_one(query, &[&group_id], |row| Group { id: Some(group_id),
                                                                              name: row.get(0),
                                                                              groupcode: row.get(1),
                                                                              tag: row.get(2),
                                                                              admin: row.get(3),
                                                                              members: Vec::new() })
                            .unwrap()
                            .unwrap(); // TODO handle error

        let query = "SELECT id, session_token, csrf_token, last_login, last_activity, permanent_login, username,
                            password, logincode, email, email_unconfirmed, email_confirmationcode, firstname, lastname,
1149
                            street, zip, city, nation, grade, sex, is_admin, is_teacher, oauth_provider, oauth_foreign_id, salt
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
                     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),
1175
                                                                                     sex: row.get(19),
1176

1177
1178
                                                                                     is_admin: row.get(20),
                                                                                     is_teacher: row.get(21),
1179
1180
                                                                                     managed_by: Some(group_id),

1181
1182
                                                                                     oauth_provider: row.get(22),
                                                                                     oauth_foreign_id: row.get(23) })
1183
1184
1185
                            .unwrap();
        Some(group)
    }
1186
    fn get_search_users(&self,
1187
1188
                        (s_id, s_firstname, s_lastname, s_logincode, s_groupcode, s_pms_id): (Option<i32>,
                         Option<String>,
1189
1190
1191
1192
                         Option<String>,
                         Option<String>,
                         Option<String>,
                         Option<String>))
1193
                        -> Result<Vec<(i32, String, String)>, Vec<(i32, String, String)>>
1194
1195
1196
1197
1198
1199
    {
        if let Some(id) = s_id {
            let query = "SELECT id, firstname, lastname
                         FROM session
                         WHERE id = ?1
                         LIMIT 30";
1200
            Ok(self.query_map_many(query, &[&id], |row| (row.get(0), row.get(1), row.get(2))).unwrap())
1201
1202
1203
1204
1205
        } else if let Some(logincode) = s_logincode {
            let query = "SELECT id, firstname, lastname
                         FROM session
                         WHERE logincode = ?1
                         LIMIT 30";
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
            Ok(self.query_map_many(query, &[&logincode], |row| (row.get(0), row.get(1), row.get(2))).unwrap())
        } else if let Some(groupcode) = s_groupcode {
            let query = "SELECT id, name, tag
                         FROM usergroup
                         WHERE groupcode = ?1
                         LIMIT 30";
            Err(self.query_map_many(query, &[&groupcode], |row| {
                        (row.get(0),
                         format!("Gruppe: {}", row.get::<_, String>(1)),
                         format!("(Marker: {})", row.get::<_, String>(2)))
                    })
                    .unwrap())
1218
1219
1220
1221
1222
        } else if let Some(pms_id) = s_pms_id {
            let query = "SELECT id, firstname, lastname
                         FROM session
                         WHERE oauth_foreign_id = ?1
                         LIMIT 30";
1223
            Ok(self.query_map_many(query, &[&pms_id], |row| (row.get(0), row.get(1), row.get(2))).unwrap())
1224
1225
1226
1227
1228
1229
        } else if let (Some(firstname), Some(lastname)) = (s_firstname, s_lastname) {
            let query = "SELECT id, firstname, lastname
                         FROM session
                         WHERE firstname LIKE ?1
                         AND lastname LIKE ?2
                         LIMIT 30";
1230
1231
            Ok(self.query_map_many(query, &[&firstname, &lastname], |row| (row.get(0), row.get(1), row.get(2)))
                   .unwrap())
1232
        } else {
1233
            Ok(Vec::new())
1234
1235
1236
        }
    }

1237
1238
1239
1240
1241
1242
1243
1244
    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;";
1245
        let n_asession: i64 = self.query_map_one(query, &[&then], |row| row.get(0)).unwrap().unwrap();
1246
1247
1248
1249

        let query = "SELECT count(*)
                     FROM participation
                     WHERE start_date > ?1;";
1250
        let n_apart: i64 = self.query_map_one(query, &[&then], |row| row.get(0)).unwrap().unwrap();
1251
1252
1253

        let query = "SELECT count(*)
                     FROM session;";
1254
        let n_session: i64 = self.query_map_one(query, &[], |row| row.get(0)).unwrap().unwrap();
1255
1256
1257

        let query = "SELECT count(*)
                     FROM session
1258
1259
                     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();
1260
1261
1262

        let query = "SELECT count(*)
                     FROM session
1263
1264
                     WHERE oauth_foreign_id IS NOT NULL;";
        let n_pmsuser: i64 = self.query_map_one(query, &[], |row| row.get(0)).unwrap().unwrap();
1265
1266
1267
1268

        let query = "SELECT count(*)
                     FROM session
                     WHERE is_teacher = ?1;";
1269
        let n_teacher: i64 = self.query_map_one(query, &[&true], |row| row.get(0)).unwrap().unwrap();
1270
1271
1272

        let query = "SELECT count(*)
                     FROM participation;";
1273
        let n_part: i64 = self.query_map_one(query, &[], |row| row.get(0)).unwrap().unwrap();
1274
1275
1276

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

1279
        let query = "SELECT contest, count(*)
1280
1281
1282
                     FROM participation
                     GROUP BY contest
                     ORDER BY contest DESC;";
1283
1284
        let n_participations_by_id: Vec<(i32, i64)> =
            self.query_map_many(query, &[], |row| (row.get(0), row.get(1))).unwrap();
1285

1286
1287
        format!(
                "{{
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
  \"timestamp\": {},
  \"active_sessions\": {},
  \"active_participations\": {},
  \"sessions\": {},
  \"users\": {},
  \"pms_users\": {},
  \"teachers\": {},
  \"participations\": {},
  \"submissions\": {},
  \"participations_by_contest_id\": {{
    {}
  }}
1300
1301
}}
",
Robert Czechowski's avatar
Robert Czechowski committed
1302
1303
1304
1305
1306
1307
1308
1309
1310
                now.sec,
                n_asession,
                n_apart,
                n_session,
                n_user,
                n_pmsuser,
                n_teacher,
                n_part,
                n_sub,
1311
                n_participations_by_id.iter()
Robert Czechowski's avatar
Robert Czechowski committed
1312
1313
                                      .map(|(x, y)| -> String { format!("\"{}\": {}", x, y) })
                                      .collect::<Vec<String>>()
1314
                                      .join(",\n    ")
1315
        )
1316
1317
    }

1318
    fn reset_all_contest_visibilities(&self) { self.execute("UPDATE contest SET public = ?1", &[&false]).unwrap(); }
1319
    fn reset_all_taskgroup_visibilities(&self) { self.execute("UPDATE taskgroup SET active = ?1", &[&false]).unwrap(); }
1320
}