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

« back to all changes in this revision

Viewing changes to ivle/database.py

  • Committer: me at id
  • Date: 2009-01-15 06:11:32 UTC
  • mto: This revision was merged to the branch mainline in revision 1090.
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:branches%2Fstorm:1164
ivle.db: Remove get_enrolment and get_subjects_status. They're unused.

Show diffs side-by-side

added added

removed removed

Lines of Context:
33
33
import ivle.conf
34
34
import ivle.caps
35
35
 
36
 
__all__ = ['get_store',
37
 
            'User',
38
 
            'Subject', 'Semester', 'Offering', 'Enrolment',
39
 
            'ProjectSet', 'Project', 'ProjectGroup', 'ProjectGroupMembership',
40
 
            'Exercise', 'Worksheet', 'WorksheetExercise',
41
 
            'ExerciseSave', 'ExerciseAttempt',
42
 
            'AlreadyEnrolledError', 'TestCase', 'TestSuite', 'TestSuiteVar'
43
 
        ]
44
 
 
45
36
def _kwarg_init(self, **kwargs):
46
37
    for k,v in kwargs.items():
47
 
        if k.startswith('_') or not hasattr(self.__class__, k):
 
38
        if k.startswith('_') or not hasattr(self, k):
48
39
            raise TypeError("%s got an unexpected keyword argument '%s'"
49
 
                % (self.__class__.__name__, k))
 
40
                % self.__class__.__name__, k)
50
41
        setattr(self, k, v)
51
42
 
52
43
def get_conn_string():
53
44
    """
54
45
    Returns the Storm connection string, generated from the conf file.
55
46
    """
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)
 
47
    return "postgres://%s:%s@%s:%d/%s" % (ivle.conf.db_user,
 
48
        ivle.conf.db_password, ivle.conf.db_host, ivle.conf.db_port,
 
49
        ivle.conf.db_dbname)
70
50
 
71
51
def get_store():
72
52
    """
75
55
    """
76
56
    return Store(create_database(get_conn_string()))
77
57
 
78
 
# USERS #
79
 
 
80
58
class User(Storm):
81
59
    """
82
60
    Represents an IVLE user.
141
119
        fieldval = self.acct_exp
142
120
        return fieldval is not None and datetime.datetime.now() > fieldval
143
121
 
144
 
    @property
145
 
    def valid(self):
146
 
        return self.state == 'enabled' and not self.account_expired
147
 
 
148
122
    def _get_enrolments(self, justactive):
149
123
        return Store.of(self).find(Enrolment,
150
124
            Enrolment.user_id == self.id,
157
131
                Desc(Subject.code)
158
132
            )
159
133
 
160
 
    def _set_password(self, password):
161
 
        if password is None:
162
 
            self.passhash = None
163
 
        else:
164
 
            self.passhash = unicode(User.hash_password(password))
165
 
    password = property(fset=_set_password)
166
 
 
167
134
    @property
168
135
    def subjects(self):
169
136
        return Store.of(self).find(Subject,
172
139
            Offering.id == Enrolment.offering_id,
173
140
            Subject.id == Offering.subject_id).config(distinct=True)
174
141
 
175
 
    # TODO: Invitations should be listed too?
176
 
    def get_groups(self, offering=None):
177
 
        preds = [
178
 
            ProjectGroupMembership.user_id == self.id,
179
 
            ProjectGroup.id == ProjectGroupMembership.project_group_id,
180
 
        ]
181
 
        if offering:
182
 
            preds.extend([
183
 
                ProjectSet.offering_id == offering.id,
184
 
                ProjectGroup.project_set_id == ProjectSet.id,
185
 
            ])
186
 
        return Store.of(self).find(ProjectGroup, *preds)
187
 
 
188
 
    @property
189
 
    def groups(self):
190
 
        return self.get_groups()
191
 
 
192
142
    @property
193
143
    def active_enrolments(self):
194
144
        '''A sanely ordered list of the user's active enrolments.'''
211
161
        """
212
162
        return store.find(cls, cls.login == unicode(login)).one()
213
163
 
