-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit-db.py
More file actions
83 lines (70 loc) · 2.96 KB
/
init-db.py
File metadata and controls
83 lines (70 loc) · 2.96 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
import sys
import os
import time
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
from sqlalchemy.exc import OperationalError
# Add the current directory to Python path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from app.models.models import Base, User as DBUser, UserRole as DBUserRole
from app.api.auth import get_password_hash
# Get the database URL from environment variable or use default
DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql://postgres:postgres@db:5432/workout_db")
def wait_for_db(engine, max_retries=30, retry_interval=2):
"""Wait for the database to be ready."""
retries = 0
while retries < max_retries:
try:
with engine.connect() as conn:
conn.execute(text("SELECT 1"))
print("Database connection successful!")
return True
except OperationalError as e:
print(f"Database not ready yet: {e}")
retries += 1
print(f"Retry {retries}/{max_retries} in {retry_interval} seconds...")
time.sleep(retry_interval)
print("Failed to connect to the database after maximum retries")
return False
def init_db():
"""Initialize the database with tables and initial data."""
engine = create_engine(DATABASE_URL)
if not wait_for_db(engine):
sys.exit(1)
# Create tables (COMMENTED OUT - Use Alembic migrations instead)
# Base.metadata.create_all(bind=engine)
# print("Tables created successfully")
# Create session
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
db = SessionLocal()
# Check if admin user exists
admin_user = db.query(DBUser).filter(DBUser.username == "admin").first()
if not admin_user:
# Create admin user
admin_password = get_password_hash("admin123")
admin_user = DBUser(
username="admin",
email="admin@example.com",
hashed_password=admin_password,
role=DBUserRole.ADMIN,
is_active=True
)
db.add(admin_user)
db.commit()
print("Admin user created successfully")
else:
print("Admin user already exists")
# After creating tables, add the profile_image_url column if it doesn't exist
with engine.begin() as conn:
# Check if column exists first
result = conn.execute(text("SELECT column_name FROM information_schema.columns WHERE table_name='user_profiles' AND column_name='profile_image_url'"))
if result.fetchone() is None:
print("Adding profile_image_url column to user_profiles table...")
conn.execute(text("ALTER TABLE user_profiles ADD COLUMN profile_image_url VARCHAR;"))
print("Column added successfully.")
else:
print("Column profile_image_url already exists.")
db.close()
print("Database initialization completed")
if __name__ == "__main__":
init_db()