Skip to content

Commit

Permalink
feat: support for setting table comments after AutoMigrate
Browse files Browse the repository at this point in the history
  • Loading branch information
iTanken committed Dec 10, 2023
1 parent 68a877c commit 919d131
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,41 @@ type Migrator struct {
migrator.Migrator
}

// AutoMigrate auto migrate values
//
// // Migrating and setting a comment for a single table
// db.Set("gorm:table_comments", "用户信息表").AutoMigrate(&User{})
//
// // Migrating and setting comments for multiple tables
// db.Set("gorm:table_comments", []string{"用户信息表", "公司信息表"}).AutoMigrate(&User{}, &Company{})
func (m Migrator) AutoMigrate(values ...interface{}) error {
if err := m.Migrator.AutoMigrate(values...); err != nil {
return err
}

if tableComments, ok := m.DB.Get("gorm:table_comments"); ok {
var comments []string
switch c := tableComments.(type) {
case string:
comments = append(comments, c)
case []string:
comments = c
default:
return nil
}
for i := 0; i < len(values) && i < len(comments); i++ {
value := values[i]
comment := strings.ReplaceAll(comments[i], "'", "''")
if err := m.RunWithValue(value, func(stmt *gorm.Statement) error {
return m.DB.Exec(fmt.Sprintf("COMMENT ON TABLE ? IS '%s'", comment), m.CurrentTable(stmt)).Error
}); err != nil {
return err
}
}
}
return nil
}

func (m Migrator) CurrentDatabase() (name string) {
m.DB.Raw("SELECT CURRENT_DATABASE()").Scan(&name)
return
Expand Down

0 comments on commit 919d131

Please sign in to comment.