-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_db.py
More file actions
42 lines (39 loc) · 1.5 KB
/
Copy pathinit_db.py
File metadata and controls
42 lines (39 loc) · 1.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
import time
from sqlalchemy import inspect
from models import Base, engine
import os
def wait_for_db(retries=10, delay=5):
for i in range(retries):
try:
with engine.connect() as conn:
return True
except Exception as e:
print(f"Database not ready ({i+1}/{retries}), retrying in {delay} seconds...")
time.sleep(delay)
raise Exception("Could not connect to the database after several retries.")
def init_database():
wait_for_db() # Wait for DB readiness
inspector = inspect(engine)
if not inspector.has_table('api_calls'):
Base.metadata.create_all(bind=engine)
print("Database tables created successfully!")
# If a data import file exists, import data from it
if os.path.exists('db_dump.sql'):
print("Found db_dump.sql. Importing initial data...")
with open('db_dump.sql', 'r') as f:
sql_statements = f.read()
with engine.connect() as conn:
trans = conn.begin()
try:
conn.execute(sql_statements)
trans.commit()
print("Data imported successfully!")
except Exception as e:
trans.rollback()
print("Error importing data:", e)
else:
print("No data import file found. Skipping data import.")
else:
print("Database already initialized!")
if __name__ == "__main__":
init_database()