~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to lib/common/db.py

  • Committer: stevenbird
  • Date: 2008-02-19 03:59:20 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:502
www/apps/tutorialservice/__init__.py
* changed name from "Problem" to "Exercise"

www/apps/tutorialservice/test/parse_tute.py,TestFramework.py
* changed "succeed" to "pass" for consistency
* added code_test functionality to TestCasePart
* added check_code to run normalisations and comparisons
  on code instead of output
* extended solution_data and attempt_data dictionaries to
  include the code
* still broken with an error on line 423 of TestFramework.py
  (the function supplied in the XML file for testing the code
  can't be called?)

Show diffs side-by-side

added added

removed removed

Lines of Context:
35
35
import conf
36
36
import md5
37
37
import copy
38
 
import time
39
38
 
40
39
from common import (caps, user)
41
40
 
42
 
TIMESTAMP_FORMAT = '%Y-%m-%d %H:%M:%S'
43
 
 
44
41
def _escape(val):
45
42
    """Wrapper around pg.escape_string. Prepares the Python value for use in
46
43
    SQL. Returns a string, which may be safely placed verbatim into an SQL
51
48
    * bool: Returns as "TRUE" or "FALSE", unquoted.
52
49
    * NoneType: Returns "NULL", unquoted.
53
50
    * common.caps.Role: Returns the role as a quoted, lowercase string.
54
 
    * time.struct_time: Returns the time as a quoted string for insertion into
55
 
        a TIMESTAMP column.
56
51
    Raises a DBException if val has an unsupported type.
57
52
    """
58
53
    # "E'" is postgres's way of making "escape" strings.
63
58
    # WARNING: PostgreSQL-specific code
64
59
    if val is None:
65
60
        return "NULL"
66
 
    elif isinstance(val, str) or isinstance(val, unicode):
 
61
    elif isinstance(val, str):
67
62
        return "E'" + pg.escape_string(val) + "'"
68
63
    elif isinstance(val, bool):
69
64
        return "TRUE" if val else "FALSE"
72
67
        return str(val)
73
68
    elif isinstance(val, caps.Role):
74
69
        return _escape(str(val))
75
 
    elif isinstance(val, time.struct_time):
76
 
        return _escape(time.strftime(TIMESTAMP_FORMAT, val))
77
70
    else:
78
71
        raise DBException("Attempt to insert an unsupported type "
79
 
            "into the database (%s)" % repr(type(val)))
80
 
 
81
 
def _parse_boolean(val):
82
 
    """
83
 
    Accepts a boolean as output from the DB (either the string 't' or 'f').
84
 
    Returns a boolean value True or False.
85
 
    Also accepts other values which mean True or False in PostgreSQL.
86
 
    If none match, raises a DBException.
87
 
    """
88
 
    # On a personal note, what sort of a language allows 7 different values
89
 
    # to denote each of True and False?? (A: SQL)
90
 
    if isinstance(val, bool):
91
 
        return val
92
 
    elif val == 't':
93
 
        return True
94
 
    elif val == 'f':
95
 
        return False
96
 
    elif val == 'true' or val == 'y' or val == 'yes' or val == '1' \
97
 
        or val == 1:
98
 
        return True
99
 
    elif val == 'false' or val == 'n' or val == 'no' or val == '0' \
100
 
        or val == 0:
101
 
        return False
102
 
    else:
103
 
        raise DBException("Invalid boolean value returned from DB")
 
72
            "into the database")
104
73
 
105
74
def _passhash(password):
106
75
    return md5.md5(password).hexdigest()
171
140
        Raises a DBException if the dictionary contains invalid fields.
172
141
        """
173
142
        if not DB.check_dict(dict, tablefields, disallowed):
174
 
            extras = set(dict.keys()) - tablefields
175
 
            raise DBException("Supplied dictionary contains invalid fields. (%s)" % (repr(extras)))
 
143
            raise DBException("Supplied dictionary contains invalid fields.")
176
144
        # Build two lists concurrently: field names and values, as SQL strings
177
145
        fieldnames = []
178
146
        values = []
187
155
        if dry: return query
188
156
        self.db.query(query)
189
157
 
190
 
    def return_insert(self, dict, tablename, tablefields, returning,
191
 
        disallowed=frozenset([]), dry=False):
192
 
        """Inserts a new row in a table, using data from a supplied
193
 
        dictionary (which will be checked by check_dict) and returns certain 
194
 
        fields as a dict.
195
 
        dict: Dictionary mapping column names to values. The values may be
196
 
            any of the following types:
197
 
            str, int, long, float, NoneType.
198
 
        tablename: String, name of the table to insert into. Will NOT be
199
 
            escaped - must be a valid identifier.
200
 
        returning: List of fields to return, not escaped
201
 
        tablefields, disallowed: see check_dict.
202
 
        dry: Returns the SQL query as a string, and does not execute it.
203
 
        Raises a DBException if the dictionary contains invalid fields.
204
 
        """
205
 
        if not DB.check_dict(dict, tablefields, disallowed):
206
 
            extras = set(dict.keys()) - tablefields
207
 
            raise DBException("Supplied dictionary contains invalid fields. (%s)" % (repr(extras)))
208
 
        # Build two lists concurrently: field names and values, as SQL strings
209
 
        fieldnames = []
210
 
        values = []
211
 
        for k,v in dict.items():
212
 
            fieldnames.append(k)
213
 
            values.append(_escape(v))
214
 
        if len(fieldnames) == 0: return
215
 
        fieldnames = ', '.join(fieldnames)
216
 
        values = ', '.join(values)
217
 
        returns = ', '.join(returning)
218
 
        query = ("INSERT INTO %s (%s) VALUES (%s) RETURNING (%s);"
219
 
            % (tablename, fieldnames, values, returns))
220
 
        if dry: return query
221
 
        return self.db.query(query)
222
 
 
223
 
 
224
158
    def update(self, primarydict, updatedict, tablename, tablefields,
225
159
        primary_keys, disallowed_update=frozenset([]), dry=False):
226
160
        """Updates a row in a table, matching against primarydict to find the
