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

« back to all changes in this revision

Viewing changes to ivle/database.py

  • Committer: William Grant
  • Date: 2009-02-27 04:50:09 UTC
  • Revision ID: grantw@unimelb.edu.au-20090227045009-eixyhqwe85xp1gj6
python-console: Fix Google Code issue 105. Multi-line indented blocks are now
possible again.

Show diffs side-by-side

added added

removed removed

Lines of Context:
29
29
 
30
30
from storm.locals import create_database, Store, Int, Unicode, DateTime, \
31
31
                         Reference, ReferenceSet, Bool, Storm, Desc
 
32
from storm.exceptions import NotOneError
32
33
 
33
34
import ivle.conf
34
 
import ivle.caps
35
35
 
36
36
__all__ = ['get_store',
37
37
            'User',
39
39
            'ProjectSet', 'Project', 'ProjectGroup', 'ProjectGroupMembership',
40
40
            'Exercise', 'Worksheet', 'WorksheetExercise',
41
41
            'ExerciseSave', 'ExerciseAttempt',
42
 
            'AlreadyEnrolledError', 'TestCase', 'TestSuite'
 
42
            'TestCase', 'TestSuite', 'TestSuiteVar'
43
43
        ]
44
44
 
45
45
def _kwarg_init(self, **kwargs):
53
53
    """
54
54
    Returns the Storm connection string, generated from the conf file.
55
55
    """
56
 
    return "postgres://%s:%s@%s:%d/%s" % (ivle.conf.db_user,
57
 
        ivle.conf.db_password, ivle.conf.db_host, ivle.conf.db_port,
58
 
        ivle.conf.db_dbname)
 
56
 
 
57
    clusterstr = ''
 
58
    if ivle.conf.db_user:
 
59
        clusterstr += ivle.conf.db_user
 
60
        if ivle.conf.db_password:
 
61
            clusterstr += ':' + ivle.conf.db_password
 
62
        clusterstr += '@'
 
63
 
 
64
    host = ivle.conf.db_host or 'localhost'
 
65
    port = ivle.conf.db_port or 5432
 
66
 
 
67
    clusterstr += '%s:%d' % (host, port)
 
68
 
 
69
    return "postgres://%s/%s" % (clusterstr, ivle.conf.db_dbname)
59
70
 
60
71
def get_store():
61
72
    """
76
87
    login = Unicode()
77
88
    passhash = Unicode()
78
89
    state = Unicode()
79
 
    rolenm = Unicode()
 
90
    admin = Bool()
80
91
    unixid = Int()
81
92
    nick = Unicode()
82
93
    pass_exp = DateTime()
88
99
    studentid = Unicode()
89
100
    settings = Unicode()
90
101
 
91
 
    def _get_role(self):
92
 
        if self.rolenm is None:
93
 
            return None
94
 
        return ivle.caps.Role(self.rolenm)
95
 
    def _set_role(self, value):
96
 
        if not isinstance(value, ivle.caps.Role):
97
 
            raise TypeError("role must be an ivle.caps.Role")
98
 
        self.rolenm = unicode(value)
99
 
    role = property(_get_role, _set_role)
100
 
 
101
102
    __init__ = _kwarg_init
102
103
 
103
104
    def __repr__(self):
114
115
            return None
115
116
        return self.hash_password(password) == self.passhash
116
117
 
117
 
    def hasCap(self, capability):
118
 
        """Given a capability (which is a Role object), returns True if this
119
 
        User has that capability, False otherwise.
