-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibrary.py
1296 lines (1203 loc) · 54.9 KB
/
library.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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import psycopg2
from colorama import init, Fore, Back, Style
from tabulate import tabulate
conn = psycopg2.connect(
database="librarydb",
host="localhost",
user="postgres",
password="Mounika@2004",
port=5432,
)
mycursor = conn.cursor()
init(autoreset=True)
menu = f"""
{Fore.BLUE}{Style.BRIGHT}┌────────────────────────────────────────────────────────────┐
│{Fore.MAGENTA}{Style.BRIGHT} IITDh Library {Fore.BLUE}{Style.BRIGHT}│
│{Fore.GREEN}{Style.BRIGHT} Main Menu {Fore.BLUE}{Style.BRIGHT}│
│{Fore.GREEN}{Style.BRIGHT} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.CYAN}{Style.BRIGHT} Enter the respective numbers to perform the required task: {Fore.BLUE}{Style.BRIGHT}│
│ {Fore.YELLOW}1. Borrow/Renew a Book {Fore.BLUE}{Style.BRIGHT}│
│ {Fore.YELLOW}2. Return a Book {Fore.BLUE}{Style.BRIGHT}│
│ {Fore.YELLOW}3. Book/Ebook Search {Fore.BLUE}{Style.BRIGHT}│
│ {Fore.YELLOW}4. Book Information {Fore.BLUE}{Style.BRIGHT}│
│ {Fore.YELLOW}5. Add records {Fore.BLUE}{Style.BRIGHT}│
│ {Fore.YELLOW}6. Delete records {Fore.BLUE}{Style.BRIGHT}│
│ {Fore.RED}7. Exit {Fore.BLUE}{Style.BRIGHT}│
{Fore.BLUE}{Style.BRIGHT}└────────────────────────────────────────────────────────────┘{Fore.WHITE}{Style.BRIGHT}
"""
def add_book(
book_id,
title,
cpys,
image_url,
ISBN,
publication_year,
description,
ddc_classification,
publication_date,
language,
price,
publication_details,
edition,
document_type,
online_access,
):
try:
if not image_url:
image_url = None
if not ISBN:
ISBN = None
if not publication_year:
publication_year = None
if not description:
description = None
if not ddc_classification:
ddc_classification = None
if not publication_details:
publication_details = None
if not online_access:
online_access = None
if not edition:
edition = None
if not document_type:
document_type = None
if not publication_date:
publication_date = None
if not language:
language = None
if not price:
price = None
if not title and book_id:
print("Title and Book ID is a required field for a book.")
return
insert_query = """
INSERT INTO books (book_id, title, image_url, ISBN, publication_year, copies_available_to_draw, total_copies, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
"""
mycursor.execute(
insert_query,
(
book_id,
title,
image_url,
ISBN,
publication_year,
cpys,
cpys,
description,
ddc_classification,
publication_date,
language,
price,
publication_details,
edition,
document_type,
online_access,
),
)
conn.commit()
print(f"Book '{title}' with ID {book_id} has been added.")
except psycopg2.Error as e:
conn.rollback()
print("An error occurred while adding a book:", e)
def add_ebook(
book_id,
title,
image_url,
ISBN,
publication_year,
description,
ddc_classification,
publication_date,
language,
price,
publication_details,
edition,
document_type,
online_access,
):
try:
if not image_url:
image_url = None
if not ISBN:
ISBN = None
if not publication_year:
publication_year = None
if not description:
description = None
if not ddc_classification:
ddc_classification = None
if not publication_details:
publication_details = None
if not online_access:
online_access = None
if not edition:
edition = None
if not document_type:
document_type = None
if not publication_date:
publication_date = None
if not language:
language = None
if not price:
price = None
if not title and book_id:
print("Title and Book ID is a required field for a E-book.")
return
insert_query = """
INSERT INTO ebooks (book_id, title, image_url, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
"""
mycursor.execute(
insert_query,
(
book_id,
title,
image_url,
ISBN,
publication_year,
description,
ddc_classification,
publication_date,
language,
price,
publication_details,
edition,
document_type,
online_access,
),
)
conn.commit()
print(f"Book '{title}' with ID {book_id} has been added.")
except psycopg2.Error as e:
conn.rollback()
print("An error occurred while adding a book:", e)
def faculty_checkout_search(sid):
try:
query = """SELECT sc.checkout_id,
sc.checkout_date,
sc.due_date,
sc.renewal_count,
sc.return_date,
b.book_id,
b.title AS book_title
FROM faculty_checkouts sc
JOIN books b ON sc.book_id = b.book_id
WHERE sc.faculty_id = %s;
"""
mycursor.execute(query, (sid,))
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print("No matching records found.")
except psycopg2.Error as e:
print("An error occurred while searching for records:", e)
def student_checkout_search(sid):
try:
query = """SELECT sc.checkout_id,
sc.checkout_date,
sc.due_date,
sc.renewal_count,
sc.return_date,
b.book_id,
b.title AS book_title
FROM student_checkouts sc
JOIN books b ON sc.book_id = b.book_id
WHERE sc.student_id = %s;
"""
mycursor.execute(query, (sid,))
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print("No matching records found.")
except psycopg2.Error as e:
print("An error occurred while searching for records:", e)
def overdue_search():
try:
query = """SELECT fc.checkout_id, fc.faculty_id AS borrower_id, fc.book_id, fc.due_date, 'Faculty' AS borrower_type, f.faculty_name AS borrower_name, CASE WHEN fc.due_date < CURRENT_DATE THEN CURRENT_DATE - fc.due_date ELSE 0 END AS days_overdue FROM faculty_checkouts fc LEFT JOIN faculty f ON fc.faculty_id = f.faculty_id WHERE fc.due_date < CURRENT_DATE AND fc.return_date IS NULL UNION ALL SELECT sc.checkout_id, sc.student_id AS borrower_id, sc.book_id, sc.due_date, 'Student' AS borrower_type, s.student_name AS borrower_name, CASE WHEN sc.due_date < CURRENT_DATE THEN CURRENT_DATE - sc.due_date ELSE 0 END AS days_overdue FROM student_checkouts sc LEFT JOIN student s ON sc.student_id = s.student_id WHERE sc.due_date < CURRENT_DATE AND sc.return_date IS NULL;"""
mycursor.execute(query)
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print("No overdue books.")
except psycopg2.Error as e:
print("An error occurred while searching for records:", e)
def document_type_search(inpdocument_type):
try:
query = """SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM books
WHERE document_type = %s
UNION
SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM ebooks
WHERE document_type = %s;"""
mycursor.execute(query, (inpdocument_type, inpdocument_type))
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print(
"No records matching the specified document type were found in the database."
)
except psycopg2.Error as e:
print("An error occurred while searching for records:", e)
def author_search(author):
try:
query = """SELECT books.book_id, books.title
FROM books
JOIN book_author ON books.book_id = book_author.book_id
JOIN author ON book_author.author_id = author.author_id
WHERE author.author_name = %s;"""
mycursor.execute(query, (author,))
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print("No books matching the author were found in the database.")
except psycopg2.Error as e:
print(e)
def subject_search(subject):
try:
query = """SELECT books.book_id, books.title
FROM books
JOIN subject_books ON books.book_id = subject_books.book_id
JOIN subjects ON subject_books.subject_id = subjects.subject_id
WHERE subjects.subject_name = %s;"""
mycursor.execute(query, (subject,))
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print("No books matching the subject were found in the database.")
except psycopg2.Error as e:
print(e)
def avgrating_search(avg_rating):
try:
query = """SELECT books.book_id, books.title, ROUND(AVG(rating.rating), 2) AS average_rating
FROM books
LEFT JOIN rating ON books.book_id = rating.book_id
GROUP BY books.book_id, books.title
HAVING AVG(rating.rating) >= %s
ORDER BY average_rating DESC;"""
mycursor.execute(query, (avg_rating,))
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print("No books above the rating were found in the database.")
except psycopg2.Error as e:
print(e)
def popular_books():
try:
query = """SELECT books.book_id, books.title, COUNT(*) AS total_checkouts
FROM books
LEFT JOIN faculty_checkouts ON books.book_id = faculty_checkouts.book_id
LEFT JOIN student_checkouts ON books.book_id = student_checkouts.book_id
GROUP BY books.book_id, books.title
ORDER BY total_checkouts DESC;"""
mycursor.execute(query)
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
except psycopg2.Error as e:
print(e)
def copycount(book_id):
try:
query = """SELECT copies_available_to_draw
FROM books
WHERE book_id = %s;"""
mycursor.execute(query, (book_id,))
results = mycursor.fetchall()
if results[0][0] > 0:
print("There are %s copies available at the moment.\n" % results[0][0])
else:
print(
"There are no copies of the requested book available at the moment.\n"
)
except psycopg2.Error as e:
print(e)
def name_search(name):
try:
query = """SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM books
WHERE title LIKE %s
UNION
SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM ebooks
WHERE title LIKE %s;"""
mycursor.execute(query, ("%" + name + "%", "%" + name + "%"))
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print("No records matching the specified name were found in the database.")
except psycopg2.Error as e:
print("An error occurred while searching for records:", e)
def language_search(inplang):
try:
query = """SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM books
WHERE language = %s
UNION
SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM ebooks
WHERE language = %s;"""
mycursor.execute(query, (inplang, inplang))
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print(
"No records matching the specified language were found in the database."
)
except psycopg2.Error as e:
print("An error occurred while searching for records:", e)
def edition_search(edition):
try:
query = """SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM books
WHERE edition = %s
UNION
SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM ebooks
WHERE edition = %s;"""
mycursor.execute(query, (edition, edition))
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print("No records with the specified edition were found in the database.")
except psycopg2.Error as e:
print("An error occurred while searching for records:", e)
def publication_year_search():
try:
query = """ SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM books WHERE publication_year = %s
UNION
SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM ebooks WHERE publication_year = %s;"""
mycursor.execute(query, (inpyear, inpyear))
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print(
"No records with the specified publication year were found in the database."
)
except psycopg2.Error as e:
print("An error occurred while searching for records:", e)
def add_student(student_id, student_name, phone, email, enrollment_date, dept_id):
try:
if not student_id or not student_name or not enrollment_date or not dept_id:
print(
"Student ID, Name, Enrollment Date, and Department are required fields."
)
return
phone = phone or None
email = email or None
query = """
INSERT INTO student (student_id, student_name, phone, email, enrollment_date, dept_id)
VALUES (%s, %s, %s, %s, %s, %s);
"""
mycursor.execute(
query, (student_id, student_name, phone, email, enrollment_date, dept_id)
)
conn.commit()
print(f"Student {student_name} with ID {student_id} has been added.")
except psycopg2.Error as e:
conn.rollback()
print("An error occurred while adding a student:", e)
def borrow_or_renew(bid, sid):
mycursor.execute("BEGIN;")
check = "SELECT COUNT(*) FROM student WHERE student_id = %s"
mycursor.execute(check, (sid,))
res = mycursor.fetchall()
if res[0][0] <= 0:
print("No matching student found with the given ID.")
return
check = "SELECT COUNT(*) FROM books WHERE book_id = %s"
mycursor.execute(check, (bid,))
res = mycursor.fetchall()
if res[0][0] <= 0:
print("No matching books found with the given ID.")
return
check = "SELECT COUNT(*) FROM books WHERE book_id = %s AND copies_available_to_draw > 0;"
mycursor.execute(check, (bid,))
res = mycursor.fetchall()
if res[0][0] <= 0:
print("No copies of requested book available to draw.")
return
# do count is 0,1,2 and renewing or count is 0,1 and not renewing check
check = "SELECT COUNT(*) FROM student_checkouts WHERE student_id = %s AND return_date IS NULL;"
mycursor.execute(check, (sid,))
res = mycursor.fetchall()
if res[0][0] == 2:
check = "SELECT COUNT(*) FROM student_checkouts WHERE student_id = %s AND book_id = %s AND return_date IS NULL"
mycursor.execute(check, (sid, bid))
res = mycursor.fetchall()
if res[0][0] == 0:
print("Cannot borrow more than 2 books at a time.")
return
else:
query = """UPDATE student_checkouts SET return_date = NOW() WHERE student_id = %s AND book_id = %s AND return_date IS NULL;
INSERT INTO student_checkouts (student_id, book_id, due_date, checkout_date, renewal_count) VALUES (%s, %s, NOW() + INTERVAL '2 weeks', NOW(), (select renewal_count FROM student_checkouts WHERE student_id = %s AND book_id = %s order by renewal_count desc limit 1) + 1);
"""
params = (sid, bid, sid, bid, sid, bid)
try:
mycursor.execute(query, params)
conn.commit()
check = "SELECT count(*) FROM student_checkouts WHERE student_id = %s AND book_id = %s AND return_date IS NULL"
mycursor.execute(check, (sid, bid))
res = mycursor.fetchall()
if res[0][0] >= 1:
print("Book renewed successfully.")
return
else:
print("Book borrowed successfully.")
return
except psycopg2.Error as e:
print(e)
return
elif res[0][0] < 2:
query = """DO $$
BEGIN
IF EXISTS (SELECT 1 FROM books WHERE book_id = %s AND copies_available_to_draw > 0) THEN
IF (SELECT COUNT(*) FROM student_checkouts WHERE student_id = %s AND return_date IS NULL) < 2 THEN
IF EXISTS (SELECT 1 FROM student WHERE student_id = %s) AND EXISTS (SELECT 1 FROM books WHERE book_id = %s) THEN
IF EXISTS (SELECT 1 FROM student_checkouts WHERE student_id = %s AND book_id = %s AND return_date IS NULL) THEN
UPDATE student_checkouts SET return_date = NOW() WHERE student_id = %s AND book_id = %s AND return_date IS NULL;
INSERT INTO student_checkouts (student_id, book_id, due_date, checkout_date, renewal_count) VALUES (%s, %s, NOW() + INTERVAL '2 weeks', NOW(), (select renewal_count FROM student_checkouts WHERE student_id = %s AND book_id = %s order by renewal_count desc limit 1) + 1);
ELSE
INSERT INTO student_checkouts (student_id, book_id, due_date, checkout_date) VALUES (%s, %s, NOW() + INTERVAL '2 weeks', NOW());
UPDATE books SET copies_available_to_draw = copies_available_to_draw - 1 WHERE book_id = %s;
END IF;
END IF;
END IF;
END IF;
END $$;"""
params = (
bid,
sid,
sid,
bid,
sid,
bid,
sid,
bid,
sid,
bid,
sid,
bid,
sid,
bid,
bid,
)
try:
mycursor.execute(query, params)
conn.commit()
check = "SELECT count(*) FROM student_checkouts WHERE student_id = %s AND book_id = %s AND return_date IS NULL"
mycursor.execute(check, (sid, bid))
res = mycursor.fetchall()
print("Book borrowed successfully.")
return
except psycopg2.Error as e:
print(e)
return
else:
print("Cannot borrow more than 2 books at a time.")
return
def retbook(bid, sid):
mycursor.execute("BEGIN;")
retcheck = "SELECT COUNT(*) FROM student_checkouts WHERE student_id = %s AND book_id = %s AND return_date is null;"
mycursor.execute(retcheck, (sid, bid))
ret = mycursor.fetchall()
if ret[0][0] > 0:
returns = "UPDATE student_checkouts SET return_date = NOW()::DATE where book_id = %s and student_id = %s and return_date IS NULL;"
params = (bid, sid)
try:
mycursor.execute(returns, params)
conn.commit()
except psycopg2.Error as e:
print(e)
q1 = "SELECT copies_available_to_draw FROM books WHERE book_id = %s;"
mycursor.execute(q1, (bid,))
book_count = mycursor.fetchall()
avail_copies = book_count[0][0]
newcopycount = avail_copies + 1
copyincrease = (
"UPDATE books SET copies_available_to_draw = %s where book_id = %s ;"
)
mycursor.execute(copyincrease, (newcopycount, bid))
conn.commit()
print("Book returned successfully.")
else:
print(
f"No records found for student ID {sid} and book ID {bid} in the return list."
)
return
def book_exists(book_id):
query = "SELECT 1 FROM books WHERE book_id = %s"
mycursor.execute(query, (book_id,))
return mycursor.fetchone() is not None
def book_exists(book_id):
query = "SELECT 1 FROM ebooks WHERE book_id = %s"
mycursor.execute(query, (book_id,))
return mycursor.fetchone() is not None
def add_rating(rating, book_id):
try:
if not book_exists(book_id):
print(f"Book with ID {book_id} does not exist.")
return
query = """
INSERT INTO rating (rating, book_id)
VALUES (%s, %s);
"""
mycursor.execute(query, (rating, book_id))
conn.commit()
print(f"Rating {rating} for Book ID {book_id} has been added.")
except psycopg2.Error as e:
conn.rollback()
print("An error occurred while adding a rating:", e)
def add_ebook_rating(rating, book_id):
try:
if not book_exists(book_id):
print(f"E-Book with ID {book_id} does not exist.")
return
query = """
INSERT INTO e_rating (rating, book_id)
VALUES (%s, %s);
"""
mycursor.execute(query, (rating, book_id))
conn.commit()
print(f"Rating {rating} for E-Book ID {book_id} has been added.")
except psycopg2.Error as e:
conn.rollback()
print("An error occurred while adding a rating:", e)
def ISBN_search(inpisbn):
try:
query = """SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM books
WHERE isbn = %s
UNION
SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM ebooks
WHERE isbn = %s LIMIT 1;"""
mycursor.execute(query, (inpisbn, inpisbn))
results = mycursor.fetchall()
if results:
rows = []
headers = [
"Book ID:",
"Title:",
"Image URL:",
"ISBN:",
"Publication Year:",
"Description:",
"DDC Classification:",
"Publication Date:",
"Language:",
"Price:",
"Publication Details:",
"Edition:",
"Document Type:",
"Online Access:",
]
for row in results:
for i in range(len(row)):
rows.append([headers[i], row[i]])
print("\n Book Details: ")
print(tabulate(rows, tablefmt="grid"))
else:
print("ISBN not found in the database.")
except psycopg2.Error as e:
print(e)
def price_search(min, max):
try:
query = """SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM books
WHERE price between %s AND %s
UNION
SELECT book_id, title, ISBN, publication_year, description, ddc_classification, publication_date, language, price, publication_details, edition, document_type, online_access
FROM ebooks
WHERE price BETWEEN %s AND %s;"""
mycursor.execute(query, (min, max, min, max))
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print(
"No books matching the specified price range were found in the database."
)
except psycopg2.Error as e:
print(e)
def subject_book_exists(subject_id, book_id):
query = "SELECT 1 FROM subject_books WHERE subject_id = %s AND book_id = %s"
mycursor.execute(query, (subject_id, book_id))
return mycursor.fetchone() is not None
def add_subject_book(subject_id, book_id):
try:
if not subject_book_exists(subject_id, book_id):
query = """
INSERT INTO subject_books (subject_id, book_id)
VALUES (%s, %s);
"""
mycursor.execute(query, (subject_id, book_id))
conn.commit()
print(
f"Subject with ID {subject_id} and Book with ID {book_id} have been associated."
)
else:
print(
f"Subject with ID {subject_id} and Book with ID {book_id} are already associated."
)
except psycopg2.Error as e:
conn.rollback()
print("An error occurred while adding a subject book association:", e)
def view_checked_out_books():
try:
query = """
SELECT fc.checkout_id, fc.faculty_id AS borrower_id, fc.book_id, fc.due_date,
'Faculty' AS borrower_type, f.faculty_name AS borrower_name
FROM faculty_checkouts fc
LEFT JOIN faculty f ON fc.faculty_id = f.faculty_id
WHERE fc.return_date IS NULL
UNION ALL
SELECT sc.checkout_id, sc.student_id AS borrower_id, sc.book_id, sc.due_date,
'Student' AS borrower_type, s.student_name AS borrower_name
FROM student_checkouts sc
LEFT JOIN student s ON sc.student_id = s.student_id
WHERE sc.return_date IS NULL;
"""
mycursor.execute(query)
results = mycursor.fetchall()
if results:
headers = [desc[0] for desc in mycursor.description]
formatted_results = [list(row) for row in results]
print(tabulate(formatted_results, headers, tablefmt="pretty"))
else:
print("No books are currently checked out.")
except psycopg2.Error as e:
print("An error occurred while retrieving checked-out books:", e)
def author_exists(author_id):
query = "SELECT 1 FROM author WHERE author_id = %s"
mycursor.execute(query, (author_id,))
return mycursor.fetchone() is not None
def get_average_rating(book_id):
try:
mycursor.execute("SELECT 1 FROM books WHERE book_id = %s", (book_id,))
if not mycursor.fetchone():
print(f"Book with ID {book_id} does not exist.")
return
mycursor.execute(
"SELECT AVG(rating) FROM rating WHERE book_id = %s", (book_id,)
)
average_rating = mycursor.fetchone()[0]
if average_rating is not None:
print(f"The average rating for Book ID {book_id} is: {average_rating:.2f}")
else:
print(f"No ratings found for Book ID {book_id}")
except psycopg2.Error as e:
print("An error occurred:", e)
def add_author(author_id, author_name):
try:
if not author_name:
print("Author Name is a required field for an author.")
return
if author_exists(author_id):
print(f"An author with ID {author_id} already exists.")
return
query = """
INSERT INTO author (author_id, author_name)
VALUES (%s, %s);
"""
mycursor.execute(query, (author_id, author_name))
conn.commit()
print(f"Author '{author_name}' with ID {author_id} has been added.")
except psycopg2.Error as e:
conn.rollback()
print("An error occurred while adding an author:", e)
def book_author_exists(book_id, author_id):
query = "SELECT 1 FROM book_author WHERE book_id = %s AND author_id = %s"
mycursor.execute(query, (book_id, author_id))
return mycursor.fetchone() is not None
def subject_exists(subject_id):
query = "SELECT 1 FROM subjects WHERE subject_id = %s"
mycursor.execute(query, (subject_id,))
return mycursor.fetchone() is not None
def add_subject(subject_id, subject_name):
try:
if not subject_name:
print("Subject Name is a required field for a subject.")
return
if subject_exists(subject_id):
print(f"A subject with ID {subject_id} already exists.")
return
query = """
INSERT INTO subjects (subject_id, subject_name)
VALUES (%s, %s);
"""
mycursor.execute(query, (subject_id, subject_name))
conn.commit()
print(f"Subject '{subject_name}' with ID {subject_id} has been added.")
except psycopg2.Error as e:
conn.rollback()
print("An error occurred while adding a subject:", e)
def create_menu(title, options):
menu = f"""
{Fore.BLUE}{Style.BRIGHT}┌─────────────────────────────────────────────┐
│{Fore.MAGENTA}{Style.BRIGHT} {title} {Fore.BLUE}{Style.BRIGHT} │
│ │
{Fore.BLUE}{Style.BRIGHT}│{Fore.CYAN}{Style.BRIGHT} Enter the respective numbers to perform {Fore.BLUE}{Style.BRIGHT}│
{Fore.BLUE}{Style.BRIGHT}│{Fore.CYAN}{Style.BRIGHT} the required task: {Fore.BLUE}{Style.BRIGHT}│
│ │
"""
for index, option in enumerate(options, start=1):
menu += f"{Fore.YELLOW}{Style.BRIGHT}│ {index}. {option} {Fore.BLUE}{Style.BRIGHT}│\n"
menu += (
f"{Fore.BLUE}{Style.BRIGHT}│ │\n"
)
menu += f"{Fore.BLUE}{Style.BRIGHT}└─────────────────────────────────────────────┘{Style.RESET_ALL}\n {Fore.WHITE}{Style.BRIGHT}"
return menu
def add_book_author(book_id, author_id):
try:
if not book_author_exists(book_id, author_id):
query = """
INSERT INTO book_author (book_id, author_id)
VALUES (%s, %s);
"""
mycursor.execute(query, (book_id, author_id))
conn.commit()
print(
f"Book with ID {book_id} and Author with ID {author_id} have been associated."
)
else:
print(
f"Book with ID {book_id} and Author with ID {author_id} are already associated."
)
except psycopg2.Error as e:
conn.rollback()
print("An error occurred while adding a book author association:", e)
def add_faculty(faculty_id, faculty_name, office_location, dept_id, office_phone):
try:
if not faculty_id or not faculty_name or not dept_id:
print("Faculty ID, Name, and Department are required fields.")
return
office_location = office_location or None
query = """
INSERT INTO faculty (faculty_id, faculty_name, office_location, dept_id)
VALUES (%s, %s, %s, %s);
"""
mycursor.execute(query, (faculty_id, faculty_name, office_location, dept_id))
conn.commit()
if office_phone:
phone_query = """
INSERT INTO faculty_office_phone (office_phone, faculty_id)
VALUES (%s, %s);
"""
mycursor.execute(phone_query, (office_phone, faculty_id))
conn.commit()
print(f"Faculty {faculty_name} with ID {faculty_id} has been added.")
except psycopg2.Error as e:
conn.rollback()
print("An error occurred while adding a faculty member:", e)
running = True
while running:
try:
option = input(menu)
if option == "1":
try:
sid = int(input("Enter Student ID: "))
check1 = "SELECT * FROM student WHERE student_id = %s;"
mycursor.execute(check1, (sid,))
student = mycursor.fetchall()
if not student:
print("Student not on the database")
conn.rollback()
exit()
bid = int(input("Enter Book ID: "))
check2 = "SELECT * FROM books WHERE book_id = %s;"
mycursor.execute(check2, (bid,))
book = mycursor.fetchall()
if not book:
print("Invalid Book")
conn.rollback()
borrow_or_renew(bid, sid)
except psycopg2.Error as e:
print(e)
if option == "2":
try:
sid = int(input("Enter Student ID: "))
check1 = "SELECT * FROM student WHERE student_id = %s;"
mycursor.execute(check1, (sid,))
student = mycursor.fetchall()
if not student:
print("Student not on the database")
conn.rollback()
exit()
bid = int(input("Enter Book ID: "))
check2 = "SELECT * FROM books WHERE book_id = %s;"
mycursor.execute(check2, (bid,))
book = mycursor.fetchall()
if not book:
print("Invalid Book")
conn.rollback()
exit()
retbook(bid, sid)
except psycopg2.Error as e:
print(e)
if option == "3":
criteria_menu = f"""
{Fore.BLUE}{Style.BRIGHT}┌────────────────────────────────────────┐
│{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}Retrieve books based on:{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.YELLOW} 1. Name{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.YELLOW} 2. Publication Year{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.YELLOW} 3. Language{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.YELLOW} 4. Price range{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.YELLOW} 5. Edition{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.YELLOW} 6. Document Type{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.YELLOW} 7. ISBN{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.YELLOW} 8. Author{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.YELLOW} 9. Subject{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.YELLOW} 10. Average Rating{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
│{Fore.YELLOW} 11. Popularity{Style.RESET_ALL} {Fore.BLUE}{Style.BRIGHT}│
└────────────────────────────────────────┘{Fore.WHITE}{Style.BRIGHT}
"""
basedon = input(criteria_menu)
if basedon == "1":
name = input("Enter Relevant Name: ")
name_search(name)
if basedon == "2":
inpyear = input("Enter the publication year you want to search for: \n")
publication_year_search()
if basedon == "3":
query = "SELECT DISTINCT(language) FROM books UNION SELECT DISTINCT(language) FROM ebooks;"
mycursor.execute(query)
print("Available languages in the database:")
for row in mycursor.fetchall():
language = row[0]
print(f"- {language}")
inplang = input("Enter the language of the books you are looking for: ")
language_search(inplang)