-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
272 lines (228 loc) · 10 KB
/
models.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
from datetime import date, datetime, timedelta
from sqlalchemy import (
inspect,
Column,
Integer,
String,
DateTime,
Date,
ForeignKey,
)
from sqlalchemy.orm import relationship, as_declarative
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
from config import databaseConfig, userRoles
from utils import hash_password
from logger import LOGGER
@as_declarative()
class Base:
@classmethod
def get_by_id(cls, id: int):
with databaseConfig.Session() as session:
return session.query(cls).get(id)
def update(self, **kwargs):
if kwargs:
for key, value in kwargs.items():
if hasattr(self, key):
setattr(self, key, value)
with databaseConfig.Session() as session:
session.merge(self)
session.commit()
return self
def delete(self):
if self:
with databaseConfig.Session() as session:
session.delete(self)
session.commit()
LOGGER.info(f'delete: {self}')
return True
return False
def as_dict(self):
return {column.key: getattr(self, column.key) for column in inspect(self).mapper.column_attrs}
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, nullable=False)
email = Column(String, unique=True, nullable=False)
first_name = Column(String, nullable=False)
last_name = Column(String, nullable=False)
password = Column(String, nullable=False)
role = Column(String, nullable=False)
created_at = Column(DateTime, default=datetime.now())
updated_at = Column(DateTime, onupdate=datetime.now())
updated_by_user_id = Column(Integer, ForeignKey("users.id"))
# Relationships
updated_by_user = relationship("User")
@classmethod
def create(cls, id: int, email: str, first_name: str, last_name: str, role: str = userRoles.STUDENT) -> 'User':
try:
with databaseConfig.Session() as session:
existing_user = session.query(User).filter((User.id == id) & (User.email == email.lower())).first()
if existing_user is None:
user = cls(
id=id,
email=email.lower(),
first_name=first_name.title(),
last_name=last_name.title(),
password=hash_password(str(id)),
role=role,
)
session.add(user)
session.commit()
LOGGER.info(f"Created user: {user}")
else:
LOGGER.warning(f"User already exists in database: {existing_user}")
return session.query(User).filter(User.id == id).first()
except IntegrityError as e:
LOGGER.error(e.orig)
raise e.orig
except SQLAlchemyError as e:
LOGGER.error(f"Unexpected error when creating user: {e}")
raise e
def update_password(self, password: str, updated_by_user_id: int) -> bool:
self.password = hash_password(password)
self.updated_by_user_id = updated_by_user_id
with databaseConfig.Session() as session:
session.merge(self)
session.commit()
return True
def __repr__(self) -> str:
return f"<user id=\"{self.id}\" email=\"{self.email}\" role=\"{self.role}\">"
def __str__(self) -> str:
return f"{self.first_name} {self.last_name}"
class Author(Base):
__tablename__ = 'authors'
id = Column(Integer, primary_key=True, nullable=False, autoincrement="auto")
first_name = Column(String, nullable=False)
last_name = Column(String, nullable=False)
@classmethod
def create(cls, first_name: str, last_name: str) -> 'Author':
try:
with databaseConfig.Session() as session:
existing_author = session.query(Author).filter((Author.first_name == first_name.title()) & (Author.last_name == last_name.title())).first()
if existing_author is None:
author = cls(
first_name=first_name.title(),
last_name=last_name.title(),
)
session.add(author)
session.commit()
LOGGER.info(f"Created author: {author}")
else:
LOGGER.warning(f"Author already exists in database: {existing_author}")
return session.query(Author).filter((Author.first_name == first_name.title()) & (Author.last_name == last_name.title())).first()
except IntegrityError as e:
LOGGER.error(e.orig)
raise e.orig
except SQLAlchemyError as e:
LOGGER.error(f"Unexpected error when creating author: {e}")
raise e
def __repr__(self) -> str:
return f"<Author id=\"{self.id}\" name=\"{self.first_name} {self.last_name}\">"
def __str__(self) -> str:
return f"{self.first_name} {self.last_name}"
class Publisher(Base):
__tablename__ = 'publishers'
id = Column(Integer, primary_key=True, nullable=False, autoincrement="auto")
publisher_name = Column(String, nullable=False)
city = Column(String, nullable=False)
@classmethod
def create(cls, publisher_name: str, city: str) -> 'Publisher':
try:
with databaseConfig.Session() as session:
existing_publisher = session.query(Publisher).filter((Publisher.publisher_name == publisher_name) & (Publisher.city == city)).first()
if existing_publisher is None:
publisher = cls(
publisher_name=publisher_name.title(),
city=city.capitalize(),
)
session.add(publisher)
session.commit()
LOGGER.info(f"Created publisher: {publisher}")
else:
LOGGER.warning(f"Publishers already exists in database: {existing_publisher}")
return session.query(Publisher).filter((Publisher.publisher_name == publisher_name) & (Publisher.city == city)).first()
except IntegrityError as e:
LOGGER.error(e.orig)
raise e.orig
except SQLAlchemyError as e:
LOGGER.error(f"Unexpected error when creating publisher: {e}")
raise e
def __repr__(self) -> str:
return f"<Publisher id=\"{self.id}\" publisher_name=\"{self.publisher_name}\">"
def __str__(self) -> str:
return f"{self.publisher_name}, {self.city}"
class Book(Base):
__tablename__ = 'books'
id = Column(Integer, primary_key=True, nullable=False, autoincrement="auto")
book_name = Column(String, nullable=False)
isbn = Column(String(13), nullable=False)
author_id = Column(Integer, ForeignKey("authors.id"), nullable=False)
publisher_id = Column(Integer, ForeignKey("publishers.id"), nullable=False)
publish_year = Column(Integer)
volume = Column(Integer)
# Relationships
author = relationship("Author")
publisher = relationship("Publisher")
@classmethod
def create(cls, book_name: str, isbn: str, author: Author, publisher: Publisher, publish_year: int = None, volume: int = None) -> 'Book':
try:
book = cls(
book_name=book_name.title(),
isbn=isbn,
author=author,
publisher=publisher,
publish_year=publish_year,
volume=volume,
)
with databaseConfig.Session() as session:
session.add(book)
session.commit()
LOGGER.info(f"Created book: {book}")
return session.query(Book).filter(Book.id == book.id).first()
except IntegrityError as e:
LOGGER.error(e.orig)
raise e.orig
except SQLAlchemyError as e:
LOGGER.error(f"Unexpected error when creating book: {e}")
raise e
def is_reserved(self) -> bool:
with databaseConfig.Session() as session:
return session.query(Request).filter(Request.book_id == self.id, Request.return_date == None).count() > 0
def __repr__(self) -> str:
return f"<Book id=\"{self.id}\" book_name=\"{self.book_name}\"" + ((" volume=\"" + str(self.volume) + "\"") if self.volume != None else "") + ">"
def __str__(self) -> str:
return self.book_name
class Request(Base):
__tablename__ = 'requests'
id = Column(Integer, primary_key=True, nullable=False, autoincrement="auto")
book_id = Column(Integer, ForeignKey("books.id"), nullable=False)
user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
delivery_date = Column(Date, default=date.today(), nullable=False)
return_deadline = Column(Date, default=date.today() + timedelta(days=14), nullable=False)
return_date = Column(Date, nullable=True)
# Relationships
book = relationship("Book")
user = relationship("User")
@classmethod
def create(cls, book: Book, user: User) -> 'Request':
try:
request = cls(book=book, user=user)
with databaseConfig.Session() as session:
session.add(request)
session.commit()
LOGGER.info(f"Created request: {request}")
return session.query(Request).filter(Request.id == request.id).first()
except IntegrityError as e:
LOGGER.error(e.orig)
raise e.orig
except SQLAlchemyError as e:
LOGGER.error(f"Unexpected error when creating request: {e}")
raise e
def __repr__(self) -> str:
return f"<Request id=\"{self.id}\" book=\"{self.book_id}\" user=\"{self.user_id}\">"
if __name__ == '__main__':
response = input("[WARNING] Do you want to create the database tables? [y] ~> ")
if response.lower() == 'y':
Base.metadata.create_all(databaseConfig.engine)
print('Database created.')
else:
print('Canceled.')