-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueries.py
More file actions
383 lines (284 loc) · 12.9 KB
/
Copy pathqueries.py
File metadata and controls
383 lines (284 loc) · 12.9 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
# Created by Gabriel Martell
'''
Version 1.11 (04/02/2024)
=========================================================
queries.py (Carleton University COMP3005 - Database Management Student Template Code)
This is the template code for the COMP3005 Database Project 1, and must be accomplished on an Ubuntu Linux environment.
Your task is to ONLY write your SQL queries within the prompted space within each Q_# method (where # is the question number).
You may modify code in terms of testing purposes (commenting out a Qn method), however, any alterations to the code, such as modifying the time,
will be flagged for suspicion of cheating - and thus will be reviewed by the staff and, if need be, the Dean.
To review the Integrity Violation Attributes of Carleton University, please view https://carleton.ca/registrar/academic-integrity/
=========================================================
'''
# Imports
import psycopg
import csv
import subprocess
import os
import re
# Connection Information
'''
The following is the connection information for this project. These settings are used to connect this file to the autograder.
You must NOT change these settings - by default, db_host, db_port and db_username are as follows when first installing and utilizing psql.
For the user "postgres", you must MANUALLY set the password to 1234.
'''
root_database_name = "project_database"
query_database_name = "query_database"
db_username = 'postgres'
db_password = '1234'
db_host = 'localhost'
db_port = '5432'
# Directory Path - Do NOT Modify
dir_path = os.path.dirname(os.path.realpath(__file__))
# Loading the Database after Drop - Do NOT Modify
#================================================
def load_database(cursor, conn):
drop_database(cursor, conn)
# Create the Database if it DNE
try:
conn.autocommit = True
cursor.execute(f"CREATE DATABASE {query_database_name};")
conn.commit()
except Exception as error:
print(error)
finally:
conn.autocommit = False
conn.close()
# Connect to this query database.
dbname = query_database_name
user = db_username
password = db_password
host = db_host
port = db_port
conn = psycopg.connect(dbname=dbname, user=user, password=password, host=host, port=port)
cursor = conn.cursor()
# Import the dbexport.sql database data into this database
try:
command = f'psql -h {host} -U {user} -d {query_database_name} -a -f {os.path.join(dir_path, "dbexport.sql")}'
env = {'PGPASSWORD': password}
subprocess.run(command, shell=True, check=True, env=env)
except subprocess.CalledProcessError as e:
print(f"An error occurred while loading the database: {e}")
# Return this connection.
return conn
# Dropping the Database after Query n Execution - Do NOT Modify
#================================================
def drop_database(cursor, conn):
# Drop database if it exists.
try:
conn.autocommit = True
cursor.execute(f"DROP DATABASE IF EXISTS {query_database_name};")
conn.commit()
except Exception as error:
print(error)
pass
finally:
conn.autocommit = False
# Reconnect to Root Database - Do NOT Modify
#================================================
def reconnect(cursor, conn):
cursor.close()
conn.close()
dbname = root_database_name
user = db_username
password = db_password
host = db_host
port = db_port
return psycopg.connect(dbname=dbname, user=user, password=password, host=host, port=port)
# Getting the execution time of the query through EXPLAIN ANALYZE - Do NOT Modify
#================================================
def get_time(cursor, conn, sql_query):
# Prefix your query with EXPLAIN ANALYZE
explain_query = f"EXPLAIN ANALYZE {sql_query}"
try:
# Execute the EXPLAIN ANALYZE query
cursor.execute(explain_query)
# Fetch all rows from the cursor
explain_output = cursor.fetchall()
# Convert the output tuples to a single string
explain_text = "\n".join([row[0] for row in explain_output])
# Use regular expression to find the execution time
# Look for the pattern "Execution Time: <time> ms"
match = re.search(r"Execution Time: ([\d.]+) ms", explain_text)
if match:
execution_time = float(match.group(1))
return f"Execution Time: {execution_time} ms"
else:
print("Execution Time not found in EXPLAIN ANALYZE output.")
return f"NA"
except Exception as error:
print(f"[ERROR] Error getting time.\n{error}")
# Write the results into some Q_n CSV. If the is an error with the query, it is a INC result - Do NOT Modify
#================================================
def write_csv(execution_time, cursor, conn, i):
# Collect all data into this csv, if there is an error from the query execution, the resulting time is INC.
try:
colnames = [desc[0] for desc in cursor.description]
rows = cursor.fetchall()
filename = f"{dir_path}/Q_{i}.csv"
with open(filename, 'w', encoding='utf-8', newline='') as csvfile:
csvwriter = csv.writer(csvfile)
# Write column names to the CSV file
csvwriter.writerow(colnames)
# Write data rows to the CSV file
csvwriter.writerows(rows)
except Exception as error:
execution_time[i-1] = "INC"
print(error)
#================================================
'''
The following 10 methods, (Q_n(), where 1 < n < 10) will be where you are tasked to input your queries.
To reiterate, any modification outside of the query line will be flagged, and then marked as potential cheating.
Once you run this script, these 10 methods will run and print the times in order from top to bottom, Q1 to Q10 in the terminal window.
'''
def Q_1(cursor, conn, execution_time):
connection = load_database(cursor, conn)
cursor = connection.cursor()
#==========================================================================
# Enter QUERY within the quotes:
query = """ """
#==========================================================================
time_val = get_time(cursor, connection, query)
cursor.execute(query)
execution_time[0] = (time_val)
write_csv(execution_time, cursor, connection, 1)
return reconnect(cursor, connection)
def Q_2(cursor, conn, execution_time):
connection = load_database(cursor, conn)
cursor = connection.cursor()
#==========================================================================
# Enter QUERY within the quotes:
query = """ """
#==========================================================================
time_val = get_time(cursor, connection, query)
cursor.execute(query)
execution_time[1] = (time_val)
write_csv(execution_time, cursor, connection, 2)
return reconnect(cursor, connection)
def Q_3(cursor, conn, execution_time):
connection = load_database(cursor, conn)
cursor = connection.cursor()
#==========================================================================
# Enter QUERY within the quotes:
query = """ """
#==========================================================================
time_val = get_time(cursor, connection, query)
cursor.execute(query)
execution_time[2] = (time_val)
write_csv(execution_time, cursor, connection, 3)
return reconnect(cursor, connection)
def Q_4(cursor, conn, execution_time):
connection = load_database(cursor, conn)
cursor = connection.cursor()
#==========================================================================
# Enter QUERY within the quotes:
query = """ """
#==========================================================================
time_val = get_time(cursor, connection, query)
cursor.execute(query)
execution_time[3] = (time_val)
write_csv(execution_time, cursor, connection, 4)
return reconnect(cursor, connection)
def Q_5(cursor, conn, execution_time):
connection = load_database(cursor, conn)
cursor = connection.cursor()
#==========================================================================
# Enter QUERY within the quotes:
query = """ """
#==========================================================================
time_val = get_time(cursor, connection, query)
cursor.execute(query)
execution_time[4] = (time_val)
write_csv(execution_time, cursor, connection, 5)
return reconnect(cursor, connection)
def Q_6(cursor, conn, execution_time):
connection = load_database(cursor, conn)
cursor = connection.cursor()
#==========================================================================
# Enter QUERY within the quotes:
query = """ """
#==========================================================================
time_val = get_time(cursor, connection, query)
cursor.execute(query)
execution_time[5] = (time_val)
write_csv(execution_time, cursor, connection, 6)
return reconnect(cursor, connection)
def Q_7(cursor, conn, execution_time):
connection = load_database(cursor, conn)
cursor = connection.cursor()
#==========================================================================
# Enter QUERY within the quotes:
query = """ """
#==========================================================================
time_val = get_time(cursor, connection, query)
cursor.execute(query)
execution_time[6] = (time_val)
write_csv(execution_time, cursor, connection, 7)
return reconnect(cursor, connection)
def Q_8(cursor, conn, execution_time):
connection = load_database(cursor, conn)
cursor = connection.cursor()
#==========================================================================
# Enter QUERY within the quotes:
query = """ """
#==========================================================================
time_val = get_time(cursor, connection, query)
cursor.execute(query)
execution_time[7] = (time_val)
write_csv(execution_time, cursor, connection, 8)
return reconnect(cursor, connection)
def Q_9(cursor, conn, execution_time):
connection = load_database(cursor, conn)
cursor = connection.cursor()
#==========================================================================
# Enter QUERY within the quotes:
query = """ """
#==========================================================================
time_val = get_time(cursor, connection, query)
cursor.execute(query)
execution_time[8] = (time_val)
write_csv(execution_time, cursor, connection, 9)
return reconnect(cursor, connection)
def Q_10(cursor, conn, execution_time):
connection = load_database(cursor, conn)
cursor = connection.cursor()
#==========================================================================
# Enter QUERY within the quotes:
query = """ """
#==========================================================================
time_val = get_time(cursor, connection, query)
cursor.execute(query)
execution_time[9] = (time_val)
write_csv(execution_time, cursor, connection, 10)
return reconnect(cursor, connection)
# Running the queries from the Q_n methods - Do NOT Modify
#=====================================================
def run_queries(cursor, conn, dbname):
execution_time = [0,0,0,0,0,0,0,0,0,0]
conn = Q_1(cursor, conn, execution_time)
conn = Q_2(cursor, conn, execution_time)
conn = Q_3(cursor, conn, execution_time)
conn = Q_4(cursor, conn, execution_time)
conn = Q_5(cursor, conn, execution_time)
conn = Q_6(cursor, conn, execution_time)
conn = Q_7(cursor, conn, execution_time)
conn = Q_8(cursor, conn, execution_time)
conn = Q_9(cursor, conn, execution_time)
conn = Q_10(cursor, conn, execution_time)
for i in range(10):
print(execution_time[i])
''' MAIN '''
try:
if __name__ == "__main__":
dbname = root_database_name
user = db_username
password = db_password
host = db_host
port = db_port
conn = psycopg.connect(dbname=dbname, user=user, password=password, host=host, port=port)
cursor = conn.cursor()
run_queries(cursor, conn, dbname)
except Exception as error:
print(error)
#print("[ERROR]: Failure to connect to database.")
#_______________________________________________________