from datetime import date from sqlalchemy import delete, func, select from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession from common.database.model.models import Event, Holiday, Place, WeatherDaily class WeekCRUD: async def daily(self, s: AsyncSession, region_code: str, since: date, until: date) -> list[WeatherDaily]: stmt = select(WeatherDaily).where( WeatherDaily.region_code == region_code, WeatherDaily.forecast_date >= since, WeatherDaily.forecast_date <= until ) return list((await s.scalars(stmt.order_by(WeatherDaily.forecast_date))).all()) async def holidays(self, s: AsyncSession, since: date, until: date) -> dict[date, str]: stmt = select(Holiday).where(Holiday.holiday_date >= since, Holiday.holiday_date <= until) return {h.holiday_date: h.name for h in (await s.scalars(stmt)).all()} async def holiday_count(self, s: AsyncSession, year: int) -> int: stmt = select(func.count()).select_from(Holiday).where(func.extract("year", Holiday.holiday_date) == year) return await s.scalar(stmt) async def upsert_holidays(self, s: AsyncSession, rows: list[dict]) -> None: if rows: await s.execute(insert(Holiday).values(rows).on_conflict_do_nothing(index_elements=["holiday_date", "name"])) async def places(self, s: AsyncSession, sido_code: str) -> list[Place]: stmt = select(Place).where(Place.region_code.startswith(sido_code)).order_by(Place.sort_order) return list((await s.scalars(stmt)).all()) async def replace_places(self, s: AsyncSession, rows: list[dict]) -> None: await s.execute(delete(Place)) if rows: await s.execute(insert(Place).values(rows)) async def events(self, s: AsyncSession, sido_codes: list[str], since: date, until: date) -> list[Event]: stmt = select(Event).where(Event.sido_code.in_(sido_codes), Event.end_date >= since, Event.start_date <= until) return list((await s.scalars(stmt.order_by(Event.start_date))).all()) async def upsert_events(self, s: AsyncSession, rows: list[dict]) -> None: if not rows: return stmt = insert(Event).values(rows) await s.execute(stmt.on_conflict_do_update( index_elements=["source_id"], set_={k: stmt.excluded[k] for k in ("name", "place_name", "start_date", "end_date", "is_confirmed", "image_url", "lat", "lon", "kind", "icon")}, )) async def replace_manual_events(self, s: AsyncSession, rows: list[dict]) -> None: await s.execute(delete(Event).where(Event.source_id.is_(None))) if rows: await s.execute(insert(Event).values(rows))