Skip to content

Commit 17ec2e2

Browse files
committed
Add fetch_from and cursor_from
1 parent 36ff4a7 commit 17ec2e2

1 file changed

Lines changed: 27 additions & 11 deletions

File tree

sql_athame/dataclasses.py

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -354,19 +354,37 @@ def select_sql(
354354
return query
355355

356356
@classmethod
357-
async def select_cursor(
357+
async def cursor_from(
358+
cls: type[T],
359+
connection: Connection,
360+
query: Fragment,
361+
prefetch: int = 1000,
362+
) -> AsyncGenerator[T, None]:
363+
async for row in connection.cursor(*query, prefetch=prefetch):
364+
yield cls.from_mapping(row)
365+
366+
@classmethod
367+
def select_cursor(
358368
cls: type[T],
359369
connection: Connection,
360370
order_by: Union[FieldNames, str] = (),
361371
for_update: bool = False,
362372
where: Where = (),
363373
prefetch: int = 1000,
364374
) -> AsyncGenerator[T, None]:
365-
async for row in connection.cursor(
366-
*cls.select_sql(order_by=order_by, for_update=for_update, where=where),
375+
return cls.cursor_from(
376+
connection,
377+
cls.select_sql(order_by=order_by, for_update=for_update, where=where),
367378
prefetch=prefetch,
368-
):
369-
yield cls.from_mapping(row)
379+
)
380+
381+
@classmethod
382+
async def fetch_from(
383+
cls: type[T],
384+
connection_or_pool: Union[Connection, Pool],
385+
query: Fragment,
386+
) -> list[T]:
387+
return [cls.from_mapping(row) for row in await connection_or_pool.fetch(*query)]
370388

371389
@classmethod
372390
async def select(
@@ -376,12 +394,10 @@ async def select(
376394
for_update: bool = False,
377395
where: Where = (),
378396
) -> list[T]:
379-
return [
380-
cls.from_mapping(row)
381-
for row in await connection_or_pool.fetch(
382-
*cls.select_sql(order_by=order_by, for_update=for_update, where=where)
383-
)
384-
]
397+
return await cls.fetch_from(
398+
connection_or_pool,
399+
cls.select_sql(order_by=order_by, for_update=for_update, where=where),
400+
)
385401

386402
@classmethod
387403
def create_sql(cls: type[T], **kwargs: Any) -> Fragment:

0 commit comments

Comments
 (0)