didier/database/crud/events.py

51 lines
1.8 KiB
Python
Raw Normal View History

2023-02-03 00:16:49 +01:00
import datetime
2023-02-02 23:16:51 +01:00
from typing import Optional
from zoneinfo import ZoneInfo
from dateutil.parser import parse
2023-02-03 00:16:49 +01:00
from sqlalchemy import delete, select
2023-02-02 23:16:51 +01:00
from sqlalchemy.ext.asyncio import AsyncSession
from database.schemas import Event
2023-02-03 00:16:49 +01:00
__all__ = ["add_event", "delete_event_by_id", "get_event_by_id", "get_events", "get_next_event"]
2023-02-02 23:16:51 +01:00
async def add_event(
session: AsyncSession, *, name: str, description: Optional[str], date_str: str, channel_id: int
) -> Event:
"""Create a new event"""
date_dt = parse(date_str, dayfirst=True).replace(tzinfo=ZoneInfo("Europe/Brussels"))
event = Event(name=name, description=description, timestamp=date_dt, notification_channel=channel_id)
session.add(event)
await session.commit()
2023-02-03 00:16:49 +01:00
await session.refresh(event)
2023-02-02 23:16:51 +01:00
return event
2023-02-03 00:16:49 +01:00
async def delete_event_by_id(session: AsyncSession, event_id: int):
"""Delete an event by its id"""
statement = delete(Event).where(Event.event_id == event_id)
await session.execute(statement)
await session.commit()
2023-02-02 23:16:51 +01:00
async def get_event_by_id(session: AsyncSession, event_id: int) -> Optional[Event]:
"""Get an event by its id"""
statement = select(Event).where(Event.event_id == event_id)
return (await session.execute(statement)).scalar_one_or_none()
2023-02-03 00:16:49 +01:00
async def get_events(session: AsyncSession, *, now: datetime.datetime) -> list[Event]:
2023-02-02 23:16:51 +01:00
"""Get a list of all upcoming events"""
2023-02-03 00:16:49 +01:00
statement = select(Event).where(Event.timestamp > now)
2023-02-02 23:16:51 +01:00
return (await session.execute(statement)).scalars().all()
2023-02-03 00:16:49 +01:00
async def get_next_event(session: AsyncSession, *, now: datetime.datetime) -> Optional[Event]:
2023-02-02 23:16:51 +01:00
"""Get the first upcoming event"""
2023-02-03 00:16:49 +01:00
statement = select(Event).where(Event.timestamp > now).order_by(Event.timestamp)
2023-02-02 23:16:51 +01:00
return (await session.execute(statement)).scalar_one_or_none()