-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_setup.py
50 lines (42 loc) · 1.75 KB
/
db_setup.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
import psycopg
from psycopg.rows import dict_row
def verify_database_setup():
"""
Verifies database connection and table existence, creates them if missing.
Returns tuple of (success: bool, message: str)
"""
try:
# Try connecting to the database
conn = psycopg.connect(
"postgresql://amani:admin@localhost/MAKERSBNB",
row_factory=dict_row
)
# Check if tables exist
with conn.cursor() as cur:
cur.execute("""
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name IN ('users', 'spaces', 'bookings');
""")
existing_tables = [row['table_name'] for row in cur.fetchall()]
if not existing_tables:
print("No required tables found. Creating tables...")
# Read and execute the seed file
with open('seeds/database_connection.sql', 'r') as seed_file:
seed_sql = seed_file.read()
cur.execute(seed_sql)
conn.commit()
return True, "Database tables created and seeded successfully!"
print(f"Found existing tables: {', '.join(existing_tables)}")
return True, "Database connection and tables verified!"
except psycopg.OperationalError as e:
return False, f"Database connection failed: {str(e)}"
except Exception as e:
return False, f"An error occurred: {str(e)}"
finally:
if 'conn' in locals():
conn.close()
if __name__ == "__main__":
success, message = verify_database_setup()
print(message)