Enhance database models with comments and table descriptions

- 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.
This commit is contained in:
nepiedg
2026-01-03 02:35:11 +00:00
parent 16844d4a42
commit 1ad775be63
9 changed files with 182 additions and 108 deletions
+33 -1
View File
@@ -3,6 +3,7 @@ package database
import (
"fmt"
"log"
"strings"
"wx_service/config"
"gorm.io/driver/mysql"
@@ -37,5 +38,36 @@ func InitDB() error {
}
func AutoMigrate(models ...interface{}) error {
return DB.AutoMigrate(models...)
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, "'", "''")
}