diff --git a/callback_update.go b/callback_update.go index e45a3a84..6c960723 100644 --- a/callback_update.go +++ b/callback_update.go @@ -37,6 +37,14 @@ func UpdateTimeStampWhenUpdate(scope *Scope) { } } +func escapeIfNeeded(scope *Scope, value string) string { + // default:'string value' OR sql expression, like: default:"(now() at timezone 'utc')" + if (strings.HasPrefix(value, "'") && strings.HasSuffix(value, "'")) || (strings.HasPrefix(value, "(") && strings.HasSuffix(value, ")")) { + return value + } + return scope.AddToVars(value) // default:'something' like:default:'false' should be between quotes (what AddToVars do) +} + func Update(scope *Scope) { if !scope.HasError() { var sqls []string @@ -53,8 +61,8 @@ func Update(scope *Scope) { if scope.changeableField(field) && !field.IsPrimaryKey && field.IsNormal { if field.HasDefaultValue { if field.IsBlank { - defaultValue := strings.Trim(parseTagSetting(field.Tag.Get("sql"))["DEFAULT"], "'") - sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), scope.AddToVars(defaultValue))) + defaultValue := parseTagSetting(field.Tag.Get("sql"))["DEFAULT"] + sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), escapeIfNeeded(scope, defaultValue))) } else { sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface()))) } diff --git a/create_test.go b/create_test.go index 97175980..56ac19c2 100644 --- a/create_test.go +++ b/create_test.go @@ -51,7 +51,7 @@ func TestCreate(t *testing.T) { DB.Model(user).Update("name", "create_user_new_name") DB.First(&user, user.Id) - if user.CreatedAt != newUser.CreatedAt { + if user.CreatedAt.Format(time.RFC3339Nano) != newUser.CreatedAt.Format(time.RFC3339Nano) { t.Errorf("CreatedAt should not be changed after update") } }