From f2b49437fbbab9c42ec85f9a0fcf4ad10abc32ec Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 25 Jun 2020 22:48:10 +0800 Subject: [PATCH] Test set string field's default value to blank string --- migrator/migrator.go | 2 +- tests/default_value_test.go | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/migrator/migrator.go b/migrator/migrator.go index 9c4ce2d5..5edd800e 100644 --- a/migrator/migrator.go +++ b/migrator/migrator.go @@ -64,7 +64,7 @@ func (m Migrator) FullDataTypeOf(field *schema.Field) (expr clause.Expr) { expr.SQL += " UNIQUE" } - if field.HasDefaultValue && field.DefaultValue != "" { + if field.HasDefaultValue && (field.DefaultValueInterface != nil || field.DefaultValue != "") { if field.DefaultValueInterface != nil { defaultStmt := &gorm.Statement{Vars: []interface{}{field.DefaultValueInterface}} m.Dialector.BindVarTo(defaultStmt, defaultStmt, field.DefaultValueInterface) diff --git a/tests/default_value_test.go b/tests/default_value_test.go index 7a7790bc..ea496d60 100644 --- a/tests/default_value_test.go +++ b/tests/default_value_test.go @@ -12,6 +12,7 @@ func TestDefaultValue(t *testing.T) { Email string `gorm:"not null;index:,unique"` Name string `gorm:"not null;default:'foo'"` Name2 string `gorm:"size:233;not null;default:'foo'"` + Name3 string `gorm:"size:233;not null;default:''"` Age int `gorm:"default:18"` Enabled bool `gorm:"default:true"` } @@ -25,14 +26,14 @@ func TestDefaultValue(t *testing.T) { var harumph = Harumph{Email: "hello@gorm.io"} if err := DB.Create(&harumph).Error; err != nil { t.Fatalf("Failed to create data with default value, got error: %v", err) - } else if harumph.Name != "foo" || harumph.Name2 != "foo" || harumph.Age != 18 || !harumph.Enabled { + } else if harumph.Name != "foo" || harumph.Name2 != "foo" || harumph.Name3 != "" || harumph.Age != 18 || !harumph.Enabled { t.Fatalf("Failed to create data with default value, got: %+v", harumph) } var result Harumph if err := DB.First(&result, "email = ?", "hello@gorm.io").Error; err != nil { t.Fatalf("Failed to find created data, got error: %v", err) - } else if result.Name != "foo" || result.Name2 != "foo" || result.Age != 18 || !result.Enabled { + } else if result.Name != "foo" || result.Name2 != "foo" || result.Name3 != "" || result.Age != 18 || !result.Enabled { t.Fatalf("Failed to find created data with default data, got %+v", result) } }