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)