52 lines
1.7 KiB
Python
52 lines
1.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Database initialization script"""
|
|
import asyncio
|
|
import asyncpg
|
|
|
|
async def init_database():
|
|
"""Initialize database with schema"""
|
|
|
|
# Read SQL file
|
|
with open('docker/init-db.sql', 'r') as f:
|
|
sql = f.read()
|
|
|
|
# Connect to database using settings or environment variable
|
|
# (fall back to defaults in .env.example which point at the local docker container)
|
|
from app.core.config import Settings
|
|
settings = Settings()
|
|
# parse DATABASE_URL to asyncpg components
|
|
from sqlalchemy.engine.url import make_url
|
|
url = make_url(settings.DATABASE_URL)
|
|
|
|
conn = await asyncpg.connect(
|
|
host=url.host or 'localhost',
|
|
port=url.port or 5432,
|
|
user=url.username or 'autostock',
|
|
password=url.password or 'autostock_password',
|
|
database=url.database or 'autostock_db'
|
|
)
|
|
|
|
try:
|
|
# Split SQL into individual statements and execute one by one
|
|
statements = [s.strip() for s in sql.split(';') if s.strip()]
|
|
|
|
for statement in statements:
|
|
try:
|
|
await conn.execute(statement)
|
|
print(f"✅ Executed: {statement[:50]}...")
|
|
except Exception as e:
|
|
# Skip if already exists
|
|
if 'already exists' in str(e):
|
|
print(f"⚠️ Skipped (already exists): {statement[:50]}...")
|
|
else:
|
|
print(f"❌ Error: {e}")
|
|
|
|
print("\n✅ Database initialization completed!")
|
|
except Exception as e:
|
|
print(f"❌ Error initializing database: {e}")
|
|
finally:
|
|
await conn.close()
|
|
|
|
if __name__ == '__main__':
|
|
asyncio.run(init_database())
|