From 6a866464695e8b0291236f9038a032f68fb0b37d Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Thu, 3 Sep 2020 20:41:00 +0800 Subject: [PATCH] Fix use db function as integer's default value, close #3384 --- schema/field.go | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/schema/field.go b/schema/field.go index 0cb210f8..f8a73c60 100644 --- a/schema/field.go +++ b/schema/field.go @@ -178,41 +178,41 @@ func (schema *Schema) ParseField(fieldStruct reflect.StructField) *Field { field.Comment = val } + defaultValueFunc := strings.Contains(field.DefaultValue, "(") && + strings.Contains(field.DefaultValue, ")") || strings.ToLower(field.DefaultValue) == "null" switch reflect.Indirect(fieldValue).Kind() { case reflect.Bool: field.DataType = Bool - if field.HasDefaultValue && field.DefaultValue != "" { + if field.HasDefaultValue && !defaultValueFunc { if field.DefaultValueInterface, err = strconv.ParseBool(field.DefaultValue); err != nil { schema.err = fmt.Errorf("failed to parse %v as default value for bool, got error: %v", field.DefaultValue, err) } } case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: field.DataType = Int - if field.HasDefaultValue && field.DefaultValue != "" { + if field.HasDefaultValue && !defaultValueFunc { if field.DefaultValueInterface, err = strconv.ParseInt(field.DefaultValue, 0, 64); err != nil { schema.err = fmt.Errorf("failed to parse %v as default value for int, got error: %v", field.DefaultValue, err) } } case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: field.DataType = Uint - if field.HasDefaultValue && field.DefaultValue != "" { + if field.HasDefaultValue && !defaultValueFunc { if field.DefaultValueInterface, err = strconv.ParseUint(field.DefaultValue, 0, 64); err != nil { schema.err = fmt.Errorf("failed to parse %v as default value for uint, got error: %v", field.DefaultValue, err) } } case reflect.Float32, reflect.Float64: field.DataType = Float - if field.HasDefaultValue && field.DefaultValue != "" { + if field.HasDefaultValue && !defaultValueFunc { if field.DefaultValueInterface, err = strconv.ParseFloat(field.DefaultValue, 64); err != nil { schema.err = fmt.Errorf("failed to parse %v as default value for float, got error: %v", field.DefaultValue, err) } } case reflect.String: field.DataType = String - isFunc := strings.Contains(field.DefaultValue, "(") && - strings.Contains(field.DefaultValue, ")") || strings.ToLower(field.DefaultValue) == "null" - if field.HasDefaultValue && !isFunc { + if field.HasDefaultValue && !defaultValueFunc { field.DefaultValue = strings.Trim(field.DefaultValue, "'") field.DefaultValue = strings.Trim(field.DefaultValue, "\"") field.DefaultValueInterface = field.DefaultValue