claude-memory/graph/fixes/fix-replace-manual-dbclose-calls-with-fastapi-middleware-in-8a4ae0.md

2.1 KiB

id type title tags importance confidence created updated relations
8a4ae0ed-5bac-459b-bdd8-d3075bfc108d fix Fix: Replace manual db.close() calls with FastAPI middleware in paper-dynasty-database
paper-dynasty-database
fastapi
peewee
python
middleware
database
connection-management
0.7 0.8 2026-03-03T05:38:10.354619+00:00 2026-03-03T05:38:11.920614+00:00
target type direction strength edge_id
947fe7fd-b23c-4e46-8065-51c0519f2756 RELATED_TO outgoing 0.68 a4562549-7763-4d02-bb47-cb58024672d0
target type direction strength edge_id
25a63239-d077-4a92-8466-0900e16b837f RELATED_TO outgoing 0.67 d3b9f90f-6f05-4178-b3f2-5c7851b01b33
target type direction strength edge_id
e80e161a-4be4-428d-8590-267b9ab4cc7c RELATED_TO outgoing 0.65 5718558e-60c9-487f-ab46-9dee64c3385c

Problem

467 manual db.close() calls across 30 router files in app/routers_v2/. Any uncaught exception would leak a Peewee DB connection. Brittle to maintain.

Solution

Added db_session_middleware to app/main.py using FastAPI's @app.middleware("http") decorator:

@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
    try:
        db.connect(reuse_if_open=True)
        response = await call_next(request)
        return response
    finally:
        if not db.is_closed():
            db.close()

Used db.connect(reuse_if_open=True) — safe for both SQLite and PooledPostgresqlDatabase (pool returns connection on close).

Removed all db.close() lines from routers with a Python regex script:

re.sub(r'^[ \t]*db\.close\(\)\n', '', content, flags=re.MULTILINE)

Files Changed

  • app/main.py — added import + middleware (11 lines)
  • app/routers_v2/*.py — removed db.close() from 30 files

Notes

  • db.close() at end of db_engine.py (line 1067) is initialization cleanup — intentionally kept
  • Some router files now have unused db imports (only used for db.close()) — harmless, can clean up later
  • PR #33 in paper-dynasty-database