-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodel.py
190 lines (161 loc) · 6.52 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import sqlite3
from contextlib import closing
import logging
DATABASE = "./gradebook.db"
logging.basicConfig(level=logging.DEBUG)
class Database(object):
def __init__(self, database_name):
"""Create an Database object associated with sqlite3 file
`database_name`"""
self.database_name = database_name
def init_db(self):
with closing(self.connect()) as db:
with open("schema.sql") as f:
db.cursor().executescript(f.read())
with open("testdata.sql") as f:
db.cursor().executescript(f.read())
db.commit()
def connect(self):
"""Return a connection to the gradebook database"""
self.con = sqlite3.connect(self.database_name)
self.con.row_factory = sqlite3.Row
# By default, foreign_key constraints are not enforced. This is enabled especially for the cascading deletes for students and assignments.
self.con.execute("PRAGMA foreign_keys=ON")
return self.con
# Commit can be false by default because of the implicit commits
# sqlite3 has, and because we commit on connection close
def execute(self, query, args=None, commit=False):
cur = self.con.cursor()
cur.execute(query, args or ())
logging.debug(str(query) + "; " + str(args))
if commit:
self.con.commit()
return cur
def close(self):
self.con.commit()
self.con.close()
db = Database(DATABASE)
class Model(object):
_table_name = None
_default_order = None
_column_names = None
def __init__(self, **kwargs):
# TODO: validation for setting proper keys as per column defs
for column in self._column_names + ['pk']:
setattr(self, column, kwargs.get(column))
self._in_db = False
def __repr__(self):
return "<{0}: {1}>".format(self.__class__.__name__, self.pk)
@classmethod
def _from_row(cls, row_dict):
obj = cls(**row_dict)
obj._in_db = True
return obj
@classmethod
def get(cls, pk=None):
query = "SELECT * FROM {0} WHERE pk=? LIMIT 1".format(cls._table_name)
cur = db.execute(query, (pk, ))
row = cur.fetchone()
obj = cls._from_row(row)
return obj
@classmethod
def where(cls, **kwargs):
# TODO kwarg validation by checking _column_names
items = kwargs.items()
columns = [i[0] for i in items]
values = [i[1] for i in items]
conditions = '=? and '.join(columns) + '=?'
query = "SELECT * FROM {0} WHERE {1}".format(cls._table_name,
conditions)
cur = db.execute(query, values)
rows = cur.fetchall()
objs = [cls._from_row(row) for row in rows]
return objs
@classmethod
def all(cls, order=None):
order = order or cls._default_order
if order:
query = "SELECT * FROM {0} ORDER BY {1} COLLATE NOCASE"
query = query.format(cls._table_name, order)
else:
query = "SELECT * FROM {0}".format(cls._table_name)
cur = db.execute(query)
rows = cur.fetchall()
objs = [cls._from_row(row) for row in rows]
return objs
def delete(self):
if self._in_db:
query = "DELETE FROM {0} WHERE pk=?".format(
self.__class__._table_name)
args = (self.pk, )
db.execute(query, args)
class Student(Model):
_table_name = 'student'
_default_order = 'first_name, last_name, pk'
_column_names = ['first_name', 'last_name', 'alias', 'grad_year', 'email']
@property
def full_name(self):
full_name = ' '.join([self.first_name, self.last_name])
# We strip to remove trailing/leading space if last or first name is
# missing.
return full_name.strip()
def save(self):
# TODO: This could benefit from getting put into the model as much as
# possible.
if self._in_db:
query = """UPDATE student SET first_name=?, last_name=?, alias=?,
grad_year=?, email=? WHERE pk=?"""
args = [self.first_name, self.last_name, self.alias,
self.grad_year, self.email, self.pk]
db.execute(query, args)
else:
query = """INSERT INTO student (first_name, last_name, alias,
grad_year, email) VALUES (?, ?, ?, ?, ?)"""
args = [self.first_name, self.last_name, self.alias,
self.grad_year, self.email]
cur = db.execute(query, args)
self.pk = cur.lastrowid
def get_grades(self):
return Grade.where(student_pk=self.pk)
class Assignment(Model):
_table_name = 'assignment'
_default_order = '-due_date, name, pk'
_column_names = ['name', 'description', 'comment', 'due_date', 'points', 'is_public']
def save(self):
# TODO: This could benefit from getting put into the model as much as
# possible.
if self._in_db:
query = """UPDATE assignment SET name=?, description=?,
due_date=?, points=?, comment=?, is_public=? WHERE pk=?"""
args = [self.name, self.description, self.due_date, self.points,
self.comment, self.is_public, self.pk]
db.execute(query, args)
else:
query = """INSERT INTO assignment (name, description, due_date,
points, comment, is_public) VALUES (?, ?, ?, ?, ?, ?)"""
args = [self.name, self.description, self.due_date, self.points,
self.comment, self.is_public]
cur = db.execute(query, args)
self.pk = cur.lastrowid
def get_grades(self):
return Grade.where(assignment_pk=self.pk)
class Grade(Model):
_table_name = 'grade'
_default_order = 'pk'
_column_names = ['student_pk', 'assignment_pk', 'points', 'comment']
def save(self):
# TODO: This could benefit from getting put into the model as much as
# possible.
if self._in_db:
query = """UPDATE grade SET student_pk=?, assignment_pk=?,
points=?, comment=? WHERE pk=?"""
args = [self.student_pk, self.assignment_pk, self.points,
self.comment, self.pk]
db.execute(query, args)
else:
query = """INSERT INTO grade (student_pk, assignment_pk, points,
comment) VALUES (?, ?, ?, ?)"""
args = [self.student_pk, self.assignment_pk, self.points,
self.comment]
cur = db.execute(query, args)
self.pk = cur.lastrowid