MCPcopy
hub / github.com/go-gorm/gorm / MigrateColumn

Method MigrateColumn

migrator/migrator.go:470–597  ·  view source on GitHub ↗

MigrateColumn migrate column

(value interface{}, field *schema.Field, columnType gorm.ColumnType)

Source from the content-addressed store, hash-verified

468
469// MigrateColumn migrate column
470func (m Migrator) MigrateColumn(value interface{}, field *schema.Field, columnType gorm.ColumnType) error {
471 if field.IgnoreMigration {
472 return nil
473 }
474
475 // found, smart migrate
476 fullDataType := strings.TrimSpace(strings.ToLower(m.DB.Migrator().FullDataTypeOf(field).SQL))
477 realDataType := strings.ToLower(columnType.DatabaseTypeName())
478 var (
479 alterColumn bool
480 isSameType = fullDataType == realDataType
481 )
482
483 if !field.PrimaryKey {
484 // check type
485 if !strings.HasPrefix(fullDataType, realDataType) {
486 // check type aliases
487 aliases := m.DB.Migrator().GetTypeAliases(realDataType)
488 for _, alias := range aliases {
489 if strings.HasPrefix(fullDataType, alias) {
490 isSameType = true
491 break
492 }
493 }
494
495 if !isSameType {
496 alterColumn = true
497 }
498 }
499 }
500
501 if !isSameType {
502 // check size
503 if length, ok := columnType.Length(); length != int64(field.Size) {
504 if length > 0 && field.Size > 0 {
505 alterColumn = true
506 } else {
507 // has size in data type and not equal
508 // Since the following code is frequently called in the for loop, reg optimization is needed here
509 matches2 := regFullDataType.FindAllStringSubmatch(fullDataType, -1)
510 if !field.PrimaryKey &&
511 (len(matches2) == 1 && matches2[0][1] != fmt.Sprint(length) && ok) {
512 alterColumn = true
513 }
514 }
515 }
516 }
517
518 // check precision
519 if realDataType == "decimal" || realDataType == "numeric" &&
520 regexp.MustCompile(realDataType+`\(.*\)`).FindString(fullDataType) != "" { // if realDataType has no precision,ignore
521 precision, scale, ok := columnType.DecimalSize()
522 if ok {
523 if !strings.HasPrefix(fullDataType, fmt.Sprintf("%s(%d,%d)", realDataType, precision, scale)) &&
524 !strings.HasPrefix(fullDataType, fmt.Sprintf("%s(%d)", realDataType, precision)) {
525 alterColumn = true
526 }
527 }

Callers

nothing calls this directly

Implementers 1

Migratormigrator/migrator.go

Calls 12

DataTypeOfMethod · 0.95
FullDataTypeOfMethod · 0.65
MigratorMethod · 0.65
DatabaseTypeNameMethod · 0.65
GetTypeAliasesMethod · 0.65
LengthMethod · 0.65
DecimalSizeMethod · 0.65
NullableMethod · 0.65
DefaultValueMethod · 0.65
CommentMethod · 0.65
AlterColumnMethod · 0.65
MigrateColumnUniqueMethod · 0.65

Tested by

no test coverage detected