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

« back to all changes in this revision

Viewing changes to ivle/database.py

Moved groups over to the new class-based xhtml templating way of being
displayed

Show diffs side-by-side

added added

removed removed

Lines of Context:
31
31
                         Reference, ReferenceSet, Bool, Storm, Desc
32
32
 
33
33
import ivle.conf
34
 
from ivle.worksheet.rst import rst
 
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
 
            'TestCase', 'TestSuite', 'TestSuiteVar'
 
42
            'AlreadyEnrolledError'
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
 
 
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)
 
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)
70
59
 
71
60
def get_store():
72
61
    """
87
76
    login = Unicode()
88
77
    passhash = Unicode()
89
78
    state = Unicode()
90
 
    admin = Bool()
 
79
    rolenm = Unicode()
91
80
    unixid = Int()
92
81
    nick = Unicode()
93
82
    pass_exp = DateTime()
99
88
    studentid = Unicode()
100
89
    settings = Unicode()
101
90
 
 
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
 
102
101
    __init__ = _kwarg_init
103
102
 
104
103
    def __repr__(self):
115
114
            return None
116
115
        return self.hash_password(password) == self.passhash
117
116
 
 
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
 
118
123
    @property
119
124
    def password_expired(self):
120
125
        fieldval = self.pass_exp
125
130
        fieldval = self.acct_exp
126
131
        return fieldval is not None and datetime.datetime.now() > fieldval
127
132
 
128
 
    @property
129
 
    def valid(self):
130
 
        return self.state == 'enabled' and not self.account_expired
131
 
 
132
133
    def _get_enrolments(self, justactive):
133
134
        return Store.of(self).find(Enrolment,
134
135
            Enrolment.user_id == self.id,
195
196
        """
196
197
        return store.find(cls, cls.login == unicode(login)).one()
197
198
 
198
 
    def get_permissions(self, user):
199
 
        if user and user.admin or user is self:
200
 
            return set(['view', 'edit'])
201
 
        else:
202
 
            return set()
203
 
 
204
199
# SUBJECTS AND ENROLMENTS #
205
200
 
206
201
class Subject(Storm):
219
214
    def __repr__(self):
220
215
        return "<%s '%s'>" % (type(self).__name__, self.short_name)
221
216
 
222
 
    def get_permissions(self, user):
223
 
        perms = set()
224
 
        if user is not None:
225
 
            perms.add('view')
226
 
            if user.admin:
227
 
                perms.add('edit')
228
 
        return perms
229
 
 
230
217
class Semester(Storm):
231
218
    __storm_table__ = "semester"
232
219
 
233
220
    id = Int(primary=True, name="semesterid")
234
221
    year = Unicode()
235
222
    semester = Unicode()
236
 
    state = Unicode()
 
223
    active = Bool()
237
224
 
238
225
    offerings = ReferenceSet(id, 'Offering.semester_id')
239
226
 
259
246
                           'User.id')
260
247
    project_sets = ReferenceSet(id, 'ProjectSet.offering_id')
261
248
 
262
 
    worksheets = ReferenceSet(id, 
263
 
        'Worksheet.offering_id', 
264
 
        order_by="seq_no"
265
 
    )
266
 
 
267
249
    __init__ = _kwarg_init
268
250
 
269
251
    def __repr__(self):
270
252
        return "<%s %r in %r>" % (type(self).__name__, self.subject,
271
253
                                  self.semester)
272
254
 
273
 
    def enrol(self, user, role=u'student'):
 
255
    def enrol(self, user):
274
256
        '''Enrol a user in this offering.'''
