VLoop 项目学习 · 篇 2 项目拆解 · 第 6 / 22 章
6数据模型与表关系:十一张表怎么设计
AutoMigrate 生成,仓库里没有一行 .sql——这两条决定了「想改表结构时会发生什么」。
6.1 表清单与整体关系图
这个项目一共有十一张表,全部由 GORM 的 AutoMigrate 依据 Go 结构体自动创建,仓库里不存在任何 .sql 迁移文件。表之间有十组「逻辑外键」,但数据库层一条外键约束都没有:在 backend/ 全目录搜索 foreignKey、constraint:、references、many2many、hasMany、belongsTo 是 0 匹配,搜 FOREIGN KEY / REFERENCES 也是 0 匹配。
| 表名 | 结构体 | 定义位置 | 作用 | 主键外的唯一约束 |
|---|---|---|---|---|
accounts | Account | backend/internal/account/entity.go:3 | 账号 + 会话 | uni_accounts_username |
videos | Video | backend/internal/video/video_entity.go:5 | 视频与两个派生计数列 | 无 |
likes | Like | backend/internal/video/like_entity.go:5 | 点赞关系 | idx_like_video_account |
comments | Comment | backend/internal/video/comment_entity.go:5 | 评论 | uk_comments_author_key |
socials | Social | backend/internal/social/entity.go:5 | 关注关系 | idx_social_follower_vlogger |
outbox_msgs | OutboxMsg | backend/internal/video/video_entity.go:42 | Outbox 待投递消息 | 无 |
tags | Tag | backend/internal/video/tag_entity.go:5 | 话题标签字典 | idx_tags_name |
video_tags | VideoTag | backend/internal/video/tag_entity.go:10 | 视频 × 标签关联 | 无 |
messages | Message | backend/internal/message/entity.go:5 | 私信 | 无 |
notifications | Notification | backend/internal/notification/entity.go:7 | 站内通知 | uk_notifications_dedupe |
failed_events | FailedEvent | backend/internal/failedevent/entity.go:17 | 停泊消息的落库记录(DLX failed.events) | uk_failed_source_event |
failed_events 是停泊消息的落库表:唯一键 (source_queue, event_id),由 FailedEventWorker 写入。
表名基本不用手写——十一张表里只有 notifications 与 failed_events 显式写了 TableName(),其余九张全部走 GORM 的默认复数化规则(Social → socials、OutboxMsg → outbox_msgs、VideoTag → video_tags)。建表清单与 DSN 都在这一个文件里:
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
dbcfg.User, dbcfg.Password, dbcfg.Host, dbcfg.Port, dbcfg.DBName)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
// …省略错误处理…
func AutoMigrate(db *gorm.DB) error {
return db.AutoMigrate(
&account.Account{}, &video.Video{}, &video.Like{}, &video.Comment{},
&social.Social{}, &video.OutboxMsg{}, &video.Tag{}, &video.VideoTag{},
&message.Message{}, ¬ification.Notification{},
// 停泊消息的落库表;建表入口只有这一个。
&failedevent.FailedEvent{},
)
}
把这十一张表的逻辑指向关系画出来,结构其实很干净——三条「主表 + 关系表」的经典形状,加上三张消息表与一张停泊落库表:
erDiagram
accounts ||--o{ videos : "author_id"
videos ||--o{ likes : "video_id"
videos ||--o{ comments : "video_id"
videos ||--o{ video_tags : "video_id"
videos ||--o{ outbox_msgs : "video_id"
accounts ||--o{ likes : "account_id"
accounts ||--o{ comments : "author_id"
accounts ||--o{ socials : "follower_id"
accounts ||--o{ socials : "vlogger_id"
accounts ||--o{ messages : "from_id"
accounts ||--o{ messages : "to_id"
accounts ||--o{ notifications : "recipient_id"
accounts ||--o{ notifications : "sender_id"
tags ||--o{ video_tags : "tag_id"
%% failed_events 无逻辑外键,source_queue 与 event_id 记停泊来源
failed_events {
string source_queue
string event_id
}
没有外键约束带来的直接后果有三个,读代码时要一直记着:删除不级联(删视频不会带走它的 likes/comments/video_tags,需要应用层自己清,而现状是根本不清,见 docs/ISSUES-REPORT.md 的 P1-7);插入不校验(往 likes 写一个不存在的 video_id 数据库不会拦,靠 service 层先 IsExist);孤儿数据无人发现(因为没有对账任务,见 A-3)。
type:,类型是 GORM MySQL 驱动(v1.6.0)推出来的,规则只有三条,但解释了本章一半的「为什么是这种类型」:①
string 且带 index / unique / uniqueIndex / 有默认值 / 是主键 → varchar(191);② 其它情况下的裸
string → longtext(这就是为什么 accounts.password 是 longtext);③
uint → bigint unsigned,int64 → bigint,time.Time → datetime(3),bool → boolean;没写 not null 的一律可空。
6.2 accounts:凭证、会话与资料字段
accounts 是十一张表里职责最混杂的一张:它同时扮演三个角色——身份凭证(password)、会话存储(token、refresh_token)、用户资料(avatar_url、bio)。
type Account struct {
ID uint `gorm:"primaryKey" json:"id"`
Username string `gorm:"unique" json:"username"`
Password string `json:"-"`
Token string `json:"-"`
RefreshToken string `json:"-"`
AvatarURL string `gorm:"type:varchar(512)" json:"avatar_url,omitempty"`
Bio string `gorm:"type:varchar(255)" json:"bio,omitempty"`
}
三个敏感字段全部用 json:"-" 关掉了序列化——这解释了为什么 /account/findByID 返回的账号对象里看不到密码和 token:不是 handler 挑字段,而是结构体本身就不会被 c.JSON 输出。反过来说,任何直接把 Account 结构体当响应返回的接口都是安全的,这是个很省心的设计。
字段落库后的实际类型如下。注意 password / token / refresh_token 三个都是 longtext:它们既没有 type: 也没有索引,正好命中 6.1 里的推导规则②。bcrypt 哈希只有 60 字节,用 longtext(最大 4GB)存是明显的浪费,但功能上无害。
| 列 | Go 类型 | 实际列类型 | 可空 | 说明 |
|---|---|---|---|---|
id | uint | bigint unsigned PK | 否 | 自增主键 |
username | string | varchar(191) | 是 | 唯一约束 uni_accounts_username(来自裸 unique 标签) |
password | string | longtext | 是 | bcrypt 哈希,永不返回给客户端 |
token | string | longtext | 是 | 当前有效的 access token(明文) |
refresh_token | string | longtext | 是 | 当前有效的 refresh token(明文) |
avatar_url | string | varchar(512) | 是 | 唯一显式声明长度的字段 |
bio | string | varchar(255) | 是 | 个人简介 |
唯一约束的名字值得留意:unique 标签生成的是 uni_accounts_username,前缀是 uni 而不是 idx(GORM 的 UniqueName 命名策略),而显式写名字的 uniqueIndex:idx_like_video_account 生成出来的就叫 idx_like_video_account——同一个库里两种命名风格并存,写 SHOW INDEX 排查时容易看漏。
UPDATE accounts,而这张表还承载着最热的「按用户名查账号」查询。② 没地方放过期时间:表里没有
expires_at 之类的列,refresh token 的有效期只存在于 Redis 键的 TTL 里(第 7 章)。也就是说 DB 里那条 refresh_token 实际上永不过期。docs/ISSUES-REPORT.md 把这记为 P1-6。③ 明文存储:两个 token 都是原样入库,泄漏即等于会话被接管。这三条都属于「已记录的现状」,不是本章的推测。
6.3 videos:派生列与三个复合索引
videos 是唯一一张把聚合结果当成列存下来的表——likes_count(点赞数)与 popularity(热度分)都是派生数据,真实来源分别是 likes 表的行数和 Redis 的分钟窗口 ZSet。这么做是为了让「按点赞数排序」和「按热度排序」不必每次 COUNT(*) 或 SUM,代价就是这两个列随时可能与真实来源不一致(第 10、11 章会具体讲它现在有多不一致)。
type Video struct {
ID uint `gorm:"primaryKey" json:"id"`
AuthorID uint `gorm:"index;not null" json:"author_id"`
Username string `gorm:"type:varchar(255);not null" json:"username"`
Title string `gorm:"type:varchar(255);not null" json:"title"`
Description string `gorm:"type:varchar(255);" json:"description,omitempty"`
PlayURL string `gorm:"type:varchar(255);not null" json:"play_url"`
CoverURL string `gorm:"type:varchar(255);not null" json:"cover_url"`
CreateTime time.Time `gorm:"autoCreateTime;index:idx_videos_create_time,sort:desc;index:idx_videos_popularity_time_id,priority:2,sort:desc" json:"create_time"`
LikesCount int64 `gorm:"column:likes_count;not null;default:0;index:idx_videos_likes_count_id,priority:1,sort:desc" json:"likes_count"`
Popularity int64 `gorm:"column:popularity;not null;default:0;index:idx_videos_popularity_time_id,priority:1,sort:desc" json:"popularity"`
}
这段 tag 里有三个信息点:username 是冗余字段(作者改名后旧视频不会跟着变);Description 的 tag 结尾多一个分号(type:varchar(255);),GORM 会忽略空段,无害但说明 tag 是手写的;两个派生列都通过 column: 显式钉住了列名(其实 Go 字段名转蛇形本来就是 likes_count,这里属于显式化保险)。
真正重要的是四个索引——它们是这张表的性能契约,因为 Feed 的四条读路径全部压在这张表上:
| 索引名 | 实际列与方向 | 类型 | 意图服务的查询 |
|---|---|---|---|
idx_videos_create_time | (create_time DESC) | 普通 | 最新流 ORDER BY create_time DESC |
idx_videos_likes_count_id | (likes_count DESC) ← 只有一列 | 普通 | 点赞榜 ORDER BY likes_count DESC, id DESC |
idx_videos_popularity_time_id | (popularity DESC, create_time DESC) | 普通 | 热度榜 ORDER BY popularity DESC, create_time DESC, id DESC |
idx_videos_author_id | (author_id) | 普通 | 按作者过滤 WHERE author_id = ? |
两个查询的写法对照着看,能立刻看出「谁想清楚了、谁没想清楚」:
// 最新流:排序键有索引,游标也只有单列 —— 覆盖良好
func (repo *FeedRepository) ListLatest(ctx context.Context, limit int, latestBefore time.Time) ([]*video.Video, error) {
query := repo.db.WithContext(ctx).Model(&video.Video{}).Order("create_time DESC")
if !latestBefore.IsZero() {
query = query.Where("create_time < ?", latestBefore)
}
return videos, query.Limit(limit).Find(&videos).Error
}
// 点赞榜:排序 + 游标都用 (likes_count, id) 复合键 —— 教科书式写法
func (repo *FeedRepository) ListLikesCountWithCursor(ctx context.Context, limit int, cursor *LikesCountCursor) ([]*video.Video, error) {
query := repo.db.WithContext(ctx).Model(&video.Video{}).
Order("likes_count DESC, id DESC")
if cursor != nil {
query = query.Where(
"(likes_count < ?) OR (likes_count = ? AND id < ?)",
cursor.LikesCount, cursor.LikesCount, cursor.ID,
)
}
return videos, query.Limit(limit).Find(&videos).Error
}
ListLikesCountWithCursor 里的 (likes_count < ?) OR (likes_count = ? AND id < ?) 是复合游标的标准写法:它保证「同点赞数的两组视频」在翻页时既不漏也不重。而 ListLatest 只有单列游标 create_time < ?——同一毫秒创建的两条视频会有一半被跳过或重复(P2-3)。
idx_videos_likes_count_id 和 idx_videos_popularity_time_id 的名字里都带 id,但索引定义里根本没有 id 这一列——只有 likes_count DESC 和 (popularity DESC, create_time DESC)。InnoDB 会把主键隐式追加到二级索引末尾(作为「行位置」),所以 SHOW INDEX 里确实能看到 id,但它永远是 ASC 方向,而查询要的是 id DESC。方向不一致时 MySQL 无法直接用索引的有序性完成排序,仍可能退化成 filesort。三条建议都写在 docs/ISSUES-REPORT.md 的 P2-3 里:把索引改成真正含 id 的复合索引、给查询补 next_id 游标、把「同名索引列」当成 review 检查项。
EXPLAIN 看 key 与 Extra 两列:key 为空说明没走索引,Extra 出现 Using filesort 说明排序是临时算的。想看真实 DDL(而不是猜 GORM 生成了什么)直接 SHOW CREATE TABLE videos\G——这是核对本章所有类型结论最快的办法。
6.4 likes / comments / social:三类互动关系
三张关系表放在一起看,能看出这个项目幂等护栏的真实覆盖范围:likes 与 socials 的联合唯一索引保证「一条关系只能有一行」;comments 的 uk_comments_author_key 管的是另一件事——同一次发送只落一条评论,判重靠 idempotency_key。
// Like 的两个索引都承载语义,不能删:
// - idx_like_video_account(video_id, account_id,唯一)是 ApplyLike 的判重门闩:
// RowsAffected==0 表示这条互动已经存在,计数与热榜都不得再加。
// - idx_likes_created_video(created_at, video_id)让热榜窗口查询只走索引,
// 不回表。created_at 是事件时间,撤销点赞要减回同一分钟。
type Like struct {
ID uint `gorm:"primaryKey" json:"id"`
VideoID uint `gorm:"uniqueIndex:idx_like_video_account;index:idx_likes_created_video,priority:2;not null" json:"video_id"`
AccountID uint `gorm:"uniqueIndex:idx_like_video_account;not null" json:"account_id"`
CreatedAt time.Time `gorm:"index:idx_likes_created_video,priority:1" json:"created_at"`
}
type Social struct {
ID uint `gorm:"primaryKey"`
FollowerID uint `gorm:"not null;index:idx_social_follower;uniqueIndex:idx_social_follower_vlogger"`
VloggerID uint `gorm:"not null;index:idx_social_vlogger;uniqueIndex:idx_social_follower_vlogger"`
}
Like 里两个字段共享同一个 uniqueIndex:idx_like_video_account,这就是「一个人对一条视频只能点一次赞」的数据库级保证。它的用法很关键:worker 与降级直写都调 ApplyLike(backend/internal/video/like_repo.go),插入时带 clause.OnConflict{DoNothing: true},然后看 RowsAffected——0 表示这行本来就在,直接返回 created = false,两个计数都不再动;1 才在同一事务里给 likes_count 与 popularity 各 +1。所以点赞这条链路是「即使消息重复投递也只算一次」的,而且判重与计数增量在同一个事务里。同一个结构体上还挂着第二个索引 idx_likes_created_video(created_at 在前、video_id 在后),它服务热榜的分钟窗口查询——backend/internal/feed/repo.go 的 ListHotWindow 正是一条 WHERE created_at >= ? AND created_at < ? GROUP BY video_id 的计数,范围扫 created_at 时 video_id 还在索引里,不必回表取。它也是 likes 上唯一涉及 created_at 的索引——所以后面那条「我点赞过的视频」查询借得到它的顺序,却借不到任何按 account_id 的等值定位。
comments 的护栏长在另一列上:author_id 与 idempotency_key 共享唯一索引 uk_comments_author_key,判重粒度是「同一个人 + 同一个幂等键」。幂等键由客户端为一次发送动作生成、重试时复用(request_id),为空时服务端补一个;IdempotencyKey 必须是 *string,否则空串会互相撞索引:
type Comment struct {
ID uint `gorm:"primaryKey" json:"id"`
Username string `gorm:"index" json:"username"`
VideoID uint `gorm:"index;index:idx_comments_created_video,priority:2" json:"video_id"`
AuthorID uint `gorm:"index;uniqueIndex:uk_comments_author_key,priority:1" json:"author_id"`
Content string `gorm:"type:text" json:"content"`
CreatedAt time.Time `gorm:"autoCreateTime;index:idx_comments_created_video,priority:1" json:"created_at"`
// IdempotencyKey 必须是 *string:空串会互撞唯一索引,NULL 不会。
IdempotencyKey *string `gorm:"column:idempotency_key;type:varchar(64);uniqueIndex:uk_comments_author_key,priority:2" json:"-"`
}
写入走 CreateIdempotentWithPopularity:插入时带 clause.OnConflict{DoNothing: true},再用 RowsAffected 判断这次到底有没有落库——0 表示同一 (author_id, idempotency_key) 的行已经存在,函数返回 created = false,videos.popularity 不再 +1;1 才在当前事务里加热度。worker 的 applyPublish 与 API 的降级直写都调这一个函数,所以重复投递与客户端重试都只算一条。仓库里还留着一个无条件的 CreateComment,但全仓已经没有调用方,判重不会绕过它。唯一的例外是 idempotency_key 为 NULL 的行:存量数据与不带 event_id 的事件都会写 NULL,多个 NULL 可以共存,也不参与判重。
| 表 | 联合唯一索引 | 幂等靠什么 | 有没有计数列 | 写入方 |
|---|---|---|---|---|
likes | idx_like_video_account (video_id, account_id) | 唯一索引 + OnConflict DoNothing(ApplyLike 用 RowsAffected 判重) | 无(计数在 videos.likes_count) | LikeWorker / 降级事务,两者都调 ApplyLike |
comments | uk_comments_author_key (author_id, idempotency_key) | 唯一索引 + OnConflict DoNothing(CreateIdempotentWithPopularity 用 RowsAffected 判重);idempotency_key 为 NULL 的行不参与判重 | 无(videos.popularity +1) | CommentWorker / 降级事务,两者都调 CreateIdempotentWithPopularity |
socials | idx_social_follower_vlogger (follower_id, vlogger_id) | 唯一索引 + OnConflict DoNothing(P1-4 之后 Follow 用 RowsAffected 判真变更,不再先查后插) | 无(关注数靠 COUNT) | 只有 SocialService(SocialWorker 已删,social.events 只承载通知) |
三张表的索引清单同样值得对照——因为三者的查询形状完全不同:
| 表 | 索引 | 服务的查询 | 覆盖情况 |
|---|---|---|---|
likes | idx_like_video_account (video_id, account_id) | IsLiked / Unlike / DeleteByVideoAndAccount:WHERE video_id = ? AND account_id = ? | 完全覆盖(两列全等值) |
likes | 同上 | BatchGetLiked:WHERE video_id IN (…) AND account_id = ? | 覆盖(video_id 前缀范围 + account_id 过滤) |
likes | 同上的唯一索引,再加 idx_likes_created_video (created_at, video_id) | ListLikedVideos:WHERE likes.account_id = ? ORDER BY likes.created_at DESC | 过滤完全覆盖不了:account_id 不是任何一个索引的前导列;idx_likes_created_video 只能按 created_at 顺序扫、省掉 filesort,每一行仍要回表判 account_id |
comments | idx_comments_username / idx_comments_video_id / idx_comments_author_id / idx_comments_created_video / uk_comments_author_key | GetAllComments:WHERE video_id = ? ORDER BY created_at ASC;uk_comments_author_key 服务幂等插入 | 只覆盖过滤:video_id 走索引,排序需 filesort |
socials | idx_social_follower / idx_social_vlogger / idx_social_follower_vlogger | GetAllFollowers / GetAllVloggers / IsFollowed / Unfollow / 两个 Count | 全部完全覆盖——这是十一张表里索引设计最贴合查询的一张 |
最差的那条查询写出来是这样的。likes 上根本没有以 account_id 打头的索引,created_at 上的 idx_likes_created_video 又只提供「按时间顺序取」这一个能力,所以「我点赞过的视频」这个页面的查询计划必然是顺着 idx_likes_created_video 全扫 + 逐行回表过滤——排序靠索引顺序省掉了,但扫描量仍随着 likes 表增长而线性变慢:
func (r *LikeRepository) ListLikedVideos(ctx context.Context, accountID uint) ([]Video, error) {
var videos []Video
if accountID == 0 {
return videos, nil
}
err := r.db.WithContext(ctx).
Model(&Video{}).
Joins("JOIN likes ON likes.video_id = videos.id").
Where("likes.account_id = ?", accountID).
Order("likes.created_at desc").
Limit(200).
Find(&videos).Error
socials 明明有联合唯一索引,但 2026-11-11 之前 SocialService.Follow 走的是「先 IsFollowed 查询、确认没关注过、再 Create」两步流程(backend/internal/social/service.go)。两个并发的关注请求可以同时通过预查,然后第二个 Create 撞上 1062 并把原始 SQL 错误抛给用户;取关同理(Unfollow 先查后删,第二个请求因 RowsAffected == 0 报错)。修法是把「预查 + 写入」合并成一次带 ON CONFLICT DO NOTHING 或 INSERT IGNORE 的写操作,再用 RowsAffected 判断是不是真的改动——likes 与 comments 早就这么做,socials 在 P1-4(2026-11-11,f658b7e)补上了:repo.Follow 返回 (bool, error),created = false 时重复关注也返回 200,取关用 DELETE 的 RowsAffected 判 deleted。现在三张表的写法同构。这个案例反过来提醒:唯一索引只保证「数据不重复」,不保证「接口幂等」——后者要求写操作自己把冲突翻译成成功语义。
6.5 tags / video_tags:话题的抽取与关联
话题标签是唯一一处「从文本里解析出的结构化数据」,由两张表配合完成:tags 是标签字典(一个标签一行),video_tags 是关联表。抽取规则只有一行正则,而且用了 Unicode 字符类,所以中文标签也能被识别:
type Tag struct {
ID uint `gorm:"primaryKey" json:"id"`
Name string `gorm:"uniqueIndex;type:varchar(100);not null" json:"name"`
}
type VideoTag struct {
ID uint `gorm:"primaryKey"`
VideoID uint `gorm:"index;not null"`
TagID uint `gorm:"index;not null"`
}
var tagRegex = regexp.MustCompile(`#([\p{L}\p{N}_]+)`)
func ExtractTags(text string) []string {
matches := tagRegex.FindAllStringSubmatch(text, -1)
seen := make(map[string]bool)
var tags []string
for _, m := range matches {
tag := m[1]
if !seen[tag] {
seen[tag] = true
tags = append(tags, tag)
}
}
return tags
}
\p{L} 匹配任意语言的字母、\p{N} 匹配任意数字、_ 匹配下划线,所以 #美食、#golang、#2026 都能抽出来;函数内部用 seen map 做了同一段文本内的去重,避免 #美食 #美食 抽出两次。抽取的输入是标题加描述拼接后的字符串(backend/internal/video/video_service.go 的 Publish)。
| 表 | 列 | 列类型 | 索引 / 约束 |
|---|---|---|---|
tags | id / name | bigint unsigned / varchar(100) | idx_tags_name UNIQUE(裸 uniqueIndex) |
video_tags | id / video_id / tag_id | 三个 bigint unsigned | idx_video_tags_video_id、idx_video_tags_tag_id 两个单列普通索引,没有联合唯一约束 |
写入路径是「FirstOrCreate 拿 tag,再插 video_tags」,全程在发布视频的那个数据库事务里。tags.name 的唯一索引保证了同一个标签不会出现两行;但 video_tags 既没有 (video_id, tag_id) 联合唯一约束、插入时也没有做重复判断,所以同一条视频关联同一个标签两次是可以通过的——今天靠 ExtractTags 的去重挡在入口,属于「靠上游保证下游不变式」的脆弱结构。
读路径 ListByTag 是一条两跳 JOIN,排序键在被驱动表上,因此即使过滤列全部走索引,排序仍然要临时算:
SELECT videos.* FROM videos JOIN video_tags ON video_tags.video_id = videos.id JOIN tags ON tags.id = video_tags.tag_id WHERE tags.name = ? -- 走 idx_tags_name(唯一索引,最优) ORDER BY videos.create_time DESC -- 排序列在 videos 上,需 filesort LIMIT ?
tags.name = ? 能精确定位到 1 个 tag,但 video_tags.tag_id 只能给出「哪些关联行」,行数等于该标签下的视频数——标签越热,这一步回表越多;② ORDER BY videos.create_time DESC 需要把所有命中行取出来排序,无法利用 idx_videos_create_time(因为驱动顺序是先 tag 后 video);③ 没有 as_of 之类的快照语义,翻页仍用 create_time 单列游标,会带上一节说的同时间戳问题。这也是 docs/ISSUES-REPORT.md 把它列为「需要补复合索引」的原因。
6.6 outbox_msgs / messages / notifications:三类消息表
三张表都叫「消息」,但它们的生命周期完全不同,这也是最容易混淆的地方:outbox_msgs 是投递中转(投完即删),messages 是永久业务数据,notifications 是面向收件人的站内信。
type OutboxMsg struct {
ID uint `gorm:"primaryKey"`
VideoID uint `gorm:"index"`
EventType string `gorm:"type:varchar(50)"`
CreateTime time.Time `gorm:"autoCreateTime"`
Status string `gorm:"type:varchar(50);index"`
}
type Notification struct {
ID uint `gorm:"primaryKey" json:"id"`
RecipientID uint `gorm:"index;not null" json:"recipient_id"`
SenderID uint `gorm:"not null" json:"sender_id"`
Type string `gorm:"type:varchar(50);not null" json:"type"`
TargetID uint `gorm:"column:target_id" json:"target_id"`
Content string `gorm:"type:varchar(255)" json:"content"`
IsRead bool `gorm:"default:false" json:"is_read"`
CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
// DedupeKey 用 *string:无意图键的通知写 NULL,不参与唯一约束。
DedupeKey *string `gorm:"column:dedupe_key;type:varchar(128);uniqueIndex:uk_notifications_dedupe" json:"-"`
}
| 表 | 谁写 | 谁读 | 生命周期 | 索引 |
|---|---|---|---|---|
outbox_msgs | 视频发布事务(与 videos 同一个事务) | Worker 进程的 Outbox 轮询器(cmd/worker/main.go:194) | 投递成功后物理删除 | idx_outbox_msgs_video_id、idx_outbox_msgs_status(均单列) |
messages | MessageRepository.Send | /message/list | 永久 | idx_message_from、idx_message_to(均单列) |
notifications | NotificationWorker(like / comment / follow);mention 由评论域直写 | SSE 推送 + /notification/list | 永久,is_read 标记已读 | idx_notifications_recipient_id(单列)、uk_notifications_dedupe(dedupe_key 唯一) |
outbox_msgs 的轮询查询是 WHERE status = 'pending' ORDER BY create_time ASC LIMIT 100(backend/internal/worker/outboxworker.go)。status 有索引、create_time 没有,所以「按创建时间取最老的一批」这一步会在命中的 pending 行里做排序;pending 行通常很少,实际影响有限,但一旦积压(例如 broker 长时间不可用)它就是最先变慢的地方。
私信表的查询形状是双向 OR,两个单列索引刚好能各自命中一半然后用 index merge:
SELECT * FROM messages WHERE (from_id = ? AND to_id = ?) OR (from_id = ? AND to_id = ?) ORDER BY created_at DESC LIMIT 50 -- limit 由 handler 硬编码传入
最需要记住的是 notifications.target_id:它是一个多态外键,含义随 type 变化。NotificationWorker 构造的三条分支写得很直白——type = "like" 与 "comment" 时指向 视频 id,type = "follow" 时指向关注者的账号 id:
// routingKey == "like.like"
notif = &Notification{RecipientID: authorID, SenderID: evt.UserID,
Type: "like", TargetID: evt.VideoID, Content: "点赞了你的视频"}
// routingKey == "comment.publish"
notif = &Notification{RecipientID: authorID, SenderID: evt.AuthorID,
Type: "comment", TargetID: evt.VideoID, Content: "评论了你的视频"}
// routingKey == "social.follow"
notif = &Notification{RecipientID: evt.VloggerID, SenderID: evt.FollowerID,
Type: "follow", TargetID: evt.FollowerID, Content: "关注了你"}
type = "mention" 是第四条分支,但它不经过 Worker:CommentService.notifyMentions 解析评论正文里的 @用户名,查出账号后构造 Type: "mention" 的通知,交给 CommentRepository.CreateMentions 直接批量插入(clause.OnConflict{DoNothing: true}),跳过了 MQ 与 NotificationWorker。它的 TargetID 同样是视频 id,DedupeKey 由「mention + 评论意图键 + 收件人 id」拼成,重复的提及由 uk_notifications_dedupe 吸收。所以 notifications 有两个写入方:like / comment / follow 走 Worker,mention 由评论域在 API 进程里直写。
type 再决定去查哪张表,前端渲染链接时也要按 type 分支。② 语义靠约定:
Type 列只是 varchar(50),没有任何约束保证它只会是 like/comment/follow/mention 四个值;新增一种通知类型时,老的读取方不会报错,只会走进「未知 type」分支。落库逻辑也因此分成两条路径:NotificationWorker 负责前三类,mention 由评论域直写——读通知时不能假设「一定是 Worker 写的」。
6.7 AutoMigrate:迁移现状与已知风险
这个项目没有版本化迁移。没有 migrations/ 目录、没有 golang-migrate、没有 schema.sql,十一张表全部靠 AutoMigrate 在进程启动时按结构体对齐。调用点其实只有一处——API 进程启动时:
| 调用点 | 位置 | 在哪个进程执行 |
|---|---|---|
| 完整十一张表 | backend/internal/db/db.go 的 AutoMigrate,由 backend/cmd/main.go 调用 | 仅 API 进程(Worker 的 main 不调) |
另外两处代码看着像调用点,其实都不执行:backend/internal/message/handler.go 的 Repository.AutoMigrate 只迁移 Message,但全仓没有调用方(router.go 装配私信时只调 NewRepository);notificationworker.go 里的建表语句已经删掉,只剩一行注释「建表由 API 进程的 db.AutoMigrate 统一负责」。所以 Worker 进程从头到尾不执行 DDL。
AutoMigrate 的能力边界必须先说清楚,否则很容易误判风险:它只会做加法——新增表、新增列、新增索引、把列改宽;不会删列、删索引、改列名或回滚任何东西。所以「改代码就能改表」这个印象只在「加字段」时成立。
| 风险 | 具体表现 | 记录位置 |
|---|---|---|
| 重命名字段会「新增列」 | 把 Bio 改名为 Signature,AutoMigrate 只会新建 signature 列,老列和它的数据原样留着 | — |
| 没有版本记录 | 无法回答「生产库现在是哪个 schema 版本」,也无法回滚某次结构变更 | — |
| DDL 无法被 review | 改表的影响面藏在 Go tag 的差异里,代码评审时不会像看 .sql 那样显眼 | — |
| 启动即改表 | 改表动作与「服务启动」绑定,大表加索引可能让启动耗时不可控 | — |
| 错误命名无法自动纠正 | idx_videos_likes_count_id 这种「名字与列不符」的索引,AutoMigrate 认为它已存在,不会重建 | P2-3 |
SHOW CREATE TABLE 核对真实结果——因为 GORM 的类型推导结果(例如 longtext)与直觉经常不一致;④ 需要删列/删索引时手写 SQL,AutoMigrate 不会替你做。
最后补一个读源码时的实用技巧:想知道某张表的真实结构,不要读 Go 结构体去推——结构体只写了 GORM tag,省略的 type:、not null、default 全由驱动补全,而补全规则会随驱动版本变化。以数据库为准,永远是对的:
-- 结构体里没写 type: 的字段,真实类型看这里 SHOW CREATE TABLE videos\G -- 索引名与实际列(注意 id 是 InnoDB 隐式追加的,方向永远是 ASC) SHOW INDEX FROM videos; -- 对照:名字里带 id,但定义里没有 id -- idx_videos_likes_count_id → Key_name = idx_videos_likes_count_id, Column_name = likes_count -- Key_name = idx_videos_likes_count_id, Column_name = id ← 隐式追加
② 幂等护栏三处半:
likes 唯一索引(真的在用)、comments 的 uk_comments_author_key(配 idempotency_key 判重)、socials 唯一索引(没用在幂等上)、tags.name 唯一索引(配合 FirstOrCreate);③ 两个派生列
likes_count 与 popularity 是「为了排序而冗余」,也因此成为一致性问题的高发区(第 10、11 章);④ 全站 DDL 只由 API 进程的一处
AutoMigrate 生成,只加不减、无版本、无回滚。
VLoop 项目学习 · 第 6 章 数据模型与表关系:十一张表怎么设计
学习地图 · 篇 2 项目拆解 · 速查与自测