from sqlalchemy import and_, select, update from sqlalchemy.dialects.postgresql import insert as pg_insert from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import local_contents from common.enums import ErrorType, LocalContentType from common.utils.gtime import GTime class LocalContentCRUD: async def list(self, db, status: int | None = None, region_code: str | None = None): conds = [local_contents.deleted == False, local_contents.content_type == LocalContentType.FESTIVAL.value] # noqa: E712 if status is not None: conds.append(local_contents.status == status) if region_code: conds.append(local_contents.region_code == region_code) return await DB_SESSION_MNG.execute( db, select(local_contents).where(and_(*conds)).order_by(local_contents.collected_at.desc()) ) async def insert(self, db, row): return await DB_SESSION_MNG.insert(db, row) async def get_by_external_id(self, db, region_code: str, external_id: str): err, rows = await DB_SESSION_MNG.execute( db, select(local_contents).where( local_contents.region_code == region_code, local_contents.content_type == LocalContentType.FESTIVAL.value, local_contents.external_id == external_id, local_contents.deleted == False, # noqa: E712 ).limit(1), ) return err, rows[0] if rows else None async def publish(self, db, ids: list, user_id): return await DB_SESSION_MNG.add_with_rowcount( db, update(local_contents).where( local_contents.local_content_id.in_(ids), local_contents.deleted == False # noqa: E712 ).values(status=2, published_at=GTime.UTC(), published_by=user_id, updated_at=GTime.UTC()), ) async def update(self, db, content_id, data: dict): return await DB_SESSION_MNG.add_with_rowcount( db, update(local_contents).where( local_contents.local_content_id == content_id, local_contents.deleted == False # noqa: E712 ).values(**data, updated_at=GTime.UTC()), ) async def end(self, db, content_id): return await self.update(db, content_id, {"status": 3}) async def get_weather(self, db, region_code: str): err, rows = await DB_SESSION_MNG.execute( db, select(local_contents).where( local_contents.region_code == region_code, local_contents.content_type == LocalContentType.WEATHER.value, local_contents.external_id.is_(None), local_contents.deleted == False, # noqa: E712 ).limit(1), ) return err, rows[0] if rows else None async def upsert_weather(self, db, values: dict): stmt = pg_insert(local_contents).values(**values) stmt = stmt.on_conflict_do_update( index_elements=[local_contents.region_code, local_contents.content_type], index_where=and_(local_contents.deleted == False, local_contents.external_id.is_(None)), # noqa: E712 set_={ "source": stmt.excluded.source, "body": stmt.excluded.body, "status": stmt.excluded.status, "collected_at": stmt.excluded.collected_at, "expires_at": stmt.excluded.expires_at, "updated_at": stmt.excluded.updated_at, }, ) return await DB_SESSION_MNG.add(db, stmt)