120
 
        """
121
 
        return self.role.hasCap(capability)
122
 
 
123
118
    @property
124
119
    def password_expired(self):
125
120
        fieldval = self.pass_exp
130
125
        fieldval = self.acct_exp
131
126
        return fieldval is not None and datetime.datetime.now() > fieldval
132
127
 
 
128
    @property
 
129
    def valid(self):
 
130
        return self.state == 'enabled' and not self.account_expired
 
131
 
133
132
    def _get_enrolments(self, justactive):
134
133
        return Store.of(self).find(Enrolment,
135
134
            Enrolment.user_id == self.id,
197
196
        return store.find(cls, cls.login == unicode(login)).one()
198
197
 
199
198
    def get_permissions(self, user):
200
 
        if user and user.rolenm == 'admin' or user is self:
 
199
        if user and user.admin or user is self:
201
200
            return set(['view', 'edit'])
202
201
        else:
203
202
            return set()
224
223
        perms = set()
225
224
        if user is not None:
226
225
            perms.add('view')
227
 
        if user.rolenm == 'admin':
228
 
            perms.add('edit')
 
226
            if user.admin:
 
227
                perms.add('edit')
229
228
        return perms
230
229
 
231
230
class Semester(Storm):
234
233
    id = Int(primary=True, name="semesterid")
235
234
    year = Unicode()
236
235
    semester = Unicode()
237
 
    active = Bool()
 
236
    state = Unicode()
238
237
 
239
238
    offerings = ReferenceSet(id, 'Offering.semester_id')
 
239
    enrolments = ReferenceSet(id,
 
240
                              'Offering.semester_id',
 
241
                              'Offering.id',
 
242
                              'Enrolment.offering_id')
240
243
 
241
244
    __init__ = _kwarg_init
242
245
 
260
263
                           'User.id')
261
264
    project_sets = ReferenceSet(id, 'ProjectSet.offering_id')
262
265
 
263
 
    worksheets = ReferenceSet(id, 'Worksheet.offering_id')
 
266
    worksheets = ReferenceSet(id, 
 
267
        'Worksheet.offering_id', 
 
268
        order_by="Worksheet.seq_no"
 
269
    )
264
270
 
265
271
    __init__ = _kwarg_init
266
272
 
268
274
        return "<%s %r in %r>" % (type(self).__name__, self.subject,
269
275
                                  self.semester)
270
276
 
271
 
    def enrol(self, user):
 
277
    def enrol(self, user, role=u'student'):
272
278
        '''Enrol a user in this offering.'''
273
 
        # We'll get a horrible database constraint violation error if we try
274
 
        # to add a second enrolment.
275
 
        if Store.of(self).find(Enrolment,
276
 
                               Enrolment.user_id == user.id,
277
 
                               Enrolment.offering_id == self.id).count() == 1:
278
 
            raise AlreadyEnrolledError()
279
 
 
280
 
        e = Enrolment(user=user, offering=self, active=True)
281
 
        self.enrolments.add(e)
 
279
        enrolment = Store.of(self).find(Enrolment,
 
280
                               Enrolment.user_id == user.id,
 
281
                               Enrolment.offering_id == self.id).one()
 
282
 
 
283
        if enrolment is None:
 
284
            enrolment = Enrolment(user=user, offering=self)
 
285
            self.enrolments.add(enrolment)
 
286
 
 
287
        enrolment.active = True
 
288
        enrolment.role = role
 
289
 
 
290
    def unenrol(self, user):
 
291
        '''Unenrol a user from this offering.'''
 
292
        enrolment = Store.of(self).find(Enrolment,
 
293
                               Enrolment.user_id == user.id,
 
294
                               Enrolment.offering_id == self.id).one()
 
295
        Store.of(enrolment).remove(enrolment)
 
296
 
 
297
    def get_permissions(self, user):
 
298
        perms = set()
 
299
        if user is not None:
 
300
            enrolment = self.get_enrolment(user)
 
301
            if enrolment or user.admin:
 
302
                perms.add('view')
 
303
            if (enrolment and enrolment.role in (u'tutor', u'lecturer')) \
 
304
               or user.admin:
 
305
                perms.add('edit')
 
306
        return perms
 
307
 
 
308
    def get_enrolment(self, user):
 
309
        try:
 
310
            enrolment = self.enrolments.find(user=user).one()
 
311
        except NotOneError:
 
312
            enrolment = None
 
313
 
 
314
        return enrolment
282
315
 
283
316
class Enrolment(Storm):
284
317
    __storm_table__ = "enrolment"
288
321
    user = Reference(user_id, User.id)
289
322
    offering_id = Int(name="offeringid")
290
323
    offering = Reference(offering_id, Offering.id)
 
324
    role = Unicode()
291
325
    notes = Unicode()
292
326
    active = Bool()
293
327
 
305
339
        return "<%s %r in %r>" % (type(self).__name__, self.user,
306
340
                                  self.offering)
307
341
 
308
 
class AlreadyEnrolledError(Exception):
309
 
    pass
310
 
 
311
342
# PROJECTS #
312
343
 
313
344
class ProjectSet(Storm):
384
415
# WORKSHEETS AND EXERCISES #
385
416
 
386
417
class Exercise(Storm):
387
 
    # Note: Table "problem" is called "Exercise" in the Object layer, since
388
 
    # it's called that everywhere else.
389
 
    __storm_table__ = "problem"
390
 
#TODO: Add in a field for the user-friendly identifier
 
418
    __storm_table__ = "exercise"
391
419
    id = Unicode(primary=True, name="identifier")
392
420
    name = Unicode()
393
421
    description = Unicode()
409
437
    def __repr__(self):
410
438
        return "<%s %s>" % (type(self).__name__, self.name)
411
439
 
412
 
    @classmethod
413
 
    def get_by_name(cls, store, name):
414
 
        """