238
172
        """
239
173
        if (not (DB.check_dict(primarydict, primary_keys, must=True)
240
174
            and DB.check_dict(updatedict, tablefields, disallowed_update))):
241
 
            raise DBException("Supplied dictionary contains invalid or missing fields (1).")
 
175
            raise DBException("Supplied dictionary contains invalid or "
 
176
                " missing fields.")
242
177
        # Make a list of SQL fragments of the form "field = 'new value'"
243
178
        # These fragments are ALREADY-ESCAPED
244
179
        setlist = []
264
199
        primarydict, tablename, primary_keys: See update.
265
200
        """
266
201
        if not DB.check_dict(primarydict, primary_keys, must=True):
267
 
            raise DBException("Supplied dictionary contains invalid or missing fields (2).")
 
202
            raise DBException("Supplied dictionary contains invalid or "
 
203
                " missing fields.")
268
204
        wherelist = []
269
205
        for k,v in primarydict.items():
270
206
            wherelist.append("%s = %s" % (k, _escape(v)))
289
225
            primary_keys is indeed the primary key).
290
226
        """
291
227
        if not DB.check_dict(primarydict, primary_keys, must=True):
292
 
            raise DBException("Supplied dictionary contains invalid or missing fields (3).")
 
228
            raise DBException("Supplied dictionary contains invalid or "
 
229
                " missing fields.")
293
230
        wherelist = []
294
231
        for k,v in primarydict.items():
295
232
            wherelist.append("%s = %s" % (k, _escape(v)))
352
289
    login_primary = frozenset(["login"])
353
290
    login_fields_list = [
354
291
        "login", "passhash", "state", "unixid", "email", "nick", "fullname",
355
 
        "rolenm", "studentid", "acct_exp", "pass_exp", "last_login", "svn_pass"
 
292
        "rolenm", "studentid", "acct_exp", "pass_exp", "last_login"
356
293
    ]
357
294
    login_fields = frozenset(login_fields_list)
 
295
    # Do not return passhash when reading from the DB
 
296
    login_getfields = login_fields - frozenset(["passhash"])
358
297
 
359
 
    def create_user(self, user_obj=None, dry=False, **kwargs):
 
298
    def create_user(self, dry=False, **kwargs):
360
299
        """Creates a user login entry in the database.
361
 
        Two ways to call this - passing a user object, or passing
362
 
        all fields as separate arguments.
363
 
 
364
 
        Either pass a "user_obj" as the first argument (in which case other
365
 
        fields will be ignored), or pass all fields as arguments.
366
 
 
367
300
        All user fields are to be passed as args. The argument names
368
301
        are the field names of the "login" table of the DB schema.
369
302
        However, instead of supplying a "passhash", you must supply a
374
307
        invalid keys or is missing required keys.
375
308
        """
376
309
        if 'passhash' in kwargs:
377
 
            raise DBException("Supplied arguments include passhash (invalid) (1).")
 
310
            raise DBException("Supplied arguments include passhash (invalid).")
378
311
        # Make a copy of the dict. Change password to passhash (hashing it),
379
312
        # and set 'state' to "no_agreement".
380
 
        if user_obj is None:
381
 
            # Use the kwargs
382
 
            fields = copy.copy(kwargs)
383
 
        else:
384
 
            # Use the user object
385
 
            fields = dict(user_obj)
386
 
        if 'password' in fields:
387
 
            fields['passhash'] = _passhash(fields['password'])
388
 
            del fields['password']
389
 
        if 'role' in fields:
390
 
            # Convert role to rolenm
391
 
            fields['rolenm'] = str(user_obj.role)
392
 
            del fields['role']
393
 
        if user_obj is None:
394
 
            fields['state'] = "no_agreement"
395
 
            # else, we'll trust the user, but it SHOULD be "no_agreement"
396
 
            # (We can't change it because then the user object would not
397
 
            # reflect the DB).
398
 
        if 'local_password' in fields:
399
 
            del fields['local_password']
 
313
        kwargs = copy.copy(kwargs)
 
314
        if 'password' in kwargs:
 
315
            kwargs['passhash'] = _passhash(kwargs['password'])
 
316
            del kwargs['password']
 
317
        kwargs['state'] = "no_agreement"
400
318
        # Execute the query.
401
 
        return self.insert(fields, "login", self.login_fields, dry=dry)
 
319
        return self.insert(kwargs, "login", self.login_fields, dry=dry)
402
320
 
403
321
    def update_user(self, login, dry=False, **kwargs):
404
322
        """Updates fields of a particular user. login is the name of the user
415
333
        with a new one.
416
334
        """
417
335
        if 'passhash' in kwargs:
418
 
            raise DBException("Supplied arguments include passhash (invalid) (2).")
 
336
            raise DBException("Supplied arguments include passhash (invalid).")
419
337
        if "password" in kwargs:
420
338
            kwargs = copy.copy(kwargs)
421
339
            kwargs['passhash'] = _passhash(kwargs['password'])
431
349
        Raises a DBException if the login is not found in the DB.
432
350
        """
