Spaces:
Running
Running
| """ | |
| 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 | |