from sqlalchemy import select, desc, func from sqlalchemy.orm import Session, selectinload from models.family import Records, Comments from schemas.record import RecordCreate, RecordUpdate, RecordResponse, RecordPageResponse def get_all_records(db: Session, skip: int = 0, limit: int = 20) -> list[RecordResponse]: result = db.execute( select(Records) .options( selectinload(Records.user), selectinload(Records.comments).selectinload(Comments.user), ) .order_by(desc(Records.create_time)) .offset(skip) .limit(limit) ) records = result.scalars().all() return [RecordResponse.model_validate(r) for r in records] def get_all_records_by_page(db: Session, page: int = 1, size: int = 20) -> RecordPageResponse: base_query = select(Records).options( selectinload(Records.user), selectinload(Records.comments).selectinload(Comments.user), ) # 总数 total = db.scalar( select(func.count()).select_from(base_query.subquery()) ) # 分页数据 records = db.execute( base_query .order_by(Records.create_time.desc()) .offset((page - 1) * size) .limit(size) ).scalars().all() return RecordPageResponse( records=[RecordResponse.model_validate(r) for r in records], total=total, page=page, size=size, pages=(total + size - 1) // size, ) def create_record(db: Session, record_dto: RecordCreate) -> bool: data = record_dto.model_dump() record = Records(**data) db.add(record) db.commit() db.refresh(record) return True def get_record_by_id(db: Session, record_id: int) -> Records | None: result = db.execute(select(Records).where(Records.id == record_id)) return result.scalar_one_or_none() def update_record(db: Session, record_id: int, record_dto: RecordUpdate) -> bool: record = get_record_by_id(db, record_id) if not record: return False for field, value in record_dto.model_dump(exclude_unset=True).items(): setattr(record, field, value) db.commit() db.refresh(record) return True def delete_record(db: Session, record_id: int) -> bool: record = get_record_by_id(db, record_id) if not record: return False db.delete(record) db.commit() return True