433
351
        userdict = self.get_single({"login": login}, "login",
434
 
            self.login_fields, self.login_primary,
 
352
            self.login_getfields, self.login_primary,
435
353
            error_notfound="get_user: No user with that login name", dry=dry)
436
354
        if dry:
437
355
            return userdict     # Query string
441
359
    def get_users(self, dry=False):
442
360
        """Returns a list of all users in the DB, as User objects.
443
361
        """
444
 
        userdicts = self.get_all("login", self.login_fields, dry=dry)
 
362
        userdicts = self.get_all("login", self.login_getfields, dry=dry)
445
363
        if dry:
446
364
            return userdicts    # Query string
447
365
        # Package into User objects
448
366
        return [user.User(**userdict) for userdict in userdicts]
449
367
 
450
 
    def get_user_loginid(self, login, dry=False):
451
 
        """Given a login, returns the integer loginid for this user.
452
 
 
453
 
        Raises a DBException if the login is not found in the DB.
454
 
        """
455
 
        userdict = self.get_single({"login": login}, "login",
456
 
            ['loginid'], self.login_primary,
457
 
            error_notfound="get_user_loginid: No user with that login name",
458
 
            dry=dry)
459
 
        if dry:
460
 
            return userdict     # Query string
461
 
        return userdict['loginid']
462
 
 
463
368
    def user_authenticate(self, login, password, dry=False):
464
369
        """Performs a password authentication on a user. Returns True if
465
370
        "passhash" is the correct passhash for the given login, False
466
 
        if the passhash does not match the password in the DB,
467
 
        and None if the passhash in the DB is NULL.
 
371
        otherwise.
468
372
        Also returns False if the login does not exist (so if you want to
469
373
        differentiate these cases, use get_user and catch an exception).
470
374
        """
471
 
        query = ("SELECT passhash FROM login WHERE login = %s;"
472
 
            % _escape(login))
473
 
        if dry: return query
474
 
        result = self.db.query(query)
475
 
        if result.ntuples() == 1:
476
 
            # Valid username. Check password.
477
 
            passhash = result.getresult()[0][0]
478
 
            if passhash is None:
479
 
                return None
480
 
            return _passhash(password) == passhash
481
 
        else:
482
 
            return False
483
 
 
484
 
    # PROBLEM AND PROBLEM ATTEMPT FUNCTIONS #
485
 
 
486
 
    def get_problem_problemid(self, exercisename, dry=False):
487
 
        """Given an exercise name, returns the associated problemID.
488
 
        If the exercise name is NOT in the database, it inserts it and returns
489
 
        the new problemID. Hence this may mutate the DB, but is idempotent.
490
 
        """
491
 
        try:
492
 
            d = self.get_single({"identifier": exercisename}, "problem",
493
 
                ['problemid'], frozenset(["identifier"]),
494
 
                dry=dry)
495
 
            if dry:
496
 
                return d        # Query string
497
 
        except DBException:
498
 
            if dry:
499
 
                # Shouldn't try again, must have failed for some other reason
500
 
                raise
501
 
            # if we failed to get a problemid, it was probably because
502
 
            # the exercise wasn't in the db. So lets insert it!
503
 
            #
504
 
            # The insert can fail if someone else simultaneously does
505
 
            # the insert, so if the insert fails, we ignore the problem. 
506
 
            try:
507
 
                self.insert({'identifier': exercisename}, "problem",
508
 
                        frozenset(['identifier']))
509
 
            except Exception, e:
510
 
                pass
511
 
 
512
 
            # Assuming the insert succeeded, we should be able to get the
513
 
            # problemid now.
514
 
            d = self.get_single({"identifier": exercisename}, "problem",
515
 
                ['problemid'], frozenset(["identifier"]))
516
 
 
517
 
        return d['problemid']
518
 
 
519
 
    def insert_problem_attempt(self, login, exercisename, date, complete,
520
 
        attempt, dry=False):
521
 
        """Inserts the details of a problem attempt into the database.
522
 
        exercisename: Name of the exercise. (identifier field of problem
523
 
            table). If this exercise does not exist, also creates a new row in
524
 
            the problem table for this exercise name.
525
 
        login: Name of the user submitting the attempt. (login field of the
526
 
            login table).
527
 
        date: struct_time, the date this attempt was made.
528
 
        complete: bool. Whether the test passed or not.
529
 
        attempt: Text of the attempt.
530
 
 
531
 
        Note: Even if dry, will still physically call get_problem_problemid,
532
 
        which may mutate the DB, and get_user_loginid, which may fail.
533
 
        """
534
 
        problemid = self.get_problem_problemid(exercisename)
535
 
        loginid = self.get_user_loginid(login)  # May raise a DBException
536
 
 
537
 
        return self.insert({
538
 
                'problemid': problemid,
539
 
                'loginid': loginid,
540
 
                'date': date,
541
 
                'complete': complete,
542
 
                'attempt': attempt,
543
 
            }, 'problem_attempt',
544
 
            frozenset(['problemid','loginid','date','complete','attempt']),
545
 
            dry=dry)
546
 
 
547
 
    def write_problem_save(self, login, exercisename, date, text, dry=False):
548
 
        """Writes text to the problem_save table (for when the user saves an
549
 
        exercise). Creates a new row, or overwrites an existing one if the
550
 
        user has already saved that problem.
551
 
        (Unlike problem_attempt, does not keep historical records).
552
 
        """
553
 
        problemid = self.get_problem_problemid(exercisename)
