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:
@@ -3,7 +3,6 @@ import httpx
|
||||
import logging
|
||||
from typing import Dict, List, Optional
|
||||
from app.core.config import settings
|
||||
from app.core.database import pool
|
||||
import json
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -130,12 +129,12 @@ def extract_country_from_lidarr(artist: Dict) -> Optional[str]:
|
||||
async def upsert_media_item(source_kind: str, source_item_id: int, title: str,
|
||||
year: Optional[int], media_type: str, arr_raw: Dict):
|
||||
"""Upsert a media item into the database"""
|
||||
# Pool should be initialized on startup
|
||||
if not pool:
|
||||
from app.core.database import init_db
|
||||
await init_db()
|
||||
from app.core.database import init_db, pool as db_pool
|
||||
await init_db()
|
||||
if db_pool is None:
|
||||
raise Exception("Database not available")
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with db_pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
# Upsert media item
|
||||
query = """
|
||||
@@ -273,12 +272,13 @@ async def sync_all_arrs() -> Dict:
|
||||
logger.error(f"Lidarr sync failed: {e}")
|
||||
results["lidarr"] = 0
|
||||
|
||||
# Update last sync time (pool should be initialized)
|
||||
if not pool:
|
||||
from app.core.database import init_db
|
||||
await init_db()
|
||||
# Update last sync time
|
||||
from app.core.database import init_db, pool as db_pool
|
||||
await init_db()
|
||||
if db_pool is None:
|
||||
raise Exception("Database not available")
|
||||
|
||||
async with pool.connection() as conn:
|
||||
async with db_pool.connection() as conn:
|
||||
async with conn.cursor() as cur:
|
||||
for source_kind in ["radarr", "sonarr", "lidarr"]:
|
||||
await cur.execute(
|
||||
|
||||
Reference in New Issue
Block a user