import atexit from collections.abc import Iterator from contextlib import contextmanager from functools import lru_cache from psycopg import Connection from psycopg.rows import dict_row from psycopg_pool import ConnectionPool from politrack.config import get_settings @lru_cache def get_pool() -> ConnectionPool: pool = ConnectionPool( get_settings().database_url, min_size=1, max_size=10, kwargs={"row_factory": dict_row}, open=False, ) pool.open() atexit.register(pool.close) return pool @contextmanager def connection() -> Iterator[Connection]: """A pooled connection inside a transaction (committed on success).""" with get_pool().connection() as conn: yield conn