214
 
    def get_permissions(self, user):
215
 
        if user and user.rolenm == 'admin' or user is self:
216
 
            return set(['view', 'edit'])
217
 
        else:
218
 
            return set()
219
 
 
220
 
# SUBJECTS AND ENROLMENTS #
221
 
 
222
164
class Subject(Storm):
223
165
    __storm_table__ = "subject"
224
166
 
235
177
    def __repr__(self):
236
178
        return "<%s '%s'>" % (type(self).__name__, self.short_name)
237
179
 
238
 
    def get_permissions(self, user):
239
 
        perms = set()
240
 
        if user is not None:
241
 
            perms.add('view')
242
 
            if user.rolenm == 'admin':
243
 
                perms.add('edit')
244
 
        return perms
245
 
 
246
180
class Semester(Storm):
247
181
    __storm_table__ = "semester"
248
182
 
269
203
    groups_student_permissions = Unicode()
270
204
 
271
205
    enrolments = ReferenceSet(id, 'Enrolment.offering_id')
272
 
    members = ReferenceSet(id,
273
 
                           'Enrolment.offering_id',
274
 
                           'Enrolment.user_id',
275
 
                           'User.id')
276
 
    project_sets = ReferenceSet(id, 'ProjectSet.offering_id')
277
 
 
278
 
    worksheets = ReferenceSet(id, 
279
 
        'Worksheet.offering_id', 
280
 
        order_by="Worksheet.seq_no"
281
 
    )
282
206
 
283
207
    __init__ = _kwarg_init
284
208
 
286
210
        return "<%s %r in %r>" % (type(self).__name__, self.subject,
287
211
                                  self.semester)
288
212
 
289
 
    def enrol(self, user):
290
 
        '''Enrol a user in this offering.'''
291
 
        # We'll get a horrible database constraint violation error if we try
292
 
        # to add a second enrolment.
293
 
        if Store.of(self).find(Enrolment,
294
 
                               Enrolment.user_id == user.id,
295
 
                               Enrolment.offering_id == self.id).count() == 1:
296
 
            raise AlreadyEnrolledError()
297
 
 
298
 
        e = Enrolment(user=user, offering=self, active=True)
299
 
        self.enrolments.add(e)
300
 
 
301
 
    def get_permissions(self, user):
302
 
        perms = set()
303
 
        if user is not None:
304
 
            perms.add('view')
305
 
            if user.rolenm in ('admin', 'lecturer'):
306
 
                perms.add('edit')
307
 
        return perms
308
 
 
309
213
class Enrolment(Storm):
310
214
    __storm_table__ = "enrolment"
311
215
    __storm_primary__ = "user_id", "offering_id"
317
221
    notes = Unicode()
318
222
    active = Bool()
319
223
 
320
 
    @property
321
 
    def groups(self):
322
 
        return Store.of(self).find(ProjectGroup,
323
 
                ProjectSet.offering_id == self.offering.id,
324
 
                ProjectGroup.project_set_id == ProjectSet.id,
325
 
                ProjectGroupMembership.project_group_id == ProjectGroup.id,
326
 
                ProjectGroupMembership.user_id == self.user.id)
327
 
 
328
 
    __init__ = _kwarg_init
329
 
 
330
 
    def __repr__(self):
331
 
        return "<%s %r in %r>" % (type(self).__name__, self.user,
332
 
                                  self.offering)
333
 
 
334
 
class AlreadyEnrolledError(Exception):
335
 
    pass
336
 
 
337
 
# PROJECTS #
338
 
 
339
 
class ProjectSet(Storm):
340
 
    __storm_table__ = "project_set"
341
 
 
342
 
    id = Int(name="projectsetid", primary=True)
343
 
    offering_id = Int(name="offeringid")
344
 
    offering = Reference(offering_id, Offering.id)
345
 
    max_students_per_group = Int()
346
 
 
347
 
    projects = ReferenceSet(id, 'Project.project_set_id')
348
 
    project_groups = ReferenceSet(id, 'ProjectGroup.project_set_id')