554
 
        loginid = self.get_user_loginid(login)  # May raise a DBException
555
 
 
556
 
        try:
557
 
            return self.insert({
558
 
                    'problemid': problemid,
559
 
                    'loginid': loginid,
560
 
                    'date': date,
561
 
                    'text': text,
562
 
                }, 'problem_save',
563
 
                frozenset(['problemid','loginid','date','text']),
564
 
                dry=dry)
565
 
        except pg.ProgrammingError:
566
 
            # May have failed because this problemid/loginid row already
567
 
            # exists (they have a unique key constraint).
568
 
            # Do an update instead.
569
 
            if dry:
570
 
                # Shouldn't try again, must have failed for some other reason
571
 
                raise
572
 
            self.update({
573
 
                    'problemid': problemid,
574
 
                    'loginid': loginid,
575
 
                },
576
 
                {
577
 
                    'date': date,
578
 
                    'text': text,
579
 
                }, "problem_save",
580
 
                frozenset(['date', 'text']),
581
 
                frozenset(['problemid', 'loginid']))
582
 
 
583
 
    def get_problem_stored_text(self, login, exercisename, dry=False):
584
 
        """Given a login name and exercise name, returns the text of the
585
 
        last saved/submitted attempt for this question.
586
 
        Returns None if the user has not saved or made an attempt on this
587
 
        problem.
588
 
        (If the user has both saved and submitted, it returns whichever was
589
 
        made last).
590
 
 
591
 
        Note: Even if dry, will still physically call get_problem_problemid,
592
 
        which may mutate the DB, and get_user_loginid, which may fail.
593
 
        """
594
 
        problemid = self.get_problem_problemid(exercisename)
595
 
        loginid = self.get_user_loginid(login)  # May raise a DBException
596
 
        # This very complex query finds all submissions made by this user for
597
 
        # this problem, as well as the save made by this user for this
598
 
        # problem, and returns the text of the newest one.
599
 
        # (Whichever is newer out of the save or the submit).
600
 
        query = """SELECT text FROM
601
 
    (
602
 
        (SELECT * FROM problem_save WHERE loginid = %d AND problemid = %d)
603
 
    UNION
604
 
        (SELECT problemid, loginid, date, text FROM problem_attempt
605
 
         AS problem_attempt (problemid, loginid, date, text)
606
 
         WHERE loginid = %d AND problemid = %d AND active)
607
 
    )
608
 
    AS _
609
 
    ORDER BY date DESC
610
 
    LIMIT 1;""" % (loginid, problemid, loginid, problemid)
611
 
        if dry: return query
612
 
        result = self.db.query(query)
613
 
        if result.ntuples() == 1:
614
 
            # The user has made at least 1 attempt. Return the newest.
615
 
            return result.getresult()[0][0]
616
 
        else:
617
 
            return None
618
 
 
619
 
    def get_problem_attempts(self, login, exercisename, allow_inactive=True,
620
 
                             dry=False):
621
 
        """Given a login name and exercise name, returns a list of dicts, one
622
 
        for each attempt made for that exercise.
623
 
        Dicts are {'date': 'formatted_time', 'complete': bool}.
624
 
        Ordered with the newest first.
625
 
        
626
 
        Note: By default, returns de-activated problem attempts (unlike
627
 
        get_problem_stored_text).
628
 
        If allow_inactive is False, will not return disabled attempts.
629
 
 
630
 
        Note: Even if dry, will still physically call get_problem_problemid,
631
 
        which may mutate the DB, and get_user_loginid, which may fail.
632
 
        """
633
 
        problemid = self.get_problem_problemid(exercisename)
634
 
        loginid = self.get_user_loginid(login)  # May raise a DBException
635
 
        andactive = '' if allow_inactive else ' AND active'
636
 
        query = """SELECT date, complete FROM problem_attempt
637
 
    WHERE loginid = %d AND problemid = %d%s
638
 
    ORDER BY date DESC;""" % (loginid, problemid, andactive)
639
 
        if dry: return query
640
 
        result = self.db.query(query).getresult()
641
 
        # Make into dicts (could use dictresult, but want to convert values)
642
 
        return [{'date': date, 'complete': _parse_boolean(complete)}
643
 
                for date, complete in result]
644
 
 
645
 
    def get_problem_attempt(self, login, exercisename, as_of,
646
 
        allow_inactive=True, dry=False):
647
 
        """Given a login name, exercise name, and struct_time, returns the
648
 
        text of the submitted attempt for this question as of that date.
649
 
        Returns None if the user had not made an attempt on this problem at
650
 
        that date.
651
 
        
652
 
        Note: By default, returns de-activated problem attempts (unlike
653
 
        get_problem_stored_text).
654
 
        If allow_inactive is False, will not return disabled attempts.
655
 
 
656
 
        Note: Even if dry, will still physically call get_problem_problemid,
657
 
        which may mutate the DB, and get_user_loginid, which may fail.
658
 
        """
659
 
        problemid = self.get_problem_problemid(exercisename)
660
 
        loginid = self.get_user_loginid(login)  # May raise a DBException
661
 
        # Very similar to query in get_problem_stored_text, but without
662
 
        # looking in problem_save, and restricting to a certain date.
663
 
        andactive = '' if allow_inactive else ' AND active'
664
 
        query = """SELECT attempt FROM problem_attempt
665
 
    WHERE loginid = %d AND problemid = %d%s AND date <= %s
666
 
    ORDER BY date DESC
667
 
    LIMIT 1;""" % (loginid, problemid, andactive, _escape(as_of))
