Add initial shared code packages
This commit is contained in:
commit
838a97d344
54 files changed
+6265
No files matched your search
@@ -0,0 +1,65 @@
|
||||
"""Shared asyncpg pool and transaction wrapper."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, AsyncIterator, Awaitable, Callable, Sequence
|
||||
|
||||
import asyncpg
|
||||
|
||||
from .config import DatabaseConfig
|
||||
|
||||
|
||||
class Database:
|
||||
"""Own one asyncpg pool and expose common lifecycle/query operations."""
|
||||
|
||||
def __init__(self, pool: asyncpg.Pool) -> None:
|
||||
self.pool = pool
|
||||
|
||||
@classmethod
|
||||
async def connect(cls, config: DatabaseConfig | str) -> "Database":
|
||||
settings = config if isinstance(config, DatabaseConfig) else DatabaseConfig(dsn=config)
|
||||
pool = await asyncpg.create_pool(
|
||||
dsn=settings.dsn,
|
||||
min_size=settings.min_size,
|
||||
max_size=settings.max_size,
|
||||
timeout=settings.timeout,
|
||||
command_timeout=settings.command_timeout,
|
||||
)
|
||||
try:
|
||||
await pool.fetchval("SELECT 1")
|
||||
except Exception:
|
||||
await pool.close()
|
||||
raise
|
||||
return cls(pool)
|
||||
|
||||
async def ping(self) -> None:
|
||||
await self.pool.fetchval("SELECT 1")
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.pool.close()
|
||||
|
||||
async def execute(self, query: str, *args: Any) -> str:
|
||||
return await self.pool.execute(query, *args)
|
||||
|
||||
async def fetch(self, query: str, *args: Any) -> list[asyncpg.Record]:
|
||||
return await self.pool.fetch(query, *args)
|
||||
|
||||
async def fetchrow(self, query: str, *args: Any) -> asyncpg.Record | None:
|
||||
return await self.pool.fetchrow(query, *args)
|
||||
|
||||
async def fetchval(self, query: str, *args: Any) -> Any:
|
||||
return await self.pool.fetchval(query, *args)
|
||||
|
||||
@asynccontextmanager
|
||||
async def transaction(self) -> AsyncIterator[asyncpg.Connection]:
|
||||
async with self.pool.acquire() as connection:
|
||||
async with connection.transaction():
|
||||
yield connection
|
||||
|
||||
async def with_transaction(
|
||||
self,
|
||||
callback: Callable[[asyncpg.Connection], Awaitable[Any]],
|
||||
) -> Any:
|
||||
async with self.transaction() as connection:
|
||||
return await callback(connection)
|
||||
Reference in new issue
Block a user