package repo import ( "context" "encoding/json" "errors" "fmt" "strings" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" "github.com/yourorg/article-platform/internal/domain" ) var ErrNotFound = errors.New("资源不存在") type ArticleRepo struct { pool *pgxpool.Pool } func NewArticleRepo(p *pgxpool.Pool) *ArticleRepo { return &ArticleRepo{pool: p} } const articleCols = ` a.id, a.mask_id, a.title, a.rich_text_title, a.subtitle, a.abstract, a.cover_img_url, a.cover_crop, a.visual_config, a.interaction_config, a.bg_style, a.bg_img_url, a.font_id, a.music_id, a.text_pos, a.enable_watermark, a.enable_comment, a.privacy, a.has_reward, a.owner_id, a.category_id, a.topic_id, a.status, a.review_status, a.review_note, a.reviewed_by, a.reviewed_at, a.published_at, a.view_count, a.like_count, a.fav_count, a.comment_count, a.share_count, a.schema_version, a.created_at, a.updated_at` func scanArticle(row pgx.Row) (*domain.Article, error) { var a domain.Article err := row.Scan( &a.ID, &a.MaskID, &a.Title, &a.RichTextTitle, &a.Subtitle, &a.Abstract, &a.CoverImgURL, &a.CoverCrop, &a.VisualConfig, &a.InteractionConfig, &a.BgStyle, &a.BgImgURL, &a.FontID, &a.MusicID, &a.TextPos, &a.EnableWatermark, &a.EnableComment, &a.Privacy, &a.HasReward, &a.OwnerID, &a.CategoryID, &a.TopicID, &a.Status, &a.ReviewStatus, &a.ReviewNote, &a.ReviewedBy, &a.ReviewedAt, &a.PublishedAt, &a.ViewCount, &a.LikeCount, &a.FavCount, &a.CommentCount, &a.ShareCount, &a.SchemaVersion, &a.CreatedAt, &a.UpdatedAt, ) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } if err != nil { return nil, err } return &a, nil } // GetByMaskID 读详情。支持按 mask_id 或 UUID 查,避免前端路由混传导致查不到。 func (r *ArticleRepo) GetByMaskID(ctx context.Context, q Querier, maskID string) (*domain.Article, error) { if strings.HasPrefix(maskID, "art_") { sql := `SELECT ` + articleCols + ` FROM articles a WHERE a.mask_id = $1 AND a.deleted_at IS NULL` return scanArticle(q.QueryRow(ctx, sql, maskID)) } // 优先按 UUID 查询 sqlID := `SELECT ` + articleCols + ` FROM articles a WHERE a.id::text = $1 AND a.deleted_at IS NULL` art, err := scanArticle(q.QueryRow(ctx, sqlID, maskID)) if err == nil { return art, nil } // 兜底按 mask_id 查询 sql := `SELECT ` + articleCols + ` FROM articles a WHERE a.mask_id = $1 AND a.deleted_at IS NULL` return scanArticle(q.QueryRow(ctx, sql, maskID)) } // GetByID 内部使用,按 UUID 查 func (r *ArticleRepo) GetByID(ctx context.Context, q Querier, id string) (*domain.Article, error) { sql := `SELECT ` + articleCols + ` FROM articles a WHERE a.id = $1 AND a.deleted_at IS NULL` return scanArticle(q.QueryRow(ctx, sql, id)) } // ListParams 列表查询参数 type ListParams struct { Status string // 为空表示不限 CategoryID string OwnerID string ReviewStatus string Keyword string Sort string // latest | hottest Cursor string // published_at 游标(keyset 分页) Limit int TagID string } // List 分页列表。 // // 用 keyset 分页(cursor)而非 OFFSET:深翻页时 OFFSET 要扫描并丢弃前面所有行, // 越翻越慢;keyset 直接定位,任意深度都是索引 seek。 func (r *ArticleRepo) List(ctx context.Context, q Querier, p ListParams) ([]domain.Article, string, error) { if p.Limit <= 0 || p.Limit > 100 { p.Limit = 20 } var where []string var args []any argN := func(v any) string { args = append(args, v) return fmt.Sprintf("$%d", len(args)) } where = append(where, "a.deleted_at IS NULL") if p.Status != "" { where = append(where, "a.status = "+argN(p.Status)) } if p.CategoryID != "" { where = append(where, "a.category_id = "+argN(p.CategoryID)) } if p.OwnerID != "" { where = append(where, "a.owner_id = "+argN(p.OwnerID)) } if p.ReviewStatus != "" { where = append(where, "a.review_status = "+argN(p.ReviewStatus)) } if p.Keyword != "" { // 标题模糊匹配:走 trgm 索引。语义化搜索由 Meilisearch 承担。 where = append(where, "a.title ILIKE "+argN("%"+escapeLike(p.Keyword)+"%")+" ESCAPE '\\'") } if p.TagID != "" { where = append(where, "EXISTS (SELECT 1 FROM article_tags at WHERE at.article_id = a.id AND at.tag_id = "+argN(p.TagID)+")") } orderBy := "a.published_at DESC NULLS LAST, a.id DESC" cursorCol := "a.published_at" if p.Sort == "hottest" { orderBy = "a.like_count * 2 + a.fav_count * 3 + a.view_count DESC, a.id DESC" cursorCol = "a.id" } else if p.Sort == "updated" { // "我的文章"按最近编辑排序 orderBy = "a.updated_at DESC, a.id DESC" cursorCol = "a.updated_at" } // keyset:cursor 是上一页最后一行的排序键 if p.Cursor != "" { where = append(where, cursorCol+" < "+argN(p.Cursor)) } sql := `SELECT ` + articleCols + `, u.nickname, u.avatar_url, c.name FROM articles a LEFT JOIN users u ON u.id = a.owner_id LEFT JOIN categories c ON c.id = a.category_id WHERE ` + strings.Join(where, " AND ") + ` ORDER BY ` + orderBy + ` LIMIT ` + argN(p.Limit+1) rows, err := q.Query(ctx, sql, args...) if err != nil { return nil, "", err } defer rows.Close() var out []domain.Article for rows.Next() { a, err := scanArticleWithJoins(rows) if err != nil { return nil, "", err } out = append(out, *a) } if err := rows.Err(); err != nil { return nil, "", err } var nextCursor string if len(out) > p.Limit { out = out[:p.Limit] last := out[len(out)-1] switch { case p.Sort == "hottest": nextCursor = last.ID case p.Sort == "updated": nextCursor = last.UpdatedAt.Format("2006-01-02T15:04:05.000Z07:00") case last.PublishedAt != nil: nextCursor = last.PublishedAt.Format("2006-01-02T15:04:05.000Z07:00") } } return out, nextCursor, nil } func scanArticleWithJoins(rows pgx.Rows) (*domain.Article, error) { var a domain.Article err := rows.Scan( &a.ID, &a.MaskID, &a.Title, &a.RichTextTitle, &a.Subtitle, &a.Abstract, &a.CoverImgURL, &a.CoverCrop, &a.VisualConfig, &a.InteractionConfig, &a.BgStyle, &a.BgImgURL, &a.FontID, &a.MusicID, &a.TextPos, &a.EnableWatermark, &a.EnableComment, &a.Privacy, &a.HasReward, &a.OwnerID, &a.CategoryID, &a.TopicID, &a.Status, &a.ReviewStatus, &a.ReviewNote, &a.ReviewedBy, &a.ReviewedAt, &a.PublishedAt, &a.ViewCount, &a.LikeCount, &a.FavCount, &a.CommentCount, &a.ShareCount, &a.SchemaVersion, &a.CreatedAt, &a.UpdatedAt, &a.AuthorNickname, &a.AuthorAvatar, &a.CategoryName, ) return &a, err } // FeedFollowing 好友圈动态流:关注的人 + 自己的已发布文章,发布时间倒序 keyset 分页。 func (r *ArticleRepo) FeedFollowing(ctx context.Context, q Querier, userID string, limit int, cursor string) ([]domain.Article, string, error) { if limit <= 0 || limit > 100 { limit = 20 } var where []string var args []any argN := func(v any) string { args = append(args, v) return fmt.Sprintf("$%d", len(args)) } where = append(where, "a.deleted_at IS NULL", "a.status = 'published'") // 朋友圈语义:关注的人的动态 ∪ 自己的动态 where = append(where, "(EXISTS (SELECT 1 FROM user_follows uf WHERE uf.follower_id = "+argN(userID)+" AND uf.following_id = a.owner_id) OR a.owner_id = "+argN(userID)+")") if cursor != "" { where = append(where, "a.published_at < "+argN(cursor)) } sql := `SELECT ` + articleCols + `, u.nickname, u.avatar_url, c.name FROM articles a LEFT JOIN users u ON u.id = a.owner_id LEFT JOIN categories c ON c.id = a.category_id WHERE ` + strings.Join(where, " AND ") + ` ORDER BY a.published_at DESC NULLS LAST, a.id DESC LIMIT ` + argN(limit+1) rows, err := q.Query(ctx, sql, args...) if err != nil { return nil, "", err } defer rows.Close() var out []domain.Article for rows.Next() { a, err := scanArticleWithJoins(rows) if err != nil { return nil, "", err } out = append(out, *a) } if err := rows.Err(); err != nil { return nil, "", err } var nextCursor string if len(out) > limit { out = out[:limit] last := out[len(out)-1] if last.PublishedAt != nil { nextCursor = last.PublishedAt.Format("2006-01-02T15:04:05.000Z07:00") } } return out, nextCursor, nil } // Count 统计数量,用于后台大盘 func (r *ArticleRepo) Count(ctx context.Context, q Querier, status, reviewStatus string) (int64, error) { sql := `SELECT count(*) FROM articles WHERE deleted_at IS NULL` var args []any if status != "" { args = append(args, status) sql += fmt.Sprintf(" AND status = $%d", len(args)) } if reviewStatus != "" { args = append(args, reviewStatus) sql += fmt.Sprintf(" AND review_status = $%d", len(args)) } var n int64 err := q.QueryRow(ctx, sql, args...).Scan(&n) return n, err } func (r *ArticleRepo) Insert(ctx context.Context, q Querier, a *domain.Article) error { sql := `INSERT INTO articles ( id, mask_id, title, rich_text_title, subtitle, abstract, cover_img_url, cover_crop, visual_config, interaction_config, bg_style, bg_img_url, font_id, music_id, text_pos, enable_watermark, enable_comment, privacy, has_reward, owner_id, category_id, topic_id, status, review_status, published_at ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25)` _, err := q.Exec(ctx, sql, a.ID, a.MaskID, a.Title, a.RichTextTitle, a.Subtitle, a.Abstract, a.CoverImgURL, a.CoverCrop, a.VisualConfig, a.InteractionConfig, a.BgStyle, a.BgImgURL, a.FontID, a.MusicID, a.TextPos, a.EnableWatermark, a.EnableComment, a.Privacy, a.HasReward, a.OwnerID, a.CategoryID, a.TopicID, a.Status, a.ReviewStatus, a.PublishedAt, ) return err } func (r *ArticleRepo) Update(ctx context.Context, q Querier, a *domain.Article) error { sql := `UPDATE articles SET title=$2, rich_text_title=$3, subtitle=$4, abstract=$5, cover_img_url=$6, cover_crop=$7, visual_config=$8, interaction_config=$9, bg_style=$10, bg_img_url=$11, font_id=$12, music_id=$13, text_pos=$14, enable_watermark=$15, enable_comment=$16, privacy=$17, has_reward=$18, category_id=$19, topic_id=$20, status=$21, review_status=$22, review_note=$23, reviewed_by=$24, reviewed_at=$25, published_at=$26, updated_at=now() WHERE id=$1 AND deleted_at IS NULL` _, err := q.Exec(ctx, sql, a.ID, a.Title, a.RichTextTitle, a.Subtitle, a.Abstract, a.CoverImgURL, a.CoverCrop, a.VisualConfig, a.InteractionConfig, a.BgStyle, a.BgImgURL, a.FontID, a.MusicID, a.TextPos, a.EnableWatermark, a.EnableComment, a.Privacy, a.HasReward, a.CategoryID, a.TopicID, a.Status, a.ReviewStatus, a.ReviewNote, a.ReviewedBy, a.ReviewedAt, a.PublishedAt, ) return err } // UpdateStatus 状态流转(审核、下线) func (r *ArticleRepo) UpdateStatus(ctx context.Context, q Querier, id string, status domain.ArticleStatus, review domain.ReviewStatus) error { sql := `UPDATE articles SET status=$2, review_status=$3, updated_at=now() WHERE id=$1` _, err := q.Exec(ctx, sql, id, status, review) return err } // SoftDelete 软删除。30 天后由清理任务物理删除。 func (r *ArticleRepo) SoftDelete(ctx context.Context, q Querier, id string) error { _, err := q.Exec(ctx, `UPDATE articles SET deleted_at=now(), updated_at=now() WHERE id=$1`, id) return err } // PageParams 管理端分页列表参数(offset 分页 + total 计数) type PageParams struct { Status string ReviewStatus string CategoryID string OwnerID string Keyword string OnlyDeleted bool // true 只看回收站;false 排除回收站 Limit int Offset int } // ListPage 管理端/回收站用的 offset 分页列表,带 total。 func (r *ArticleRepo) ListPage(ctx context.Context, q Querier, p PageParams) ([]domain.Article, int64, error) { if p.Limit <= 0 || p.Limit > 100 { p.Limit = 20 } if p.Offset < 0 { p.Offset = 0 } var where []string var args []any argN := func(v any) string { args = append(args, v) return fmt.Sprintf("$%d", len(args)) } if p.OnlyDeleted { where = append(where, "a.deleted_at IS NOT NULL") } else { where = append(where, "a.deleted_at IS NULL") } if p.Status != "" { where = append(where, "a.status = "+argN(p.Status)) } if p.ReviewStatus != "" { where = append(where, "a.review_status = "+argN(p.ReviewStatus)) } if p.CategoryID != "" { where = append(where, "a.category_id = "+argN(p.CategoryID)) } if p.OwnerID != "" { where = append(where, "a.owner_id = "+argN(p.OwnerID)) } if p.Keyword != "" { where = append(where, "a.title ILIKE "+argN("%"+escapeLike(p.Keyword)+"%")+" ESCAPE '\\'") } cond := strings.Join(where, " AND ") var total int64 if err := q.QueryRow(ctx, "SELECT count(*) FROM articles a WHERE "+cond, args...).Scan(&total); err != nil { return nil, 0, err } sql := `SELECT ` + articleCols + `, u.nickname, u.avatar_url, c.name FROM articles a LEFT JOIN users u ON u.id = a.owner_id LEFT JOIN categories c ON c.id = a.category_id WHERE ` + cond + ` ORDER BY a.updated_at DESC, a.id DESC LIMIT ` + argN(p.Limit) + ` OFFSET ` + argN(p.Offset) rows, err := q.Query(ctx, sql, args...) if err != nil { return nil, 0, err } defer rows.Close() var out []domain.Article for rows.Next() { a, err := scanArticleWithJoins(rows) if err != nil { return nil, 0, err } out = append(out, *a) } if err := rows.Err(); err != nil { return nil, 0, err } if out == nil { out = []domain.Article{} } return out, total, nil } // Restore 从回收站恢复文章。参数兼容 UUID 与 mask_id。 func (r *ArticleRepo) Restore(ctx context.Context, q Querier, rawID string) error { ct, err := q.Exec(ctx, `UPDATE articles SET deleted_at=NULL, updated_at=now() WHERE (id::text=$1 OR mask_id=$1) AND deleted_at IS NOT NULL`, rawID) if err != nil { return err } if ct.RowsAffected() == 0 { return ErrNotFound } return nil } // HardDelete 物理删除。子表(sections/comments/likes/...)均 ON DELETE CASCADE。 func (r *ArticleRepo) HardDelete(ctx context.Context, q Querier, id string) error { _, err := q.Exec(ctx, `DELETE FROM articles WHERE id=$1`, id) return err } // ListByTopic 话题下已发布文章(offset 分页) func (r *ArticleRepo) ListByTopic(ctx context.Context, q Querier, topicID string, limit, offset int) ([]domain.Article, int64, error) { if limit <= 0 || limit > 100 { limit = 20 } if offset < 0 { offset = 0 } var total int64 if err := q.QueryRow(ctx, `SELECT count(*) FROM articles a WHERE a.topic_id=$1 AND a.status='published' AND a.deleted_at IS NULL`, topicID).Scan(&total); err != nil { return nil, 0, err } sql := `SELECT ` + articleCols + `, u.nickname, u.avatar_url, c.name FROM articles a LEFT JOIN users u ON u.id = a.owner_id LEFT JOIN categories c ON c.id = a.category_id WHERE a.topic_id=$1 AND a.status='published' AND a.deleted_at IS NULL ORDER BY a.published_at DESC NULLS LAST, a.id DESC LIMIT $2 OFFSET $3` rows, err := q.Query(ctx, sql, topicID, limit, offset) if err != nil { return nil, 0, err } defer rows.Close() var out []domain.Article for rows.Next() { a, err := scanArticleWithJoins(rows) if err != nil { return nil, 0, err } out = append(out, *a) } if err := rows.Err(); err != nil { return nil, 0, err } if out == nil { out = []domain.Article{} } return out, total, nil } // ── 区块 ── func (r *ArticleRepo) ListSections(ctx context.Context, q Querier, articleID string) ([]domain.Section, error) { rows, err := q.Query(ctx, `SELECT id, article_id, order_index, kind, payload, created_at, updated_at FROM sections WHERE article_id=$1 ORDER BY order_index`, articleID) if err != nil { return nil, err } defer rows.Close() var out []domain.Section for rows.Next() { var s domain.Section if err := rows.Scan(&s.ID, &s.ArticleID, &s.OrderIndex, &s.Kind, &s.Payload, &s.CreatedAt, &s.UpdatedAt); err != nil { return nil, err } out = append(out, s) } return out, rows.Err() } func (r *ArticleRepo) UpsertSection(ctx context.Context, q Querier, s *domain.Section) error { sql := `INSERT INTO sections (id, article_id, order_index, kind, payload) VALUES ($1,$2,$3,$4,$5) ON CONFLICT (id) DO UPDATE SET order_index=$3, kind=$4, payload=$5, updated_at=now()` _, err := q.Exec(ctx, sql, s.ID, s.ArticleID, s.OrderIndex, s.Kind, s.Payload) return err } func (r *ArticleRepo) DeleteSection(ctx context.Context, q Querier, articleID, sectionID string) error { _, err := q.Exec(ctx, `DELETE FROM sections WHERE id=$1 AND article_id=$2`, sectionID, articleID) return err } // ReorderSections 批量重排。用 unnest 一次更新,避免 N 次 UPDATE。 func (r *ArticleRepo) ReorderSections(ctx context.Context, q Querier, articleID string, ids []string) error { if len(ids) == 0 { return nil } // 先移到负数区避免唯一索引 uq_sections_art_order 冲突,再赋正式序号 sql := `UPDATE sections SET order_index = -1 - u.ord, updated_at=now() FROM unnest($2::uuid[]) WITH ORDINALITY AS u(id, ord) WHERE sections.id = u.id AND sections.article_id = $1` if _, err := q.Exec(ctx, sql, articleID, ids); err != nil { return err } sql2 := `UPDATE sections SET order_index = ord - 1 FROM unnest($2::uuid[]) WITH ORDINALITY AS u(id, ord) WHERE sections.id = u.id AND sections.article_id = $1` _, err := q.Exec(ctx, sql2, articleID, ids) return err } // ReplaceSections 全量替换文章区块(常用于文章保存/发布覆盖旧内容) func (r *ArticleRepo) ReplaceSections(ctx context.Context, q Querier, articleID string, secs []domain.Section) error { if _, err := q.Exec(ctx, `DELETE FROM sections WHERE article_id=$1`, articleID); err != nil { return err } for i := range secs { secs[i].ArticleID = articleID secs[i].OrderIndex = i if err := r.UpsertSection(ctx, q, &secs[i]); err != nil { return err } } return nil } // ── 草稿快照与版本控制 ── type DraftItem struct { ID string `json:"id"` ArticleID string `json:"article_id"` Title string `json:"title"` SectionsJSON json.RawMessage `json:"sections_json,omitempty"` ClientSavedAt time.Time `json:"client_saved_at"` CreatedAt time.Time `json:"saved_at"` } func (r *ArticleRepo) EnsureDraftsTable(ctx context.Context, q Querier) error { _, err := q.Exec(ctx, `CREATE TABLE IF NOT EXISTS article_drafts ( id UUID PRIMARY KEY, article_id UUID NOT NULL REFERENCES articles(id) ON DELETE CASCADE, title TEXT NOT NULL DEFAULT '', sections_json JSONB NOT NULL DEFAULT '[]'::jsonb, client_saved_at TIMESTAMPTZ NOT NULL DEFAULT now(), created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); CREATE INDEX IF NOT EXISTS idx_drafts_article_created ON article_drafts (article_id, created_at DESC);`) return err } func (r *ArticleRepo) SaveDraft(ctx context.Context, q Querier, id, articleID, title string, sectionsJSON []byte, clientSavedAt time.Time) (*DraftItem, error) { _ = r.EnsureDraftsTable(ctx, q) if len(sectionsJSON) == 0 { sectionsJSON = []byte("[]") } now := time.Now().UTC() if clientSavedAt.IsZero() { clientSavedAt = now } _, err := q.Exec(ctx, `INSERT INTO article_drafts (id, article_id, title, sections_json, client_saved_at, created_at) VALUES ($1, $2, $3, $4, $5, $6)`, id, articleID, title, sectionsJSON, clientSavedAt, now) if err != nil { return nil, err } _, _ = q.Exec(ctx, `DELETE FROM article_drafts WHERE article_id = $1 AND id NOT IN ( SELECT id FROM article_drafts WHERE article_id = $1 ORDER BY created_at DESC LIMIT 20 )`, articleID) return &DraftItem{ ID: id, ArticleID: articleID, Title: title, SectionsJSON: sectionsJSON, ClientSavedAt: clientSavedAt, CreatedAt: now, }, nil } func (r *ArticleRepo) ListDrafts(ctx context.Context, q Querier, articleID string) ([]DraftItem, error) { _ = r.EnsureDraftsTable(ctx, q) rows, err := q.Query(ctx, `SELECT id, article_id, title, client_saved_at, created_at FROM article_drafts WHERE article_id=$1 ORDER BY created_at DESC LIMIT 20`, articleID) if err != nil { return nil, err } defer rows.Close() var out []DraftItem for rows.Next() { var d DraftItem if err := rows.Scan(&d.ID, &d.ArticleID, &d.Title, &d.ClientSavedAt, &d.CreatedAt); err != nil { return nil, err } out = append(out, d) } if out == nil { out = []DraftItem{} } return out, rows.Err() } func (r *ArticleRepo) GetDraftByID(ctx context.Context, q Querier, draftID string) (*DraftItem, error) { _ = r.EnsureDraftsTable(ctx, q) var d DraftItem err := q.QueryRow(ctx, `SELECT id, article_id, title, sections_json, client_saved_at, created_at FROM article_drafts WHERE id=$1`, draftID).Scan(&d.ID, &d.ArticleID, &d.Title, &d.SectionsJSON, &d.ClientSavedAt, &d.CreatedAt) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } return &d, err } func (r *ArticleRepo) GetLatestDraft(ctx context.Context, q Querier, articleID string) (*DraftItem, error) { _ = r.EnsureDraftsTable(ctx, q) var d DraftItem err := q.QueryRow(ctx, `SELECT id, article_id, title, sections_json, client_saved_at, created_at FROM article_drafts WHERE article_id=$1 ORDER BY created_at DESC LIMIT 1`, articleID).Scan(&d.ID, &d.ArticleID, &d.Title, &d.SectionsJSON, &d.ClientSavedAt, &d.CreatedAt) if errors.Is(err, pgx.ErrNoRows) { return nil, ErrNotFound } return &d, err } // ── 标签 ── func (r *ArticleRepo) SetTags(ctx context.Context, q Querier, articleID string, tagIDs []string) error { if _, err := q.Exec(ctx, `DELETE FROM article_tags WHERE article_id=$1`, articleID); err != nil { return err } if len(tagIDs) == 0 { return nil } _, err := q.Exec(ctx, `INSERT INTO article_tags (article_id, tag_id) SELECT $1, unnest($2::uuid[]) ON CONFLICT DO NOTHING`, articleID, tagIDs) return err } func (r *ArticleRepo) ListTagsOfArticle(ctx context.Context, q Querier, articleID string) ([]domain.Tag, error) { rows, err := q.Query(ctx, `SELECT t.id, t.name, t.article_count, t.heat_count, t.status, t.created_at FROM tags t JOIN article_tags at ON at.tag_id = t.id WHERE at.article_id=$1`, articleID) 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() } // ── 计数落库(worker 批量调用) ── // FlushCounters 把 Valkey 里的实时计数写回 PG。 // 只在 worker 里以固定频率调用,绝不放在请求路径。 func (r *ArticleRepo) FlushCounters(ctx context.Context, q Querier, articleID string, c map[string]int64) error { _, err := q.Exec(ctx, `UPDATE articles SET view_count = COALESCE($2, view_count), like_count = COALESCE($3, like_count), fav_count = COALESCE($4, fav_count), comment_count = COALESCE($5, comment_count), share_count = COALESCE($6, share_count) WHERE id = $1`, articleID, nullable(c, "view"), nullable(c, "like"), nullable(c, "fav"), nullable(c, "comment"), nullable(c, "share")) return err } func nullable(m map[string]int64, k string) any { if v, ok := m[k]; ok { return v } return nil } // ── 事务包装 ── // WithTx 在事务里执行,供需要在同一事务写文章+区块+标签的场景使用 func (r *ArticleRepo) WithTx(ctx context.Context, fn func(tx pgx.Tx) error) error { tx, err := r.pool.Begin(ctx) if err != nil { return err } defer func() { if p := recover(); p != nil { _ = tx.Rollback(ctx) panic(p) } }() if err := fn(tx); err != nil { _ = tx.Rollback(ctx) return err } return tx.Commit(ctx) } // Querier 抽象掉 pool 与 tx,让仓储方法能在两种上下文中复用。 // pgxpool.Pool 与 pgx.Tx 都满足这个接口。 type Querier interface { Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row }