275
 
        enrolment = Store.of(self).find(Enrolment,
 
257
        # We'll get a horrible database constraint violation error if we try
 
258
        # to add a second enrolment.
 
259
        if Store.of(self).find(Enrolment,
276
260
                               Enrolment.user_id == user.id,
277
 
                               Enrolment.offering_id == self.id).one()
278
 
 
279
 
        if enrolment is None:
280
 
            enrolment = Enrolment(user=user, offering=self)
281
 
            self.enrolments.add(enrolment)
282
 
 
283
 
        enrolment.active = True
284
 
        enrolment.role = role
285
 
 
286
 
    def get_permissions(self, user):
287
 
        perms = set()
288
 
        if user is not None:
289
 
            perms.add('view')
290
 
            if user.admin:
291
 
                perms.add('edit')
292
 
        return perms
 
261
                               Enrolment.offering_id == self.id).count() == 1:
 
262
            raise AlreadyEnrolledError()
 
263
 
 
264
        e = Enrolment(user=user, offering=self, active=True)
 
265
        self.enrolments.add(e)
293
266
 
294
267
class Enrolment(Storm):
295
268
    __storm_table__ = "enrolment"
299
272
    user = Reference(user_id, User.id)
300
273
    offering_id = Int(name="offeringid")
301
274
    offering = Reference(offering_id, Offering.id)
302
 
    role = Unicode()
303
275
    notes = Unicode()
304
276
    active = Bool()
305
277
 
317
289
        return "<%s %r in %r>" % (type(self).__name__, self.user,
318
290
                                  self.offering)
319
291
 
 
292
class AlreadyEnrolledError(Exception):
 
293
    pass
 
294
 
320
295
# PROJECTS #
321
296
 
322
297
class ProjectSet(Storm):
393
368
# WORKSHEETS AND EXERCISES #
394
369
 
395
370
class Exercise(Storm):
396
 
    __storm_table__ = "exercise"
397
 
    id = Unicode(primary=True, name="identifier")
398
 
    name = Unicode()
399
 
    description = Unicode()
400
 
    partial = Unicode()
401
 
    solution = Unicode()
402
 
    include = Unicode()
403
 
    num_rows = Int()
 
371
    # Note: Table "problem" is called "Exercise" in the Object layer, since
 
372
    # it's called that everywhere else.
 
373
    __storm_table__ = "problem"
 
374
 
 
375
    id = Int(primary=True, name="problemid")
 
376
    name = Unicode(name="identifier")
 
377
    spec = Unicode()
404
378
 
405
379
    worksheets = ReferenceSet(id,
406
380
        'WorksheetExercise.exercise_id',
407
381
        'WorksheetExercise.worksheet_id',
408
382
        'Worksheet.id'
409
383
    )
410
 
    
411
 
    test_suites = ReferenceSet(id, 
412
 
        'TestSuite.exercise_id',
413
 
        order_by='seq_no')
414
384
 
415
385
    __init__ = _kwarg_init
416
386
 
417
387
    def __repr__(self):
418
388
        return "<%s %s>" % (type(self).__name__, self.name)
419
389
 
420
 
    def get_permissions(self, user):
421
 
        perms = set()
422
 
        if user is not None:
423
 
            if user.admin:
424
 
                perms.add('edit')
425
 
                perms.add('view')
426
 
        return perms
 
390
    @classmethod
 
391
    def get_by_name(cls, store, name):
 
392
        """
 
393
        Get the Exercise from the db associated with a given store and name.
 
394
        If the exercise is not in the database, creates it and inserts it
 
395
        automatically.
 
396
        """
 
397
        ex = store.find(cls, cls.name == unicode(name)).one()
 
398
        if ex is not None:
 
399
            return ex
 
400
        ex = Exercise(name=unicode(name))
 
401
        store.add(ex)
 
402
        store.commit()
 
403
        return ex
427
404
 
428
405
class Worksheet(Storm):
429
406
    __storm_table__ = "worksheet"
430
407
 
431
408
    id = Int(primary=True, name="worksheetid")
432
 
    offering_id = Int(name="offeringid")
433
 
    identifier = Unicode()
434
 
    name = Unicode()
 