349
 
 
350
 
    __init__ = _kwarg_init
351
 
 
352
 
    def __repr__(self):
353
 
        return "<%s %d in %r>" % (type(self).__name__, self.id,
354
 
                                  self.offering)
355
 
 
356
 
class Project(Storm):
357
 
    __storm_table__ = "project"
358
 
 
359
 
    id = Int(name="projectid", primary=True)
360
 
    synopsis = Unicode()
361
 
    url = Unicode()
362
 
    project_set_id = Int(name="projectsetid")
363
 
    project_set = Reference(project_set_id, ProjectSet.id)
364
 
    deadline = DateTime()
365
 
 
366
 
    __init__ = _kwarg_init
367
 
 
368
 
    def __repr__(self):
369
 
        return "<%s '%s' in %r>" % (type(self).__name__, self.synopsis,
370
 
                                  self.project_set.offering)
371
 
 
372
 
class ProjectGroup(Storm):
373
 
    __storm_table__ = "project_group"
374
 
 
375
 
    id = Int(name="groupid", primary=True)
376
 
    name = Unicode(name="groupnm")
377
 
    project_set_id = Int(name="projectsetid")
378
 
    project_set = Reference(project_set_id, ProjectSet.id)
379
 
    nick = Unicode()
380
 
    created_by_id = Int(name="createdby")
381
 
    created_by = Reference(created_by_id, User.id)
382
 
    epoch = DateTime()
383
 
 
384
 
    members = ReferenceSet(id,
385
 
                           "ProjectGroupMembership.project_group_id",
386
 
                           "ProjectGroupMembership.user_id",
387
 
                           "User.id")
388
 
 
389
 
    __init__ = _kwarg_init
390
 
 
391
 
    def __repr__(self):
392
 
        return "<%s %s in %r>" % (type(self).__name__, self.name,
393
 
                                  self.project_set.offering)
394
 
 
395
 
class ProjectGroupMembership(Storm):
396
 
    __storm_table__ = "group_member"
397
 
    __storm_primary__ = "user_id", "project_group_id"
398
 
 
399
 
    user_id = Int(name="loginid")
400
 
    user = Reference(user_id, User.id)
401
 
    project_group_id = Int(name="groupid")
402
 
    project_group = Reference(project_group_id, ProjectGroup.id)
403
 
 
404
 
    __init__ = _kwarg_init
405
 
 
406
 
    def __repr__(self):
407
 
        return "<%s %r in %r>" % (type(self).__name__, self.user,
408
 
                                  self.project_group)
409
 
 
410
 
# WORKSHEETS AND EXERCISES #
411
 
 
412
 
class Exercise(Storm):
413
 
    __storm_table__ = "exercise"
414
 
    id = Unicode(primary=True, name="identifier")
415
 
    name = Unicode()
416
 
    description = Unicode()
417
 
    partial = Unicode()
418
 
    solution = Unicode()
419
 
    include = Unicode()
420
 
    num_rows = Int()
421
 
 
422
 
    worksheets = ReferenceSet(id,
423
 
        'WorksheetExercise.exercise_id',
424
 
        'WorksheetExercise.worksheet_id',
425
 
        'Worksheet.id'
426
 
    )
427
 
    
428
 
    test_suites = ReferenceSet(id, 'TestSuite.exercise_id')
429
 
 
430
 
    __init__ = _kwarg_init
431
 
 
432
 
    def __repr__(self):
433
 
        return "<%s %s>" % (type(self).__name__, self.name)
434
 
 
435
 
    def get_permissions(self, user):
436
 
        perms = set()
437
 
        if user is not None:
438
 
            if user.rolenm in ('admin', 'lecturer'):
439
 
                perms.add('edit')
440
 
                perms.add('view')
441
 
        return perms
442
 
 
443
 
class Worksheet(Storm):
444
 
    __storm_table__ = "worksheet"
445
 
 
446
 
    id = Int(primary=True, name="worksheetid")
447
 
    offering_id = Int(name="offeringid")
448
 
    identifier = Unicode()
449
 
    name = Unicode()
450
 
    assessable = Bool()
