package repo import ( "context" "encoding/json" "errors" "fmt" "strings" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "github.com/yourorg/article-platform/internal/domain" ) type UserRepo struct{ pool *pgxpool.Pool } func NewUserRepo(p *pgxpool.Pool) *UserRepo { return &UserRepo{pool: p} } const userCols = `id, account, nickname, email, avatar_url, role, status, bio, gender, region, last_login_at, created_at` func scanUser(row pgx.Row) (*domain.User, error) { var u domain.User err := row.Scan(&u.ID, &u.Account, &u.Nickname, &u.Email, &u.AvatarURL, &u.Role, &u.Status, &u.Bio, &u.Gender, &u.Region, &u.LastLoginAt, &u.CreatedAt) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } return &u, err } // GetByAccount 登录用。大小写不敏感(库里有 lower(account) 唯一索引)。 func (r *UserRepo) GetByAccount(ctx context.Context, q Querier, account string) (*domain.User, error) { return scanUser(q.QueryRow(ctx, `SELECT `+userCols+` FROM users WHERE lower(account)=lower($1) AND deleted_at IS NULL`, account)) } func (r *UserRepo) GetByID(ctx context.Context, q Querier, id string) (*domain.User, error) { return scanUser(q.QueryRow(ctx, `SELECT `+userCols+` FROM users WHERE id=$1 AND deleted_at IS NULL`, id)) } // GetPasswordHash 单独取哈希,避免把敏感字段混进 domain.User func (r *UserRepo) GetPasswordHash(ctx context.Context, q Querier, id string) (string, error) { var h string err := q.QueryRow(ctx, `SELECT password_hash FROM users WHERE id=$1`, id).Scan(&h) return h, err } func (r *UserRepo) Insert(ctx context.Context, q Querier, u *domain.User, passwordHash string) error { _, err := q.Exec(ctx, `INSERT INTO users (id, account, nickname, email, password_hash, avatar_url, role, status, bio) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, u.ID, u.Account, u.Nickname, u.Email, passwordHash, u.AvatarURL, u.Role, u.Status, u.Bio) return err } func (r *UserRepo) TouchLogin(ctx context.Context, q Querier, id string) { _, _ = q.Exec(ctx, `UPDATE users SET last_login_at=now() WHERE id=$1`, id) } func (r *UserRepo) UpdateProfile(ctx context.Context, q Querier, id, nickname, bio, avatar, gender, region string) error { _, err := q.Exec(ctx, `UPDATE users SET nickname=$2, bio=$3, avatar_url=$4, gender=$5, region=$6, updated_at=now() WHERE id=$1`, id, nickname, bio, avatar, gender, region) return err } func (r *UserRepo) UpdatePassword(ctx context.Context, q Querier, id, passwordHash string) error { _, err := q.Exec(ctx, `UPDATE users SET password_hash=$2, updated_at=now() WHERE id=$1`, id, passwordHash) return err } // List 后台用户列表 func (r *UserRepo) List(ctx context.Context, q Querier, keyword, role, status string, limit, offset int) ([]domain.User, int64, error) { where := "deleted_at IS NULL" var args []any add := func(cond string, v any) { args = append(args, v) where += " AND " + cond } if keyword != "" { args = append(args, "%"+escapeLike(keyword)+"%") where += ` AND (account ILIKE $` + itoa(len(args)) + ` ESCAPE '\' OR nickname ILIKE $` + itoa(len(args)) + ` ESCAPE '\')` } if role != "" { add("role = $"+itoa(len(args)+1), role) } if status != "" { add("status = $"+itoa(len(args)+1), status) } var total int64 if err := q.QueryRow(ctx, `SELECT count(*) FROM users WHERE `+where, args...).Scan(&total); err != nil { return nil, 0, err } if limit <= 0 || limit > 200 { limit = 20 } args = append(args, limit, offset) sql := `SELECT ` + userCols + ` FROM users WHERE ` + where + ` ORDER BY created_at DESC LIMIT $` + itoa(len(args)-1) + ` OFFSET $` + itoa(len(args)) rows, err := q.Query(ctx, sql, args...) if err != nil { return nil, 0, err } defer rows.Close() var out []domain.User for rows.Next() { u, err := scanUser(rows) if err != nil { return nil, 0, err } out = append(out, *u) } return out, total, rows.Err() } // SearchActiveUsers 面向搜索结果页的用户检索:仅 active 用户, // 昵称前缀命中优先于包含命中(美篇式相关度),不带角色/状态过滤条件。 func (r *UserRepo) SearchActiveUsers(ctx context.Context, q Querier, keyword string, limit int) ([]domain.User, error) { if keyword == "" { return []domain.User{}, nil } if limit <= 0 || limit > 50 { limit = 10 } contains := "%" + escapeLike(keyword) + "%" prefix := escapeLike(keyword) + "%" sql := `SELECT ` + userCols + ` FROM users WHERE deleted_at IS NULL AND status = 'active' AND (nickname ILIKE $1 ESCAPE '\' OR account ILIKE $2 ESCAPE '\') ORDER BY (nickname ILIKE $3 ESCAPE '\') DESC, created_at DESC LIMIT $4` rows, err := q.Query(ctx, sql, contains, contains, prefix, limit) if err != nil { return nil, err } defer rows.Close() var out []domain.User for rows.Next() { u, err := scanUser(rows) if err != nil { return nil, err } out = append(out, *u) } return out, rows.Err() } // SetStatus 封禁/解封。封禁后 requireUser 每次查库会立即 403,旧 token 不生效。 func (r *UserRepo) SetStatus(ctx context.Context, q Querier, id, status string) error { _, err := q.Exec(ctx, `UPDATE users SET status=$2, updated_at=now() WHERE id=$1`, id, status) return err } // UpdateRole 修改用户角色 func (r *UserRepo) UpdateRole(ctx context.Context, q Querier, id, role string) error { _, err := q.Exec(ctx, `UPDATE users SET role=$2, updated_at=now() WHERE id=$1`, id, role) return err } func (r *UserRepo) Count(ctx context.Context, q Querier) (int64, error) { var n int64 err := q.QueryRow(ctx, `SELECT count(*) FROM users WHERE deleted_at IS NULL`).Scan(&n) return n, err } // ── 评论 ── type CommentRepo struct{ pool *pgxpool.Pool } func NewCommentRepo(p *pgxpool.Pool) *CommentRepo { return &CommentRepo{pool: p} } // CommentThread 是评论树的一个顶层节点及其全部后代。 // 分页只发生在顶层,回复跟着父级走 —— 这样翻页永远不会把讨论串切成两半。 type CommentThread struct { Comment domain.Comment `json:"comment"` Replies []domain.Comment `json:"replies"` ReplyCount int `json:"reply_count"` } // ListThreads 分页拉取顶层评论树。 // // 三条关键设计: // 1. keyset 分页(cursor = 上一页最后一条顶层评论的 created_at|id), // 不用 OFFSET —— 有人发新评论时 OFFSET 会错位导致漏读或重读。 // 2. 回复用递归 CTE 一次捞出,但限制每个顶层节点返回的子回复数量, // 避免一个几千条回复的热帖把响应体撑爆。 // 3. reply_count 返回真实总数,前端据此显示「查看全部 N 条回复」。 func (r *CommentRepo) ListThreads(ctx context.Context, q Querier, articleID string, limit int, cursorCreatedAt, cursorID string, repliesPerThread int) ([]CommentThread, string, int64, error) { if limit <= 0 || limit > 100 { limit = 20 } if repliesPerThread <= 0 || repliesPerThread > 100 { repliesPerThread = 10 } var total int64 if err := q.QueryRow(ctx, `SELECT count(*) FROM comments WHERE article_id=$1 AND parent_id IS NULL AND status='visible' AND deleted_at IS NULL`, articleID).Scan(&total); err != nil { return nil, "", 0, err } // 第一步:取一页顶层评论 topSQL := `SELECT c.id, c.article_id, c.user_id, c.parent_id, c.depth, c.content, c.like_count, c.status, u.nickname, u.avatar_url, c.created_at FROM comments c JOIN users u ON u.id=c.user_id WHERE c.article_id=$1 AND c.parent_id IS NULL AND c.status='visible' AND c.deleted_at IS NULL` args := []any{articleID} if cursorCreatedAt != "" && cursorID != "" { // (created_at, id) 复合游标:同一毫秒内多条评论也能稳定排序 topSQL += ` AND (c.created_at, c.id) < ($2::timestamptz, $3::uuid)` args = append(args, cursorCreatedAt, cursorID) } args = append(args, limit+1) topSQL += fmt.Sprintf(` ORDER BY c.created_at DESC, c.id DESC LIMIT $%d`, len(args)) rows, err := q.Query(ctx, topSQL, args...) if err != nil { return nil, "", 0, err } defer rows.Close() var roots []domain.Comment for rows.Next() { var c domain.Comment if err := rows.Scan(&c.ID, &c.ArticleID, &c.UserID, &c.ParentID, &c.Depth, &c.Content, &c.LikeCount, &c.Status, &c.AuthorNickname, &c.AuthorAvatar, &c.CreatedAt); err != nil { return nil, "", 0, err } roots = append(roots, c) } if err := rows.Err(); err != nil { return nil, "", 0, err } var nextCursor string if len(roots) > limit { roots = roots[:limit] last := roots[len(roots)-1] nextCursor = last.CreatedAt.UTC().Format(time.RFC3339Nano) + "|" + last.ID } if len(roots) == 0 { return []CommentThread{}, nextCursor, total, nil } // 第二步:一次捞回这些顶层评论的后代。 // 用 DISTINCT ON 给每个顶层根节点限制前 N 条回复,避免热帖撑爆响应。 rootIDs := make([]string, len(roots)) for i, c := range roots { rootIDs[i] = c.ID } replySQL := ` WITH RECURSIVE tree AS ( -- 起点:本页顶层评论的直接子节点 SELECT c.id, c.article_id, c.user_id, c.parent_id, c.depth, c.content, c.like_count, c.status, c.created_at, c.parent_id AS root_id, 1 AS lvl FROM comments c WHERE c.parent_id = ANY($1::uuid[]) AND c.status='visible' AND c.deleted_at IS NULL UNION ALL -- 递归:更深层的回复 SELECT c.id, c.article_id, c.user_id, c.parent_id, c.depth, c.content, c.like_count, c.status, c.created_at, t.root_id, t.lvl + 1 FROM comments c JOIN tree t ON c.parent_id = t.id WHERE c.status='visible' AND c.deleted_at IS NULL AND t.lvl < 4 ), ranked AS ( SELECT tree.*, row_number() OVER (PARTITION BY root_id ORDER BY created_at ASC, id ASC) AS rn FROM tree ) SELECT r.id, r.article_id, r.user_id, r.parent_id, r.depth, r.content, r.like_count, r.status, u.nickname, u.avatar_url, r.created_at, r.root_id, r.rn FROM ranked r JOIN users u ON u.id=r.user_id WHERE r.rn <= $2 ORDER BY r.root_id, r.created_at ASC, r.id ASC` replyRows, err := q.Query(ctx, replySQL, rootIDs, repliesPerThread) if err != nil { return nil, "", 0, err } defer replyRows.Close() byRoot := map[string][]domain.Comment{} for replyRows.Next() { var c domain.Comment var rootID string var rn int if err := replyRows.Scan(&c.ID, &c.ArticleID, &c.UserID, &c.ParentID, &c.Depth, &c.Content, &c.LikeCount, &c.Status, &c.AuthorNickname, &c.AuthorAvatar, &c.CreatedAt, &rootID, &rn); err != nil { return nil, "", 0, err } byRoot[rootID] = append(byRoot[rootID], c) } if err := replyRows.Err(); err != nil { return nil, "", 0, err } // 每个顶层节点的回复真实总数(含被限制掉的部分) countSQL := ` WITH RECURSIVE tree AS ( SELECT id, parent_id AS root_id FROM comments WHERE parent_id = ANY($1::uuid[]) AND status='visible' AND deleted_at IS NULL UNION ALL SELECT c.id, t.root_id FROM comments c JOIN tree t ON c.parent_id = t.id WHERE c.status='visible' AND c.deleted_at IS NULL ) SELECT root_id, count(*) FROM tree GROUP BY root_id` counts := map[string]int{} cRows, err := q.Query(ctx, countSQL, rootIDs) if err == nil { for cRows.Next() { var rootID string var n int if err := cRows.Scan(&rootID, &n); err == nil { counts[rootID] = n } } cRows.Close() } out := make([]CommentThread, len(roots)) for i, root := range roots { replies := byRoot[root.ID] if replies == nil { replies = []domain.Comment{} } out[i] = CommentThread{ Comment: root, Replies: replies, ReplyCount: counts[root.ID], } } return out, nextCursor, total, nil } // ListReplies 懒加载某个顶层评论的全部回复(分页)。 // 前端点「查看全部 N 条回复」时调用。 func (r *CommentRepo) ListReplies(ctx context.Context, q Querier, rootID string, limit, offset int) ([]domain.Comment, int64, error) { if limit <= 0 || limit > 100 { limit = 20 } // 注意:WITH 必须放在最外层。写成 SELECT ... FROM (WITH RECURSIVE ...) AS s // 在 PostgreSQL 里是语法错误 —— 子查询不能以 CTE 开头。 var total int64 if err := q.QueryRow(ctx, ` WITH RECURSIVE tree AS ( SELECT id FROM comments WHERE parent_id = $1 AND status='visible' AND deleted_at IS NULL UNION ALL SELECT c.id FROM comments c JOIN tree t ON c.parent_id = t.id WHERE c.status='visible' AND c.deleted_at IS NULL ) SELECT count(*) FROM tree`, rootID).Scan(&total); err != nil { return nil, 0, err } rows, err := q.Query(ctx, ` WITH RECURSIVE tree AS ( SELECT c.id, c.article_id, c.user_id, c.parent_id, c.depth, c.content, c.like_count, c.status, c.created_at FROM comments c WHERE c.parent_id = $1 AND c.status='visible' AND c.deleted_at IS NULL UNION ALL SELECT c.id, c.article_id, c.user_id, c.parent_id, c.depth, c.content, c.like_count, c.status, c.created_at FROM comments c JOIN tree t ON c.parent_id = t.id WHERE c.status='visible' AND c.deleted_at IS NULL ) SELECT t.id, t.article_id, t.user_id, t.parent_id, t.depth, t.content, t.like_count, t.status, u.nickname, u.avatar_url, t.created_at FROM tree t JOIN users u ON u.id=t.user_id ORDER BY t.created_at ASC, t.id ASC LIMIT $2 OFFSET $3`, rootID, limit, offset) if err != nil { return nil, 0, err } defer rows.Close() var out []domain.Comment for rows.Next() { var c domain.Comment if err := rows.Scan(&c.ID, &c.ArticleID, &c.UserID, &c.ParentID, &c.Depth, &c.Content, &c.LikeCount, &c.Status, &c.AuthorNickname, &c.AuthorAvatar, &c.CreatedAt); err != nil { return nil, 0, err } out = append(out, c) } return out, total, rows.Err() } func (r *CommentRepo) Insert(ctx context.Context, q Querier, c *domain.Comment) error { // 回填 DB 生成的 created_at / status,否则新建评论的响应会带零值时间, // 前端列表插到顶部后排序和"刚刚"显示都不对。 return q.QueryRow(ctx, `INSERT INTO comments (id, article_id, user_id, parent_id, depth, content, status) VALUES ($1,$2,$3,$4,$5,$6,'visible') RETURNING status, created_at`, c.ID, c.ArticleID, c.UserID, c.ParentID, c.Depth, c.Content).Scan(&c.Status, &c.CreatedAt) } func (r *CommentRepo) GetByID(ctx context.Context, q Querier, id string) (*domain.Comment, error) { var c domain.Comment err := q.QueryRow(ctx, `SELECT id, article_id, user_id, parent_id, depth, content, like_count, status, created_at FROM comments WHERE id=$1 AND deleted_at IS NULL`, id).Scan( &c.ID, &c.ArticleID, &c.UserID, &c.ParentID, &c.Depth, &c.Content, &c.LikeCount, &c.Status, &c.CreatedAt) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } return &c, err } func (r *CommentRepo) GetParentDepth(ctx context.Context, q Querier, parentID string) (string, int, error) { var articleID string var depth int err := q.QueryRow(ctx, `SELECT article_id, depth FROM comments WHERE id=$1 AND deleted_at IS NULL`, parentID). Scan(&articleID, &depth) return articleID, depth, err } func (r *CommentRepo) SetStatus(ctx context.Context, q Querier, id, status string) error { _, err := q.Exec(ctx, `UPDATE comments SET status=$2, updated_at=now() WHERE id=$1`, id, status) return err } // ListForAdmin 后台评论管理 func (r *CommentRepo) ListForAdmin(ctx context.Context, q Querier, status string, limit, offset int) ([]domain.Comment, int64, error) { where := "c.deleted_at IS NULL" var args []any if status != "" { args = append(args, status) where += ` AND c.status=$1` } var total int64 if err := q.QueryRow(ctx, `SELECT count(*) FROM comments c WHERE `+where, args...).Scan(&total); err != nil { return nil, 0, err } args = append(args, limit, offset) sql := `SELECT c.id, c.article_id, c.user_id, c.parent_id, c.depth, c.content, c.like_count, c.status, u.nickname, u.avatar_url, c.created_at FROM comments c JOIN users u ON u.id=c.user_id WHERE ` + where + ` ORDER BY c.created_at DESC LIMIT $` + itoa(len(args)-1) + ` OFFSET $` + itoa(len(args)) rows, err := q.Query(ctx, sql, args...) if err != nil { return nil, 0, err } defer rows.Close() var out []domain.Comment for rows.Next() { var c domain.Comment if err := rows.Scan(&c.ID, &c.ArticleID, &c.UserID, &c.ParentID, &c.Depth, &c.Content, &c.LikeCount, &c.Status, &c.AuthorNickname, &c.AuthorAvatar, &c.CreatedAt); err != nil { return nil, 0, err } out = append(out, c) } return out, total, rows.Err() } // ── 通知 ── type NotificationRepo struct{ pool *pgxpool.Pool } func NewNotificationRepo(p *pgxpool.Pool) *NotificationRepo { return &NotificationRepo{pool: p} } func (r *NotificationRepo) List(ctx context.Context, q Querier, userID string, onlyUnread bool, limit, offset int) ([]domain.Notification, int64, error) { where := "user_id=$1" args := []any{userID} if onlyUnread { where += " AND is_read=false" } var total int64 if err := q.QueryRow(ctx, `SELECT count(*) FROM notifications WHERE `+where, args...).Scan(&total); err != nil { return nil, 0, err } args = append(args, limit, offset) rows, err := q.Query(ctx, `SELECT id, user_id, actor_id, type, entity_type, entity_id, title, content, is_read, created_at FROM notifications WHERE `+where+ ` ORDER BY created_at DESC LIMIT $2 OFFSET $3`, args...) if err != nil { return nil, 0, err } defer rows.Close() var out []domain.Notification for rows.Next() { var n domain.Notification if err := rows.Scan(&n.ID, &n.UserID, &n.ActorID, &n.Type, &n.EntityType, &n.EntityID, &n.Title, &n.Content, &n.IsRead, &n.CreatedAt); err != nil { return nil, 0, err } out = append(out, n) } return out, total, rows.Err() } func (r *NotificationRepo) UnreadCount(ctx context.Context, q Querier, userID string) (int64, error) { var n int64 err := q.QueryRow(ctx, `SELECT count(*) FROM notifications WHERE user_id=$1 AND is_read=false`, userID).Scan(&n) return n, err } func (r *NotificationRepo) MarkRead(ctx context.Context, q Querier, userID string, ids []string) error { if len(ids) == 0 { _, err := q.Exec(ctx, `UPDATE notifications SET is_read=true WHERE user_id=$1 AND is_read=false`, userID) return err } _, err := q.Exec(ctx, `UPDATE notifications SET is_read=true WHERE user_id=$1 AND id = ANY($2::uuid[])`, userID, ids) return err } // InsertBatch 批量写入。通知是高频写,永远走批量。 func (r *NotificationRepo) InsertBatch(ctx context.Context, q Querier, ns []domain.Notification) error { if len(ns) == 0 { return nil } ids := make([]string, len(ns)) userIDs := make([]string, len(ns)) actorIDs := make([]*string, len(ns)) types := make([]string, len(ns)) entityTypes := make([]string, len(ns)) entityIDs := make([]*string, len(ns)) titles := make([]string, len(ns)) contents := make([]string, len(ns)) for i, n := range ns { ids[i] = n.ID userIDs[i] = n.UserID actorIDs[i] = n.ActorID types[i] = n.Type entityTypes[i] = n.EntityType entityIDs[i] = n.EntityID titles[i] = n.Title contents[i] = n.Content } _, err := q.Exec(ctx, `INSERT INTO notifications (id, user_id, actor_id, type, entity_type, entity_id, title, content) SELECT * FROM unnest($1::uuid[], $2::uuid[], $3::uuid[], $4::text[], $5::text[], $6::uuid[], $7::text[], $8::text[])`, ids, userIDs, actorIDs, types, entityTypes, entityIDs, titles, contents) return err } // ── 互动(点赞/收藏/关注) ── type InteractionRepo struct{ pool *pgxpool.Pool } func NewInteractionRepo(p *pgxpool.Pool) *InteractionRepo { return &InteractionRepo{pool: p} } func (r *InteractionRepo) AddLike(ctx context.Context, q Querier, articleID, userID string) error { _, err := q.Exec(ctx, `INSERT INTO article_likes (article_id, user_id) VALUES ($1,$2) ON CONFLICT DO NOTHING`, articleID, userID) return err } func (r *InteractionRepo) RemoveLike(ctx context.Context, q Querier, articleID, userID string) error { _, err := q.Exec(ctx, `DELETE FROM article_likes WHERE article_id=$1 AND user_id=$2`, articleID, userID) return err } func (r *InteractionRepo) IsLiked(ctx context.Context, q Querier, articleID, userID string) (bool, error) { var exists bool err := q.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM article_likes WHERE article_id=$1 AND user_id=$2)`, articleID, userID).Scan(&exists) return exists, err } func (r *InteractionRepo) AddFavorite(ctx context.Context, q Querier, articleID, userID, folder string) error { _, err := q.Exec(ctx, `INSERT INTO article_favorites (article_id, user_id, folder_name) VALUES ($1,$2,$3) ON CONFLICT (article_id, user_id) DO UPDATE SET folder_name=$3`, articleID, userID, folder) return err } func (r *InteractionRepo) RemoveFavorite(ctx context.Context, q Querier, articleID, userID string) error { _, err := q.Exec(ctx, `DELETE FROM article_favorites WHERE article_id=$1 AND user_id=$2`, articleID, userID) return err } func (r *InteractionRepo) IsFavorited(ctx context.Context, q Querier, articleID, userID string) (bool, error) { var exists bool err := q.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM article_favorites WHERE article_id=$1 AND user_id=$2)`, articleID, userID).Scan(&exists) return exists, err } func (r *InteractionRepo) Follow(ctx context.Context, q Querier, followerID, followingID string) error { if followerID == followingID { return errors.New("不能关注自己") } _, err := q.Exec(ctx, `INSERT INTO user_follows (follower_id, following_id) VALUES ($1,$2) ON CONFLICT DO NOTHING`, followerID, followingID) return err } func (r *InteractionRepo) Unfollow(ctx context.Context, q Querier, followerID, followingID string) error { _, err := q.Exec(ctx, `DELETE FROM user_follows WHERE follower_id=$1 AND following_id=$2`, followerID, followingID) return err } func (r *InteractionRepo) IsFollowing(ctx context.Context, q Querier, followerID, followingID string) (bool, error) { if followerID == "" || followerID == followingID { return false, nil } var exists bool err := q.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM user_follows WHERE follower_id=$1 AND following_id=$2)`, followerID, followingID).Scan(&exists) return exists, err } // ViewerStates 批量查询当前登录用户对一批文章的点赞/收藏状态,以及对其作者的关注状态。 // 列表页一次查询即可填充所有卡片的按钮初态,避免逐条 N+1。 // 未登录(userID 为空)时直接返回空集合,调用方按全 false 处理。 func (r *InteractionRepo) ViewerStates(ctx context.Context, q Querier, articleIDs, authorIDs []string, userID string) ( liked, favorited, following map[string]bool, err error, ) { liked = map[string]bool{} favorited = map[string]bool{} following = map[string]bool{} if userID == "" { return liked, favorited, following, nil } if len(articleIDs) > 0 { if liked, err = r.existenceSet(ctx, q, `SELECT article_id FROM article_likes WHERE user_id=$1 AND article_id = ANY($2)`, userID, articleIDs); err != nil { return nil, nil, nil, err } if favorited, err = r.existenceSet(ctx, q, `SELECT article_id FROM article_favorites WHERE user_id=$1 AND article_id = ANY($2)`, userID, articleIDs); err != nil { return nil, nil, nil, err } } if len(authorIDs) > 0 { if following, err = r.existenceSet(ctx, q, `SELECT following_id FROM user_follows WHERE follower_id=$1 AND following_id = ANY($2)`, userID, authorIDs); err != nil { return nil, nil, nil, err } } return liked, favorited, following, nil } func (r *InteractionRepo) existenceSet(ctx context.Context, q Querier, sql, userID string, ids []string) (map[string]bool, error) { rows, err := q.Query(ctx, sql, userID, ids) if err != nil { return nil, err } defer rows.Close() set := make(map[string]bool, len(ids)) for rows.Next() { var id string if err := rows.Scan(&id); err != nil { return nil, err } set[id] = true } return set, rows.Err() } func (r *InteractionRepo) FollowerCount(ctx context.Context, q Querier, userID string) (int64, error) { var n int64 err := q.QueryRow(ctx, `SELECT count(*) FROM user_follows WHERE following_id=$1`, userID).Scan(&n) return n, err } // ── 标签/分类 ── type TaxonomyRepo struct{ pool *pgxpool.Pool } func NewTaxonomyRepo(p *pgxpool.Pool) *TaxonomyRepo { return &TaxonomyRepo{pool: p} } func (r *TaxonomyRepo) ListCategories(ctx context.Context, q Querier) ([]domain.Category, error) { rows, err := q.Query(ctx, `SELECT id, name, slug, parent_id, sort_order, icon_url, status FROM categories WHERE status='active' ORDER BY sort_order, name`) if err != nil { return nil, err } defer rows.Close() var flat []domain.Category for rows.Next() { var c domain.Category if err := rows.Scan(&c.ID, &c.Name, &c.Slug, &c.ParentID, &c.SortOrder, &c.IconURL, &c.Status); err != nil { return nil, err } flat = append(flat, c) } return buildTree(flat), nil } // buildTree 内存里组装树,避免递归 SQL func buildTree(flat []domain.Category) []domain.Category { byParent := map[string][]domain.Category{} var roots []domain.Category for _, c := range flat { if c.ParentID == nil || *c.ParentID == "" { roots = append(roots, c) } else { byParent[*c.ParentID] = append(byParent[*c.ParentID], c) } } var attach func(list []domain.Category) []domain.Category attach = func(list []domain.Category) []domain.Category { for i := range list { if ch, ok := byParent[list[i].ID]; ok { list[i].Children = attach(ch) } } return list } return attach(roots) } func (r *TaxonomyRepo) ListTags(ctx context.Context, q Querier, limit int) ([]domain.Tag, error) { if limit <= 0 { limit = 50 } rows, err := q.Query(ctx, `SELECT id, name, article_count, heat_count, status, created_at FROM tags WHERE status='active' ORDER BY heat_count DESC, article_count DESC LIMIT $1`, limit) if err != nil { return nil, err } defer rows.Close() var out []domain.Tag for rows.Next() { var t domain.Tag if err := rows.Scan(&t.ID, &t.Name, &t.ArticleCount, &t.HeatCount, &t.Status, &t.CreatedAt); err != nil { return nil, err } out = append(out, t) } return out, rows.Err() } func (r *TaxonomyRepo) UpsertTag(ctx context.Context, q Querier, id, name string) error { _, err := q.Exec(ctx, `INSERT INTO tags (id, name) VALUES ($1,$2) ON CONFLICT (lower(name)) DO NOTHING`, id, name) return err } func (r *TaxonomyRepo) UpsertCategory(ctx context.Context, q Querier, id, name, slug string, parent *string, sortOrder int) error { _, err := q.Exec(ctx, `INSERT INTO categories (id, name, slug, parent_id, sort_order) VALUES ($1,$2,$3,$4,$5) ON CONFLICT (slug) DO UPDATE SET name=$2, sort_order=$5`, id, name, slug, parent, sortOrder) return err } // UpdateCategoryByID 按 ID 更新分类(管理端编辑) func (r *TaxonomyRepo) UpdateCategoryByID(ctx context.Context, q Querier, id, name, slug string, parent *string, sortOrder int) error { _, err := q.Exec(ctx, `UPDATE categories SET name=$2, slug=$3, parent_id=$4, sort_order=$5, updated_at=now() WHERE id=$1`, id, name, slug, parent, sortOrder) return err } // DeleteCategory 删除分类。有子分类时 RESTRICT 约束会报错,由 handler 转译。 func (r *TaxonomyRepo) DeleteCategory(ctx context.Context, q Querier, id string) error { ct, err := q.Exec(ctx, `DELETE FROM categories WHERE id=$1`, id) if err != nil { return err } if ct.RowsAffected() == 0 { return ErrNotFound } return nil } // ListTagsPaged 管理端标签分页列表(含非 active 状态,支持关键字) func (r *TaxonomyRepo) ListTagsPaged(ctx context.Context, q Querier, keyword string, limit, offset int) ([]domain.Tag, int64, error) { where := "1=1" var args []any if keyword != "" { args = append(args, "%"+escapeLike(keyword)+"%") where = "name ILIKE $1 ESCAPE '\\'" } var total int64 if err := q.QueryRow(ctx, `SELECT count(*) FROM tags WHERE `+where, args...).Scan(&total); err != nil { return nil, 0, err } args = append(args, limit, offset) rows, err := q.Query(ctx, `SELECT id, name, article_count, heat_count, status, created_at FROM tags WHERE `+where+` ORDER BY heat_count DESC, article_count DESC LIMIT $`+itoa(len(args)-1)+` OFFSET $`+itoa(len(args)), args...) if err != nil { return nil, 0, err } defer rows.Close() var out []domain.Tag for rows.Next() { var t domain.Tag if err := rows.Scan(&t.ID, &t.Name, &t.ArticleCount, &t.HeatCount, &t.Status, &t.CreatedAt); err != nil { return nil, 0, err } out = append(out, t) } if out == nil { out = []domain.Tag{} } return out, total, rows.Err() } // SetTagStatus 启用/禁用标签(表内合法值为 active|hidden) func (r *TaxonomyRepo) SetTagStatus(ctx context.Context, q Querier, id, status string) error { ct, err := q.Exec(ctx, `UPDATE tags SET status=$2, updated_at=now() WHERE id=$1`, id, status) if err != nil { return err } if ct.RowsAffected() == 0 { return ErrNotFound } return nil } // ── 系统设置 ── type SettingsRepo struct{ pool *pgxpool.Pool } func NewSettingsRepo(p *pgxpool.Pool) *SettingsRepo { return &SettingsRepo{pool: p} } // Get 读取全部设置项(k→v,v 为 JSON 值) func (r *SettingsRepo) Get(ctx context.Context, q Querier) (map[string]json.RawMessage, error) { rows, err := q.Query(ctx, `SELECT k, v FROM site_settings`) if err != nil { return nil, err } defer rows.Close() out := map[string]json.RawMessage{} for rows.Next() { var k string var v json.RawMessage if err := rows.Scan(&k, &v); err != nil { return nil, err } out[k] = v } return out, rows.Err() } // Set upsert 一个设置项 func (r *SettingsRepo) Set(ctx context.Context, q Querier, key string, value any) error { raw, err := json.Marshal(value) if err != nil { return err } _, err = q.Exec(ctx, `INSERT INTO site_settings (k, v, updated_at) VALUES ($1,$2,now()) ON CONFLICT (k) DO UPDATE SET v=$2, updated_at=now()`, key, raw) return err } // ── 统计 ── type StatsRepo struct{ pool *pgxpool.Pool } func NewStatsRepo(p *pgxpool.Pool) *StatsRepo { return &StatsRepo{pool: p} } type Overview struct { TotalArticles int64 `json:"total_articles"` PendingAuditCount int64 `json:"pending_audit_count"` PublishedCount int64 `json:"published_count"` TotalUsers int64 `json:"total_users"` TodayNewUsers int64 `json:"today_new_users"` BannedUsers int64 `json:"banned_users"` TotalComments int64 `json:"total_comments"` TotalLikes int64 `json:"total_likes"` } func (r *StatsRepo) Overview(ctx context.Context, q Querier) (*Overview, error) { var o Overview err := q.QueryRow(ctx, ` SELECT (SELECT count(*) FROM articles WHERE deleted_at IS NULL), (SELECT count(*) FROM articles WHERE review_status='pending' AND deleted_at IS NULL), (SELECT count(*) FROM articles WHERE status='published' AND deleted_at IS NULL), (SELECT count(*) FROM users WHERE deleted_at IS NULL), (SELECT count(*) FROM users WHERE created_at >= date_trunc('day', now())), (SELECT count(*) FROM users WHERE status='banned'), (SELECT count(*) FROM comments WHERE deleted_at IS NULL), (SELECT coalesce(sum(like_count),0) FROM articles WHERE deleted_at IS NULL) `).Scan(&o.TotalArticles, &o.PendingAuditCount, &o.PublishedCount, &o.TotalUsers, &o.TodayNewUsers, &o.BannedUsers, &o.TotalComments, &o.TotalLikes) return &o, err } // TrendPoint 趋势图数据点 type TrendPoint struct { Date string `json:"date"` Count int64 `json:"count"` } func (r *StatsRepo) Trend(ctx context.Context, q Querier, days int) ([]TrendPoint, error) { if days <= 0 || days > 90 { days = 30 } rows, err := q.Query(ctx, ` SELECT to_char(d.day, 'YYYY-MM-DD'), count(a.id) FROM generate_series( date_trunc('day', now()) - ($1::int - 1) * interval '1 day', date_trunc('day', now()), interval '1 day') AS d(day) LEFT JOIN articles a ON date_trunc('day', a.created_at) = d.day AND a.deleted_at IS NULL GROUP BY d.day ORDER BY d.day`, days) if err != nil { return nil, err } defer rows.Close() var out []TrendPoint for rows.Next() { var p TrendPoint if err := rows.Scan(&p.Date, &p.Count); err != nil { return nil, err } out = append(out, p) } return out, rows.Err() } // ── 举报 ── type ReportRepo struct{ pool *pgxpool.Pool } func NewReportRepo(p *pgxpool.Pool) *ReportRepo { return &ReportRepo{pool: p} } func (r *ReportRepo) Insert(ctx context.Context, q Querier, id, reporterID, targetType, targetID, reason, desc string) error { _, err := q.Exec(ctx, `INSERT INTO reports (id, reporter_id, target_type, target_id, reason, description) VALUES ($1,$2,$3,$4,$5,$6)`, id, reporterID, targetType, targetID, reason, desc) return err } type ReportRow struct { ID string `json:"id"` ReporterID string `json:"reporter_id"` TargetType string `json:"target_type"` TargetID string `json:"target_id"` Reason string `json:"reason"` Description *string `json:"description,omitempty"` Status string `json:"status"` HandleNote *string `json:"handle_note,omitempty"` CreatedAt time.Time `json:"created_at"` } func (r *ReportRepo) List(ctx context.Context, q Querier, status, targetType string, limit, offset int) ([]ReportRow, int64, error) { where := "1=1" var args []any if status != "" { args = append(args, status) where = "status=$" + itoa(len(args)) } if targetType != "" { args = append(args, targetType) where += " AND target_type=$" + itoa(len(args)) } var total int64 if err := q.QueryRow(ctx, `SELECT count(*) FROM reports WHERE `+where, args...).Scan(&total); err != nil { return nil, 0, err } args = append(args, limit, offset) rows, err := q.Query(ctx, `SELECT id, reporter_id, target_type, target_id, reason, description, status, handle_note, created_at FROM reports WHERE `+where+ ` ORDER BY created_at DESC LIMIT $`+itoa(len(args)-1)+` OFFSET $`+itoa(len(args)), args...) if err != nil { return nil, 0, err } defer rows.Close() var out []ReportRow for rows.Next() { var x ReportRow if err := rows.Scan(&x.ID, &x.ReporterID, &x.TargetType, &x.TargetID, &x.Reason, &x.Description, &x.Status, &x.HandleNote, &x.CreatedAt); err != nil { return nil, 0, err } out = append(out, x) } return out, total, rows.Err() } func (r *ReportRepo) Handle(ctx context.Context, q Querier, id, handlerID, note, status string) error { _, err := q.Exec(ctx, `UPDATE reports SET status=$2, handler_id=$3, handle_note=$4, handled_at=now() WHERE id=$1`, id, status, handlerID, note) return err } // ── 搜索 outbox ── type OutboxRepo struct{ pool *pgxpool.Pool } func NewOutboxRepo(p *pgxpool.Pool) *OutboxRepo { return &OutboxRepo{pool: p} } func (r *OutboxRepo) Enqueue(ctx context.Context, q Querier, entityType, entityID, op string) error { _, err := q.Exec(ctx, `INSERT INTO search_outbox (entity_type, entity_id, op) VALUES ($1,$2,$3)`, entityType, entityID, op) return err } // FetchPending 取未处理批次,FOR UPDATE SKIP LOCKED 支持多 worker 并发消费 func (r *OutboxRepo) FetchPending(ctx context.Context, q Querier, limit int) ([]struct { ID int64 EntityType string EntityID string Op string }, error) { rows, err := q.Query(ctx, `SELECT id, entity_type, entity_id, op FROM search_outbox WHERE processed=false ORDER BY id LIMIT $1 FOR UPDATE SKIP LOCKED`, limit) if err != nil { return nil, err } defer rows.Close() var out []struct { ID int64 EntityType string EntityID string Op string } for rows.Next() { var x struct { ID int64 EntityType string EntityID string Op string } if err := rows.Scan(&x.ID, &x.EntityType, &x.EntityID, &x.Op); err != nil { return nil, err } out = append(out, x) } return out, rows.Err() } func (r *OutboxRepo) MarkProcessed(ctx context.Context, q Querier, ids []int64) error { if len(ids) == 0 { return nil } _, err := q.Exec(ctx, `UPDATE search_outbox SET processed=true WHERE id = ANY($1::bigint[])`, ids) return err } // ── 小工具 ── // escapeLike 转义 LIKE/ILIKE 通配符,配合 SQL 的 ESCAPE '\' 子句使用, // 让用户输入中的 % 和 _ 按字面匹配,防止 "100%" 之类关键词变成全匹配。 func escapeLike(s string) string { s = strings.ReplaceAll(s, `\`, `\\`) s = strings.ReplaceAll(s, `%`, `\%`) s = strings.ReplaceAll(s, `_`, `\_`) return s } func itoa(n int) string { if n == 0 { return "0" } var buf [20]byte i := len(buf) for n > 0 { i-- buf[i] = byte('0' + n%10) n /= 10 } return string(buf[i:]) }