Skip to content

query_single_async

query_single_async can execute a query and serialize the first result. It throws an exception if there is not exactly one record in the result set.

Parameters🔗

name type description optional default
sql str the sql query str to execute 👎
param ParamType params to substitute in the query 👍 None
model Any the callable to serialize the model; callable must be able to accept column names as kwargs. 👍 dict

First, Single and Default🔗

Be careful to use the right method. first and single methods are very different.

method no item one item many items
first NoResultException item first item
single NoResultException item MoreThanOneResultException
first_or_default default item first item
single_or_default default item MoreThanOneResultException

Example🔗

Execute a query and map the first result to a dataclass.

import asyncio
import datetime
from dataclasses import dataclass

from pydapper import connect_async


@dataclass
class Task:
    id: int
    description: str
    due_date: datetime.date
    owner_id: int


async def main():
    async with connect_async() as commands:
        task = await commands.query_single_async("select * from task where id = 1", model=Task)

    print(task)
    # Task(id=1, description='Set up a test database', due_date=datetime.date(2021, 12, 31), owner_id=1)


asyncio.run(main())
(This script is complete, it should run "as is")