-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject.py
More file actions
402 lines (335 loc) · 14.5 KB
/
Copy pathproject.py
File metadata and controls
402 lines (335 loc) · 14.5 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
import psycopg2
import datetime
import re
from prettytable import PrettyTable
print("\nConnecting...")
# Connect to an existing database
conn = psycopg2.connect(database="Project", user="Project", host="162.243.19.108")
print("Connected\n")
# Open a cursor to perform database operations
cur = conn.cursor()
run = True
def edit():
print("OPTIONS:\n1. INSERT\n2. UPDATE\n3. DELETE")
options = input("Choose an option: ")
if str(options) == '1':
sql = input("Enter insert statement: ")
cur.execute(sql)
elif str(options) == '2':
sql = input("Enter update statement: ")
cur.execute(sql)
elif str(options) == '3':
sql = input("Enter delete statement: ")
cur.execute(sql)
def entry(options = []):
print("\nTables:\n")
sql="select table_name from information_schema.tables where table_schema='public';"
tables = sql_print_first(sql)
option = input("\nSelect a table: ")
selected = tables[int(option)-1][0]
data = sql_get_all(selected)
print_table(data, options)
def sql_print_first(sql):
cur.execute(sql)
i = 1
rows = cur.fetchall()
for row in rows:
print(str(i) + ". " + str(row[0]))
i += 1
return rows
def sql_print_column_names(columns):
i = 1
j = 0
for column in columns:
print(str(i) + ". " + str(columns[j]))
i += 1
j += 1
def print_table(rows, options = []):
table = PrettyTable()
names = rows[0]
table.field_names = names
for i in range(1,len(rows)):
table.add_row(rows[i])
#if sort == 0:
#print("\nSort by which column?")
#sql_print_column_names(names)
#option = input("Sort by (Enter 0 to skip sorting): ")
#if str(option) != '0':
#sort = names[int(option)-1]
#table.get_string(sortby = str(sort))
#elif sort == 1:
#table.get_string(sortby = "code")
#table.sortby = sort
index = []
index.extend(range(1, len(rows)))
table.add_column("index", index)
if len(options) != 0:
print(table.get_string(fields = options))
else:
print(table)
def sql_get_all(table):
sql="select column_name from information_schema.columns where table_name='" + table + "';"
cur.execute(sql)
i = 0
columns = cur.fetchall()
names = []
rows = []
for name in columns:
names.append(name[0])
rows.append(names)
sql="select * from " + table + " order by " + names[0] + " ASC"
cur.execute(sql)
results = cur.fetchall()
for row in results:
data = []
i = 0
for datum in row:
data.append(row[i])
i += 1
rows.append(data)
return rows
def create_reservation(round_trip = False):
pass_name = input("Enter passenger's name: ")
pass_phone = input("Enter passenger's phone number (no hyphens or spaces): ")
print("Choose destinations.\n")
rows = sql_get_all('airports')
print_table(rows)
start = input("Starting destination index number: ")
start_code = rows[int(start)][0]
end = input("Ending destination index number: ")
end_code = rows[int(end)][0]
depart_date = input("Departure date (yyyy-mm-dd): ")
cost = get_trip(start_code, end_code, depart_date, pass_name, pass_phone)
if round_trip == True:
return_date = input("Return Date (yyyy-mm-dd): ")
return_cost = get_trip(end_code, start_code, return_date, pass_name, pass_phone)
total_cost = get_total_cost(cost, return_cost)
print("Total cost of your round trip is $" + str(total_cost))
def create_multiflight():
pass_name = input("Enter passenger's name: ")
pass_phone = input("Enter passenger's phone number (no hyphens or spaces): ")
print("Choose the destination.\n")
rows = sql_get_all('airports')
print_table(rows)
final = input("Final destination index number: ")
final_code = rows[int(final)][0]
sql="select column_name from information_schema.columns where table_name='flights';"
cur.execute(sql)
i = 0
columns = cur.fetchall()
names = []
rows = []
for name in columns:
names.append(name[0])
rows.append(names)
sql = "select * from flights where end_point = '" + final_code + "';"
cur.execute(sql)
mids = cur.fetchall()
for row in mids:
data = []
i = 0
for datum in row:
data.append(row[i])
i += 1
rows.append(data)
print_table(rows)
mid = input("Midpoint destination index number: ")
mid_code = rows[int(mid)][10]
mid_flight = rows[int(mid)]
sql = "select * from flights where end_point = '" + mid_code + "';"
cur.execute(sql)
starts = cur.fetchall()
rows = []
rows.append(names)
for row in starts:
data = []
i = 0
for datum in row:
data.append(row[i])
i += 1
rows.append(data)
print_table(rows)
start = input("Starting Location index number: ")
start_code = rows[int(start)][10]
start_flight = rows[int(start)]
depart_date = input("Departure date (yyyy-mm-dd): ")
depart_date = datetime.datetime(int(depart_date[0:4]), int(depart_date[5:7]), int(depart_date[8:10]))
second_date = depart_date
if start_flight[depart_date.weekday() + 1] != mid_flight[depart_date.weekday()]:
second_date += datetime.timedelta(days = 1)
get_trip(start_code, mid_code, date_str(depart_date), pass_name, pass_phone)
get_trip(mid_code, final_code, date_str(second_date), pass_name, pass_phone)
def get_trip(start_code, end_code, depart_date, pass_name, pass_phone):
sql = "SELECT flight_num, fare_code FROM flights WHERE start_point='{}' AND end_point='{}';".format(start_code, end_code)
cur.execute(sql)
flight = cur.fetchall()[0]
sql = "SELECT * FROM leg_instance WHERE flight_num = {} AND date = '{}' AND seats > 0".format(flight[0], depart_date)
cur.execute(sql)
legs = cur.fetchall()
if len(legs) > 0:
for leg in legs:
seats = leg[4] - 1
sql = "SELECT max(seat_num) from reservations WHERE leg_num = " + str(leg[2]) + " and date ='" + depart_date + "';"
cur.execute(sql)
test = cur.fetchall()[0][0]
if test == None: test = 0
seat_num = int(test) + 1
sql = "INSERT INTO reservations (seat_num, date, flight_num, leg_num, pass_phone, pass_name) VALUES ({},'{}',{},{},'{}','{}')".format(seat_num, depart_date, leg[1], leg[2], pass_phone, pass_name)
cur.execute(sql)
cur.execute("UPDATE leg_instance SET seats = " + str(seats) + " WHERE leg_num = " + str(leg[2]) + " AND date = '" + depart_date + "';")
cur.execute("select cost from fares where code = " + str(flight[1]) + ";")
cost = cur.fetchall()[0][0]
print("Cost for flight from", start_code, "to", end_code, "is " + str(cost))
conn.commit()
return cost
else: print("No Available flights with those parameters")
#leg_instance = date, flight_num, leg_num, tail_number, seats, depart_time, arrival_time, index
#reservations = seat_num, date, flight_num, leg_num, pass_phone, pass_name, index
def get_total_cost(cost, return_cost):
cost = re.sub('[$]', '', cost)
return_cost = re.sub('[$]', '', return_cost)
total_cost = float(cost) + float(return_cost)
return total_cost
def get_weekday(num):
days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
return(days[num])
def populate_week():
start_date = datetime.datetime.now()
for i in range(0,7):
date = start_date + datetime.timedelta(days=i)
cur.execute("select count(*) from leg_instance where date = '" + date_str(date) + "';")
if cur.fetchall()[0][0] == 0:
populate_day(date)
def populate_day(date):
weekday = get_weekday(date.weekday())
planes = check_planes(date)
sql = "select * from flights where " + weekday + "=true;"
cur.execute(sql)
flights = cur.fetchall()
for flight in flights:
sql = "select * from flight_legs where flight_num = " + str(flight[0]) + ";"
cur.execute(sql)
for leg in cur.fetchall():
sql = "insert into leg_instance (date, flight_num, leg_num, tail_number, depart_time, arrival_time) values ('{}', {}, {}, {}, '{}', '{}');".format(date_str(date), leg[1], leg[0], planes.pop(), leg[4], leg[5])
cur.execute(sql)
conn.commit()
def date_str(date):
return str(date.year) + "-" + str(date.month) + "-" + str(date.day)
def check_planes(date):
sql = "select tail_number from leg_instance where date = '" + date_str(date) + "';"
cur.execute(sql)
used_planes = []
for row in cur.fetchall():
used_planes.append(row[0])
sql = "select tail_number from airplanes;"
cur.execute(sql)
all_planes = []
for row in cur.fetchall():
all_planes.append(row[0])
return(list(set(all_planes)-set(used_planes)))
def cancel_reservation(delete_date = None, pass_phone = None):
sql="select column_name from information_schema.columns where table_name='{}';".format("reservations")
cur.execute(sql)
columns = cur.fetchall()
names = []
rows = []
for name in columns:
names.append(name[0])
rows.append(names)
pass_phone = input("Enter customer phone number: ")
sql = "SELECT * FROM reservations WHERE pass_phone = '{}';".format(pass_phone)
cur.execute(sql)
results = cur.fetchall()
for row in results:
data = []
i = 0
for datum in row:
data.append(row[i])
i += 1
rows.append(data)
print_table(rows)
delete_date = input("Enter date of reservation to cancel (yyyy-mm-dd): ")
sql = "DELETE FROM reservations WHERE date = '{}' AND pass_phone = '{}'".format(delete_date, pass_phone)
cur.execute(sql)
def change_reservation():
sql="select column_name from information_schema.columns where table_name='{}';".format("reservations")
cur.execute(sql)
columns = cur.fetchall()
names = []
rows = []
for name in columns:
names.append(name[0])
rows.append(names)
pass_phone = input("Enter customer phone number: ")
sql = "SELECT * FROM reservations WHERE pass_phone = '{}';".format(pass_phone)
cur.execute(sql)
results = cur.fetchall()
for row in results:
data = []
i = 0
for datum in row:
data.append(row[i])
i += 1
rows.append(data)
print_table(rows)
delete_date = input("Enter date of reservation to change (yyyy-mm-dd): ")
sql = "SELECT * FROM reservations WHERE date = '{}' AND pass_phone = '{}'".format(delete_date, pass_phone)
cur.execute(sql)
results = cur.fetchall()[0]
seat_num = results[1]
flight_num = results[2]
pass_phone = results[4]
pass_name = results[5]
sql = "SELECT * FROM flights WHERE flight_num = {};".format(flight_num)
cur.execute(sql)
results = cur.fetchall()[0]
start_code = results[10]
end_code = results[11]
sql = "DELETE FROM reservations WHERE date = '{}' AND pass_phone = '{}';".format(delete_date, pass_phone)
cur.execute(sql)
new_date = input("Enter new date of reservation (yyyy-mm-dd): ")
get_trip(start_code, end_code, new_date, pass_name, pass_phone)
#flight = flight_num | monday | tuesday | wednesday | thursday | friday | saturday | sunday | airline | fare_code | start_point | end_point | index
#reservations = | date | seat_num | flight_num | leg_num | pass_phone | pass_name | index |
while run:
print("MAIN MENU:\n1. Manual Entry\n2. View Data\n3. Plan Trip\n4. Plan Round Trip\n5. Plan Multi-Flight Trip \n6. Change Trip\n7. Cancel Trip\n8. EXIT\n")
option = input("Choose an option: ")
if (str(option) == '1'):
edit()
input("Press Enter to continue...")
print("\n")
elif (str(option) == '2'):
entry()
input("Press Enter to continue...")
print("\n")
elif (str(option) == '3'):
populate_week()
create_reservation()
input("Press Enter to continue...")
print("\n")
elif (str(option) == '4'):
populate_week()
create_reservation(True)
input("Press Enter to continue...")
print("\n")
elif (str(option) == '5'):
populate_week()
create_multiflight()
elif (str(option) == '6'):
change_reservation()
input("Press Enter to continue...")
print("\n")
elif (str(option) == '7'):
cancel_reservation()
input("Press Enter to continue...")
print("\n")
elif (str(option) == '8'):
run = False
else:
print("Invalid option choice!\n")
input("Press Enter to continue...")
print("\n")
conn.commit()
# Close communication with the database
cur.close()
conn.close()