-
Notifications
You must be signed in to change notification settings - Fork 1
/
database.py
1309 lines (1001 loc) · 50.8 KB
/
database.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
import queue
import sys
import os
_database_url = os.getenv('DATABASE_URL')
_connection_pool = queue.Queue()
def _get_connection():
try:
conn = _connection_pool.get(block=False)
except queue.Empty:
conn = psycopg2.connect(_database_url)
return conn
def _put_connection(conn):
_connection_pool.put(conn)
def insert_student(data):
# data is a dict which contains two key-values pairs, with keys student_name and student_email
connection = _get_connection()
try:
with connection.cursor() as cursor:
#check for missing arguments
for key, value in data.items():
if value is None or value == '':
return(False, "missing " + str(key) + ". Please try again with a proper input.")
cursor.execute('BEGIN')
#check for duplicates via user_email
statement = "SELECT FROM users WHERE user_email = %s;"
cursor.execute(statement, [data['student_email']])
table = cursor.fetchall()
if len(table) != 0:
return(False, "Email already in database. Please try again with a proper input.")
#create user_id
statement = "SELECT user_id FROM users ORDER BY user_id DESC LIMIT 1;"
cursor.execute(statement)
table = cursor.fetchall()
if len(table) != 0:
user_id = int(table[0][0]) + 1
else:
user_id = 1
#insert student info into users table
statement = "INSERT INTO users (user_id, user_name, user_email, user_status) VALUES (%s, %s, %s, 'student');"
params = [user_id, data['student_name'], data['student_email']]
cursor.execute(statement, params)
#update program_status table
statement = "SELECT program_id, program_availability FROM programs;"
cursor.execute(statement)
table = cursor.fetchall()
for row in table:
#row[0] is program_id
#row[1] is the program_availability
if row[1] == 'all':
user_program_status = 'available'
else:
user_program_status = 'locked'
statement = "INSERT INTO program_status (user_id, program_id, user_program_status) VALUES (%s, %s, %s);"
params = [user_id, row[0], user_program_status]
cursor.execute(statement, params)
#update assessment_status table
statement = "SELECT module_id FROM modules WHERE modules.content_type = 'assessment';"
cursor.execute(statement)
table = cursor.fetchall()
for row in table:
statement = "INSERT INTO assessment_status (user_id, module_id, user_assessment_status) VALUES (%s, %s, %s);"
# default 0 for incomplete
params = [user_id, row[0], 0]
cursor.execute(statement, params)
cursor.execute('COMMIT')
return (True, "successfully added a new student")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def insert_admin(data):
connection = _get_connection()
try:
with connection.cursor() as cursor:
#check for missing arguments
for key, value in data.items():
if value is None or value == '':
return(False, "Missing " + str(key) + ". Please try again with a proper input.")
cursor.execute('BEGIN')
#check for duplicates via user_email
statement = "SELECT FROM users WHERE user_email = %s;"
cursor.execute(statement, [data['admin_email']])
table = cursor.fetchall()
if len(table) != 0:
return(False, "Email already in database. Please try again with a proper input.")
#generate user_id
statement = "SELECT user_id FROM users ORDER BY user_id DESC LIMIT 1;"
cursor.execute(statement)
table = cursor.fetchall()
if len(table) != 0:
user_id = int(table[0][0]) + 1
else:
user_id = 1
# insert admin info into users table
statement = "INSERT INTO users (user_id, user_name, user_email, user_status) VALUES (%s, %s, %s, 'admin');"
params = [user_id, data['admin_name'], data['admin_email']]
cursor.execute(statement, params)
cursor.execute('COMMIT')
return (True, "successfully added a new admin")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def delete_user(user_id):
connection = _get_connection()
try:
with connection.cursor() as cursor:
assert user_id != None, 'User id should not be None. Please try again with a proper input or return.'
assert user_id != '', 'User id should not be empty. Please try again with a proper input or return.'
cursor.execute('BEGIN')
statement = "DELETE FROM users WHERE user_id=%s;"
cursor.execute(statement, [user_id])
statement = "DELETE FROM program_status WHERE user_id=%s;"
cursor.execute(statement, [user_id])
statement = "DELETE FROM assessment_status WHERE user_id=%s;"
cursor.execute(statement, [user_id])
cursor.execute('COMMIT')
return(True, "successfully deleted user")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def insert_program(data):
# data is a dict containing 3 values: name , desc, avail
connection = _get_connection()
try:
with connection.cursor() as cursor:
#check for missing arguments
for key, value in data.items():
if value is None or value == '':
return(False, "missing " + str(key) + ". Please try again with a proper input.")
if data['program_availability'] != 'all' and data['program_availability'] != 'none':
return(False, 'Program availability must be all or none. Please try again with a proper input.')
cursor.execute('BEGIN')
# check for duplicates via program name
statement = "SELECT FROM programs WHERE program_name = %s;"
cursor.execute(statement, [data['program_name']])
table = cursor.fetchall()
if len(table) != 0:
return(False, "Duplicate program name. Insertion aborted. Please try again with a proper input.")
# generate program_id
statement = """SELECT substring(program_id FROM '\d+')
from programs ORDER BY substring(program_id FROM '\d+')::INTEGER
DESC LIMIT 1;"""
cursor.execute(statement)
table = cursor.fetchall()
if len(table) != 0:
num = int(table[0][0]) + 1
else:
num = 1
program_id = 'p' + str(num)
print('program_id = ', program_id)
#insert program data
statement = "INSERT INTO programs (program_id, program_name, program_description, program_availability) VALUES (%s, %s, %s, %s);"
params = [program_id, data['program_name'], data['program_description'], data['program_availability']]
cursor.execute(statement, params)
# setting up user program status based on program availability
if data['program_availability'] == 'all':
user_pgm_status= 'available'
else:
user_pgm_status = 'locked'
#extracting all present students
statement = "SELECT user_id FROM users WHERE user_status='student';"
cursor.execute(statement)
table = cursor.fetchall()
# insert into program status, each user's corresponding status info
for row in table:
statement = "INSERT INTO program_status (user_id, program_id, user_program_status) VALUES (%s, %s, %s);"
params = [row[0], program_id, user_pgm_status]
cursor.execute(statement, params)
cursor.execute('COMMIT')
return (True, program_id)
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def delete_program(program_id):
connection = _get_connection()
try:
with connection.cursor() as cursor:
assert program_id != None, 'Program id should not be None. Please try again with a proper input or return.'
assert program_id != '', 'Program id should not be empty. Please try again with a proper input or return.'
cursor.execute('BEGIN')
# remove program from programs table
statement = "DELETE FROM programs WHERE program_id = %s;"
cursor.execute(statement, [program_id])
# find modules in program
statement = "SELECT module_id FROM modules WHERE program_id = %s;"
cursor.execute(statement, [program_id])
table = cursor.fetchall()
modules = []
for row in table:
modules.append(row[0])
# remove program from modules table
statement = "DELETE FROM modules WHERE program_id = %s;"
cursor.execute(statement, [program_id])
# remove program from program status
statement = "DELETE FROM program_status WHERE program_id = %s;"
cursor.execute(statement, [program_id])
# remove program's relevant modules from assessment status
for module_id in modules:
statement = "DELETE FROM assessment_status WHERE module_id = %s;"
cursor.execute(statement, [module_id])
cursor.execute('COMMIT')
return (True, "deleted program successfully")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def insert_module(data):
connection = _get_connection()
try:
with connection.cursor() as cursor:
#check for missing arguments
for key, value in data.items():
if value is None or value == '':
return(False, "missing " + str(key) + ". Please try again with a proper input.")
print('content type = ', data['content_type'])
if data['content_type'] != 'assessment' and data['content_type'] != 'text':
return(False, 'Module content type must be assessment or text. Please try again with a proper input.')
cursor.execute('BEGIN')
# check for duplicates for module name
statement = "SELECT FROM modules WHERE module_name = %s AND modules.program_id = %s;"
cursor.execute(statement, [data['module_name'], data['program_id']])
table = cursor.fetchall()
if len(table) != 0:
return(False, "Duplicate module name conflict. Insertion aborted. Please try again with a proper input.")
# generate module id
statement = """SELECT substring(module_id FROM '\d+')
from modules ORDER BY substring(module_id FROM '\d+')::INTEGER
DESC limit 1 """
cursor.execute(statement)
table = cursor.fetchall()
if len(table) != 0:
num = int(table[0][0]) + 1
else:
num = 1
module_id = 'm' + str(num)
# get module index
statement = "SELECT COUNT(module_id) FROM modules WHERE modules.program_id=%s;"
cursor.execute(statement, [data['program_id']])
table = cursor.fetchall()
module_index = table[0][0]+1
# insert module info into modules table
statement = "INSERT INTO modules (module_id, program_id, module_name, content_type, content_link, module_index) VALUES (%s, %s, %s, %s, %s, %s);"
params = [module_id, data['program_id'], data['module_name'], data['content_type'], data['content_link'], module_index]
cursor.execute(statement, params)
# if the module is an assessment, update user assessment status
if data['content_type'] == "assessment":
statement = "SELECT user_id FROM users WHERE user_status='student';"
cursor.execute(statement)
table = cursor.fetchall()
for row in table:
statement = "INSERT INTO assessment_status (user_id, module_id, user_assessment_status) VALUES (%s, %s, %s); "
# default of 0 = incomplete
params = [row[0], module_id, 0]
cursor.execute(statement, params)
cursor.execute('COMMIT')
return (True, module_id)
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def delete_module(module_id):
#print("modify_database.py: delete_module", module_id)
connection = _get_connection()
try:
with connection.cursor() as cursor:
assert module_id != None, 'Module id should not be None. Please try again with a proper input or return.'
assert module_id != '', 'Module id should not be empty. Please try again with a proper input or return.'
cursor.execute('BEGIN')
# get module index and program id
statement = "SELECT module_index, program_id, content_type FROM modules WHERE module_id = %s;"
cursor.execute(statement, [module_id])
table = cursor.fetchall()
if len(table) == 0:
return(False, "Nonexisting module id. Please try again with a proper input.")
module_index = table[0][0]
program_id = table[0][1]
content_type = table[0][2]
print('program_id, module_index, content_type', program_id, module_index, content_type)
# delete row modules table
statement = "DELETE FROM modules WHERE module_id = %s;"
cursor.execute(statement, [module_id])
# get list of module_ids to update indices
statement = "SELECT module_id, module_index FROM modules WHERE program_id = %s AND module_index > %s;"
cursor.execute(statement, [program_id, module_index])
table = cursor.fetchall()
modules = []
for row in table:
module_row = {}
module_row['module_id'] = row[0]
module_row['module_index'] = row[1]
modules.append(module_row)
# update module indices to make sure they're adjacent
for module in modules:
statement = "UPDATE modules SET module_index = %s WHERE module_id = %s;"
cursor.execute(statement, [module['module_index']-1, module['module_id']])
# delete module from assessment status table
if content_type == 'assessment':
statement = "DELETE FROM assessment_status WHERE module_id = %s;"
cursor.execute(statement, [module_id])
cursor.execute('COMMIT')
return (True, "module successfully deleted")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
#
def update_program_name(program_id, new_program_name):
connection = _get_connection()
try:
with connection.cursor() as cursor:
#check for missing arguments
if program_id is None or program_id == '':
return(False, "Missing program id. Please try again with a proper input.")
if new_program_name is None or new_program_name =='':
return(False, "Missing program name. Please try again with a proper input.")
cursor.execute('BEGIN')
#! check for duplicates via program name
statement = "SELECT FROM programs WHERE program_name = %s;"
cursor.execute(statement, [new_program_name])
table = cursor.fetchall()
if len(table) != 0:
return(False, "Duplicate program name. Update aborted. Please try again with a proper input.")
statement = "UPDATE programs SET program_name=%s WHERE program_id = %s;"
cursor.execute(statement, [new_program_name, program_id])
cursor.execute('COMMIT')
return (True, "program name updated")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def update_program_description(program_id, new_program_description):
connection = _get_connection()
try:
with connection.cursor() as cursor:
#check for missing arguments
if program_id is None or program_id == '':
return(False, "Missing program id, Please try again with a proper input.")
if new_program_description is None or new_program_description =='':
return(False, "Missing program description. Please try again with a proper input.")
cursor.execute('BEGIN')
statement = "UPDATE programs SET program_description=%s WHERE program_id=%s;"
cursor.execute(statement, [new_program_description, program_id])
cursor.execute('COMMIT')
return (True, "program description updated")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def update_program_availability(program_id, new_program_availability):
connection = _get_connection()
try:
with connection.cursor() as cursor:
#check for missing arguments
if program_id is None or program_id == '':
return(False, "Missing program id. Please try again with a proper input.")
if new_program_availability is None or new_program_availability =='':
return(False, "Missing program availability. Please try again with a proper input.")
if new_program_availability!= 'all' and new_program_availability != 'none':
return(False, 'Program availability must be all or none. Please try again with a proper input.')
cursor.execute('BEGIN')
statement = "UPDATE programs SET program_availability=%s WHERE program_id=%s;"
cursor.execute(statement, [new_program_availability, program_id])
cursor.execute('COMMIT')
return (True, "program availability updated")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def update_module_name(program_id, module_id, new_module_name):
connection = _get_connection()
try:
with connection.cursor() as cursor:
#check for missing arguments
if program_id is None or program_id == '':
return(False, "Missing program id. Please try again with a proper input.")
if module_id is None or module_id == '':
return(False, "Missing module id. Please try again with a proper input.")
if new_module_name is None or new_module_name =='':
return(False, "Missing module name. Please try again with a proper input.")
cursor.execute('BEGIN')
# check for duplicates for module name
statement = "SELECT FROM modules WHERE module_name = %s AND modules.program_id = %s;"
cursor.execute(statement, [new_module_name, program_id])
table = cursor.fetchall()
if len(table) != 0:
return(False, "Duplicate program name. Update aborted. Please try again with a proper input.")
statement = "UPDATE modules SET module_name=%s WHERE module_id= %s;"
cursor.execute(statement, [new_module_name, module_id])
cursor.execute('COMMIT')
return (True, "module name successfully updated")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def update_module_content_type(module_id, new_content_type):
connection = _get_connection()
try:
with connection.cursor() as cursor:
if module_id is None or module_id == '':
return(False, "Missing module id. Please try again with a proper input.")
if new_content_type is None or new_content_type =='':
return(False, "Missing content type. Please try again with a proper input.")
if new_content_type != 'assessment' and new_content_type != 'text':
return(False, 'Module content type must be assessment or text. Please try again with a proper input.')
cursor.execute('BEGIN')
statement = "UPDATE modules SET content_type= %s WHERE module_id= %s;"
cursor.execute(statement, [new_content_type, module_id])
#update user assessment status
if new_content_type == 'assessment':
statement = "SELECT user_id FROM users WHERE user_status='student';"
cursor.execute(statement)
table = cursor.fetchall()
for row in table:
statement = "INSERT INTO assessment_status (user_id, module_id, user_assessment_status) VALUES (%s, %s, %s); "
# default of 0 = incomplete
params = [row[0], module_id, 0]
cursor.execute(statement, params)
else:
statement = "DELETE FROM assessment_status WHERE module_id=%s;"
cursor.execute(statement, [module_id])
cursor.execute('COMMIT')
return (True, "module content type updated")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def update_module_content_link(module_id, new_content_link):
connection = _get_connection()
try:
with connection.cursor() as cursor:
if module_id is None or module_id == '':
return(False, "Missing module id. Please try again with a proper input.")
if new_content_link is None or new_content_link =='':
return(False, "Missing content link. Please try again with a proper input.")
cursor.execute('BEGIN')
statement = "UPDATE modules SET content_link= %s WHERE module_id= %s;"
cursor.execute(statement, [new_content_link, module_id])
cursor.execute('COMMIT')
return (True, "module content link updated")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
## please do not use, should not be used on its own
## should only be used by edit_module_seq in oea
def update_module_index(module_id, new_module_index):
connection = _get_connection()
try:
with connection.cursor() as cursor:
if module_id is None or module_id == '':
return(False, "Missing module id. Please try again with a proper input.")
if new_module_index is None or new_module_index =='':
return(False, "Missing module index. Please try again with a proper input.")
cursor.execute('BEGIN')
statement = "UPDATE modules SET module_index= %s WHERE module_id= %s;"
cursor.execute(statement, [new_module_index, module_id])
cursor.execute('COMMIT')
return (True, "successfully changed module index")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def update_program_status(student_id, program_id, new_program_status):
connection = _get_connection()
try:
with connection.cursor() as cursor:
if student_id is None or student_id == '':
return(False, "Missing student id. Please try again with a proper input.")
if program_id is None or program_id == '':
return(False, "Missing program id. Please try again with a proper input.")
if new_program_status is None or new_program_status =='':
return(False, "Missing program status. Please try again with a proper input.")
if new_program_status != 'enrolled' and new_program_status != 'available' and new_program_status != 'locked':
return(False, 'Program status must be enrolled, available, or locked. Please try again with a proper input.')
cursor.execute('BEGIN')
statement = "UPDATE program_status SET user_program_status = %s WHERE user_id=%s AND program_id=%s;"
cursor.execute(statement, [new_program_status, student_id, program_id])
cursor.execute('COMMIT')
return (True, "program status updated")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def update_assessment_status(student_id, module_id, new_assessment_status):
connection = _get_connection()
try:
with connection.cursor() as cursor:
if student_id is None or student_id == '':
return(False, "Missing student id. Please try again with a proper input.")
if module_id is None or module_id == '':
return(False, "Missing module id. Please try again with a proper input.")
if new_assessment_status is None or new_assessment_status =='':
return(False, "Missing assessment status. Please try again with a proper input.")
print(new_assessment_status)
if new_assessment_status != '0' and new_assessment_status != '1':
return(False, 'Assessment status must be complete (1) or incomplete (0). Please try again with a proper input.')
cursor.execute('BEGIN')
statement = "UPDATE assessment_status SET user_assessment_status = %s WHERE user_id=%s AND module_id=%s;"
cursor.execute(statement, [new_assessment_status, student_id, module_id])
cursor.execute('COMMIT')
return (True, "assessment status updated")
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
#---------------------------------------------
# ACCESSING DATABASE
# --------------------------------------------
def is_admin_authorized(username):
connection = _get_connection()
try:
with connection.cursor() as cursor:
assert username != None, 'Username should not be None. Please try again with a proper input or return.'
assert username != '', 'Username should not be empty. Please try again with a proper input or return.'
cursor.execute('BEGIN')
#print("database: is_admin_authorized", username)
statement = "SELECT * FROM users where user_status = 'admin' AND user_email=%s;"
cursor.execute(statement, [username])
table = cursor.fetchall()
cursor.execute('COMMIT')
return (True, len(table)!=0)
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def is_student_authorized(username):
connection = _get_connection()
try:
with connection.cursor() as cursor:
assert username != None, 'Username should not be None. Please try again with a proper input or return.'
assert username != '', 'Username should not be empty. Please try again with a proper input or return.'
cursor.execute('BEGIN')
#print("database: is_student_authorized", username)
statement = "SELECT * FROM users where user_status = 'student' AND user_email=%s;"
cursor.execute(statement, [username])
table = cursor.fetchall()
cursor.execute('COMMIT')
return (True, len(table)!=0)
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def get_student_info(user_email):
connection = _get_connection()
try:
with connection.cursor() as cursor:
if user_email is None or user_email == '':
return(False, "Missing user email. Please try again with a proper input or return.")
cursor.execute('BEGIN')
statement = "SELECT * FROM users WHERE user_status = 'student' AND user_email=%s;"
cursor.execute(statement, [user_email])
table = cursor.fetchall()
if len(table) == 0:
return(False, "Student not in database. Please try again with a proper input or return.")
student = table[0]
student_info = {}
student_info['user_id'] = student[0]
student_info['user_name'] = student[1]
student_info['user_email'] = student[2]
statement = "SELECT program_id, user_program_status FROM program_status WHERE user_id=%s;"
cursor.execute(statement, [student_info['user_id']])
table = cursor.fetchall()
available_programs = []
locked_programs = []
enrolled_programs = []
for row in table:
program_id = row[0]
user_program_status = row[1]
statement = "SELECT program_name, program_description FROM programs WHERE program_id = %s;"
cursor.execute(statement, [program_id])
program_table = cursor.fetchall()
if len(program_table) == 0:
return(False, "Empty program in program_status when looking for student info. Please contact system administrator.")
program_name = program_table[0][0]
program_description = program_table[0][1]
program_info = {}
program_info['program_id'] = program_id
program_info['program_name'] = program_name
program_info['program_description'] = program_description
if user_program_status == 'available' :
available_programs.append(program_info)
elif user_program_status == 'locked':
locked_programs.append(program_info)
elif user_program_status == 'enrolled':
enrolled_programs.append(program_info)
#sort programs via program_name
available_programs = sorted(available_programs, key=lambda x:x['program_name'])
locked_programs = sorted(locked_programs, key=lambda x:x['program_name'])
enrolled_programs = sorted(enrolled_programs, key=lambda x:x['program_name'])
student_info['available_programs'] = available_programs
student_info['locked_programs'] = locked_programs
student_info['enrolled_programs'] = enrolled_programs
cursor.execute('COMMIT')
return (True, student_info)
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def get_all_admins():
connection = _get_connection()
try:
with connection.cursor() as cursor:
cursor.execute('BEGIN')
statement = "SELECT * FROM users WHERE user_status='admin';"
cursor.execute(statement)
table = cursor.fetchall()
# list of dictionaries of programs
admins = []
for row in table:
admin_row = {}
admin_row['user_id'] = row[0]
admin_row['user_name'] = row[1]
admin_row['user_email'] = row[2]
admins.append(admin_row)
#sort admins via user_name
admins = sorted(admins, key=lambda x:x['user_name'])
cursor.execute('COMMIT')
return (True, admins)
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def get_all_students():
connection = _get_connection()
try:
with connection.cursor() as cursor:
cursor.execute('BEGIN')
statement = "SELECT * FROM users WHERE user_status='student';"
cursor.execute(statement)
table = cursor.fetchall()
# list of dictionaries of programs
students = []
for row in table:
student_row = {}
student_row['user_id'] = row[0]
student_row['user_name'] = row[1]
student_row['user_email'] = row[2]
students.append(student_row)
#sort students via user_name
students = sorted(students, key=lambda x:x['user_name'])
cursor.execute('COMMIT')
return (True, students)
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def get_all_programs():
connection = _get_connection()
try:
with connection.cursor() as cursor:
cursor.execute('BEGIN')
#print("access_database.py: get_programslist")
statement = "SELECT * FROM programs;"
cursor.execute(statement)
table = cursor.fetchall()
# list of list of dictionaries of programs
programs = []
for row in table:
program_row = {}
program_row['program_id'] = row[0]
program_row['program_name'] = row[1]
program_row['program_description'] = row[2]
program_row['program_availability'] = row[3]
programs.append(program_row)
#sort programs via program_name
programs = sorted(programs, key=lambda x:x['program_name'])
cursor.execute('COMMIT')
return (True, programs)
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def get_program_info(program_id):
connection = _get_connection()
try:
with connection.cursor() as cursor:
if program_id is None or program_id == '':
return(False, "Missing program id. Please try again with a proper input or return.")
cursor.execute('BEGIN')
print(' program id in get program info =', program_id)
statement = "SELECT * FROM programs WHERE program_id=%s;"
cursor.execute(statement, [program_id])
table = cursor.fetchall()
if len(table) == 0:
return(False, "No such program exists in database. Please try again with a proper input or return.")
program_info = {}
program_info['program_id'] = table[0][0]
program_info['program_name'] = table[0][1]
program_info['program_description'] = table[0][2]
program_info['program_availability'] = table[0][3]
# get program modules
statement = "SELECT * FROM modules WHERE modules.program_id=%s;"
cursor.execute(statement, [program_id])
table = cursor.fetchall()
# list of dictionaries of modules within program
modules = []
for row in table:
module_row = {}
module_row['module_id'] = row[0]
module_row['program_id'] = row[1]
module_row['module_name'] = row[2]
module_row['content_type'] = row[3]
module_row['content_link'] = row[4]
module_row['module_index'] = row[5]
modules.append(module_row)
#sort modules via index
modules = sorted(modules, key=lambda x:x['module_index'])
program_info['modules'] = modules
cursor.execute('COMMIT')
# print("success access_database.py: get_program_modules")
return (True, program_info)
except Exception as error:
err_msg = "A server error occurred. Please contact the system administrator."
print(sys.argv[0] + ': ' + str(error), file=sys.stderr)
return (False, err_msg)
finally:
_put_connection(connection)
def get_module_info(module_id):
connection = _get_connection()
try: