forked from mtusi2026/mtusi2026lab2
72 lines
1.6 KiB
Python
72 lines
1.6 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
from contextlib import contextmanager
|
|
from typing import Iterator
|
|
|
|
import psycopg
|
|
from psycopg.rows import dict_row
|
|
from psycopg_pool import ConnectionPool
|
|
|
|
|
|
_pool: ConnectionPool | None = None
|
|
|
|
|
|
def _database_url() -> str:
|
|
url = os.environ.get("DATABASE_URL")
|
|
if not url:
|
|
raise RuntimeError("DATABASE_URL environment variable is required")
|
|
return url
|
|
|
|
|
|
from psycopg_pool import ConnectionPool
|
|
|
|
def init_pool(min_size: int = 1, max_size: int = 10) -> None:
|
|
global _pool
|
|
if _pool is not None:
|
|
return
|
|
|
|
dsn = _database_url()
|
|
sep = "&" if "?" in dsn else "?"
|
|
dsn_with_opts = (
|
|
dsn
|
|
+ sep
|
|
+ "options="
|
|
+ "-c%20statement_timeout%3D5000"
|
|
+ "%20-c%20lock_timeout%3D3000"
|
|
+ "%20-c%20idle_in_transaction_session_timeout%3D10000"
|
|
)
|
|
|
|
_pool = ConnectionPool(
|
|
conninfo=dsn_with_opts,
|
|
min_size=min_size,
|
|
max_size=max_size,
|
|
kwargs={"row_factory": dict_row},
|
|
open=True,
|
|
timeout=5.0,
|
|
check=ConnectionPool.check_connection,
|
|
max_lifetime=120,
|
|
max_idle=60,
|
|
)
|
|
|
|
|
|
def close_pool() -> None:
|
|
global _pool
|
|
if _pool is not None:
|
|
_pool.close()
|
|
_pool = None
|
|
|
|
|
|
@contextmanager
|
|
def connection() -> Iterator[psycopg.Connection]:
|
|
if _pool is None:
|
|
raise RuntimeError("Connection pool is not initialized")
|
|
with _pool.connection() as conn:
|
|
yield conn
|
|
|
|
|
|
@contextmanager
|
|
def transaction() -> Iterator[psycopg.Connection]:
|
|
with connection() as conn:
|
|
with conn.transaction():
|
|
yield conn |