- Added all seven issued service trees without omissions. - Preserved the supplied runtime configuration, binaries, and assets.
44 lines
1.2 KiB
Python
Executable File
44 lines
1.2 KiB
Python
Executable File
import os
|
|
|
|
from typing import Any
|
|
|
|
import psycopg
|
|
|
|
from psycopg_pool import AsyncConnectionPool
|
|
|
|
DSN = os.environ.get(
|
|
"DATABASE_URL", "postgresql://billing:billing@127.0.0.1:5432/billing"
|
|
)
|
|
|
|
pool: AsyncConnectionPool
|
|
|
|
class QueryError(Exception):
|
|
def __init__(self, sqlstate: str, message: str):
|
|
super().__init__(message)
|
|
self.sqlstate = sqlstate
|
|
self.message = message
|
|
|
|
def query_error(exc: psycopg.Error) -> QueryError:
|
|
message = getattr(exc.diag, "message_primary", None) or str(exc).splitlines()[0]
|
|
return QueryError(exc.sqlstate or "", message)
|
|
|
|
async def open_pool():
|
|
global pool
|
|
pool = AsyncConnectionPool(
|
|
DSN, min_size=1, max_size=8, open=False, kwargs={"autocommit": True},
|
|
check=AsyncConnectionPool.check_connection,
|
|
)
|
|
await pool.open(wait=True)
|
|
|
|
async def close_pool():
|
|
await pool.close()
|
|
|
|
async def call(sql: str, params: tuple = ()) -> Any:
|
|
try:
|
|
async with pool.connection() as connection:
|
|
cursor = await connection.execute(sql, params)
|
|
row = await cursor.fetchone()
|
|
except psycopg.Error as exc:
|
|
raise query_error(exc) from None
|
|
return row[0] if row else None
|