668
 
        if dry: return query
669
 
        result = self.db.query(query)
670
 
        if result.ntuples() == 1:
671
 
            # The user has made at least 1 attempt. Return the newest.
672
 
            return result.getresult()[0][0]
673
 
        else:
674
 
            return None
675
 
 
676
 
    def get_problem_status(self, login, exercisename, dry=False):
677
 
        """Given a login name and exercise name, returns information about the
678
 
        user's performance on that problem.
679
 
        Returns a tuple of:
680
 
            - A boolean, whether they have successfully passed this exercise.
681
 
            - An int, the number of attempts they have made up to and
682
 
              including the first successful attempt (or the total number of
683
 
              attempts, if not yet successful).
684
 
        Note: exercisename may be an int, in which case it will be directly
685
 
        used as the problemid.
686
 
        """
687
 
        if isinstance(exercisename, int):
688
 
            problemid = exercisename
689
 
        else:
690
 
            problemid = self.get_problem_problemid(exercisename)
691
 
        loginid = self.get_user_loginid(login)  # May raise a DBException
692
 
 
693
 
        # ASSUME that it is completed, get the total number of attempts up to
694
 
        # and including the first successful attempt.
695
 
        # (Get the date of the first successful attempt. Then count the number
696
 
        # of attempts made <= that date).
697
 
        # Will return an empty table if the problem has never been
698
 
        # successfully completed.
699
 
        query = """SELECT COUNT(*) FROM problem_attempt
700
 
    WHERE loginid = %d AND problemid = %d AND active AND date <=
701
 
        (SELECT date FROM problem_attempt
702
 
            WHERE loginid = %d AND problemid = %d AND complete AND active
703
 
            ORDER BY date ASC
704
 
            LIMIT 1);""" % (loginid, problemid, loginid, problemid)
705
 
        if dry: return query
706
 
        result = self.db.query(query)
707
 
        count = int(result.getresult()[0][0])
708
 
        if count > 0:
709
 
            # The user has made at least 1 successful attempt.
710
 
            # Return True for success, and the number of attempts up to and
711
 
            # including the successful one.
712
 
            return (True, count)
713
 
        else:
714
 
            # Returned 0 rows - this indicates that the problem has not been
715
 
            # completed.
716
 
            # Return the total number of attempts, and False for success.
717
 
            query = """SELECT COUNT(*) FROM problem_attempt
718
 
    WHERE loginid = %d AND problemid = %d AND active;""" % (loginid, problemid)
719
 
            result = self.db.query(query)
720
 
            count = int(result.getresult()[0][0])
721
 
            return (False, count)
722
 
 
723
 
    # WORKSHEET/PROBLEM ASSOCIATION AND MARKS CALCULATION
724
 
 
725
 
    def get_worksheet_mtime(self, subject, worksheet, dry=False):
726
 
        """
727
 
        For a given subject/worksheet name, gets the time the worksheet was
728
 
        last updated in the DB, if any.
729
 
        This can be used to check if there is a newer version on disk.
730
 
        Returns the timestamp as a time.struct_time, or None if the worksheet
731
 
        is not found or has no stored mtime.
732
 
        """
733
 
        try:
734
 
            r = self.get_single(
735
 
                {"subject": subject, "identifier": worksheet},
736
 
                "worksheet", ["mtime"], ["subject", "identifier"],
737
 
                dry=dry)
738
 
        except DBException:
739
 
            # Assume the worksheet is not in the DB
740
 
            return None
741
 
        if dry:
742
 
            return r
743
 
        if r["mtime"] is None:
744
 
            return None
745
 
        return time.strptime(r["mtime"], TIMESTAMP_FORMAT)
746
 
 
747
 
    def create_worksheet(self, subject, worksheet, problems=None,
748
 
        assessable=None):
749
 
        """
750
 
        Inserts or updates rows in the worksheet and worksheet_problems
751
 
        tables, to create a worksheet in the database.
752
 
        This atomically performs all operations. If the worksheet is already
753
 
        in the DB, removes it and all its associated problems and rebuilds.
754
 
        Sets the timestamp to the current time.
755
 
 
756
 
        problems is a collection of pairs. The first element of the pair is
757
 
        the problem identifier ("identifier" column of the problem table). The
758
 
        second element is an optional boolean, "optional". This can be omitted
759
 
        (so it's a 1-tuple), and then it will default to False.
760
 
 
761
 
        Problems and assessable are optional, and if omitted, will not change
762
 
        the existing data. If the worksheet does not yet exist, and assessable
763
 
        is omitted, it defaults to False.
764
 
 
765
 
        Note: As with get_problem_problemid, if a problem name is not in the
766
 
        DB, it will be added to the problem table.
767
 
        """
768
 
        self.start_transaction()
769
 
        try:
770
 
            # Use the current time as the "mtime" field
771
 
            mtime = time.localtime()
772
 
            try:
773
 
                # Get the worksheetid
774
 
                r = self.get_single(
775
 
                    {"subject": subject, "identifier": worksheet},
776
 
                    "worksheet", ["worksheetid"], ["subject", "identifier"])
777
 
                worksheetid = r["worksheetid"]
778
 
 
779
 
                # Delete any problems which might exist, if problems is
780
 
                # supplied. If it isn't, keep the existing ones.
781
 
                if problems is not None:
782
 
                    query = ("DELETE FROM worksheet_problem "
783
 
                        "WHERE worksheetid = %d;" % worksheetid)
784
 
                    self.db.query(query)
