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