`video` 与 `worker` 各有一份 `notifications` 表的实体。 两份定义会漂移,所以合并到 `internal/notification`。 新增 `entity.go` 保存唯一一份列标签。 `worker`、`ssehub`、`comment_repo`、`db` 与两个集成测试改为引用新包。 `db` 包不再 import `worker`。 去重键仍是 `*string`,因此 NULL 才能共存。 验证:go test -count=1 ./... 全绿;集成测试三包全绿。
59 lines
1.9 KiB
Go
59 lines
1.9 KiB
Go
package db
|
||
|
||
import (
|
||
"feedsystem_video_go/internal/account"
|
||
"feedsystem_video_go/internal/config"
|
||
"feedsystem_video_go/internal/failedevent"
|
||
"feedsystem_video_go/internal/message"
|
||
"feedsystem_video_go/internal/notification"
|
||
"feedsystem_video_go/internal/social"
|
||
"feedsystem_video_go/internal/video"
|
||
"fmt"
|
||
|
||
"gorm.io/driver/mysql"
|
||
"gorm.io/gorm"
|
||
)
|
||
|
||
// BuildDSN 组装 MySQL DSN。
|
||
//
|
||
// 抽成函数只是为了让"DSN 里有哪些参数"可被单测钉住——它看起来是纯配置,
|
||
// 实际上承载着一个正确性前提:**不得开启 clientFoundRows**。
|
||
//
|
||
// clientFoundRows 会让 MySQL 在 UPDATE 未改动任何行时也报告 1 行受影响,
|
||
// 而 P0-4 的判重依赖 RowsAffected==0 来识别"这条意图已经落过库"
|
||
// (见 video.CommentRepository.CreateIdempotentWithPopularity)。一旦打开,
|
||
// 重复写入会被当成首次写入,评论去重与热度门控同时静默失效——它不会报错,
|
||
// 只会悄悄多出一行评论和一份热度。
|
||
func BuildDSN(dbcfg config.DatabaseConfig) string {
|
||
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
||
dbcfg.User, dbcfg.Password, dbcfg.Host, dbcfg.Port, dbcfg.DBName)
|
||
}
|
||
|
||
func NewDB(dbcfg config.DatabaseConfig) (*gorm.DB, error) {
|
||
db, err := gorm.Open(mysql.Open(BuildDSN(dbcfg)), &gorm.Config{})
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
|
||
return db, nil
|
||
}
|
||
|
||
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{},
|
||
// 停泊消息的落库表(P0-3)。它的写入方是 Worker 的 FailedEventWorker,
|
||
// 但建表仍由 API 进程的 AutoMigrate 统一负责——建表入口只有一个。
|
||
&failedevent.FailedEvent{},
|
||
)
|
||
}
|
||
|
||
func CloseDB(db *gorm.DB) error {
|
||
sqlDB, err := db.DB()
|
||
if err != nil {
|
||
return err
|
||
}
|
||
return sqlDB.Close()
|
||
}
|