Files
dtf-system/app/core/db.py
Cauê Faleiros 5b7e95ad86 feat: a database connection pool behind DB_POOL (off in production)
Every db.connect() opened a new Postgres connection; with DB_POOL=on each
process keeps a psycopg_pool pool (DB_POOL_SIZE, default 20, 10 s
acquisition timeout, dropped connections replaced) with the same
commit/rollback contract. Production stays off until switched in Portainer;
the local stack and CI run with it on. Two nested acquisitions that ran on
every board load and in audits now reuse the caller's connection.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-09 17:57:42 -03:00

70 lines
2.3 KiB
Python

import os
import threading
from pathlib import Path
import psycopg
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
from .. import migrate
# One pool per process, created on first use when DB_POOL is on (default off).
_pool = None
_pool_lock = threading.Lock()
def _direct():
# Production passes credentials as discrete libpq fields. This avoids
# treating characters in a generated password as URL syntax. Local and
# test environments retain DATABASE_URL compatibility.
if os.environ.get('DATABASE_HOST'):
return psycopg.connect(
host=os.environ['DATABASE_HOST'],
dbname=os.environ['DATABASE_NAME'],
user=os.environ['DATABASE_USER'],
password=os.environ['DATABASE_PASSWORD'],
row_factory=dict_row,
)
return psycopg.connect(os.environ['DATABASE_URL'], row_factory=dict_row)
def _pool_arguments():
"""The conninfo and kwargs for the pool, matching _direct()'s settings."""
if os.environ.get('DATABASE_HOST'):
return '', {
'host': os.environ['DATABASE_HOST'],
'dbname': os.environ['DATABASE_NAME'],
'user': os.environ['DATABASE_USER'],
'password': os.environ['DATABASE_PASSWORD'],
'row_factory': dict_row,
}
return os.environ['DATABASE_URL'], {'row_factory': dict_row}
def _pool_instance():
global _pool
if _pool is None:
with _pool_lock:
if _pool is None:
conninfo, kwargs = _pool_arguments()
_pool = ConnectionPool(
conninfo, kwargs=kwargs, min_size=1,
max_size=int(os.environ.get('DB_POOL_SIZE') or 20),
open=True, timeout=10, check=ConnectionPool.check_connection)
return _pool
def connect():
"""A connection for one `with` block. Pooled when DB_POOL is on (default
off): the same commit/rollback contract, the connection goes back to the
pool instead of closing."""
if os.environ.get('DB_POOL', 'off').lower() != 'on':
return _direct()
return _pool_instance().connection()
def initialize():
with connect() as c:
# The schema lives at the package root, one level up from core/.
c.execute((Path(__file__).resolve().parent.parent / 'schema.sql').read_text())
migrate.apply(c)