Skip to content

query_single_or_default_async

query_single_or_default_async can execute a query and serialize the first result, or return a default value if the result set is empty; this method throws an exception if there is more than one element in the result set.

Parameters🔗

name type description optional default
sql str the sql query str to execute 👎
default Any any object to return if the result set is empty 👎
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 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


sentinel = object()


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

    if task is sentinel:
        print("No results found!")
    # No results found!


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