-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsql_commands.py
More file actions
1640 lines (1488 loc) · 64.6 KB
/
Copy pathsql_commands.py
File metadata and controls
1640 lines (1488 loc) · 64.6 KB
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
#!/usr/bin/env python3
import cx_Oracle
import getpass
import sys
import os
import re
import validators
from rich.console import Console
from rich.prompt import Prompt, IntPrompt
from rich.table import Table
from rich.panel import Panel
from rich import box
from datetime import datetime
# Import the search module for option 15
import search_module # <--- New Import
import ra_module
# Initialize Rich Console
console = Console()
# Database connection parameters
DB_HOST = "oracle12c.cs.torontomu.ca" # Replace with your Oracle server host
DB_PORT = 1521 # Default Oracle port
DB_SID = "orcl12c" # Replace with your Oracle SID
# Function to establish database connection
def get_db_connection(username, password):
dsn = cx_Oracle.makedsn(DB_HOST, DB_PORT, sid=DB_SID)
try:
connection = cx_Oracle.connect(user=username, password=password, dsn=dsn)
return connection
except cx_Oracle.DatabaseError as e:
# Suppress detailed error messages for silent operations
if username and password:
# Attempt to provide minimal feedback if credentials are provided
console.print("[red]Failed to connect to the Oracle database. Please check your credentials and try again.[/red]")
sys.exit(1)
# Function to clean and split SQL script into executable statements
def split_sql_statements(sql_script):
# Remove all block comments (/* */)
sql_script = re.sub(r'/\*.*?\*/', '', sql_script, flags=re.DOTALL)
# Remove all single-line comments (-- ...)
sql_script = re.sub(r'--.*', '', sql_script)
# Split by semicolon
statements = sql_script.strip().split(';')
# Remove any leading/trailing whitespace from each statement
statements = [stmt.strip() for stmt in statements]
return statements
# Function to execute SQL from a file without printing errors
def execute_sql_file(connection, file_path):
if not os.path.isfile(file_path):
return False
with open(file_path, 'r') as file:
sql_script = file.read()
statements = split_sql_statements(sql_script)
try:
cursor = connection.cursor()
for stmt in statements:
if not stmt:
continue
if stmt.upper().startswith('SET') or stmt.upper().startswith('SPOOL'):
continue
try:
cursor.execute(stmt)
except cx_Oracle.DatabaseError:
continue # Silently ignore errors
connection.commit()
cursor.close()
return True
except cx_Oracle.DatabaseError:
try:
connection.rollback()
except:
pass
return False
# Function to run SQL scripts silently for options 1-6
def silent_execute(connection, file_path):
execute_sql_file(connection, file_path)
console.print("Finished executing script.")
# Functions corresponding to menu options 1-6
def create_tables(connection):
silent_execute(connection, "schema_creation.sql")
def drop_tables(connection):
silent_execute(connection, "delete_all_tables.sql")
def populate_tables(connection):
silent_execute(connection, "insert_sample_data.sql")
def delete_all_data(connection):
silent_execute(connection, "delete_all_data.sql")
def create_views(connection):
silent_execute(connection, "create_views.sql")
def drop_views(connection):
silent_execute(connection, "delete_all_views.sql")
def validate_date_format(date_str):
try:
datetime.strptime(date_str, '%Y-%m-%d')
return True
except ValueError:
return False
def validate_date_order(start_date, end_date):
start = datetime.strptime(start_date, '%Y-%m-%d')
end = datetime.strptime(end_date, '%Y-%m-%d')
return end >= start
def validate_zip_code(zip_code):
us_zip_pattern = r'^\d{5}(?:-\d{4})?$'
ca_zip_pattern = r'^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$'
return re.match(us_zip_pattern, zip_code) or re.match(ca_zip_pattern, zip_code)
def validate_email(email):
return validators.email(email)
# Function to execute an inline SQL query and display results
def execute_query(connection, query, params=None):
try:
cursor = connection.cursor()
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
columns = [desc[0] for desc in cursor.description]
table = Table(show_header=True, header_style="bold magenta", box=box.MINIMAL_DOUBLE_HEAD)
for col in columns:
table.add_column(str(col))
for row in cursor:
table.add_row(*[str(item) if item is not None else "NULL" for item in row])
console.print(table)
cursor.close()
except cx_Oracle.DatabaseError:
pass # Silently ignore query execution errors
def find_top_borrowed_authors(connection):
query = """
SELECT
A.Author_ID,
A.Name AS Author_Name,
COUNT(L.Loan_Number) AS Borrow_Count
FROM
Authors A
JOIN
BookAuthor BA ON A.Author_ID = BA.Author_ID
JOIN
Loans L ON BA.ISBN = L.ISBN
GROUP BY
A.Author_ID, A.Name
ORDER BY
Borrow_Count DESC
FETCH FIRST 5 ROWS ONLY
"""
execute_query(connection, query)
def list_overdue_loans(connection):
query = """
SELECT
BR.Borrower_ID,
U.First_Name || ' ' || U.Last_Name AS Borrower_Name,
L.Loan_Number,
L.Due_Date,
L.Return_Status,
TRUNC(SYSDATE - L.Due_Date) AS Days_Overdue
FROM
Loans L
JOIN
Borrowers BR ON L.Borrower_ID = BR.Borrower_ID
JOIN
Users U ON BR.User_ID = U.User_ID
WHERE
L.Return_Status = 'N'
AND L.Due_Date < SYSDATE
ORDER BY
Days_Overdue DESC
"""
execute_query(connection, query)
def find_genres_with_most_books(connection):
query = """
SELECT
G.Genre_ID,
G.Title AS Genre_Title,
COUNT(BG.ISBN) AS Number_of_Books
FROM
Genres G
JOIN
BookGenre BG ON G.Genre_ID = BG.Genre_ID
GROUP BY
G.Genre_ID, G.Title
HAVING COUNT(BG.ISBN) > 1
"""
execute_query(connection, query)
def list_admins_managing_most_books(connection):
query = """
SELECT
A.Admin_ID,
U.First_Name || ' ' || U.Last_Name AS Admin_Name,
COUNT(B.ISBN) AS Books_Managed
FROM
Administrators A
JOIN
Users U ON A.User_ID = U.User_ID
JOIN
Books B ON A.Admin_ID = B.Admin_ID
GROUP BY
A.Admin_ID, U.First_Name, U.Last_Name
ORDER BY
Books_Managed DESC
"""
execute_query(connection, query)
def show_total_fines(connection):
query = """
SELECT
A.Admin_ID,
U.First_Name || ' ' || U.Last_Name AS Admin_Name,
SUM(L.Fine_Amount) AS Total_Fines_Collected
FROM
Administrators A
JOIN
Users U ON A.User_ID = U.User_ID
JOIN
Loans L ON A.Admin_ID = L.Admin_ID
GROUP BY
A.Admin_ID, U.First_Name, U.Last_Name
ORDER BY
Total_Fines_Collected DESC
"""
execute_query(connection, query)
def find_authors_no_borrowed_books(connection):
query = """
SELECT
A.Author_ID,
A.Name AS Author_Name
FROM
Authors A
WHERE
NOT EXISTS (
SELECT 1
FROM BookAuthor BA
JOIN Loans L ON BA.ISBN = L.ISBN
WHERE BA.Author_ID = A.Author_ID
)
"""
execute_query(connection, query)
def list_unique_genres(connection):
query = """
SELECT Title AS Genre_Title FROM Genres
UNION
SELECT DISTINCT G.Title AS Genre_Title FROM Genres G
"""
execute_query(connection, query)
def show_books_not_borrowed_last_year(connection):
query = """
SELECT
B.ISBN,
B.Title
FROM
Books B
WHERE
B.ISBN NOT IN (
SELECT L.ISBN
FROM Loans L
WHERE L.Loan_Date >= ADD_MONTHS(SYSDATE, -12)
)
"""
execute_query(connection, query)
# New Functions: Adding, Updating, Deleting Records
def add_record(connection):
while True:
add_menu = Panel(
"\n".join([
"Add Records",
"----------------------------------------",
"1. Add Book",
"2. Add Author",
"3. Add Borrower",
"4. Add User",
"5. Add Administrator", # <--- New Option
"6. Add Genre", # <--- New Option
"7. Add Loan",
"8. Back to Main Menu",
"----------------------------------------"
]),
title="Add Menu",
subtitle="Choose an option [1-8]",
style="bold green",
box=box.DOUBLE_EDGE
)
console.print(add_menu)
try:
choice = IntPrompt.ask("Your choice", default=8)
except Exception:
console.print("[red]Invalid input. Please enter a number between 1 and 8.[/red]")
continue
console.print("\n")
if choice == 1:
add_book(connection)
elif choice == 2:
add_author(connection)
elif choice == 3:
add_borrower(connection)
elif choice == 4:
add_user(connection)
elif choice == 5:
add_administrator(connection) # <--- New Function
elif choice == 6:
add_genre(connection) # <--- New Function
elif choice == 7:
add_loan(connection)
elif choice == 8:
break
else:
console.print("[red]Invalid option. Please try again.[/red]")
pause()
def add_book(connection):
console.print("[bold underline]Add New Book[/bold underline]")
isbn = Prompt.ask("Enter ISBN")
title = Prompt.ask("Enter Title")
publication_date = Prompt.ask("Enter Publication Date (YYYY-MM-DD)")
pages = Prompt.ask("Enter Number of Pages")
copies_available = Prompt.ask("Enter Number of Copies Available")
publisher = Prompt.ask("Enter Publisher")
admin_id = Prompt.ask("Enter Admin ID who is adding the book")
# Check if Admin ID exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Administrators WHERE Admin_ID = :admin_id", admin_id=admin_id)
if cursor.fetchone() is None:
console.print(f"[red]Admin ID {admin_id} does not exist. Please add the administrator first.[/red]")
cursor.close()
return
cursor.close()
# Insert into Books
query = """
INSERT INTO Books (ISBN, Title, Publication_Date, Pages, Copies_Available, Publisher, Admin_ID)
VALUES (:isbn, :title, TO_DATE(:publication_date, 'YYYY-MM-DD'), :pages, :copies_available, :publisher, :admin_id)
"""
try:
cursor = connection.cursor()
cursor.execute(query, isbn=isbn, title=title, publication_date=publication_date,
pages=pages, copies_available=copies_available, publisher=publisher, admin_id=admin_id)
connection.commit()
console.print("[green]Book added successfully to the Books table.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to add book: {error.message}[/red]")
return
# Now, add entries to BookAuthor and BookGenre
# First, handle authors
while True:
author_id = Prompt.ask("Enter Author ID to associate with this book (leave blank to finish adding authors)")
if not author_id:
break
# Check if author exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Authors WHERE Author_ID = :author_id", author_id=author_id)
if cursor.fetchone() is None:
# Author does not exist
console.print(f"[red]Author ID {author_id} does not exist. Please add the author first.[/red]")
cursor.close()
continue
cursor.close()
# Insert into BookAuthor
try:
cursor = connection.cursor()
cursor.execute("INSERT INTO BookAuthor (ISBN, Author_ID) VALUES (:isbn, :author_id)", isbn=isbn, author_id=author_id)
connection.commit()
console.print(f"[green]Associated Author ID {author_id} with the book.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to associate author: {error.message}[/red]")
continue
# Now, handle genres
while True:
genre_id = Prompt.ask("Enter Genre ID to associate with this book (leave blank to finish adding genres)")
if not genre_id:
break
# Check if genre exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Genres WHERE Genre_ID = :genre_id", genre_id=genre_id)
if cursor.fetchone() is None:
# Genre does not exist
console.print(f"[red]Genre ID {genre_id} does not exist. Please add the genre first.[/red]")
cursor.close()
continue
cursor.close()
# Insert into BookGenre
try:
cursor = connection.cursor()
cursor.execute("INSERT INTO BookGenre (ISBN, Genre_ID) VALUES (:isbn, :genre_id)", isbn=isbn, genre_id=genre_id)
connection.commit()
console.print(f"[green]Associated Genre ID {genre_id} with the book.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to associate genre: {error.message}[/red]")
continue
def add_author(connection):
console.print("[bold underline]Add New Author[/bold underline]")
author_id = Prompt.ask("Enter Author ID")
# Check if Author ID already exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Authors WHERE Author_ID = :author_id", author_id=author_id)
if cursor.fetchone():
console.print(f"[red]Author ID {author_id} already exists. Please use a different Author ID.[/red]")
cursor.close()
return
cursor.close()
name = Prompt.ask("Enter Name")
nationality = Prompt.ask("Enter Nationality")
date_of_birth = Prompt.ask("Enter Date of Birth (YYYY-MM-DD)")
date_of_death = Prompt.ask("Enter Date of Death (YYYY-MM-DD, leave blank if alive)", default=None)
biography = Prompt.ask("Enter Biography", default=None)
languages = Prompt.ask("Enter Languages")
query = """
INSERT INTO Authors (Author_ID, Name, Nationality, Date_of_Birth, Date_of_Death, Biography, Languages)
VALUES (:author_id, :name, :nationality, TO_DATE(:date_of_birth, 'YYYY-MM-DD'),
TO_DATE(:date_of_death, 'YYYY-MM-DD'), :biography, :languages)
"""
try:
cursor = connection.cursor()
cursor.execute(query, author_id=author_id, name=name, nationality=nationality,
date_of_birth=date_of_birth, date_of_death=date_of_death if date_of_death else None,
biography=biography, languages=languages)
connection.commit()
console.print("[green]Author added successfully.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to add author: {error.message}[/red]")
def add_borrower(connection):
console.print("[bold underline]Add New Borrower[/bold underline]")
borrower_id = Prompt.ask("Enter Borrower ID")
user_id = Prompt.ask("Enter User ID")
# Check if User ID exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Users WHERE User_ID = :user_id", user_id=user_id)
user_exists = cursor.fetchone() is not None
cursor.close()
if not user_exists:
console.print(f"[yellow]User ID {user_id} does not exist in Users table.[/yellow]")
add_user_prompt = Prompt.ask("Do you want to add a new user? (y/n)", default="y").lower()
if add_user_prompt == 'y':
add_user(connection, user_id) # Pass user_id to add_user function
else:
console.print("[red]Cannot proceed without a valid User ID. Aborting add borrower.[/red]")
return
borrowing_limit = Prompt.ask("Enter Borrowing Limit")
amount_payable = Prompt.ask("Enter Amount Payable")
query = """
INSERT INTO Borrowers (Borrower_ID, User_ID, Borrowing_Limit, Amount_Payable)
VALUES (:borrower_id, :user_id, :borrowing_limit, :amount_payable)
"""
try:
cursor = connection.cursor()
cursor.execute(query, borrower_id=borrower_id, user_id=user_id, borrowing_limit=borrowing_limit, amount_payable=amount_payable)
connection.commit()
console.print("[green]Borrower added successfully.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to add borrower: {error.message}[/red]")
def add_user(connection, user_id=None):
console.print("[bold underline]Add New User[/bold underline]")
if user_id is None:
user_id = Prompt.ask("Enter User ID")
# Check if User ID already exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Users WHERE User_ID = :user_id", user_id=user_id)
if cursor.fetchone() is not None:
console.print(f"[red]User ID {user_id} already exists. Please use a different User ID.[/red]")
cursor.close()
return
cursor.close()
first_name = Prompt.ask("Enter First Name")
last_name = Prompt.ask("Enter Last Name")
phone_number = Prompt.ask("Enter Phone Number")
email = Prompt.ask("Enter Email")
while not validate_email(email):
console.print("[red]Invalid email format. Please enter a valid email address.[/red]")
email = Prompt.ask("Enter Email")
username = Prompt.ask("Enter Username")
password = Prompt.ask("Enter Password")
street = Prompt.ask("Enter Street")
city = Prompt.ask("Enter City")
state = Prompt.ask("Enter State")
zip_code = Prompt.ask("Enter ZIP Code")
while not validate_zip_code(zip_code):
console.print("[red]Invalid ZIP Code format. Please enter a valid US or Canadian ZIP Code.[/red]")
zip_code = Prompt.ask("Enter ZIP Code")
query = """
INSERT INTO Users (User_ID, First_Name, Last_Name, Phone_Number, Email, Username, Password, Street, City, State, ZIP_Code)
VALUES (:user_id, :first_name, :last_name, :phone_number, :email, :username, :password, :street, :city, :state, :zip_code)
"""
try:
cursor = connection.cursor()
cursor.execute(query, user_id=user_id, first_name=first_name, last_name=last_name,
phone_number=phone_number, email=email, username=username, password=password,
street=street, city=city, state=state, zip_code=zip_code)
connection.commit()
console.print("[green]User added successfully.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to add user: {error.message}[/red]")
def add_administrator(connection):
console.print("[bold underline]Add New Administrator[/bold underline]")
admin_id = Prompt.ask("Enter Admin ID")
user_id = Prompt.ask("Enter User ID")
# Check if User ID exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Users WHERE User_ID = :user_id", user_id=user_id)
user_exists = cursor.fetchone() is not None
cursor.close()
if not user_exists:
console.print(f"[yellow]User ID {user_id} does not exist in Users table.[/yellow]")
add_user_prompt = Prompt.ask("Do you want to add a new user? (y/n)", default="y").lower()
if add_user_prompt == 'y':
add_user(connection, user_id) # Pass user_id to add_user function
else:
console.print("[red]Cannot proceed without a valid User ID. Aborting add administrator.[/red]")
return
role = Prompt.ask("Enter Role")
permissions = Prompt.ask("Enter Permissions")
last_login = Prompt.ask("Enter Last Login Date (YYYY-MM-DD)", default=None)
query = """
INSERT INTO Administrators (Admin_ID, User_ID, Role, Permissions, Last_Login)
VALUES (:admin_id, :user_id, :role, :permissions, TO_DATE(:last_login, 'YYYY-MM-DD'))
"""
try:
cursor = connection.cursor()
cursor.execute(query, admin_id=admin_id, user_id=user_id, role=role,
permissions=permissions, last_login=last_login if last_login else None)
connection.commit()
console.print("[green]Administrator added successfully.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to add administrator: {error.message}[/red]")
def add_genre(connection):
console.print("[bold underline]Add New Genre[/bold underline]")
genre_id = Prompt.ask("Enter Genre ID")
# Check if Genre ID already exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Genres WHERE Genre_ID = :genre_id", genre_id=genre_id)
if cursor.fetchone():
console.print(f"[red]Genre ID {genre_id} already exists. Please use a different Genre ID.[/red]")
cursor.close()
return
cursor.close()
title = Prompt.ask("Enter Genre Title")
description = Prompt.ask("Enter Genre Description", default=None)
query = """
INSERT INTO Genres (Genre_ID, Title, Description)
VALUES (:genre_id, :title, :description)
"""
try:
cursor = connection.cursor()
cursor.execute(query, genre_id=genre_id, title=title, description=description)
connection.commit()
console.print("[green]Genre added successfully.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to add genre: {error.message}[/red]")
def add_loan(connection):
console.print("[bold underline]Add New Loan[/bold underline]")
loan_number = Prompt.ask("Enter Loan Number")
# Check if Loan Number already exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Loans WHERE Loan_Number = :loan_number", loan_number=loan_number)
if cursor.fetchone():
console.print(f"[red]Loan Number {loan_number} already exists. Please use a different Loan Number.[/red]")
cursor.close()
return
cursor.close()
borrower_id = Prompt.ask("Enter Borrower ID")
# Check if Borrower ID exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Borrowers WHERE Borrower_ID = :borrower_id", borrower_id=borrower_id)
if cursor.fetchone() is None:
console.print(f"[red]Borrower ID {borrower_id} does not exist.[/red]")
cursor.close()
return
cursor.close()
isbn = Prompt.ask("Enter ISBN")
# Check if ISBN exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Books WHERE ISBN = :isbn", isbn=isbn)
if cursor.fetchone() is None:
console.print(f"[red]ISBN {isbn} does not exist.[/red]")
cursor.close()
return
cursor.close()
admin_id = Prompt.ask("Enter Admin ID")
# Check if Admin ID exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Administrators WHERE Admin_ID = :admin_id", admin_id=admin_id)
if cursor.fetchone() is None:
console.print(f"[red]Admin ID {admin_id} does not exist.[/red]")
cursor.close()
return
cursor.close()
loan_date = Prompt.ask("Enter Loan Date (YYYY-MM-DD)", default=None)
due_date = Prompt.ask("Enter Due Date (YYYY-MM-DD)")
return_status = Prompt.ask("Enter Return Status (Y/N)", choices=['Y', 'N'], default='N')
# Validate dates
if not due_date:
console.print("[red]Due Date is required.[/red]")
return
if loan_date:
if not validate_date_format(loan_date):
console.print("[red]Invalid Loan Date format.[/red]")
return
else:
loan_date = None
if not validate_date_format(due_date):
console.print("[red]Invalid Due Date format.[/red]")
return
if loan_date and not validate_date_order(loan_date, due_date):
console.print("[red]Due Date cannot be earlier than Loan Date.[/red]")
return
query = """
INSERT INTO Loans (Loan_Number, Borrower_ID, ISBN, Loan_Date, Due_Date, Return_Status, Admin_ID)
VALUES (:loan_number, :borrower_id, :isbn, TO_DATE(:loan_date, 'YYYY-MM-DD'), TO_DATE(:due_date, 'YYYY-MM-DD'), :return_status, :admin_id)
"""
try:
cursor = connection.cursor()
cursor.execute(query, loan_number=loan_number, borrower_id=borrower_id, isbn=isbn,
loan_date=loan_date, due_date=due_date, return_status=return_status, admin_id=admin_id)
connection.commit()
console.print("[green]Loan added successfully.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to add loan: {error.message}[/red]")
def update_record(connection):
while True:
update_menu = Panel(
"\n".join([
"Update Records",
"----------------------------------------",
"1. Update Book",
"2. Update Author",
"3. Update Borrower",
"4. Update User",
"5. Update Administrator", # <--- New Option
"6. Update Book Genres", # <--- New Option
"7. Update Book Authors", # <--- New Option
"8. Update Genre", # <--- New Option
"9. Update Loans",
"10. Back to Main Menu",
"----------------------------------------"
]),
title="Update Menu",
subtitle="Choose an option [1-10]",
style="bold yellow",
box=box.DOUBLE_EDGE
)
console.print(update_menu)
try:
choice = IntPrompt.ask("Your choice", default=10)
except Exception:
console.print("[red]Invalid input. Please enter a number between 1 and 10.[/red]")
continue
console.print("\n")
if choice == 1:
update_book(connection)
elif choice == 2:
update_author(connection)
elif choice == 3:
update_borrower(connection)
elif choice == 4:
update_user(connection)
elif choice == 5:
update_administrator(connection) # <--- New Function
elif choice == 6:
manage_book_genres(connection) # <--- New Function
elif choice == 7:
manage_book_authors(connection) # <--- New Function
elif choice == 8:
update_genre(connection) # <--- New Function
elif choice == 9:
update_loan(connection)
elif choice == 10:
break
else:
console.print("[red]Invalid option. Please try again.[/red]")
pause()
def update_book(connection):
console.print("[bold underline]Update Book[/bold underline]")
isbn = Prompt.ask("Enter ISBN of the book to update")
# Fetch current data
query = "SELECT Title, Publication_Date, Pages, Copies_Available, Publisher, Admin_ID FROM Books WHERE ISBN = :isbn"
try:
cursor = connection.cursor()
cursor.execute(query, isbn=isbn)
result = cursor.fetchone()
if not result:
console.print("[red]Book not found.[/red]")
cursor.close()
return
(current_title, current_pub_date, current_pages, current_copies, current_publisher, current_admin_id) = result
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Error fetching book: {error.message}[/red]")
return
# Prompt for new data
title = Prompt.ask(f"Enter new Title (current: {current_title})", default=current_title)
publication_date = Prompt.ask(f"Enter new Publication Date (YYYY-MM-DD) (current: {current_pub_date.strftime('%Y-%m-%d')})",
default=current_pub_date.strftime('%Y-%m-%d'))
pages = Prompt.ask(f"Enter new Number of Pages (current: {current_pages})", default=str(current_pages))
copies_available = Prompt.ask(f"Enter new Copies Available (current: {current_copies})", default=str(current_copies))
publisher = Prompt.ask(f"Enter new Publisher (current: {current_publisher})", default=current_publisher)
admin_id = Prompt.ask(f"Enter new Admin ID (current: {current_admin_id})", default=str(current_admin_id))
# Check if Admin ID exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Administrators WHERE Admin_ID = :admin_id", admin_id=admin_id)
if cursor.fetchone() is None:
console.print(f"[red]Admin ID {admin_id} does not exist. Please add the administrator first.[/red]")
cursor.close()
return
cursor.close()
update_query = """
UPDATE Books
SET Title = :title,
Publication_Date = TO_DATE(:publication_date, 'YYYY-MM-DD'),
Pages = :pages,
Copies_Available = :copies_available,
Publisher = :publisher,
Admin_ID = :admin_id
WHERE ISBN = :isbn
"""
try:
cursor = connection.cursor()
cursor.execute(update_query, title=title, publication_date=publication_date, pages=pages,
copies_available=copies_available, publisher=publisher, admin_id=admin_id, isbn=isbn)
connection.commit()
console.print("[green]Book updated successfully.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to update book: {error.message}[/red]")
def update_loan(connection):
console.print("[bold underline]Update Loan[/bold underline]")
loan_number = Prompt.ask("Enter Loan Number to update")
# Fetch current data
query = "SELECT Borrower_ID, ISBN, Loan_Date, Due_Date, Return_Date, Fine_Amount, Return_Status, Admin_ID FROM Loans WHERE Loan_Number = :loan_number"
try:
cursor = connection.cursor()
cursor.execute(query, loan_number=loan_number)
result = cursor.fetchone()
if not result:
console.print("[red]Loan not found.[/red]")
cursor.close()
return
(current_borrower_id, current_isbn, current_loan_date, current_due_date, current_return_date,
current_fine_amount, current_return_status, current_admin_id) = result
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Error fetching loan: {error.message}[/red]")
return
# Prompt for new data
borrower_id = Prompt.ask(f"Enter new Borrower ID (current: {current_borrower_id})", default=str(current_borrower_id))
# Check if Borrower ID exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Borrowers WHERE Borrower_ID = :borrower_id", borrower_id=borrower_id)
if cursor.fetchone() is None:
console.print(f"[red]Borrower ID {borrower_id} does not exist.[/red]")
cursor.close()
return
cursor.close()
isbn = Prompt.ask(f"Enter new ISBN (current: {current_isbn})", default=current_isbn)
# Check if ISBN exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Books WHERE ISBN = :isbn", isbn=isbn)
if cursor.fetchone() is None:
console.print(f"[red]ISBN {isbn} does not exist.[/red]")
cursor.close()
return
cursor.close()
loan_date = Prompt.ask(f"Enter new Loan Date (YYYY-MM-DD) (current: {current_loan_date.strftime('%Y-%m-%d') if current_loan_date else 'N/A'})",
default=current_loan_date.strftime('%Y-%m-%d') if current_loan_date else None)
due_date = Prompt.ask(f"Enter new Due Date (YYYY-MM-DD) (current: {current_due_date.strftime('%Y-%m-%d') if current_due_date else 'N/A'})",
default=current_due_date.strftime('%Y-%m-%d') if current_due_date else None)
return_date = Prompt.ask(f"Enter new Return Date (YYYY-MM-DD) (current: {current_return_date.strftime('%Y-%m-%d') if current_return_date else 'N/A'})",
default=current_return_date.strftime('%Y-%m-%d') if current_return_date else None)
fine_amount = Prompt.ask(f"Enter new Fine Amount (current: {current_fine_amount})", default=str(current_fine_amount))
return_status = Prompt.ask(f"Enter new Return Status (Y/N) (current: {current_return_status})",
choices=['Y', 'N'], default=current_return_status)
admin_id = Prompt.ask(f"Enter new Admin ID (current: {current_admin_id})", default=str(current_admin_id))
# Check if Admin ID exists
cursor = connection.cursor()
cursor.execute("SELECT * FROM Administrators WHERE Admin_ID = :admin_id", admin_id=admin_id)
if cursor.fetchone() is None:
console.print(f"[red]Admin ID {admin_id} does not exist.[/red]")
cursor.close()
return
cursor.close()
# Validate dates
if loan_date and not validate_date_format(loan_date):
console.print("[red]Invalid Loan Date format.[/red]")
return
if due_date and not validate_date_format(due_date):
console.print("[red]Invalid Due Date format.[/red]")
return
if return_date and not validate_date_format(return_date):
console.print("[red]Invalid Return Date format.[/red]")
return
if loan_date and due_date and not validate_date_order(loan_date, due_date):
console.print("[red]Due Date cannot be earlier than Loan Date.[/red]")
return
if loan_date and return_date and not validate_date_order(loan_date, return_date):
console.print("[red]Return Date cannot be earlier than Loan Date.[/red]")
return
update_query = """
UPDATE Loans
SET Borrower_ID = :borrower_id,
ISBN = :isbn,
Loan_Date = TO_DATE(:loan_date, 'YYYY-MM-DD'),
Due_Date = TO_DATE(:due_date, 'YYYY-MM-DD'),
Return_Date = TO_DATE(:return_date, 'YYYY-MM-DD'),
Fine_Amount = :fine_amount,
Return_Status = :return_status,
Admin_ID = :admin_id
WHERE Loan_Number = :loan_number
"""
try:
cursor = connection.cursor()
cursor.execute(update_query, borrower_id=borrower_id, isbn=isbn,
loan_date=loan_date if loan_date else None,
due_date=due_date if due_date else None,
return_date=return_date if return_date else None,
fine_amount=fine_amount, return_status=return_status,
admin_id=admin_id, loan_number=loan_number)
connection.commit()
console.print("[green]Loan updated successfully.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to update loan: {error.message}[/red]")
def update_author(connection):
console.print("[bold underline]Update Author[/bold underline]")
author_id = Prompt.ask("Enter Author ID to update")
# Fetch current data
query = "SELECT Name, Nationality, Date_of_Birth, Date_of_Death, Biography, Languages FROM Authors WHERE Author_ID = :author_id"
try:
cursor = connection.cursor()
cursor.execute(query, author_id=author_id)
result = cursor.fetchone()
if not result:
console.print("[red]Author not found.[/red]")
cursor.close()
return
(current_name, current_nationality, current_dob, current_dod, current_bio, current_languages) = result
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Error fetching author: {error.message}[/red]")
return
# Prompt for new data
name = Prompt.ask(f"Enter new Name (current: {current_name})", default=current_name)
nationality = Prompt.ask(f"Enter new Nationality (current: {current_nationality})", default=current_nationality)
date_of_birth = Prompt.ask(f"Enter new Date of Birth (YYYY-MM-DD) (current: {current_dob.strftime('%Y-%m-%d')})",
default=current_dob.strftime('%Y-%m-%d'))
date_of_death = Prompt.ask(f"Enter new Date of Death (YYYY-MM-DD) (current: {current_dod.strftime('%Y-%m-%d') if current_dod else 'N/A'})",
default=current_dod.strftime('%Y-%m-%d') if current_dod else None)
biography = Prompt.ask(f"Enter new Biography (current: {current_bio})", default=current_bio if current_bio else "")
languages = Prompt.ask(f"Enter new Languages (current: {current_languages})", default=current_languages)
update_query = """
UPDATE Authors
SET Name = :name,
Nationality = :nationality,
Date_of_Birth = TO_DATE(:date_of_birth, 'YYYY-MM-DD'),
Date_of_Death = TO_DATE(:date_of_death, 'YYYY-MM-DD'),
Biography = :biography,
Languages = :languages
WHERE Author_ID = :author_id
"""
try:
cursor = connection.cursor()
cursor.execute(update_query, name=name, nationality=nationality, date_of_birth=date_of_birth,
date_of_death=date_of_death if date_of_death else None,
biography=biography, languages=languages, author_id=author_id)
connection.commit()
console.print("[green]Author updated successfully.[/green]")
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Failed to update author: {error.message}[/red]")
def update_borrower(connection):
console.print("[bold underline]Update Borrower[/bold underline]")
borrower_id = Prompt.ask("Enter Borrower ID to update")
# Fetch current data
query = "SELECT User_ID, Borrowing_Limit, Amount_Payable FROM Borrowers WHERE Borrower_ID = :borrower_id"
try:
cursor = connection.cursor()
cursor.execute(query, borrower_id=borrower_id)
result = cursor.fetchone()
if not result:
console.print("[red]Borrower not found.[/red]")
cursor.close()
return
current_user_id, current_limit, current_payable = result
cursor.close()
except cx_Oracle.DatabaseError as e:
error, = e.args
console.print(f"[red]Error fetching borrower: {error.message}[/red]")
return
# Prompt for new data
user_id = Prompt.ask(f"Enter new User ID (current: {current_user_id})", default=current_user_id)
# Check if User ID exists
cursor = connection.cursor()