Files
ctms/backend/app/crud/comment.py
T
2025-12-30 14:07:57 +08:00

82 lines
2.1 KiB
Python

import uuid
from typing import Sequence
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.comment import Comment
from app.schemas.comment import CommentCreate
async def create_comment(
db: AsyncSession,
study_id: uuid.UUID,
entity_type: str,
entity_id: uuid.UUID,
comment_in: CommentCreate,
created_by: uuid.UUID,
) -> Comment:
comment = Comment(
study_id=study_id,
entity_type=entity_type,
entity_id=entity_id,
content=comment_in.content,
quote_comment_id=comment_in.quote_comment_id,
created_by=created_by,
)
db.add(comment)
await db.commit()
await db.refresh(comment)
return comment
async def list_comments(
db: AsyncSession,
study_id: uuid.UUID,
entity_type: str,
entity_id: uuid.UUID,
) -> Sequence[Comment]:
result = await db.execute(
select(Comment)
.where(
Comment.study_id == study_id,
Comment.entity_type == entity_type,
Comment.entity_id == entity_id,
Comment.is_deleted.is_(False),
)
.order_by(Comment.created_at.asc())
)
return result.scalars().all()
async def get_comment(db: AsyncSession, comment_id: uuid.UUID, *, include_deleted: bool = False) -> Comment | None:
stmt = select(Comment).where(Comment.id == comment_id)
if not include_deleted:
stmt = stmt.where(Comment.is_deleted.is_(False))
result = await db.execute(stmt)
return result.scalar_one_or_none()
async def get_comments_by_ids(
db: AsyncSession,
ids: set[uuid.UUID],
*,
include_deleted: bool = False,
) -> dict[uuid.UUID, Comment]:
if not ids:
return {}
stmt = select(Comment).where(Comment.id.in_(ids))
if not include_deleted:
stmt = stmt.where(Comment.is_deleted.is_(False))
result = await db.execute(stmt)
comments = result.scalars().all()
return {c.id: c for c in comments}
async def soft_delete_comment(db: AsyncSession, comment: Comment) -> Comment:
comment.is_deleted = True
db.add(comment)
await db.commit()
await db.refresh(comment)
return comment