Refactor database connection handling in API endpoints

- Removed direct pool checks and replaced them with a centralized database initialization method in `init_db`.
- Updated API endpoints in `admin.py`, `collection.py`, `pins.py`, and `watched.py` to ensure the database connection pool is initialized before usage.
- Enhanced error handling to raise HTTP exceptions if the database is unavailable.
- Improved the `init_db` function in `database.py` to prevent multiple simultaneous initializations using an asyncio lock.
This commit is contained in:
Danilo Reyes
2025-12-28 21:37:31 -06:00
parent 98622c4119
commit c0371d85ce
6 changed files with 90 additions and 73 deletions

View File

@@ -4,7 +4,7 @@ from pydantic import BaseModel
from typing import Optional
from datetime import datetime
from uuid import UUID
from app.core.database import pool
from app.core.database import init_db, pool as db_pool
import json
router = APIRouter()
@@ -30,12 +30,11 @@ class WatchedItemUpdate(BaseModel):
@router.get("/summary")
async def get_watched_summary():
"""Get watched items summary by country"""
# Pool should be initialized on startup
if not pool:
from app.core.database import init_db
await init_db()
await init_db()
if db_pool is None:
raise HTTPException(status_code=503, detail="Database not available")
async with pool.connection() as conn:
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
query = """
SELECT
@@ -63,12 +62,11 @@ async def get_watched_summary():
@router.get("")
async def list_watched_items():
"""List all watched items"""
# Pool should be initialized on startup
if not pool:
from app.core.database import init_db
await init_db()
await init_db()
if db_pool is None:
raise HTTPException(status_code=503, detail="Database not available")
async with pool.connection() as conn:
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
query = """
SELECT
@@ -100,15 +98,14 @@ async def list_watched_items():
@router.post("")
async def create_watched_item(item: WatchedItemCreate):
"""Create a new watched item"""
# Pool should be initialized on startup
if not pool:
from app.core.database import init_db
await init_db()
await init_db()
if db_pool is None:
raise HTTPException(status_code=503, detail="Database not available")
if item.media_type not in ["movie", "show"]:
raise HTTPException(status_code=400, detail="media_type must be 'movie' or 'show'")
async with pool.connection() as conn:
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
query = """
INSERT INTO moviemap.watched_item
@@ -136,12 +133,11 @@ async def create_watched_item(item: WatchedItemCreate):
@router.patch("/{item_id}")
async def update_watched_item(item_id: UUID, item: WatchedItemUpdate):
"""Update a watched item"""
# Pool should be initialized on startup
if not pool:
from app.core.database import init_db
await init_db()
await init_db()
if db_pool is None:
raise HTTPException(status_code=503, detail="Database not available")
async with pool.connection() as conn:
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
# Build dynamic update query
updates = []
@@ -189,12 +185,11 @@ async def update_watched_item(item_id: UUID, item: WatchedItemUpdate):
@router.delete("/{item_id}")
async def delete_watched_item(item_id: UUID):
"""Delete a watched item"""
# Pool should be initialized on startup
if not pool:
from app.core.database import init_db
await init_db()
await init_db()
if db_pool is None:
raise HTTPException(status_code=503, detail="Database not available")
async with pool.connection() as conn:
async with db_pool.connection() as conn:
async with conn.cursor() as cur:
query = "DELETE FROM moviemap.watched_item WHERE id = %s RETURNING id"
await cur.execute(query, (str(item_id),))