store: Fix: Replace manual db.close() calls with FastAPI middleware in paper-dynasty-database

This commit is contained in:
Cal Corum 2026-03-02 23:38:10 -06:00
parent 9f0dc6fa1b
commit 0ddea9deb2

View File

@ -0,0 +1,44 @@
---
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:10.354619+00:00"
---
## 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