409
    # XXX subject is not linked to a Subject object. This is a property of
 
410
    # the database, and will be refactored.
 
411
    subject = Unicode()
 
412
    name = Unicode(name="identifier")
435
413
    assessable = Bool()
436
 
    data = Unicode()
437
 
    seq_no = Int()
438
 
    format = Unicode()
439
 
 
440
 
    attempts = ReferenceSet(id, "ExerciseAttempt.worksheetid")
441
 
    offering = Reference(offering_id, 'Offering.id')
442
 
 
443
 
    all_worksheet_exercises = ReferenceSet(id,
 
414
    mtime = DateTime()
 
415
 
 
416
    exercises = ReferenceSet(id,
 
417
        'WorksheetExercise.worksheet_id',
 
418
        'WorksheetExercise.exercise_id',
 
419
        Exercise.id)
 
420
    # Use worksheet_exercises to get access to the WorksheetExercise objects
 
421
    # binding worksheets to exercises. This is required to access the
 
422
    # "optional" field.
 
423
    worksheet_exercises = ReferenceSet(id,
444
424
        'WorksheetExercise.worksheet_id')
445
425
 
446
 
    # Use worksheet_exercises to get access to the *active* WorksheetExercise
447
 
    # objects binding worksheets to exercises. This is required to access the
448
 
    # "optional" field.
449
 
 
450
 
    @property
451
 
    def worksheet_exercises(self):
452
 
        return self.all_worksheet_exercises.find(active=True)
453
 
 
454
426
    __init__ = _kwarg_init
455
427
 
456
428
    def __repr__(self):
476
448
        """
477
449
        store.find(WorksheetExercise,
478
450
            WorksheetExercise.worksheet == self).remove()
479
 
            
480
 
    def get_permissions(self, user):
481
 
        return self.offering.get_permissions(user)
482
 
    
483
 
    def get_xml(self):
484
 
        """Returns the xml of this worksheet, converts from rst if required."""
485
 
        if self.format == u'rst':
486
 
            ws_xml = '<worksheet>' + rst(self.data) + '</worksheet>'
487
 
            return ws_xml
488
 
        else:
489
 
            return self.data
490
451
 
491
452
class WorksheetExercise(Storm):
492
 
    __storm_table__ = "worksheet_exercise"
493
 
    
494
 
    id = Int(primary=True, name="ws_ex_id")
 
453
    __storm_table__ = "worksheet_problem"
 
454
    __storm_primary__ = "worksheet_id", "exercise_id"
495
455
 
496
456
    worksheet_id = Int(name="worksheetid")
497
457
    worksheet = Reference(worksheet_id, Worksheet.id)
498
 
    exercise_id = Unicode(name="exerciseid")
 
458
    exercise_id = Int(name="problemid")
499
459
    exercise = Reference(exercise_id, Exercise.id)
500
460
    optional = Bool()
501
 
    active = Bool()
502
 
    seq_no = Int()
503
 
    
504
 
    saves = ReferenceSet(id, "ExerciseSave.ws_ex_id")
505
 
    attempts = ReferenceSet(id, "ExerciseAttempt.ws_ex_id")
506
461
 
507
462
    __init__ = _kwarg_init
508
463
 
509
464
    def __repr__(self):
510
465
        return "<%s %s in %s>" % (type(self).__name__, self.exercise.name,
511
 
                                  self.worksheet.identifier)
 
466
                                  self.worksheet.name)
512
467
 
513
468
class ExerciseSave(Storm):
514
469
    """
519
474
    ExerciseSave may be extended with additional semantics (such as
520
475
    ExerciseAttempt).
521
476
    """
522
 
    __storm_table__ = "exercise_save"
523
 
    __storm_primary__ = "ws_ex_id", "user_id"
524
 
 
525
 
    ws_ex_id = Int(name="ws_ex_id")
526
 
    worksheet_exercise = Reference(ws_ex_id, "WorksheetExercise.id")
527
 
 
 
477
    __storm_table__ = "problem_save"
 
478
    __storm_primary__ = "exercise_id", "user_id", "date"
 
479
 
 
480
    exercise_id = Int(name="problemid")
 
481
    exercise = Reference(exercise_id, Exercise.id)
528
482
    user_id = Int(name="loginid")
529
483
    user = Reference(user_id, User.id)
530
484
    date = DateTime()
549
503
        they won't count (either as a penalty or success), but will still be
550
504
        stored.
551
505
    """
552
 
    __storm_table__ = "exercise_attempt"
553
 
    __storm_primary__ = "ws_ex_id", "user_id", "date"
 
506
    __storm_table__ = "problem_attempt"
 
507
    __storm_primary__ = "exercise_id", "user_id", "date"
554
508
 
555
509
    # The "text" field is the same but has a different name in the DB table
556
510
    # for some reason.
557
511
    text = Unicode(name="attempt")
558
512
    complete = Bool()
559
513
    active = Bool()
560
 
    
561
 
    def get_permissions(self, user):
562
 
        return set(['view']) if user is self.user else set()
563
 
  
564
 
class TestSuite(Storm):
565
 
    """A Testsuite acts as a container for the test cases of an exercise."""
566
 
    __storm_table__ = "test_suite"
567
 
    __storm_primary__ = "exercise_id", "suiteid"
568
 
    
569
 
    suiteid = Int()
570
 
    exercise_id = Unicode(name="exerciseid")
571
 
    description = Unicode()
572
 
    seq_no = Int()
573
 
    function = Unicode()
574
 
    stdin = Unicode()
575
 
    exercise = Reference(exercise_id, Exercise.id)
576
 
    test_cases = ReferenceSet(suiteid, 'TestCase.suiteid', order_by="seq_no")
577
 
    variables = ReferenceSet(suiteid, 'TestSuiteVar.suiteid', order_by='arg_no')
578
 
 
579
 
class TestCase(Storm):
580
 
    """A TestCase is a member of a TestSuite.
581
 
    
582
 
    It contains the data necessary to check if an exercise is correct"""
583
 
    __storm_table__ = "test_case"
584
 
    __storm_primary__ = "testid", "suiteid"
585
 
    
586
 
    testid = Int()
587
 
    suiteid = Int()
588
 
    suite = Reference(suiteid, "TestSuite.suiteid")
589
 
    passmsg = Unicode()
590
 
    failmsg = Unicode()
591
 
    test_default = Unicode()
592
 
    seq_no = Int()
593
 
    
594
 
    parts = ReferenceSet(testid, "TestCasePart.testid")
595
 
    
596
 
    __init__ = _kwarg_init
597
 
 
598
 
class TestSuiteVar(Storm):
599
 
    """A container for the arguments of a Test Suite"""
600
 
    __storm_table__ = "suite_variable"
601
 
    __storm_primary__ = "varid"
602
 
    
603
 
    varid = Int()
604
 
    suiteid = Int()
605
 
    var_name = Unicode()
606
 
    var_value = Unicode()
607
 
    var_type = Unicode()
608
 
    arg_no = Int()
609
 
    
610
 
    suite = Reference(suiteid, "TestSuite.suiteid")
611
 
    
612
 
    __init__ = _kwarg_init
613
 
    
614
 
class TestCasePart(Storm):
615
 
    """A container for the test elements of a Test Case"""
616
 
    __storm_table__ = "test_case_part"
617
 
    __storm_primary__ = "partid"
618
 
    
619
 
    partid = Int()
620
 
    testid = Int()
621
 
    
622
 
    part_type = Unicode()
623
 
    test_type = Unicode()
624
 
    data = Unicode()
625
 
    filename = Unicode()
626
 
    
627
 
    test = Reference(testid, "TestCase.testid")
628
 
    
629
 
    __init__ = _kwarg_init