Fix AutoMigrate for bool fields with default value

This commit is contained in:
Jinzhu 2024-03-18 19:24:16 +08:00
parent e0c3be03fb
commit 1b0aa802df
2 changed files with 24 additions and 7 deletions

View File

@ -7,6 +7,7 @@ import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"time"
@ -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
}
}
}

View File

@ -7,6 +7,7 @@ import (
"math/rand"
"os"
"reflect"
"strconv"
"strings"
"testing"
"time"
@ -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")
@ -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"
@ -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,