-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
424 lines (389 loc) · 14.2 KB
/
server.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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
from config import host, user, password, dbname
import psycopg2
class Server:
"""
Класс Server устанавливает подключение к базе данных и позволяет получать результаты SQL-запросов
"""
def connectDB(self):
"""
ПОДКЛЮЧЕНИЕ К БАЗЕ ДАННЫХ
Возвращает: Экземпляр класса при успешном подключении и None при неуспешном
"""
self.connection = None
try:
self.connection = psycopg2.connect(
host=host,
user=user,
password=password,
dbname=dbname
)
self.connection.autocommit = True
self.cursor = self.connection.cursor()
print('[INFO] Соединение установлено')
except Exception as e:
print('[INFO] Ошибка во время подключения к базе данных', e)
return self.connection
def selectVersion(self):
"""
Получить версию
Возвращает: Вресию psql в tulpe
"""
self.cursor.execute(
"SELECT version();"
)
return self.cursor.fetchone()
def close(self):
"""Закрытие соединения"""
if self.connection:
self.connection.close()
print('[ИНФО] Соединение с базой данных остановлено')
def selectBooks(self, nameBook, state, genre, publishYear, idAuthor):
nameBook = nameBook.lower()
state = state.lower()
genre = genre.lower()
if state != 'true' or state != 'false':
stateStr = 'state IS NOT NULL'
else:
stateStr = f"state = '{state}'"
if publishYear == '':
yearStr = ''
else:
yearStr = f"and publish_year = date('{publishYear}')"
if idAuthor == '':
idStr = ''
else:
idStr = f"and id_author = {idAuthor}"
try:
self.cursor.execute(
f"SELECT * FROM books WHERE LOWER(name_book) LIKE '%{nameBook}%' and {stateStr} and LOWER(genre) LIKE "
f"'%{genre}%' {yearStr} {idStr} ORDER BY id_book;"
)
return self.cursor.fetchall()
except Exception as e:
print(e)
return []
def selectAuthors(self, firstName, lastName, birthday):
firstName = firstName.lower()
lastName = lastName.lower()
if birthday == '':
yearStr = ''
else:
yearStr = f"and birthday = date('{birthday}')"
try:
self.cursor.execute(
f"SELECT * FROM authors WHERE LOWER(first_name) LIKE '%{firstName}%' and LOWER(last_name) LIKE '%{lastName}%'"
f" {yearStr} ORDER BY id_author;"
)
return self.cursor.fetchall()
except Exception as e:
print(e)
return []
def selectFormulars(self, idTicket, idWorker, dateTake, dateBack, books):
books = books.lower()
if dateTake == '':
yearStr = ''
else:
yearStr = f"and date_take = date('{dateTake}')"
if dateBack == '':
yearStr2 = ''
else:
yearStr2 = f"and date_back = date('{dateBack}')"
if idTicket == '':
idStr = ''
else:
idStr = f"and id_ticket = {idTicket}"
if idWorker == '':
idStr2 = ''
else:
idStr2 = f"and id_worker = {idWorker}"
try:
self.cursor.execute(
f"SELECT * FROM formulars WHERE Lower(books) LIKE '%{books}%' {idStr} {idStr2} {yearStr} {yearStr2} "
f"ORDER BY formular_num;"
)
return self.cursor.fetchall()
except Exception as e:
print(e)
return []
def selectLibraryWorkers(self, firstName, lastName, birthday, namePost):
firstName = firstName.lower()
lastName = lastName.lower()
namePost = namePost.lower()
if birthday == '':
yearStr = ''
else:
yearStr = f"and birthday = date('{birthday}')"
try:
self.cursor.execute(
f"SELECT * FROM library_workers WHERE LOWER(first_name) LIKE '%{firstName}%' and LOWER(last_name) LIKE "
f"'%{lastName}%' and LOWER(name_post) LIKE '%{namePost}%' {yearStr} ORDER BY id_worker;"
)
return self.cursor.fetchall()
except Exception as e:
print(e)
return []
def selectPosts(self, salary, term, clearenceLevel):
if clearenceLevel == '':
idStr = ''
else:
idStr = f"and clearence_level = {clearenceLevel}"
if salary == '':
idStr2 = ''
else:
idStr2 = f"and salary = {salary}"
if term == '':
yearStr = ''
else:
yearStr = f"and term = date('{term}')"
try:
self.cursor.execute(
f"SELECT * FROM posts WHERE name_post LIKE '%%' {idStr} {idStr2} {yearStr} ORDER BY name_post;"
)
return self.cursor.fetchall()
except Exception as e:
print(e)
return []
def selectTickets(self, firstName, lastName, birthday, rating):
firstName = firstName.lower()
lastName = lastName.lower()
if birthday == '':
yearStr = ''
else:
yearStr = f"and birthday = date('{birthday}')"
if rating == '':
idStr = ''
else:
idStr = f"and rating = {rating}"
try:
self.cursor.execute(
f"SELECT * FROM tickets WHERE first_name LIKE '%{firstName}%' and last_name LIKE '%{lastName}%' {yearStr} "
f"{idStr} ORDER BY id_ticket;"
)
return self.cursor.fetchall()
except Exception as e:
print(e)
return []
def insertBooks(self, idBook, nameBook, state, genre, publishYear, idAuthor):
try:
self.cursor.execute(
F"INSERT INTO books(id_book, name_book, state, genre, publish_year, id_author) VALUES ({idBook}, "
F"'{nameBook}', {state}, '{genre}', '{publishYear}', {idAuthor});"
)
return True
except Exception as e:
print(e)
return False
def insertAuthors(self, idAuthor, firstName, lastName, birthday):
try:
self.cursor.execute(
F"INSERT INTO authors(id_author, first_name, last_name, birthday) VALUES ({idAuthor}, '{firstName}', "
F"'{lastName}', '{birthday}');"
)
return True
except Exception as e:
print(e)
return False
def insertFormulars(self, formularNum, idTicket, idWorker, dateTake, dateBack, books):
try:
self.cursor.execute(
F"INSERT INTO formulars(formular_num, id_ticket, id_worker, date_take, date_back, books) VALUES ("
F"{formularNum}, {idTicket}, {idWorker}, '{dateTake}', '{dateBack}', '{books}');"
)
return True
except Exception as e:
print(e)
return False
def insertTickets(self, idTicket, firstName, lastName, birthday, rating):
try:
self.cursor.execute(
F"INSERT INTO tickets(id_ticket, first_name, last_name, birthday, rating) VALUES ({idTicket}, "
F"'{firstName}', '{lastName}', '{birthday}', {rating});"
)
return True
except Exception as e:
print(e)
return False
def insertWorkers(self, idWorker, firstName, lastName, birthday, namePost):
try:
self.cursor.execute(
F"INSERT INTO library_workers(id_worker, first_name, last_name, birthday, name_post) VALUES ({idWorker},"
F"'{firstName}', '{lastName}', '{birthday}', '{namePost}');"
)
return True
except Exception as e:
print(e)
return False
def insertPost(self, namePost, salary, term, clearenceLevel):
try:
self.cursor.execute(
F"INSERT INTO posts(name_post, salary, term, clearence_level) VALUES ('{namePost}', {salary}, '{term}',"
F" {clearenceLevel});"
)
return True
except Exception as e:
print(e)
return False
def updateAuthors(self, idAuthor, firstName, lastName, birthday):
try:
self.cursor.execute(
F"UPDATE authors SET first_name='{firstName}', last_name='{lastName}', birthday='{birthday}'"
F"WHERE id_author = {idAuthor};"
)
return True
except Exception as e:
print(e)
return False
def updateBooks(self, idBook, nameBook, state, genre, publishYear, idAuthor):
try:
self.cursor.execute(
F"UPDATE books SET name_book='{nameBook}', state={state}, genre='{genre}', publish_year = '{publishYear}'"
F", id_author={idAuthor} WHERE id_book = {idBook};"
)
return True
except Exception as e:
print(e)
return False
def updateFormulars(self, formularNum, idTicket, idWorker, dateTake, dateBack, books):
try:
self.cursor.execute(
F"UPDATE formulars SET id_ticket={idTicket}, id_worker={idWorker}, date_take='{dateTake}', "
F"date_back = '{dateBack}', books='{books}' WHERE formular_num = {formularNum};"
)
return True
except Exception as e:
print(e)
return False
def updateTickets(self, idTicket, firstName, lastName, birthday, rating):
try:
self.cursor.execute(
F"UPDATE tickets SET first_name='{firstName}', last_name='{lastName}', birthday='{birthday}', "
F"rating = {rating} WHERE id_ticket = {idTicket};"
)
return True
except Exception as e:
print(e)
return False
def updateWorkers(self, idWorker, firstName, lastName, birthday, namePost):
try:
self.cursor.execute(
F"UPDATE library_workers SET first_name='{firstName}', last_name='{lastName}', birthday='{birthday}', "
F"name_post = '{namePost}' WHERE id_worker = {idWorker};"
)
return True
except Exception as e:
print(e)
return False
def updatePost(self, namePost, salary, term, clearenceLevel):
try:
self.cursor.execute(
F"UPDATE posts SET salary={salary}, term='{term}', clearence_level ='{clearenceLevel}'"
F" WHERE name_post = '{namePost}';"
)
return True
except Exception as e:
print(e)
return False
def deleteBook(self, idBook):
try:
self.cursor.execute(
F"DELETE FROM books WHERE id_book={idBook};"
)
return True
except Exception as e:
print(e)
return False
def deleteAuthor(self, idAuthor):
try:
self.cursor.execute(
F"DELETE FROM authors WHERE id_author={idAuthor};"
)
return True
except Exception as e:
print(e)
return False
def deleteFormular(self, formularNum):
try:
self.cursor.execute(
F"DELETE FROM formulars WHERE formular_num={formularNum};"
)
return True
except Exception as e:
print(e)
return False
def deleteTicket(self, idTicket):
try:
self.cursor.execute(
F"DELETE FROM tickets WHERE id_ticket={idTicket};"
)
return True
except Exception as e:
print(e)
return False
def deleteWorker(self, idWorker):
try:
self.cursor.execute(
F"DELETE FROM library_workers WHERE id_worker={idWorker};"
)
return True
except Exception as e:
print(e)
return False
def deletePost(self, postName):
try:
self.cursor.execute(
F"DELETE FROM posts WHERE name_post='{postName}';"
)
return True
except Exception as e:
print(e)
return False
def selectReaders(self):
try:
self.cursor.execute(
'SELECT public."getMax"(), public."getMin"();'
)
return self.cursor.fetchall()
except Exception as e:
print(e)
return []
def addBook(self, str, num):
try:
self.cursor.execute(
f"CALL public.add_book( '{str}', {num})"
)
except Exception as e:
print(e)
def changeState(self, num):
try:
self.cursor.execute(
f"CALL public.swap_state({num})"
)
except Exception as e:
print(e)
def selectFree(self, dbName, values):
try:
self.cursor.execute(
f'SELECT {values} FROM public."{dbName}";'
)
return self.cursor.fetchall()
except Exception as e:
print(e)
return []
def selectIJ(self, values, dbName, dbNameJoin, key):
try:
self.cursor.execute(
f'SELECT {values} FROM public."{dbName}" INNER JOIN public."{dbNameJoin}" ON {dbNameJoin}.{key} = {dbName}.{key};'
)
return self.cursor.fetchall()
except Exception as e:
print(e)
return []
def selectOB(self, values, dbName, key):
try:
self.cursor.execute(
f'SELECT {values} FROM public."{dbName}" ORDER BY {key};'
)
return self.cursor.fetchall()
except Exception as e:
print(e)
return []