Skip to content

Commit

Permalink
Fix AutoMigrate for bool fields with default value
Browse files Browse the repository at this point in the history
  • Loading branch information
jinzhu committed Mar 18, 2024
1 parent e0c3be0 commit 1b0aa80
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
19 changes: 13 additions & 6 deletions migrator/migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -518,12 +519,18 @@ func (m Migrator) MigrateColumn(value interface{}, field *schema.Field, columnTy
} else if !dvNotNull && currentDefaultNotNull {
// null -> default value
alterColumn = true
} else if (field.GORMDataType != schema.Time && dv != field.DefaultValue) ||
(field.GORMDataType == schema.Time && !strings.EqualFold(strings.TrimSuffix(dv, "()"), strings.TrimSuffix(field.DefaultValue, "()"))) {
// default value not equal
// not both null
if currentDefaultNotNull || dvNotNull {
alterColumn = true
} else if currentDefaultNotNull || dvNotNull {
switch field.GORMDataType {
case schema.Time:
if !strings.EqualFold(strings.TrimSuffix(dv, "()"), strings.TrimSuffix(field.DefaultValue, "()")) {
alterColumn = true
}
case schema.Bool:
v1, _ := strconv.ParseBool(dv)
v2, _ := strconv.ParseBool(field.DefaultValue)
alterColumn = v1 != v2
default:
alterColumn = dv != field.DefaultValue
}
}
}
Expand Down
12 changes: 11 additions & 1 deletion tests/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"math/rand"
"os"
"reflect"
"strconv"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -1420,7 +1421,7 @@ func TestMigrateSameEmbeddedFieldName(t *testing.T) {
AssertEqual(t, nil, err)
}

func TestMigrateDefaultNullString(t *testing.T) {
func TestMigrateWithDefaultValue(t *testing.T) {
if DB.Dialector.Name() == "sqlserver" {
// sqlserver driver treats NULL and 'NULL' the same
t.Skip("skip sqlserver")
Expand All @@ -1434,6 +1435,7 @@ func TestMigrateDefaultNullString(t *testing.T) {
type NullStringModel struct {
ID uint
Content string `gorm:"default:'null'"`
Active bool `gorm:"default:false"`
}

tableName := "null_string_model"
Expand All @@ -1454,6 +1456,14 @@ func TestMigrateDefaultNullString(t *testing.T) {
AssertEqual(t, defVal, "null")
AssertEqual(t, ok, true)

columnType2, err := findColumnType(tableName, "active")
AssertEqual(t, err, nil)

defVal, ok = columnType2.DefaultValue()
bv, _ := strconv.ParseBool(defVal)
AssertEqual(t, bv, false)
AssertEqual(t, ok, true)

// default 'null' -> 'null'
session := DB.Session(&gorm.Session{Logger: Tracer{
Logger: DB.Config.Logger,
Expand Down

0 comments on commit 1b0aa80

Please sign in to comment.