~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 01:29:07 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:1147
ivle.makeuser: Don't create a local.auth. It wasn't used anywhere, and seems
    to have only been there for historical reasons.
setup.configure: Remove svn_auth_local from the config.py boilerplate; it was
    used solely by ivle.makeuser.

Show diffs side-by-side

added added

removed removed

Lines of Context:
28
28
import datetime
29
29
 
30
30
from storm.locals import create_database, Store, Int, Unicode, DateTime, \
31
 
                         Reference, ReferenceSet, Bool, Storm, Desc
 
31
                         Reference
32
32
 
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
 
def _kwarg_init(self, **kwargs):
46
 
    for k,v in kwargs.items():
47
 
        if k.startswith('_') or not hasattr(self.__class__, k):
48
 
            raise TypeError("%s got an unexpected keyword argument '%s'"
49
 
                % (self.__class__.__name__, k))
50
 
        setattr(self, k, v)
51
 
 
52
36
def get_conn_string():
53
37
    """
54
38
    Returns the Storm connection string, generated from the conf file.
55
39
    """
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)
 
40
    return "postgres://%s:%s@%s:%d/%s" % (ivle.conf.db_user,
 
41
        ivle.conf.db_password, ivle.conf.db_host, ivle.conf.db_port,
 
42
        ivle.conf.db_dbname)
70
43
 
71
44
def get_store():
72
45
    """
75
48
    """
76
49
    return Store(create_database(get_conn_string()))
77
50
 
78
 
# USERS #
79
 
 
80
 
class User(Storm):
 
51
class User(object):
81
52
    """
82
53
    Represents an IVLE user.
83
54
    """
109
80
        self.rolenm = unicode(value)
110
81
    role = property(_get_role, _set_role)
111
82
 
112
 
    __init__ = _kwarg_init
 
83
    def __init__(self, **kwargs):
 
84
        """
 
85
        Create a new User object. Supply any columns as a keyword argument.
 
86
        """
 
87
        for k,v in kwargs.items():
 
88
            if k.startswith('_') or not hasattr(self, k):
 
89
                raise TypeError("User got an unexpected keyword argument '%s'"
 
90
                    % k)
 
91
            setattr(self, k, v)
113
92
 
114
93
    def __repr__(self):
115
94
        return "<%s '%s'>" % (type(self).__name__, self.login)
141
120
        fieldval = self.acct_exp
142
121
        return fieldval is not None and datetime.datetime.now() > fieldval
143
122
 
144
 
    @property
145
 
    def valid(self):
146
 
        return self.state == 'enabled' and not self.account_expired
147
 
 
148
 
    def _get_enrolments(self, justactive):
149
 
        return Store.of(self).find(Enrolment,
150
 
            Enrolment.user_id == self.id,
151
 
            (Enrolment.active == True) if justactive else True,
152
 
            Enrolment.offering_id == Offering.id,
153
 
            Offering.semester_id == Semester.id,
154
 
            Offering.subject_id == Subject.id).order_by(
155
 
                Desc(Semester.year),
156
 
                Desc(Semester.semester),
157
 
                Desc(Subject.code)
158
 
            )
159
 
 
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
 
    @property
168
 
    def subjects(self):
169
 
        return Store.of(self).find(Subject,
170
 
            Enrolment.user_id == self.id,
171
 
            Enrolment.active == True,
172
 
            Offering.id == Enrolment.offering_id,
173
 
            Subject.id == Offering.subject_id).config(distinct=True)
174
 
 
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
 
    @property
193
 
    def active_enrolments(self):
194
 
        '''A sanely ordered list of the user's active enrolments.'''
195
 
        return self._get_enrolments(True)
196
 
 
197
 
    @property
198
 
    def enrolments(self):
199
 
        '''A sanely ordered list of all of the user's enrolments.'''
200
 
        return self._get_enrolments(False) 
201
 
 
202
123
    @staticmethod
203
124
    def hash_password(password):
204
125
        return md5.md5(password).hexdigest()
210
131
        login.
