Repository navigation
Expand file tree
/
Copy pathasyncpg.py
More file actions
51 lines (37 loc) · 1.7 KB
/
Copy pathasyncpg.py
File metadata and controls
51 lines (37 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from typing import Any, Type, Optional, AsyncIterator, TypeVar
import asyncpg
import pydantic
from sqlc_runtime import AsyncCursor, AsyncConnection
T = TypeVar("T", bound=pydantic.BaseModel)
def build_asyncpg_connection(conn: asyncpg.Connection) -> AsyncConnection:
return AsyncpgConnection(conn)
class AsyncpgConnection:
def __init__(self, conn: asyncpg.Connection):
self._conn = conn
async def execute(self, query: str, *params: Any) -> AsyncCursor:
return await self._conn.cursor(query, *params)
async def execute_none(self, query: str, *params: Any) -> None:
await self._conn.execute(query, *params)
async def execute_rowcount(self, query: str, *params: Any) -> int:
status = await self._conn.execute(query, *params)
return int(status.split(" ")[-1])
async def execute_one(self, query: str, *params: Any) -> Any:
row = await self._conn.fetchrow(query, *params)
return row[0] if row is not None else None
async def execute_one_model(
self, model: Type[T], query: str, *params: Any
) -> Optional[T]:
row = await self._conn.fetchrow(query, *params)
if row is None:
return None
return model.parse_obj(row)
async def execute_many(self, query: str, *params: Any) -> AsyncIterator[Any]:
async with self._conn.transaction():
async for row in self._conn.cursor(query, *params):
yield row[0]
async def execute_many_model(
self, model: Type[T], query: str, *params: Any
) -> AsyncIterator[T]:
async with self._conn.transaction():
async for row in self._conn.cursor(query, *params):
yield model.parse_obj(row)