80 lines
2.3 KiB
Python
Executable File
80 lines
2.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""
|
|
Database initialization script
|
|
|
|
Creates all tables in the PostgreSQL database.
|
|
|
|
Usage:
|
|
python scripts/init_db.py
|
|
"""
|
|
import asyncio
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# Add parent directory to path to import app modules
|
|
sys.path.insert(0, str(Path(__file__).parent.parent))
|
|
|
|
from app.database import init_db, close_db, engine
|
|
from app.config import settings
|
|
from sqlalchemy import text
|
|
import logging
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
async def main():
|
|
"""Initialize database"""
|
|
logger.info("=" * 60)
|
|
logger.info("Cosmo Database Initialization")
|
|
logger.info("=" * 60)
|
|
logger.info(f"Database URL: {settings.database_url.split('@')[1]}") # Hide password
|
|
logger.info("=" * 60)
|
|
|
|
try:
|
|
# Test database connection
|
|
logger.info("Testing database connection...")
|
|
async with engine.begin() as conn:
|
|
await conn.execute(text("SELECT 1"))
|
|
logger.info("✓ Database connection successful")
|
|
|
|
# Create all tables
|
|
logger.info("Creating database tables...")
|
|
await init_db()
|
|
logger.info("✓ All tables created successfully")
|
|
|
|
# Display created tables
|
|
async with engine.connect() as conn:
|
|
result = await conn.execute(text("""
|
|
SELECT table_name
|
|
FROM information_schema.tables
|
|
WHERE table_schema = 'public'
|
|
ORDER BY table_name
|
|
"""))
|
|
tables = [row[0] for row in result]
|
|
|
|
logger.info(f"\nCreated {len(tables)} tables:")
|
|
for table in tables:
|
|
logger.info(f" - {table}")
|
|
|
|
logger.info("\n" + "=" * 60)
|
|
logger.info("Database initialization completed successfully!")
|
|
logger.info("=" * 60)
|
|
|
|
except Exception as e:
|
|
logger.error(f"\n✗ Database initialization failed: {e}")
|
|
logger.error("\nPlease ensure:")
|
|
logger.error(" 1. PostgreSQL is running")
|
|
logger.error(" 2. Database 'cosmo_db' exists")
|
|
logger.error(" 3. Database credentials in .env are correct")
|
|
sys.exit(1)
|
|
finally:
|
|
await close_db()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|