Files
o2o-weather/backend/crud/feed_crud.py

43 lines
2.4 KiB
Python

from datetime import date
from typing import Optional
from sqlalchemy import exists, select, update
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from common.database.model.models import Comment, Post
class FeedCRUD:
async def day(self, s: AsyncSession, day: date, scopes: list[str]) -> list[Post]:
stmt = select(Post).where(Post.feed_date == day, Post.scope.in_(scopes), Post.deleted.is_(False)).order_by(Post.position, Post.scope)
return list((await s.scalars(stmt)).all())
async def positions(self, s: AsyncSession, day: date) -> set[tuple[str, int]]:
"""그날 이미 만든 (scope, 카드 번호). 지운 카드도 넣어 다시 만들지 않게 한다."""
return {(scope, pos) for scope, pos in (await s.execute(select(Post.scope, Post.position).where(Post.feed_date == day))).all()}
async def insert_day(self, s: AsyncSession, rows: list[dict]) -> None:
if rows:
await s.execute(insert(Post).values(rows).on_conflict_do_nothing())
async def without_bot(self, s: AsyncSession, day: date) -> list[Post]:
"""그날 포스트 중 캐릭터 댓글이 아직 없는 것."""
has_bot = exists().where(Comment.post_id == Post.post_id, Comment.bot.is_not(None))
return list((await s.scalars(select(Post).where(Post.feed_date == day, Post.deleted.is_(False), ~has_bot))).all())
async def add_bot_comments(self, s: AsyncSession, lines: dict[int, list[tuple[str, str]]]) -> None:
"""캐릭터 댓글을 넣고 포스트 댓글 수를 늘린다. 같은 포스트·캐릭터는 한 번만 (동시에 불려도 겹치지 않게)."""
rows = [{"post_id": post_id, "bot": bot, "body": body} for post_id, x in lines.items() for bot, body in x]
if not rows:
return
added = (await s.execute(insert(Comment).values(rows).on_conflict_do_nothing().returning(Comment.post_id))).scalars().all()
for n in (1, 2):
ids = [post_id for post_id in set(added) if added.count(post_id) == n]
if ids:
await s.execute(update(Post).where(Post.post_id.in_(ids)).values(comment_count=Post.comment_count + n))
async def get(self, s: AsyncSession, post_id: int) -> Optional[Post]:
post = await s.get(Post, post_id)
return post if post is not None and not post.deleted else None