Refactor manual db.close() calls to middleware-based connection management #71
Labels
No Milestone
No project
No Assignees
2 Participants
Notifications
Due Date
No due date set.
Dependencies
No dependencies set.
Reference: cal/major-domo-database#71
Loading…
Reference in New Issue
Block a user
No description provided.
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem
There are ~180 manual
db.close()calls scattered across 28 router files. WithPooledPostgresqlDatabase, this creates several problems:model_to_dict(recurse=True). If the connection is returned to the pool before serialization completes, concurrent requests can steal it.@handle_db_errorsdecorator already callsdb.rollback()anddb.close()on exceptions.db.close()then raises HTTPException, the decorator also closes.Fix
Use Peewee's
@db.connection_context()decorator or FastAPI middleware to manage connection lifecycle per-request. Remove all manualdb.close()calls from routers.Severity
High — latent reliability risk under load.
PR #97 implements this fix: #97
Approach: Added
db_connection_middlewaretoapp/main.pythat opensdb.connect(reuse_if_open=True)at the start of each HTTP request and closes in afinallyblock after the response is fully sent. Removed all 177 manualdb.close()calls from 26 router files.This ensures the connection stays alive through FastAPI's response serialization (fixing the FK lazy-load race), eliminates double-close on error paths, and centralizes connection lifecycle in one place.