Optimize migrator.go MigrateColumn and ColumnTypes func. (#4532)

This commit is contained in:
heige 2021-08-02 18:44:10 +08:00 committed by GitHub
parent 7a49629fd1
commit 413fe587c6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 25 additions and 15 deletions

View File

@ -2,6 +2,7 @@ package migrator
import ( import (
"context" "context"
"database/sql"
"fmt" "fmt"
"reflect" "reflect"
"regexp" "regexp"
@ -386,11 +387,11 @@ func (m Migrator) MigrateColumn(value interface{}, field *schema.Field, columnTy
alterColumn = true alterColumn = true
} else { } else {
// has size in data type and not equal // has size in data type and not equal
// Since the following code is frequently called in the for loop, reg optimization is needed here // Since the following code is frequently called in the for loop, reg optimization is needed here
matches := regRealDataType.FindAllStringSubmatch(realDataType, -1) matches := regRealDataType.FindAllStringSubmatch(realDataType, -1)
matches2 := regFullDataType.FindAllStringSubmatch(fullDataType, -1) matches2 := regFullDataType.FindAllStringSubmatch(fullDataType, -1)
if (len(matches) == 1 && matches[0][1] != fmt.Sprint(field.Size) || !field.PrimaryKey) && (len(matches2) == 1 && matches2[0][1] != fmt.Sprint(length)) { if (len(matches) == 1 && matches[0][1] != fmt.Sprint(field.Size) || !field.PrimaryKey) &&
(len(matches2) == 1 && matches2[0][1] != fmt.Sprint(length)) {
alterColumn = true alterColumn = true
} }
} }
@ -418,22 +419,31 @@ func (m Migrator) MigrateColumn(value interface{}, field *schema.Field, columnTy
return nil return nil
} }
func (m Migrator) ColumnTypes(value interface{}) (columnTypes []gorm.ColumnType, err error) { // ColumnTypes return columnTypes []gorm.ColumnType and execErr error
columnTypes = make([]gorm.ColumnType, 0) func (m Migrator) ColumnTypes(value interface{}) ([]gorm.ColumnType, error) {
err = m.RunWithValue(value, func(stmt *gorm.Statement) error { columnTypes := make([]gorm.ColumnType, 0)
execErr := m.RunWithValue(value, func(stmt *gorm.Statement) error {
rows, err := m.DB.Session(&gorm.Session{}).Table(stmt.Table).Limit(1).Rows() rows, err := m.DB.Session(&gorm.Session{}).Table(stmt.Table).Limit(1).Rows()
if err == nil { if err != nil {
return err
}
defer rows.Close() defer rows.Close()
rawColumnTypes, err := rows.ColumnTypes()
if err == nil { var rawColumnTypes []*sql.ColumnType
rawColumnTypes, err = rows.ColumnTypes()
if err != nil {
return err
}
for _, c := range rawColumnTypes { for _, c := range rawColumnTypes {
columnTypes = append(columnTypes, c) columnTypes = append(columnTypes, c)
} }
}
} return nil
return err
}) })
return
return columnTypes, execErr
} }
func (m Migrator) CreateView(name string, option gorm.ViewOption) error { func (m Migrator) CreateView(name string, option gorm.ViewOption) error {