Spaces:
Running
Running
File size: 1,005 Bytes
cfcf570 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
"""
Database utilities for chat history.
"""
from typing import Iterator
from psycopg_pool import ConnectionPool
from app.core.chatbot.config import DATABASE_URL
# Connection pool for efficient connection management
# min_size=1 keeps at least 1 connection ready
# max_size=10 limits concurrent connections
_connection_pool = None
def get_connection_pool() -> ConnectionPool:
"""Get or create the connection pool (lazy initialization)."""
global _connection_pool
if _connection_pool is None:
_connection_pool = ConnectionPool(
DATABASE_URL,
min_size=1,
max_size=10,
kwargs={"connect_timeout": 10},
)
return _connection_pool
def get_db_connection():
"""Get a database connection from the pool."""
return get_connection_pool().connection()
def db_connection_dependency() -> Iterator:
"""FastAPI dependency that yields a pooled DB connection."""
with get_db_connection() as conn:
yield conn
|