451
 
    data = Unicode()
452
 
    seq_no = Int()
453
 
    format = Unicode()
454
 
 
455
 
    attempts = ReferenceSet(id, "ExerciseAttempt.worksheetid")
456
 
    offering = Reference(offering_id, 'Offering.id')
457
 
 
458
 
    # Use worksheet_exercises to get access to the WorksheetExercise objects
459
 
    # binding worksheets to exercises. This is required to access the
460
 
    # "optional" field.
461
 
    worksheet_exercises = ReferenceSet(id,
462
 
        'WorksheetExercise.worksheet_id')
463
 
        
464
 
 
465
 
    __init__ = _kwarg_init
466
 
 
467
 
    def __repr__(self):
468
 
        return "<%s %s>" % (type(self).__name__, self.name)
469
 
 
470
 
    # XXX Refactor this - make it an instance method of Subject rather than a
471
 
    # class method of Worksheet. Can't do that now because Subject isn't
472
 
    # linked referentially to the Worksheet.
473
 
    @classmethod
474
 
    def get_by_name(cls, store, subjectname, worksheetname):
475
 
        """
476
 
        Get the Worksheet from the db associated with a given store, subject
477
 
        name and worksheet name.
478
 
        """
479
 
        return store.find(cls, cls.subject == unicode(subjectname),
480
 
            cls.name == unicode(worksheetname)).one()
481
 
 
482
 
    def remove_all_exercises(self, store):
483
 
        """
484
 
        Remove all exercises from this worksheet.
485
 
        This does not delete the exercises themselves. It just removes them
486
 
        from the worksheet.
487
 
        """
488
 
        store.find(WorksheetExercise,
489
 
            WorksheetExercise.worksheet == self).remove()
490
 
            
491
 
    def get_permissions(self, user):
492
 
        return self.offering.get_permissions(user)
493
 
 
494
 
class WorksheetExercise(Storm):
495
 
    __storm_table__ = "worksheet_exercise"
496
 
    
497
 
    id = Int(primary=True, name="ws_ex_id")
498
 
 
499
 
    worksheet_id = Int(name="worksheetid")
500
 
    worksheet = Reference(worksheet_id, Worksheet.id)
501
 
    exercise_id = Unicode(name="exerciseid")
502
 
    exercise = Reference(exercise_id, Exercise.id)
503
 
    optional = Bool()
504
 
    active = Bool()
505
 
    seq_no = Int()
506
 
    
507
 
    saves = ReferenceSet(id, "ExerciseSave.ws_ex_id")
508
 
    attempts = ReferenceSet(id, "ExerciseAttempt.ws_ex_id")
509
 
 
510
 
    __init__ = _kwarg_init
511
 
 
512
 
    def __repr__(self):
513
 
        return "<%s %s in %s>" % (type(self).__name__, self.exercise.name,
514
 
                                  self.worksheet.identifier)
515
 
 
516
 
class ExerciseSave(Storm):
517
 
    """
518
 
    Represents a potential solution to an exercise that a user has submitted
519
 
    to the server for storage.
520
 
    A basic ExerciseSave is just the current saved text for this exercise for
521
 
    this user (doesn't count towards their attempts).
522
 
    ExerciseSave may be extended with additional semantics (such as
523
 
    ExerciseAttempt).
524
 
    """
525
 
    __storm_table__ = "exercise_save"
526
 
    __storm_primary__ = "ws_ex_id", "user_id"
527
 
 
528
 
    ws_ex_id = Int(name="ws_ex_id")
529
 
    worksheet_exercise = Reference(ws_ex_id, "WorksheetExercise.id")
530
 
 
531
 
    user_id = Int(name="loginid")
532
 
    user = Reference(user_id, User.id)
533
 
    date = DateTime()
534
 
    text = Unicode()
535
 
 
536
 
    __init__ = _kwarg_init
537
 
 
538
 
    def __repr__(self):
539
 
        return "<%s %s by %s at %s>" % (type(self).__name__,
540
 
            self.exercise.name, self.user.login, self.date.strftime("%c"))
