77 lines
2.0 KiB
Python
77 lines
2.0 KiB
Python
|
|
"""
|
||
|
|
Database initialization script.
|
||
|
|
|
||
|
|
Usage:
|
||
|
|
python scripts/init_db.py
|
||
|
|
"""
|
||
|
|
import sys
|
||
|
|
import os
|
||
|
|
|
||
|
|
# Add src to path
|
||
|
|
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
|
||
|
|
|
||
|
|
# Load .env from project root
|
||
|
|
from dotenv import load_dotenv
|
||
|
|
project_root = os.path.dirname(os.path.dirname(__file__))
|
||
|
|
env_path = os.path.join(project_root, '.env')
|
||
|
|
print(f"Loading .env from: {env_path}")
|
||
|
|
load_dotenv(env_path)
|
||
|
|
|
||
|
|
from app.config import get_settings
|
||
|
|
from app.db.session import init_db_manager
|
||
|
|
from app.db.models import Base
|
||
|
|
|
||
|
|
|
||
|
|
def main():
|
||
|
|
"""Initialize database tables."""
|
||
|
|
print("=" * 50)
|
||
|
|
print("Database Initialization Script")
|
||
|
|
print("=" * 50)
|
||
|
|
|
||
|
|
# Load settings
|
||
|
|
try:
|
||
|
|
settings = get_settings()
|
||
|
|
print(f"✓ Settings loaded")
|
||
|
|
print(f" Database URL: {settings.database_url.split('@')[1] if '@' in settings.database_url else settings.database_url}")
|
||
|
|
except Exception as e:
|
||
|
|
print(f"✗ Failed to load settings: {e}")
|
||
|
|
print("\nPlease ensure .env file exists and contains:")
|
||
|
|
print(" - DATABASE_URL")
|
||
|
|
print(" - OPENAI_API_KEY")
|
||
|
|
return 1
|
||
|
|
|
||
|
|
# Initialize database manager
|
||
|
|
try:
|
||
|
|
db_manager = init_db_manager(settings)
|
||
|
|
print(f"✓ Database manager initialized")
|
||
|
|
except Exception as e:
|
||
|
|
print(f"✗ Failed to initialize database manager: {e}")
|
||
|
|
return 1
|
||
|
|
|
||
|
|
# Create all tables
|
||
|
|
try:
|
||
|
|
print("\nCreating tables...")
|
||
|
|
db_manager.create_all_tables()
|
||
|
|
print("✓ Tables created successfully!")
|
||
|
|
|
||
|
|
# List tables
|
||
|
|
print("\nCreated tables:")
|
||
|
|
from sqlalchemy import inspect
|
||
|
|
inspector = inspect(db_manager.engine)
|
||
|
|
for table_name in inspector.get_table_names():
|
||
|
|
print(f" - {table_name}")
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
print(f"✗ Failed to create tables: {e}")
|
||
|
|
return 1
|
||
|
|
|
||
|
|
print("\n" + "=" * 50)
|
||
|
|
print("Database initialization complete!")
|
||
|
|
print("=" * 50)
|
||
|
|
return 0
|
||
|
|
|
||
|
|
|
||
|
|
if __name__ == "__main__":
|
||
|
|
exit_code = main()
|
||
|
|
sys.exit(exit_code)
|