-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun_queries.py
More file actions
57 lines (49 loc) · 1.54 KB
/
run_queries.py
File metadata and controls
57 lines (49 loc) · 1.54 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
import re
import psycopg2
import random
from pathlib import Path
SQL_FILE = Path("sql/02_sample_queries.sql")
def load_queries(sql_path: Path):
text = sql_path.read_text(encoding="utf-8")
parts = re.split(r'(?m)^--\s*(Q\d+)\b.*$', text)
queries = {}
for i in range(1, len(parts), 2):
qname = parts[i].strip()
body = parts[i+1].strip()
if body:
queries[qname] = body
return queries
def run_query(sql: str, params=None):
conn = psycopg2.connect(
host="localhost",
port=5432,
dbname="overbooking_db",
user="ob_user",
password="ob_pass"
)
try:
with conn:
with conn.cursor() as cur:
cur.execute(sql, params or [])
try:
rows = cur.fetchall()
colnames = [d[0] for d in cur.description]
print("Columns:", colnames)
for r in rows:
print(r)
except psycopg2.ProgrammingError:
print("Query executed successfully (no result set).")
finally:
conn.close()
if __name__ == "__main__":
queries = load_queries(SQL_FILE)
print("Available queries:", sorted(queries.keys()))
numbers = input("Enter nany numbers (1-21):")
q_id = "Q{}".format(numbers)
if q_id not in queries:
print(f"{q_id} not found in {SQL_FILE}")
else:
print(f"\nRunning {q_id}:\n")
print(queries[q_id])
print("\nResult:\n")
run_query(queries[q_id])