56 lines
2.7 KiB
Python
56 lines
2.7 KiB
Python
from datetime import date
|
|
|
|
from sqlalchemy import func, select, text
|
|
from sqlalchemy.dialects.postgresql import insert
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from common.database.model.models import Holiday, IndexDefinition, IndexScore
|
|
|
|
|
|
class IndexCRUD:
|
|
async def definitions(self, s: AsyncSession) -> list[IndexDefinition]:
|
|
return list((await s.scalars(select(IndexDefinition).order_by(IndexDefinition.sort_order))).all())
|
|
|
|
async def upsert_definitions(self, s: AsyncSession, rows: list[dict]) -> None:
|
|
stmt = insert(IndexDefinition).values(rows)
|
|
await s.execute(stmt.on_conflict_do_update(
|
|
index_elements=["code"],
|
|
set_={k: stmt.excluded[k] for k in rows[0] if k != "code"},
|
|
))
|
|
|
|
async def scores(self, s: AsyncSession, region_code: str, since: date, until: date) -> list[IndexScore]:
|
|
stmt = select(IndexScore).where(
|
|
IndexScore.region_code == region_code, IndexScore.score_date >= since, IndexScore.score_date <= until
|
|
)
|
|
return list((await s.scalars(stmt)).all())
|
|
|
|
async def score_dates(self, s: AsyncSession, region_code: str, since: date, until: date) -> set[date]:
|
|
stmt = select(IndexScore.score_date).distinct().where(
|
|
IndexScore.region_code == region_code, IndexScore.score_date >= since, IndexScore.score_date <= until
|
|
)
|
|
return set((await s.scalars(stmt)).all())
|
|
|
|
async def last_computed(self, s: AsyncSession, region_code: str, day: date):
|
|
stmt = select(func.min(IndexScore.computed_at)).where(IndexScore.region_code == region_code, IndexScore.score_date == day)
|
|
return await s.scalar(stmt)
|
|
|
|
async def has_unslotted(self, s: AsyncSession, region_code: str, day: date) -> bool:
|
|
"""그날 행 중 구간 점수가 비어 있는 행(구간 계산 전 행)이 있는지."""
|
|
stmt = select(IndexScore.index_id).where(
|
|
IndexScore.region_code == region_code, IndexScore.score_date == day, text("index_score.slots = '{}'::jsonb")
|
|
).limit(1)
|
|
return (await s.scalar(stmt)) is not None
|
|
|
|
async def upsert_scores(self, s: AsyncSession, rows: list[dict]) -> None:
|
|
if not rows:
|
|
return
|
|
stmt = insert(IndexScore).values(rows)
|
|
await s.execute(stmt.on_conflict_do_update(
|
|
index_elements=["region_code", "score_date", "index_id"],
|
|
set_={k: stmt.excluded[k] for k in rows[0] if k not in ("region_code", "score_date", "index_id")},
|
|
))
|
|
|
|
async def holidays(self, s: AsyncSession, since: date, until: date) -> set[date]:
|
|
stmt = select(Holiday.holiday_date).where(Holiday.holiday_date >= since, Holiday.holiday_date <= until)
|
|
return set((await s.scalars(stmt)).all())
|