211
132
        """
212
133
        return store.find(cls, cls.login == unicode(login)).one()
213
 
 
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
 
class Subject(Storm):
223
 
    __storm_table__ = "subject"
224
 
 
225
 
    id = Int(primary=True, name="subjectid")
226
 
    code = Unicode(name="subj_code")
227
 
    name = Unicode(name="subj_name")
228
 
    short_name = Unicode(name="subj_short_name")
229
 
    url = Unicode()
230
 
 
231
 
    offerings = ReferenceSet(id, 'Offering.subject_id')
232
 
 
233
 
    __init__ = _kwarg_init
234
 
 
235
 
    def __repr__(self):
236
 
        return "<%s '%s'>" % (type(self).__name__, self.short_name)
237
 
 
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
 
class Semester(Storm):
247
 
    __storm_table__ = "semester"
248
 
 
249
 
    id = Int(primary=True, name="semesterid")
250
 
    year = Unicode()
251
 
    semester = Unicode()
252
 
    active = Bool()
253
 
 
254
 
    offerings = ReferenceSet(id, 'Offering.semester_id')
255
 
 
256
 
    __init__ = _kwarg_init
257
 
 
258
 
    def __repr__(self):
259
 
        return "<%s %s/%s>" % (type(self).__name__, self.year, self.semester)
260
 
 
261
 
class Offering(Storm):
262
 
    __storm_table__ = "offering"
263
 
 
264
 
    id = Int(primary=True, name="offeringid")
265
 
    subject_id = Int(name="subject")
266
 
    subject = Reference(subject_id, Subject.id)
267
 
    semester_id = Int(name="semesterid")
268
 
    semester = Reference(semester_id, Semester.id)
269
 
    groups_student_permissions = Unicode()
270
 
 
271
 
    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
 
 
283
 
    __init__ = _kwarg_init
284
 
 
285
 
    def __repr__(self):
286
 
        return "<%s %r in %r>" % (type(self).__name__, self.subject,
287
 
                                  self.semester)
288
 
 
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 == 'admin':
306
 
                perms.add('edit')
307
 
        return perms
308
 
 
309
 
class Enrolment(Storm):
310
 
    __storm_table__ = "enrolment"
311
 
    __storm_primary__ = "user_id", "offering_id"
312
 
 
313
 
    user_id = Int(name="loginid")
314
 
    user = Reference(user_id, User.id)
315
 
    offering_id = Int(name="offeringid")
316
 
    offering = Reference(offering_id, Offering.id)
317
 
    notes = Unicode()
318
 
    active = Bool()
319
 
 
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
 
 
436
 
class Worksheet(Storm):
437
 
    __storm_table__ = "worksheet"
438
 
 
439
 
    id = Int(primary=True, name="worksheetid")
440
 
    offering_id = Int(name="offeringid")
441
 
    identifier = Unicode()
442
 
    name = Unicode()
443
 
    assessable = Bool()
444
 
    data = Unicode()
445
 
    seq_no = Int()
446
 
    format = Unicode()
447
 
 
448
 
    attempts = ReferenceSet(id, "ExerciseAttempt.worksheetid")
449
 
    offering = Reference(offering_id, 'Offering.id')
450
 
 
451
 
    # Use worksheet_exercises to get access to the WorksheetExercise objects
452
 
    # binding worksheets to exercises. This is required to access the
453
 
    # "optional" field.
454
 
    worksheet_exercises = ReferenceSet(id,
455
 
        'WorksheetExercise.worksheet_id')
456
 
        
457
 
 
458
 
    __init__ = _kwarg_init
459
 
 
460
 
    def __repr__(self):
461
 
        return "<%s %s>" % (type(self).__name__, self.name)
462
 
 
463
 
    # XXX Refactor this - make it an instance method of Subject rather than a
464
 
    # class method of Worksheet. Can't do that now because Subject isn't
465
 
    # linked referentially to the Worksheet.
466
 
    @classmethod
467
 
    def get_by_name(cls, store, subjectname, worksheetname):
468
 
        """
469
 
        Get the Worksheet from the db associated with a given store, subject
470
 
        name and worksheet name.
471
 
        """
472
 
        return store.find(cls, cls.subject == unicode(subjectname),
473
 
            cls.name == unicode(worksheetname)).one()
474
 
 
475
 
    def remove_all_exercises(self, store):
476
 
        """
477
 
        Remove all exercises from this worksheet.
478
 
        This does not delete the exercises themselves. It just removes them
479
 
        from the worksheet.
480
 
        """
481
 
        store.find(WorksheetExercise,
482
 
            WorksheetExercise.worksheet == self).remove()
483
 
            
484
 
    def get_permissions(self, user):
485
 
        return self.offering.get_permissions(user)
486
 
 
487
 
class WorksheetExercise(Storm):
488
 
    __storm_table__ = "worksheet_exercise"
489
 
    
490
 
    id = Int(primary=True, name="ws_ex_id")
491
 
 
492
 
    worksheet_id = Int(name="worksheetid")
493
 
    worksheet = Reference(worksheet_id, Worksheet.id)
494
 
    exercise_id = Unicode(name="exerciseid")
495
 
    exercise = Reference(exercise_id, Exercise.id)
496
 
    optional = Bool()
497
 
    active = Bool()
498
 
    seq_no = Int()
499
 
    
500
 
    saves = ReferenceSet(id, "ExerciseSave.ws_ex_id")
501
 
    attempts = ReferenceSet(id, "ExerciseAttempt.ws_ex_id")
502
 
 
503
 
    __init__ = _kwarg_init
504
 
 
505
 
    def __repr__(self):
506
 
        return "<%s %s in %s>" % (type(self).__name__, self.exercise.name,
507
 
                                  self.worksheet.identifier)
508
 
 
509
 
class ExerciseSave(Storm):
510
 
    """
