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"
|
|
|
|
|
|
"feedsystem_video_go/internal/social"
|
|
|
|
|
|
"feedsystem_video_go/internal/video"
|
|
|
|
|
|
"feedsystem_video_go/internal/worker"
|
|
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
|
|
|
|
"gorm.io/driver/mysql"
|
|
|
|
|
|
"gorm.io/gorm"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
func NewDB(dbcfg config.DatabaseConfig) (*gorm.DB, error) {
|
|
|
|
|
|
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{})
|
|
|
|
|
|
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{}, &worker.Notification{},
|
2026-10-30 13:13:29 +08:00
|
|
|
|
// 停泊消息的落库表(P0-3)。它的写入方是 Worker 的 FailedEventWorker,
|
|
|
|
|
|
// 但建表仍由 API 进程的 AutoMigrate 统一负责——建表入口只有一个。
|
|
|
|
|
|
&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()
|
|
|
|
|
|
}
|