Files
backend/reset_db.py
2026-01-24 11:02:08 -08:00

38 lines
1.4 KiB
Python

import asyncio
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import text
import os
# Use 'db' for docker-compose execution (service name)
# Note: In docker-compose, internal is 'db', but from host it is 'localhost' mapped port 5432
DATABASE_URL = "postgresql+asyncpg://user:password@db:5432/fastapi_db"
async def reset_db():
print(f"Connecting to {DATABASE_URL}...")
engine = create_async_engine(DATABASE_URL, echo=True)
async with engine.begin() as conn:
print("Dropping all tables...")
# Disable foreign key checks to allow dropping in any order (Postgres specific)
await conn.execute(text("DROP SCHEMA public CASCADE;"))
await conn.execute(text("CREATE SCHEMA public;"))
print("Schema reset complete.")
await engine.dispose()
if __name__ == "__main__":
try:
asyncio.run(reset_db())
print("Database reset successfully.")
except Exception as e:
print(f"Error resetting database: {e}")
# Try 'db' host if localhost fails (in case running inside container)
if "Connection refused" in str(e) or "gaierror" in str(e):
print("Retrying with host 'db'...")
DATABASE_URL = "postgresql+asyncpg://user:password@db:5432/fastapi_db"
try:
asyncio.run(reset_db())
except Exception as e2:
print(f"Failed inside container too: {e2}")