785
 
                # Update the row with the new details
786
 
                if assessable is None:
787
 
                    query = ("UPDATE worksheet "
788
 
                        "SET mtime = %s WHERE worksheetid = %d;"
789
 
                        % (_escape(mtime), worksheetid))
790
 
                else:
791
 
                    query = ("UPDATE worksheet "
792
 
                        "SET assessable = %s, mtime = %s "
793
 
                        "WHERE worksheetid = %d;"
794
 
                        % (_escape(assessable), _escape(mtime), worksheetid))
795
 
                self.db.query(query)
796
 
            except DBException:
797
 
                # Assume the worksheet is not in the DB
798
 
                # If assessable is not supplied, default to False.
799
 
                if assessable is None:
800
 
                    assessable = False
801
 
                # Create the worksheet row
802
 
                query = ("INSERT INTO worksheet "
803
 
                    "(subject, identifier, assessable, mtime) "
804
 
                    "VALUES (%s, %s, %s, %s);"""
805
 
                    % (_escape(subject), _escape(worksheet),
806
 
                    _escape(assessable), _escape(mtime)))
807
 
                self.db.query(query)
808
 
                # Now get the worksheetid again - should succeed
809
 
                r = self.get_single(
810
 
                    {"subject": subject, "identifier": worksheet},
811
 
                    "worksheet", ["worksheetid"], ["subject", "identifier"])
812
 
                worksheetid = r["worksheetid"]
813
 
 
814
 
            # Now insert each problem into the worksheet_problem table
815
 
            if problems is not None:
816
 
                for problem in problems:
817
 
                    if isinstance(problem, tuple):
818
 
                        prob_identifier = problem[0]
819
 
                        try:
820
 
                            optional = problem[1]
821
 
                        except IndexError:
822
 
                            optional = False
823
 
                    else:
824
 
                        prob_identifier = problem
825
 
                        optional = False
826
 
                    problemid = self.get_problem_problemid(prob_identifier)
827
 
                    query = ("INSERT INTO worksheet_problem "
828
 
                        "(worksheetid, problemid, optional) "
829
 
                        "VALUES (%d, %d, %s);"
830
 
                        % (worksheetid, problemid, _escape(optional)))
831
 
                    self.db.query(query)
832
 
 
833
 
            self.commit()
834
 
        except:
835
 
            self.rollback()
836
 
            raise
837
 
 
838
 
    def set_worksheet_assessable(self, subject, worksheet, assessable,
839
 
        dry=False):
840
 
        """
841
 
        Sets the "assessable" field of a worksheet without updating the mtime.
842
 
 
843
 
        IMPORTANT: This will NOT update the mtime. This is designed to allow
844
 
        updates which did not come from the worksheet XML file. It would be
845
 
        bad to update the mtime without consulting the XML file because then
846
 
        it would appear the database is up to date, when it isn't.
847
 
 
848
 
        Therefore, call this method if you are getting "assessable"
849
 
        information from outside the worksheet XML file (eg. from the subject
850
 
        XML file).
851
 
 
852
 
        Unlike create_worksheet, raises a DBException if the worksheet is not
853
 
        in the database.
854
 
        """
855
 
        return self.update({"subject": subject, "identifier": worksheet},
856
 
            {"assessable": assessable}, "worksheet", ["assessable"],
857
 
            ["subject", "identifier"], dry=dry)
858
 
 
859
 
    def worksheet_is_assessable(self, subject, worksheet, dry=False):
860
 
        r = self.get_single(
861
 
            {"subject": subject, "identifier": worksheet},
862
 
            "worksheet", ["assessable"], ["subject", "identifier"], dry=dry)
863
 
        return _parse_boolean(r["assessable"])
864
 
 
865
 
    def calculate_score_worksheet(self, login, subject, worksheet):
866
 
        """
867
 
        Calculates the score for a user on a given worksheet.
868
 
        Returns a 4-tuple of ints, consisting of:
869
 
        (No. mandatory exercises completed,
870
 
         Total no. mandatory exercises,
871
 
         No. optional exercises completed,
872
 
         Total no. optional exercises)
873
 
        """
874
 
        self.start_transaction()
875
 
        try:
876
 
            mand_done = 0
877
 
            mand_total = 0
878
 
            opt_done = 0
879
 
            opt_total = 0
880
 
            # Get a list of problems and optionality for all problems in the
881
 
            # worksheet
882
 
            query = ("""SELECT problemid, optional FROM worksheet_problem
883
 
    WHERE worksheetid = (SELECT worksheetid FROM worksheet
884
 
                         WHERE subject = %s and identifier = %s);"""
885
 
                    % (_escape(subject), _escape(worksheet)))
886
 
            result = self.db.query(query)
887
 
            # Now get the student's pass/fail for each problem in this worksheet
888
 
            for problemid, optional in result.getresult():
889
 
                done, _ = self.get_problem_status(login, problemid)
890
 
                # done is a bool, whether this student has completed that
891
 
                # problem
892
 
                if _parse_boolean(optional):
893
 
                    opt_total += 1
894
 
                    if done: opt_done += 1
895
 
                else:
896
 
                    mand_total += 1
897
 
                    if done: mand_done += 1
898
 
            self.commit()
899
 
        except:
900
 
            self.rollback()
901
 
            raise
902
 
        return mand_done, mand_total, opt_done, opt_total
903
 
 
904
 
    # ENROLMENT INFORMATION
905
 
 
906
 
    def add_enrolment(self, login, subj_code, semester, year=None, dry=False):
