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。 // // 不得开启 clientFoundRows:它会让 UPDATE 未改动行时也报告 1 行受影响, // 而判重依赖 RowsAffected==0。 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{}, // 停泊消息的落库表;建表入口只有这一个。 &failedevent.FailedEvent{}, ) } func CloseDB(db *gorm.DB) error { sqlDB, err := db.DB() if err != nil { return err } return sqlDB.Close() }