415
 
        Get the Exercise from the db associated with a given store and name.
416
 
        If the exercise is not in the database, creates it and inserts it
417
 
        automatically.
418
 
        """
419
 
        ex = store.find(cls, cls.name == unicode(name)).one()
420
 
        if ex is not None:
421
 
            return ex
422
 
        ex = Exercise(name=unicode(name))
423
 
        store.add(ex)
424
 
        store.commit()
425
 
        return ex
 
440
    def get_permissions(self, user):
 
441
        perms = set()
 
442
        if user is not None:
 
443
            if user.admin:
 
444
                perms.add('edit')
 
445
                perms.add('view')
 
446
        return perms
426
447
 
427
448
class Worksheet(Storm):
428
449
    __storm_table__ = "worksheet"
429
450
 
430
451
    id = Int(primary=True, name="worksheetid")
431
 
    # XXX subject is not linked to a Subject object. This is a property of
432
 
    # the database, and will be refactored.
433
 
    subject = Unicode()
434
452
    offering_id = Int(name="offeringid")
435
 
    name = Unicode(name="identifier")
 
453
    identifier = Unicode()
 
454
    name = Unicode()
436
455
    assessable = Bool()
437
 
    mtime = DateTime()
438
 
 
439
 
    offering = Reference (offeringid, 'Offering.id')
440
 
 
441
 
    exercises = ReferenceSet(id,
442
 
        'WorksheetExercise.worksheet_id',
443
 
        'WorksheetExercise.exercise_id',
444
 
        Exercise.id)
445
 
    # Use worksheet_exercises to get access to the WorksheetExercise objects
446
 
    # binding worksheets to exercises. This is required to access the
 
456
    data = Unicode()
 
457
    seq_no = Int()
 
458
    format = Unicode()
 
459
 
 
460
    attempts = ReferenceSet(id, "ExerciseAttempt.worksheetid")
 
461
    offering = Reference(offering_id, 'Offering.id')
 
462
 
 
463
    all_worksheet_exercises = ReferenceSet(id,
 
464
        'WorksheetExercise.worksheet_id')
 
465
 
 
466
    # Use worksheet_exercises to get access to the *active* WorksheetExercise
 
467
    # objects binding worksheets to exercises. This is required to access the
447
468
    # "optional" field.
448
 
    worksheet_exercises = ReferenceSet(id,
449
 
        'WorksheetExercise.worksheet_id')
450
 
        
 
469
    @property
 
470
    def worksheet_exercises(self):
 
471
        return self.all_worksheet_exercises.find(active=True)
451
472
 
452
473
    __init__ = _kwarg_init
453
474
 
474
495
        """
475
496
        store.find(WorksheetExercise,
476
497
            WorksheetExercise.worksheet == self).remove()
 
498
            
 
499
    def get_permissions(self, user):
 
500
        return self.offering.get_permissions(user)
477
501
 
478
502
class WorksheetExercise(Storm):
479
 
    __storm_table__ = "worksheet_problem"
480
 
    __storm_primary__ = "worksheet_id", "exercise_id"
 
503
    __storm_table__ = "worksheet_exercise"
 
504
    
 
505
    id = Int(primary=True, name="ws_ex_id")
481
506
 
482
507
    worksheet_id = Int(name="worksheetid")
483
508
    worksheet = Reference(worksheet_id, Worksheet.id)
484
 
    exercise_id = Unicode(name="problemid")
 
509
    exercise_id = Unicode(name="exerciseid")
485
510
    exercise = Reference(exercise_id, Exercise.id)
486
511
    optional = Bool()
 
512
    active = Bool()
 
513
    seq_no = Int()
 
514
    
 
515
    saves = ReferenceSet(id, "ExerciseSave.ws_ex_id")
 
516
    attempts = ReferenceSet(id, "ExerciseAttempt.ws_ex_id")
487
517
 
488
518
    __init__ = _kwarg_init
489
519
 
490
520
    def __repr__(self):
491
521
        return "<%s %s in %s>" % (type(self).__name__, self.exercise.name,
492
 
                                  self.worksheet.name)
 
