44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
import os
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy import text
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.db.session import engine
|
|
from app.core.config import settings
|
|
|
|
|
|
def init_db() -> None:
|
|
"""Initialize database with required tables and data."""
|
|
|
|
# Ensure database directory exists
|
|
Path(settings.DB_DIR).mkdir(parents=True, exist_ok=True)
|
|
|
|
# Try to connect to check if the database is accessible
|
|
with engine.connect() as conn:
|
|
try:
|
|
conn.execute(text("SELECT 1"))
|
|
print("Database connection successful")
|
|
except Exception as e:
|
|
print(f"Database connection error: {e}")
|
|
raise
|
|
|
|
# Run alembic upgrade to create tables
|
|
try:
|
|
# Get the project root directory (where alembic.ini is located)
|
|
project_root = Path(__file__).parent.parent.parent.absolute()
|
|
|
|
# Change to project root directory and run alembic
|
|
os.chdir(project_root)
|
|
subprocess.run(["alembic", "upgrade", "head"], check=True)
|
|
print("Database migration successful")
|
|
except subprocess.CalledProcessError as e:
|
|
print(f"Database migration error: {e}")
|
|
raise
|
|
|
|
print("Database initialized successfully")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
init_db() |