1ad775be63
- Added comments to various fields in the database models for better clarity and understanding. - Implemented TableComment methods for several models to provide descriptive information about their purpose. - Updated the AutoMigrate function to support setting table comments in the database. - Improved overall documentation within the code to facilitate future maintenance and development.
74 lines
1.5 KiB
Go
Executable File
74 lines
1.5 KiB
Go
Executable File
package database
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"strings"
|
|
"wx_service/config"
|
|
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
var DB *gorm.DB
|
|
|
|
func InitDB() error {
|
|
cfg := config.AppConfig.Database
|
|
|
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
|
cfg.User,
|
|
cfg.Password,
|
|
cfg.Host,
|
|
cfg.Port,
|
|
cfg.DBName,
|
|
)
|
|
|
|
var err error
|
|
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
|
|
Logger: logger.Default.LogMode(logger.Info),
|
|
})
|
|
|
|
if err != nil {
|
|
return fmt.Errorf("连接数据库失败: %v", err)
|
|
}
|
|
|
|
log.Println("数据库连接成功")
|
|
return nil
|
|
}
|
|
|
|
func AutoMigrate(models ...interface{}) error {
|
|
type tableCommenter interface {
|
|
TableComment() string
|
|
}
|
|
|
|
for _, m := range models {
|
|
tx := DB
|
|
comment := ""
|
|
if tc, ok := m.(tableCommenter); ok {
|
|
comment = strings.TrimSpace(tc.TableComment())
|
|
if comment != "" {
|
|
tx = tx.Set("gorm:table_options", fmt.Sprintf("COMMENT='%s'", escapeSQLComment(comment)))
|
|
}
|
|
}
|
|
|
|
if err := tx.AutoMigrate(m); err != nil {
|
|
return err
|
|
}
|
|
|
|
// 尝试为已存在的表补齐 table comment(即使表已创建,也能更新注释)。
|
|
if comment != "" {
|
|
stmt := &gorm.Statement{DB: DB}
|
|
if err := stmt.Parse(m); err == nil && stmt.Schema != nil && stmt.Schema.Table != "" {
|
|
_ = DB.Exec(fmt.Sprintf("ALTER TABLE `%s` COMMENT = '%s'", stmt.Schema.Table, escapeSQLComment(comment))).Error
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func escapeSQLComment(s string) string {
|
|
// MySQL: 单引号用两个单引号转义
|
|
return strings.ReplaceAll(s, "'", "''")
|
|
}
|