907
 
        """
908
 
        Enrol a student in the given offering of a subject.
909
 
        Returns True on success, False on failure (which usually means either
910
 
        the student is already enrolled in the subject, the student was not
911
 
        found, or no offering existed with the given details).
912
 
        The return value can usually be ignored.
913
 
        """
914
 
        subj_code = str(subj_code)
915
 
        semester = str(semester)
916
 
        if year is None:
917
 
            year = str(time.gmtime().tm_year)
918
 
        else:
919
 
            year = str(year)
920
 
        query = """\
921
 
INSERT INTO enrolment (loginid, offeringid)
922
 
    VALUES (
923
 
        (SELECT loginid FROM login WHERE login=%s),
924
 
        (SELECT offeringid
925
 
            FROM offering, subject, semester
926
 
                WHERE subject.subjectid = offering.subject
927
 
                AND semester.semesterid = offering.semesterid
928
 
                AND subj_code=%s AND semester=%s AND year=%s)
929
 
        );""" % (_escape(login), _escape(subj_code), _escape(semester),
930
 
                 _escape(year))
931
 
        if dry:
932
 
            return query
933
 
        try:
934
 
            result = self.db.query(query)
935
 
        except pg.ProgrammingError:
936
 
            return False
937
 
        return True
938
 
 
939
 
    # SUBJECTS AND ENROLEMENT
940
 
 
941
 
    def get_subjects(self, dry=False):
942
 
        """
943
 
        Get all subjects in IVLE.
944
 
        Returns a list of dicts (all values strings), with the keys:
945
 
        subj_code, subj_name, subj_short_name, url
946
 
        """
947
 
        return self.get_all("subject",
948
 
            ("subjectid", "subj_code", "subj_name", "subj_short_name", "url"),
949
 
            dry)
950
 
 
951
 
    def get_offering_semesters(self, subjectid, dry=False):
952
 
        """
953
 
        Get the semester information for a subject as well as providing 
954
 
        information about if the subject is active and which semester it is in.
955
 
        """
956
 
        query = """\
957
 
SELECT offeringid, subj_name, year, semester, active
958
 
FROM semester, offering, subject
959
 
WHERE offering.semesterid = semester.semesterid AND
960
 
    offering.subject = subject.subjectid AND
961
 
    offering.subject = %d;"""%subjectid
962
 
        if dry:
963
 
            return query
964
 
        results = self.db.query(query).dictresult()
965
 
        # Parse boolean varibles
966
 
        for result in results:
967
 
            result['active'] = _parse_boolean(result['active'])
968
 
        return results
969
 
 
970
 
    def get_offering_members(self, offeringid, dry=False):
971
 
        """
972
 
        Gets the logins of all the people enroled in an offering
973
 
        """
974
 
        query = """\
975
 
SELECT login.login AS login, login.fullname AS fullname
976
 
FROM login, enrolment
977
 
WHERE login.loginid = enrolment.loginid AND
978
 
    enrolment.offeringid = %d
979
 
    ORDER BY login.login;"""%offeringid
980
 
        if dry:
981
 
            return query
982
 
        return self.db.query(query).dictresult()
983
 
 
984
 
 
985
 
    def get_enrolment(self, login, dry=False):
986
 
        """
987
 
        Get all offerings (in IVLE) the student is enrolled in.
988
 
        Returns a list of dicts (all values strings), with the keys:
989
 
        offeringid, subj_code, subj_name, subj_short_name, year, semester, url
990
 
        """
991
 
        query = """\
992
 
SELECT offering.offeringid, subj_code, subj_name, subj_short_name,
993
 
       semester.year, semester.semester, subject.url
994
 
FROM login, enrolment, offering, subject, semester
995
 
WHERE enrolment.offeringid=offering.offeringid
996
 
  AND login.loginid=enrolment.loginid
997
 
  AND offering.subject=subject.subjectid
998
 
  AND semester.semesterid=offering.semesterid
999
 
  AND enrolment.active
1000
 
  AND login=%s;""" % _escape(login)
1001
 
        if dry:
1002
 
            return query
1003
 
        return self.db.query(query).dictresult()
1004
 
 
1005
 
    def get_enrolment_groups(self, login, offeringid, dry=False):
1006
 
        """
1007
 
        Get all groups the user is member of in the given offering.
1008
 
        Returns a list of dicts (all values strings), with the keys:
1009
 
        name, nick
1010
 
        """
1011
 
        query = """\
1012
 
SELECT project_group.groupnm as name, project_group.nick as nick
1013
 
FROM project_set, project_group, group_member, login
1014
 
WHERE login.login=%s
1015
 
  AND project_set.offeringid=%s
1016
 
  AND group_member.loginid=login.loginid
1017
 
  AND project_group.groupid=group_member.groupid
1018
 
  AND project_group.projectsetid=project_set.projectsetid
1019
 
""" % (_escape(login), _escape(offeringid))
1020
 
        if dry:
1021
 
            return query
1022
 
        return self.db.query(query).dictresult()
1023
 
 
1024
 
    def get_subjects_status(self, login, dry=False):
1025
 
        """
1026
 
        Get all subjects in IVLE, split into lists of enrolled and unenrolled
1027
 
        subjects.
1028
 
        Returns a tuple of lists (enrolled, unenrolled) of dicts
1029
 
        (all values strings) with the keys:
1030
 
        subj_code, subj_name, subj_short_name, url
1031
 
        """
1032
 
        enrolments = self.get_enrolment(login)
1033
 
        all_subjects = self.get_subjects()