541
 
 
542
 
class ExerciseAttempt(ExerciseSave):
543
 
    """
544
 
    An ExerciseAttempt is a special case of an ExerciseSave. Like an
545
 
    ExerciseSave, it constitutes exercise solution data that the user has
546
 
    submitted to the server for storage.
547
 
    In addition, it contains additional information about the submission.
548
 
    complete - True if this submission was successful, rendering this exercise
549
 
        complete for this user.
550
 
    active - True if this submission is "active" (usually true). Submissions
551
 
        may be de-activated by privileged users for special reasons, and then
552
 
        they won't count (either as a penalty or success), but will still be
553
 
        stored.
554
 
    """
555
 
    __storm_table__ = "exercise_attempt"
556
 
    __storm_primary__ = "ws_ex_id", "user_id", "date"
557
 
 
558
 
    # The "text" field is the same but has a different name in the DB table
559
 
    # for some reason.
560
 
    text = Unicode(name="attempt")
561
 
    complete = Bool()
562
 
    active = Bool()
563
 
    
564
 
    def get_permissions(self, user):
565
 
        return set(['view']) if user is self.user else set()
566
 
  
567
 
class TestSuite(Storm):
568
 
    """A Testsuite acts as a container for the test cases of an exercise."""
569
 
    __storm_table__ = "test_suite"
570
 
    __storm_primary__ = "exercise_id", "suiteid"
571
 
    
572
 
    suiteid = Int()
573
 
    exercise_id = Unicode(name="exerciseid")
574
 
    description = Unicode()
575
 
    seq_no = Int()
576
 
    function = Unicode()
577
 
    stdin = Unicode()
578
 
    exercise = Reference(exercise_id, Exercise.id)
579
 
    test_cases = ReferenceSet(suiteid, 'TestCase.suiteid')
580
 
    variables = ReferenceSet(suiteid, 'TestSuiteVar.suiteid')
581
 
 
582
 
class TestCase(Storm):
583
 
    """A TestCase is a member of a TestSuite.
584
 
    
585
 
    It contains the data necessary to check if an exercise is correct"""
586
 
    __storm_table__ = "test_case"
587
 
    __storm_primary__ = "testid", "suiteid"
588
 
    
589
 
    testid = Int()
590
 
    suiteid = Int()
591
 
    suite = Reference(suiteid, "TestSuite.suiteid")
592
 
    passmsg = Unicode()
593
 
    failmsg = Unicode()
594
 
    test_default = Unicode()
595
 
    seq_no = Int()
596
 
    
597
 
    parts = ReferenceSet(testid, "TestCasePart.testid")
598
 
    
599
 
    __init__ = _kwarg_init
600
 
 
601
 
class TestSuiteVar(Storm):
602
 
    """A container for the arguments of a Test Suite"""
603
 
    __storm_table__ = "suite_variable"
604
 
    __storm_primary__ = "varid"
605
 
    
606
 
    varid = Int()
607
 
    suiteid = Int()
608
 
    var_name = Unicode()
609
 
    var_value = Unicode()
610
 
    var_type = Unicode()
611
 
    arg_no = Int()
612
 
    
613
 
    suite = Reference(suiteid, "TestSuite.suiteid")
614
 
    
615
 
    __init__ = _kwarg_init
616
 
    
617
 
class TestCasePart(Storm):
618
 
    """A container for the test elements of a Test Case"""
619
 
    __storm_table__ = "test_case_part"
620
 
    __storm_primary__ = "partid"
621
 
    
622
 
    partid = Int()
623
 
    testid = Int()
624
 
    
625
 
    part_type = Unicode()
626
 
    test_type = Unicode()
627
 
    data = Unicode()
628
 
    filename = Unicode()
629
 
    
630
 
    test = Reference(testid, "TestCase.testid")
631
 
    
632
 
    __init__ = _kwarg_init
 
224
    __init__ = _kwarg_init
 
225
 
 
226
    def __repr__(self):
 
227
        return "<%s %r in %r>" % (type(self).__name__, self.user,
 
228
                                  self.offering)