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_in_box(self, s: AsyncSession, lat: float, lon: float, dlat: float, dlon: float) -> list[Place]: stmt = select(Place).where(Place.lat.between(lat - dlat, lat + dlat), Place.lon.between(lon - dlon, lon + dlon)) return list((await s.scalars(stmt)).all()) async def all_places(self, s: AsyncSession) -> list[Place]: return list((await s.scalars(select(Place).where(Place.lat.is_not(None)))).all()) async def replace_places(self, s: AsyncSession, rows: list[dict]) -> None: await s.execute(delete(Place)) # asyncpg 는 한 문장에 인자 32767개까지라 나눠 넣는다. for i in range(0, len(rows), 1000): await s.execute(insert(Place).values(rows[i:i + 1000])) 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))