Files
sensgw/sensgw/db.py
2025-12-16 12:13:43 +06:00

40 lines
860 B
Python

# sensgw/db.py
import asyncpg
import json
from typing import Optional
async def _init_connection(con: asyncpg.Connection) -> None:
await con.set_type_codec(
"json",
encoder=json.dumps,
decoder=json.loads,
schema="pg_catalog",
)
await con.set_type_codec(
"jsonb",
encoder=json.dumps,
decoder=json.loads,
schema="pg_catalog",
)
class Database:
def __init__(self, dsn: str):
self._dsn = dsn
self.pool: Optional[asyncpg.Pool] = None
async def start(self) -> None:
self.pool = await asyncpg.create_pool(
dsn=self._dsn,
min_size=1,
max_size=10,
init=_init_connection,
)
async def stop(self) -> None:
if self.pool:
await self.pool.close()
self.pool = None