522
                                  self.worksheet.identifier)
 
523
 
 
524
    def get_permissions(self, user):
 
525
        return self.worksheet.get_permissions(user)
493
526
 
494
527
class ExerciseSave(Storm):
495
528
    """
500
533
    ExerciseSave may be extended with additional semantics (such as
501
534
    ExerciseAttempt).
502
535
    """
503
 
    __storm_table__ = "problem_save"
504
 
    __storm_primary__ = "exercise_id", "user_id", "date"
505
 
 
506
 
    exercise_id = Unicode(name="problemid")
507
 
    exercise = Reference(exercise_id, Exercise.id)
 
536
    __storm_table__ = "exercise_save"
 
537
    __storm_primary__ = "ws_ex_id", "user_id"
 
538
 
 
539
    ws_ex_id = Int(name="ws_ex_id")
 
540
    worksheet_exercise = Reference(ws_ex_id, "WorksheetExercise.id")
 
541
 
508
542
    user_id = Int(name="loginid")
509
543
    user = Reference(user_id, User.id)
510
544
    date = DateTime()
511
545
    text = Unicode()
512
 
    worksheetid = Int()
513
 
    worksheet = Reference(worksheetid, Worksheet.id)
514
546
 
515
547
    __init__ = _kwarg_init
516
548
 
531
563
        they won't count (either as a penalty or success), but will still be
532
564
        stored.
533
565
    """
534
 
    __storm_table__ = "problem_attempt"
535
 
    __storm_primary__ = "exercise_id", "user_id", "date"
 
566
    __storm_table__ = "exercise_attempt"
 
567
    __storm_primary__ = "ws_ex_id", "user_id", "date"
536
568
 
537
569
    # The "text" field is the same but has a different name in the DB table
538
570
    # for some reason.
549
581
    __storm_primary__ = "exercise_id", "suiteid"
550
582
    
551
583
    suiteid = Int()
552
 
    exercise_id = Unicode(name="problemid")
 
584
    exercise_id = Unicode(name="exerciseid")
 
585
    description = Unicode()
 
586
    seq_no = Int()
 
587
    function = Unicode()
 
588
    stdin = Unicode()
553
589
    exercise = Reference(exercise_id, Exercise.id)
554
590
    test_cases = ReferenceSet(suiteid, 'TestCase.suiteid')
555
 
    description = Unicode()
556
 
    seq_no = Int()
 
591
    variables = ReferenceSet(suiteid, 'TestSuiteVar.suiteid')
557
592
 
558
593
class TestCase(Storm):
559
594
    """A TestCase is a member of a TestSuite.
564
599
    
565
600
    testid = Int()
566
601
    suiteid = Int()
567
 
    suite = Reference(suiteid, TestSuite.suiteid)
 
602
    suite = Reference(suiteid, "TestSuite.suiteid")
568
603
    passmsg = Unicode()
569
604
    failmsg = Unicode()
570
 
    init = Unicode()
571
 
    code_type = Unicode()
572
 
    code = Unicode()
573
 
    testtype = Unicode()
 
605
    test_default = Unicode()
574
606
    seq_no = Int()
575
607
    
 
608
    parts = ReferenceSet(testid, "TestCasePart.testid")
 
609
    
 
610
    __init__ = _kwarg_init
 
611
 
 
612
class TestSuiteVar(Storm):
 
613
    """A container for the arguments of a Test Suite"""
 
614
    __storm_table__ = "suite_variable"
 
615
    __storm_primary__ = "varid"
 
616
    
 
617
    varid = Int()
 
618
    suiteid = Int()
 
619
    var_name = Unicode()
 
620
    var_value = Unicode()
 
621
    var_type = Unicode()
 
622
    arg_no = Int()
 
623
    
 
624
    suite = Reference(suiteid, "TestSuite.suiteid")
 
625
    
 
626
    __init__ = _kwarg_init
 
627
    
 
628
class TestCasePart(Storm):
 
629
    """A container for the test elements of a Test Case"""
 
630
    __storm_table__ = "test_case_part"
 
631
    __storm_primary__ = "partid"
 
632
    
 
633
    partid = Int()
 
634
    testid = Int()
 
635
    
 
636
    part_type = Unicode()
 
637
    test_type = Unicode()
 
638
    data = Unicode()
 
639
    filename = Unicode()
 
640
    
 
641
    test = Reference(testid, "TestCase.testid")
 
642
    
576
643
    __init__ = _kwarg_init