1034
 
 
1035
 
        enrolled_set = set(x['subj_code'] for x in enrolments)
1036
 
 
1037
 
        enrolled_subjects = [x for x in all_subjects
1038
 
                             if x['subj_code'] in enrolled_set]
1039
 
        unenrolled_subjects = [x for x in all_subjects
1040
 
                               if x['subj_code'] not in enrolled_set]
1041
 
        enrolled_subjects.sort(key=lambda x: x['subj_code'])
1042
 
        unenrolled_subjects.sort(key=lambda x: x['subj_code'])
1043
 
        return (enrolled_subjects, unenrolled_subjects)
1044
 
 
1045
 
 
1046
 
    # PROJECT GROUPS
1047
 
    def get_groups_by_user(self, login, offeringid=None, dry=False):
1048
 
        """
1049
 
        Get all project groups the student is in, corresponding to a
1050
 
        particular subject offering (or all offerings, if omitted).
1051
 
        Returns a list of tuples:
1052
 
        (int groupid, str groupnm, str group_nick, bool is_member).
1053
 
        (Note: If is_member is false, it means they have just been invited to
1054
 
        this group, not a member).
1055
 
        """
1056
 
        if offeringid is None:
1057
 
            and_offering = ""
1058
 
        else:
1059
 
            and_projectset_table = ", project_set"
1060
 
            and_offering = """
1061
 
AND project_group.projectsetid = project_set.projectsetid
1062
 
AND project_set.offeringid = %s""" % _escape(offeringid)
1063
 
        # Union both the groups this user is a member of, and the groups this
1064
 
        # user is invited to.
1065
 
        query = """\
1066
 
    SELECT project_group.groupid, groupnm, project_group.nick, True
1067
 
    FROM project_group, group_member, login %(and_projectset_table)s
1068
 
    WHERE project_group.groupid = group_member.groupid
1069
 
      AND group_member.loginid = login.loginid
1070
 
      AND login = %(login)s
1071
 
      %(and_offering)s
1072
 
UNION
1073
 
    SELECT project_group.groupid, groupnm, project_group.nick, False
1074
 
    FROM project_group, group_invitation, login %(and_projectset_table)s
1075
 
    WHERE project_group.groupid = group_invitation.groupid
1076
 
      AND group_invitation.loginid = login.loginid
1077
 
      AND login = %(login)s
1078
 
      %(and_offering)s
1079
 
;""" % {"login": _escape(login), "and_offering": and_offering,
1080
 
        "and_projectset_table": and_projectset_table}
1081
 
        if dry:
1082
 
            return query
1083
 
        # Convert 't' -> True, 'f' -> False
1084
 
        return [(groupid, groupnm, nick, ismember == 't')
1085
 
                for groupid, groupnm, nick, ismember
1086
 
                in self.db.query(query).getresult()]
1087
 
 
1088
 
    def get_offering_info(self, projectsetid, dry=False):
1089
 
        """Takes information from projectset and returns useful information 
1090
 
        about the subject and semester. Returns as a dictionary.
1091
 
        """
1092
 
        query = """\
1093
 
SELECT subjectid, subj_code, subj_name, subj_short_name, url, year, semester, 
1094
 
active
1095
 
FROM subject, offering, semester, project_set
1096
 
WHERE offering.subject = subject.subjectid AND
1097
 
    offering.semesterid = semester.semesterid AND
1098
 
    project_set.offeringid = offering.offeringid AND
1099
 
    project_set.projectsetid = %d;"""%projectsetid
1100
 
        if dry:
1101
 
            return query
1102
 
        return self.db.query(query).dictresult()[0]
1103
 
 
1104
 
    def get_projectgroup_members(self, groupid, dry=False):
1105
 
        """Returns the logins of all students in a project group
1106
 
        """
1107
 
        query = """\
1108
 
SELECT login.login as login, login.fullname as fullname
1109
 
FROM login, group_member
1110
 
WHERE login.loginid = group_member.loginid AND
1111
 
    group_member.groupid = %d
1112
 
ORDER BY login.login;"""%groupid
1113
 
        if dry:
1114
 
            return query
1115
 
        return self.db.query(query).dictresult()
1116
 
 
1117
 
    def get_projectsets_by_offering(self, offeringid, dry=False):
1118
 
        """Returns all the projectsets in a particular offering"""
1119
 
        query = """\
1120
 
SELECT projectsetid, max_students_per_group
1121
 
FROM project_set
1122
 
WHERE project_set.offeringid = %d;"""%offeringid
1123
 
        if dry:
1124
 
            return query
1125
 
        return self.db.query(query).dictresult()
1126
 
 
1127
 
    def get_groups_by_projectset(self, projectsetid, dry=False):
1128
 
        """Returns all the groups that are in a particular projectset"""
1129
 
        query = """\
1130
 
SELECT groupid, groupnm, nick, createdby, epoch
1131
 
FROM project_group
1132
 
WHERE project_group.projectsetid = %d;"""%projectsetid
1133
 
        if dry:
1134
 
            return query
1135
 
        return self.db.query(query).dictresult()
 
375
        query = ("SELECT login FROM login "
 
376
            "WHERE login = '%s' AND passhash = %s;"
 
377
            % (login, _escape(_passhash(password))))
 
378
        if dry: return query
 
379
        result = self.db.query(query)
 
380
        # If one row was returned, succeed.
 
381
        # Otherwise, fail to authenticate.
 
382
        return result.ntuples() == 1
1136
383
 
1137
384
    def close(self):
1138
385
        """Close the DB connection. Do not call any other functions after