511
 
    Represents a potential solution to an exercise that a user has submitted
512
 
    to the server for storage.
513
 
    A basic ExerciseSave is just the current saved text for this exercise for
514
 
    this user (doesn't count towards their attempts).
515
 
    ExerciseSave may be extended with additional semantics (such as
516
 
    ExerciseAttempt).
517
 
    """
518
 
    __storm_table__ = "exercise_save"
519
 
    __storm_primary__ = "ws_ex_id", "user_id"
520
 
 
521
 
    ws_ex_id = Int(name="ws_ex_id")
522
 
    worksheet_exercise = Reference(ws_ex_id, "WorksheetExercise.id")
523
 
 
524
 
    user_id = Int(name="loginid")
525
 
    user = Reference(user_id, User.id)
526
 
    date = DateTime()
527
 
    text = Unicode()
528
 
 
529
 
    __init__ = _kwarg_init
530
 
 
531
 
    def __repr__(self):
532
 
        return "<%s %s by %s at %s>" % (type(self).__name__,
533
 
            self.exercise.name, self.user.login, self.date.strftime("%c"))
534
 
 
535
 
class ExerciseAttempt(ExerciseSave):
536
 
    """
537
 
    An ExerciseAttempt is a special case of an ExerciseSave. Like an
538
 
    ExerciseSave, it constitutes exercise solution data that the user has
539
 
    submitted to the server for storage.
540
 
    In addition, it contains additional information about the submission.
541
 
    complete - True if this submission was successful, rendering this exercise
542
 
        complete for this user.
543
 
    active - True if this submission is "active" (usually true). Submissions
544
 
        may be de-activated by privileged users for special reasons, and then
545
 
        they won't count (either as a penalty or success), but will still be
546
 
        stored.
547
 
    """
548
 
    __storm_table__ = "exercise_attempt"
549
 
    __storm_primary__ = "ws_ex_id", "user_id", "date"
550
 
 
551
 
    # The "text" field is the same but has a different name in the DB table
552
 
    # for some reason.
553
 
    text = Unicode(name="attempt")
554
 
    complete = Bool()
555
 
    active = Bool()
556
 
    
557
 
    def get_permissions(self, user):
558
 
        return set(['view']) if user is self.user else set()
559
 
  
560
 
class TestSuite(Storm):
561
 
    """A Testsuite acts as a container for the test cases of an exercise."""
562
 
    __storm_table__ = "test_suite"
563
 
    __storm_primary__ = "exercise_id", "suiteid"
564
 
    
565
 
    suiteid = Int()
566
 
    exercise_id = Unicode(name="exerciseid")
567
 
    description = Unicode()
568
 
    seq_no = Int()
569
 
    function = Unicode()
570
 
    stdin = Unicode()
571
 
    exercise = Reference(exercise_id, Exercise.id)
572
 
    test_cases = ReferenceSet(suiteid, 'TestCase.suiteid')
573
 
    variables = ReferenceSet(suiteid, 'TestSuiteVar.suiteid')
574
 
 
575
 
class TestCase(Storm):
576
 
    """A TestCase is a member of a TestSuite.
577
 
    
578
 
    It contains the data necessary to check if an exercise is correct"""
579
 
    __storm_table__ = "test_case"
580
 
    __storm_primary__ = "testid", "suiteid"
581
 
    
582
 
    testid = Int()
583
 
    suiteid = Int()
584
 
    suite = Reference(suiteid, "TestSuite.suiteid")
585
 
    passmsg = Unicode()
586
 
    failmsg = Unicode()
587
 
    test_default = Unicode()
588
 
    seq_no = Int()
589
 
    
590
 
    parts = ReferenceSet(testid, "TestCasePart.testid")
591
 
    
592
 
    __init__ = _kwarg_init
593
 
 
594
 
class TestSuiteVar(Storm):
595
 
    """A container for the arguments of a Test Suite"""
596
 
    __storm_table__ = "suite_variable"
597
 
    __storm_primary__ = "varid"
598
 
    
599
 
    varid = Int()
600
 
    suiteid = Int()
601
 
    var_name = Unicode()
602
 
    var_value = Unicode()
603
 
    var_type = Unicode()
604
 
    arg_no = Int()
605
 
    
606
 
    suite = Reference(suiteid, "TestSuite.suiteid")
607
 
    
608
 
    __init__ = _kwarg_init
609
 
    
610
 
class TestCasePart(Storm):
611
 
    """A container for the test elements of a Test Case"""
612
 
    __storm_table__ = "test_case_part"
613
 
    __storm_primary__ = "partid"
614
 
    
615
 
    partid = Int()
616
 
    testid = Int()
617
 
    
618
 
    part_type = Unicode()
619
 
    test_type = Unicode()
620
 
    data = Unicode()
621
 
    filename = Unicode()
622
 
    
623
 
    test = Reference(testid, "TestCase.testid")
624
 
    
625
 
    __init__ = _kwarg_init