didier/database/crud/memes.py

36 lines
1.1 KiB
Python
Raw Permalink Normal View History

2022-08-25 02:07:02 +02:00
from typing import Optional
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.asyncio import AsyncSession
2022-08-29 20:24:42 +02:00
from database.schemas import MemeTemplate
2022-08-25 02:07:02 +02:00
2022-08-25 11:04:25 +02:00
__all__ = ["add_meme", "get_all_memes", "get_meme_by_name"]
2022-08-25 02:07:02 +02:00
async def add_meme(session: AsyncSession, name: str, template_id: int, field_count: int) -> Optional[MemeTemplate]:
"""Add a new meme into the database"""
try:
meme = MemeTemplate(name=name, template_id=template_id, field_count=field_count)
session.add(meme)
await session.commit()
return meme
except IntegrityError:
return None
2022-08-25 11:04:25 +02:00
async def get_all_memes(session: AsyncSession) -> list[MemeTemplate]:
"""Get a list of all memes"""
statement = select(MemeTemplate)
2023-07-08 01:23:47 +02:00
return list((await session.execute(statement)).scalars().all())
2022-08-25 11:04:25 +02:00
2022-08-25 02:07:02 +02:00
async def get_meme_by_name(session: AsyncSession, query: str) -> Optional[MemeTemplate]:
"""Try to find a meme by its name
Returns the first match found by PSQL
"""
statement = select(MemeTemplate).where(MemeTemplate.name.ilike(f"%{query.lower()}%"))
return (await session.execute(statement)).scalar()