2022-07-16 00:14:02 +02:00
|
|
|
from sqlalchemy import func, select
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
|
|
from database.exceptions.not_found import NoResultFoundException
|
2022-08-29 20:24:42 +02:00
|
|
|
from database.schemas import DadJoke
|
2022-07-16 00:14:02 +02:00
|
|
|
|
2022-07-18 22:00:39 +02:00
|
|
|
__all__ = ["add_dad_joke", "get_random_dad_joke"]
|
2022-07-16 00:14:02 +02:00
|
|
|
|
|
|
|
|
|
|
|
async def add_dad_joke(session: AsyncSession, joke: str) -> DadJoke:
|
|
|
|
"""Add a new dad joke to the database"""
|
|
|
|
dad_joke = DadJoke(joke=joke)
|
|
|
|
session.add(dad_joke)
|
|
|
|
await session.commit()
|
|
|
|
|
|
|
|
return dad_joke
|
|
|
|
|
|
|
|
|
2022-07-30 18:27:58 +02:00
|
|
|
async def get_random_dad_joke(session: AsyncSession) -> DadJoke: # pragma: no cover # randomness is untestable
|
2022-07-16 00:14:02 +02:00
|
|
|
"""Return a random database entry"""
|
|
|
|
statement = select(DadJoke).order_by(func.random())
|
2022-07-16 00:19:05 +02:00
|
|
|
row = (await session.execute(statement)).first()
|
|
|
|
if row is None:
|
|
|
|
raise NoResultFoundException
|
|
|
|
|
|
|
|
return row[0]
|