Files
VLoop/backend/internal/video/comment_repo.go

173 lines
5.7 KiB
Go
Raw Normal View History

2026-05-20 16:34:19 +08:00
package video
import (
"context"
"time"
2026-05-20 16:34:19 +08:00
"gorm.io/gorm"
"gorm.io/gorm/clause"
2026-05-20 16:34:19 +08:00
)
type CommentRepository struct {
db *gorm.DB
}
func NewCommentRepository(db *gorm.DB) *CommentRepository {
return &CommentRepository{db: db}
}
func (r *CommentRepository) CreateComment(ctx context.Context, comment *Comment) error {
return r.db.WithContext(ctx).Create(comment).Error
}
// CreateIdempotentWithPopularity 是 P0-4 的核心写入口。
//
// 它把两件必须同生共死的事放进同一个事务:
//
// 1. 插入评论——由 uk_comments_author_key(author_id, idempotency_key) 判重,
// 重复时静默返回 created=false,不报错、不覆盖。
// 2. 视频热度 +delta——只在真的插入了这一行时才执行。
//
// 为什么判重不能靠"先 SELECT 再 INSERT":两个 goroutine 之间永远有窗口,
// 而这条窗口正好是 P0-4 的场景(MQ 假失败后兜底直写 + worker 稍后消费)。
// 让数据库的唯一索引来裁决,判重与写入就变成同一个原子动作,没有窗口。
//
// 为什么不用 1062 判重:报错与去重是两种不同的语义,用报错表达去重会让
// 每一条正常路径都经过一次 error 分支,也难以区分"真冲突"与"别的 1062"。
// OnConflict DoNothing 直接给出 RowsAffected——它就是"我是否真的插入了"。
//
// 注意:本项目 DSN(internal/db/db.go)刻意没有 clientFoundRows。若有人
// 加上它,MySQL 会在"行未变化"时也报告 1 行受影响,本函数就会把重复写入
// 当成首次写入,热度变成 +2——判重静默失效。db 包与集成测试各有护栏。
func (r *CommentRepository) CreateIdempotentWithPopularity(ctx context.Context, c *Comment, delta int64) (bool, error) {
var created bool
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
res := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(c)
if res.Error != nil {
return res.Error
}
if res.RowsAffected == 0 {
// 这条意图已经落过库:不是错误,也不再加热度。
return nil
}
created = true
if delta == 0 {
return nil
}
// 与插入同一个事务:要么"评论与热度"一起生效,要么都不生效。
// GREATEST(...,0) 防止热度被回滚到负数(与点赞侧一致)。
return tx.Model(&Video{}).
Where("id = ?", c.VideoID).
UpdateColumn("popularity", gorm.Expr("GREATEST(popularity + ?, 0)", delta)).Error
})
if err != nil {
return false, err
}
return created, nil
}
2026-05-20 16:34:19 +08:00
func (r *CommentRepository) DeleteComment(ctx context.Context, comment *Comment) error {
return r.db.WithContext(ctx).Delete(comment).Error
}
// DeleteByID 汇报"这次调用是否真的删掉了一行"。
//
// 删除的重复投递与新增的重复投递同样致命:把热度回退当成无条件动作,
// 同一条删除事件投递两次就会把热度减两次(P2-20 的门控点就是这个返回值)。
func (r *CommentRepository) DeleteByID(ctx context.Context, id uint) (bool, error) {
if id == 0 {
return false, nil
}
res := r.db.WithContext(ctx).Delete(&Comment{}, id)
if res.Error != nil {
return false, res.Error
}
return res.RowsAffected > 0, nil
}
2026-05-20 16:34:19 +08:00
func (r *CommentRepository) GetAllComments(ctx context.Context, videoID uint) ([]Comment, error) {
var comments []Comment
err := r.db.WithContext(ctx).
Where("video_id = ?", videoID).
Order("created_at asc").
Limit(200).
Find(&comments).Error
return comments, err
}
func (r *CommentRepository) IsExist(ctx context.Context, id uint) (bool, error) {
var comment Comment
if err := r.db.WithContext(ctx).First(&comment, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return false, nil
}
return false, err
}
return true, nil
}
func (r *CommentRepository) GetByID(ctx context.Context, id uint) (*Comment, error) {
var comment Comment
if err := r.db.WithContext(ctx).First(&comment, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
}
return nil, err
}
return &comment, nil
}
// CreateMentions 幂等写入提及通知:DedupeKey 相同则静默跳过。
//
// 显式写 CreatedAt 而不依赖 autoCreateTime:这条路径写的是"列投影"而不是
// worker 包的实体,autoCreateTime 只在 GORM 认为字段是零值时才生效——一旦
// 有人在调用前给 CreatedAt 赋了零值以外的值,两种来源就会打架(P2-16 ①)。
func (r *CommentRepository) CreateMentions(ctx context.Context, mentions []Mention) error {
if len(mentions) == 0 {
return nil
}
now := time.Now()
rows := make([]NotificationRow, 0, len(mentions))
for _, m := range mentions {
rows = append(rows, NotificationRow{
RecipientID: m.RecipientID,
SenderID: m.SenderID,
Type: "mention",
TargetID: m.TargetID,
Content: m.Content,
CreatedAt: now,
DedupeKey: nilIfEmpty(m.DedupeKey),
})
}
return r.db.WithContext(ctx).
Clauses(clause.OnConflict{DoNothing: true}).
Create(&rows).Error
}
// FindAccountIDs 一次查询解析一批用户名。
//
// 逐个 SELECT 会让"一条评论里 @ 了 5 个人"变成 5 次往返,而这段代码跑在
// 用户请求路径上(P0-4 §6.5)。不存在的用户名不出现在结果里,调用方按
// map 的不存在分支跳过即可。
func (r *CommentRepository) FindAccountIDs(ctx context.Context, usernames []string) (map[string]uint, error) {
out := make(map[string]uint, len(usernames))
if len(usernames) == 0 {
return out, nil
}
var rows []struct {
ID uint
Username string
}
if err := r.db.WithContext(ctx).
Table("accounts").
Select("id, username").
Where("username IN ?", usernames).
Scan(&rows).Error; err != nil {
return nil, err
}
for _, row := range rows {
out[row.Username] = row.ID
}
return out, nil
}