1
# IVLE - Informatics Virtual Learning Environment
2
# Copyright (C) 2007-2009 The University of Melbourne
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
# Author: Matt Giuca, Will Grant
21
Database Classes and Utilities for Storm ORM
23
This module provides all of the classes which map to database tables.
24
It also provides miscellaneous utility functions for database interaction.
30
from storm.locals import create_database, Store, Int, Unicode, DateTime, \
31
Reference, ReferenceSet, Bool, Storm, Desc
36
__all__ = ['get_store',
38
'Subject', 'Semester', 'Offering', 'Enrolment',
39
'ProjectSet', 'Project', 'ProjectGroup', 'ProjectGroupMembership',
40
'Exercise', 'Worksheet', 'WorksheetExercise',
41
'ExerciseSave', 'ExerciseAttempt',
42
'AlreadyEnrolledError', 'TestCase', 'TestSuite', 'TestSuiteVar'
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))
52
def get_conn_string():
54
Returns the Storm connection string, generated from the conf file.
59
clusterstr += ivle.conf.db_user
60
if ivle.conf.db_password:
61
clusterstr += ':' + ivle.conf.db_password
64
host = ivle.conf.db_host or 'localhost'
65
port = ivle.conf.db_port or 5432
67
clusterstr += '%s:%d' % (host, port)
69
return "postgres://%s/%s" % (clusterstr, ivle.conf.db_dbname)
73
Open a database connection and transaction. Return a storm.store.Store
74
instance connected to the configured IVLE database.
76
return Store(create_database(get_conn_string()))
82
Represents an IVLE user.
84
__storm_table__ = "login"
86
id = Int(primary=True, name="loginid")
95
last_login = DateTime()
103
if self.rolenm is None:
105
return ivle.caps.Role(self.rolenm)
106
def _set_role(self, value):
107
if not isinstance(value, ivle.caps.Role):
108
raise TypeError("role must be an ivle.caps.Role")
109
self.rolenm = unicode(value)
110
role = property(_get_role, _set_role)
112
__init__ = _kwarg_init
115
return "<%s '%s'>" % (type(self).__name__, self.login)
117
def authenticate(self, password):
118
"""Validate a given password against this user.
120
Returns True if the given password matches the password hash for this
121
User, False if it doesn't match, and None if there is no hash for the
124
if self.passhash is None:
126
return self.hash_password(password) == self.passhash
128
def hasCap(self, capability):
129
"""Given a capability (which is a Role object), returns True if this
130
User has that capability, False otherwise.
132
return self.role.hasCap(capability)
135
def password_expired(self):
136
fieldval = self.pass_exp
137
return fieldval is not None and datetime.datetime.now() > fieldval
140
def account_expired(self):
141
fieldval = self.acct_exp
142
return fieldval is not None and datetime.datetime.now() > fieldval
146
return self.state == 'enabled' and not self.account_expired
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(
156
Desc(Semester.semester),
160
def _set_password(self, password):
164
self.passhash = unicode(User.hash_password(password))
165
password = property(fset=_set_password)
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)
175
# TODO: Invitations should be listed too?
176
def get_groups(self, offering=None):
178
ProjectGroupMembership.user_id == self.id,
179
ProjectGroup.id == ProjectGroupMembership.project_group_id,
183
ProjectSet.offering_id == offering.id,
184
ProjectGroup.project_set_id == ProjectSet.id,
186
return Store.of(self).find(ProjectGroup, *preds)
190
return self.get_groups()
193
def active_enrolments(self):
194
'''A sanely ordered list of the user's active enrolments.'''
195
return self._get_enrolments(True)
198
def enrolments(self):
199
'''A sanely ordered list of all of the user's enrolments.'''
200
return self._get_enrolments(False)
203
def hash_password(password):
204
return md5.md5(password).hexdigest()
207
def get_by_login(cls, store, login):
209
Get the User from the db associated with a given store and
212
return store.find(cls, cls.login == unicode(login)).one()
214
def get_permissions(self, user):
215
if user and user.rolenm == 'admin' or user is self:
216
return set(['view', 'edit'])
220
# SUBJECTS AND ENROLMENTS #
222
class Subject(Storm):
223
__storm_table__ = "subject"
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")
231
offerings = ReferenceSet(id, 'Offering.subject_id')
233
__init__ = _kwarg_init
236
return "<%s '%s'>" % (type(self).__name__, self.short_name)
238
def get_permissions(self, user):
242
if user.rolenm == 'admin':
246
class Semester(Storm):
247
__storm_table__ = "semester"
249
id = Int(primary=True, name="semesterid")
254
offerings = ReferenceSet(id, 'Offering.semester_id')
256
__init__ = _kwarg_init
259
return "<%s %s/%s>" % (type(self).__name__, self.year, self.semester)
261
class Offering(Storm):
262
__storm_table__ = "offering"
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()
271
enrolments = ReferenceSet(id, 'Enrolment.offering_id')
272
members = ReferenceSet(id,
273
'Enrolment.offering_id',
276
project_sets = ReferenceSet(id, 'ProjectSet.offering_id')
278
worksheets = ReferenceSet(id,
279
'Worksheet.offering_id',
280
order_by="Worksheet.seq_no"
283
__init__ = _kwarg_init
286
return "<%s %r in %r>" % (type(self).__name__, self.subject,
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()
298
e = Enrolment(user=user, offering=self, active=True)
299
self.enrolments.add(e)
301
def get_permissions(self, user):
305
if user.rolenm == 'admin':
309
class Enrolment(Storm):
310
__storm_table__ = "enrolment"
311
__storm_primary__ = "user_id", "offering_id"
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)
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)
328
__init__ = _kwarg_init
331
return "<%s %r in %r>" % (type(self).__name__, self.user,
334
class AlreadyEnrolledError(Exception):
339
class ProjectSet(Storm):
340
__storm_table__ = "project_set"
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()
347
projects = ReferenceSet(id, 'Project.project_set_id')
348
project_groups = ReferenceSet(id, 'ProjectGroup.project_set_id')
350
__init__ = _kwarg_init
353
return "<%s %d in %r>" % (type(self).__name__, self.id,
356
class Project(Storm):
357
__storm_table__ = "project"
359
id = Int(name="projectid", primary=True)
362
project_set_id = Int(name="projectsetid")
363
project_set = Reference(project_set_id, ProjectSet.id)
364
deadline = DateTime()
366
__init__ = _kwarg_init
369
return "<%s '%s' in %r>" % (type(self).__name__, self.synopsis,
370
self.project_set.offering)
372
class ProjectGroup(Storm):
373
__storm_table__ = "project_group"
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)
380
created_by_id = Int(name="createdby")
381
created_by = Reference(created_by_id, User.id)
384
members = ReferenceSet(id,
385
"ProjectGroupMembership.project_group_id",
386
"ProjectGroupMembership.user_id",
389
__init__ = _kwarg_init
392
return "<%s %s in %r>" % (type(self).__name__, self.name,
393
self.project_set.offering)
395
class ProjectGroupMembership(Storm):
396
__storm_table__ = "group_member"
397
__storm_primary__ = "user_id", "project_group_id"
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)
404
__init__ = _kwarg_init
407
return "<%s %r in %r>" % (type(self).__name__, self.user,
410
# WORKSHEETS AND EXERCISES #
412
class Exercise(Storm):
413
# Note: Table "problem" is called "Exercise" in the Object layer, since
414
# it's called that everywhere else.
415
__storm_table__ = "problem"
416
id = Unicode(primary=True, name="identifier")
418
description = Unicode()
424
worksheets = ReferenceSet(id,
425
'WorksheetExercise.exercise_id',
426
'WorksheetExercise.worksheet_id',
430
test_suites = ReferenceSet(id, 'TestSuite.exercise_id')
432
__init__ = _kwarg_init
435
return "<%s %s>" % (type(self).__name__, self.name)
438
class Worksheet(Storm):
439
__storm_table__ = "worksheet"
441
id = Int(primary=True, name="worksheetid")
442
offering_id = Int(name="offeringid")
443
identifier = Unicode()
450
attempts = ReferenceSet(id, "ExerciseAttempt.worksheetid")
451
offering = Reference(offering_id, 'Offering.id')
453
# Use worksheet_exercises to get access to the WorksheetExercise objects
454
# binding worksheets to exercises. This is required to access the
456
worksheet_exercises = ReferenceSet(id,
457
'WorksheetExercise.worksheet_id')
460
__init__ = _kwarg_init
463
return "<%s %s>" % (type(self).__name__, self.name)
465
# XXX Refactor this - make it an instance method of Subject rather than a
466
# class method of Worksheet. Can't do that now because Subject isn't
467
# linked referentially to the Worksheet.
469
def get_by_name(cls, store, subjectname, worksheetname):
471
Get the Worksheet from the db associated with a given store, subject
472
name and worksheet name.
474
return store.find(cls, cls.subject == unicode(subjectname),
475
cls.name == unicode(worksheetname)).one()
477
def remove_all_exercises(self, store):
479
Remove all exercises from this worksheet.
480
This does not delete the exercises themselves. It just removes them
483
store.find(WorksheetExercise,
484
WorksheetExercise.worksheet == self).remove()
486
def get_permissions(self, user):
487
return self.offering.get_permissions(user)
489
class WorksheetExercise(Storm):
490
__storm_table__ = "worksheet_problem"
492
id = Int(primary=True, name="ws_prob_id")
494
worksheet_id = Int(name="worksheetid")
495
worksheet = Reference(worksheet_id, Worksheet.id)
496
exercise_id = Unicode(name="problemid")
497
exercise = Reference(exercise_id, Exercise.id)
502
saves = ReferenceSet(id, "ExerciseSave.ws_ex_id")
503
attempts = ReferenceSet(id, "ExerciseAttempt.ws_ex_id")
505
__init__ = _kwarg_init
508
return "<%s %s in %s>" % (type(self).__name__, self.exercise.name,
509
self.worksheet.identifier)
511
class ExerciseSave(Storm):
513
Represents a potential solution to an exercise that a user has submitted
514
to the server for storage.
515
A basic ExerciseSave is just the current saved text for this exercise for
516
this user (doesn't count towards their attempts).
517
ExerciseSave may be extended with additional semantics (such as
520
__storm_table__ = "problem_save"
521
__storm_primary__ = "ws_ex_id", "user_id"
523
ws_ex_id = Int(name="ws_prob_id")
524
worksheet_exercise = Reference(ws_ex_id, "WorksheetExercise.id")
526
user_id = Int(name="loginid")
527
user = Reference(user_id, User.id)
531
__init__ = _kwarg_init
534
return "<%s %s by %s at %s>" % (type(self).__name__,
535
self.exercise.name, self.user.login, self.date.strftime("%c"))
537
class ExerciseAttempt(ExerciseSave):
539
An ExerciseAttempt is a special case of an ExerciseSave. Like an
540
ExerciseSave, it constitutes exercise solution data that the user has
541
submitted to the server for storage.
542
In addition, it contains additional information about the submission.
543
complete - True if this submission was successful, rendering this exercise
544
complete for this user.
545
active - True if this submission is "active" (usually true). Submissions
546
may be de-activated by privileged users for special reasons, and then
547
they won't count (either as a penalty or success), but will still be
550
__storm_table__ = "problem_attempt"
551
__storm_primary__ = "ws_ex_id", "user_id", "date"
553
# The "text" field is the same but has a different name in the DB table
555
text = Unicode(name="attempt")
559
def get_permissions(self, user):
560
return set(['view']) if user is self.user else set()
562
class TestSuite(Storm):
563
"""A Testsuite acts as a container for the test cases of an exercise."""
564
__storm_table__ = "test_suite"
565
__storm_primary__ = "exercise_id", "suiteid"
568
exercise_id = Unicode(name="problemid")
569
description = Unicode()
573
exercise = Reference(exercise_id, Exercise.id)
574
test_cases = ReferenceSet(suiteid, 'TestCase.suiteid')
575
variables = ReferenceSet(suiteid, 'TestSuiteVar.suiteid')
577
class TestCase(Storm):
578
"""A TestCase is a member of a TestSuite.
580
It contains the data necessary to check if an exercise is correct"""
581
__storm_table__ = "test_case"
582
__storm_primary__ = "testid", "suiteid"
586
suite = Reference(suiteid, "TestSuite.suiteid")
589
test_default = Unicode()
592
parts = ReferenceSet(testid, "TestCasePart.testid")
594
__init__ = _kwarg_init
596
class TestSuiteVar(Storm):
597
"""A container for the arguments of a Test Suite"""
598
__storm_table__ = "suite_variables"
599
__storm_primary__ = "varid"
604
var_value = Unicode()
608
suite = Reference(suiteid, "TestSuite.suiteid")
610
__init__ = _kwarg_init
612
class TestCasePart(Storm):
613
"""A container for the test elements of a Test Case"""
614
__storm_table__ = "test_case_parts"
615
__storm_primary__ = "partid"
620
part_type = Unicode()
621
test_type = Unicode()
625
test = Reference(testid, "TestCase.testid")
627
__init__ = _kwarg_init