2026-05-20 16:34:19 +08:00
|
|
|
|
package db
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"feedsystem_video_go/internal/account"
|
|
|
|
|
|
"feedsystem_video_go/internal/config"
|
2026-10-30 13:13:29 +08:00
|
|
|
|
"feedsystem_video_go/internal/failedevent"
|
2026-05-20 16:34:19 +08:00
|
|
|
|
"feedsystem_video_go/internal/message"
|
2026-10-30 23:48:43 +08:00
|
|
|
|
"feedsystem_video_go/internal/notification"
|
2026-05-20 16:34:19 +08:00
|
|
|
|
"feedsystem_video_go/internal/social"
|
|
|
|
|
|
"feedsystem_video_go/internal/video"
|
|
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
|
|
|
|
"gorm.io/driver/mysql"
|
|
|
|
|
|
"gorm.io/gorm"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2026-10-30 13:21:04 +08:00
|
|
|
|
// BuildDSN 组装 MySQL DSN。
|
|
|
|
|
|
//
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// 不得开启 clientFoundRows:它会让 UPDATE 未改动行时也报告 1 行受影响,
|
|
|
|
|
|
// 而判重依赖 RowsAffected==0。
|
2026-10-30 13:21:04 +08:00
|
|
|
|
func BuildDSN(dbcfg config.DatabaseConfig) string {
|
|
|
|
|
|
return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
2026-05-20 16:34:19 +08:00
|
|
|
|
dbcfg.User, dbcfg.Password, dbcfg.Host, dbcfg.Port, dbcfg.DBName)
|
2026-10-30 13:21:04 +08:00
|
|
|
|
}
|
2026-05-20 16:34:19 +08:00
|
|
|
|
|
2026-10-30 13:21:04 +08:00
|
|
|
|
func NewDB(dbcfg config.DatabaseConfig) (*gorm.DB, error) {
|
|
|
|
|
|
db, err := gorm.Open(mysql.Open(BuildDSN(dbcfg)), &gorm.Config{})
|
2026-05-20 16:34:19 +08:00
|
|
|
|
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{},
|
2026-10-30 23:48:43 +08:00
|
|
|
|
&message.Message{}, ¬ification.Notification{},
|
2026-10-31 10:08:03 +08:00
|
|
|
|
// 停泊消息的落库表;建表入口只有这一个。
|
2026-10-30 13:13:29 +08:00
|
|
|
|
&failedevent.FailedEvent{},
|
2026-05-20 16:34:19 +08:00
|
|
|
|
)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func CloseDB(db *gorm.DB) error {
|
|
|
|
|
|
sqlDB, err := db.DB()
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
return sqlDB.Close()
|
|
|
|
|
|
}
|