Add support for sql expressions in struct tag default fileds, on update. Fixes create_test.go time comparison

This commit is contained in:
Paolo Galeone 2015-11-22 23:22:34 +01:00
parent 40b51709ff
commit 5399fd879f
2 changed files with 11 additions and 3 deletions

View File

@ -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) { func Update(scope *Scope) {
if !scope.HasError() { if !scope.HasError() {
var sqls []string var sqls []string
@ -53,8 +61,8 @@ func Update(scope *Scope) {
if scope.changeableField(field) && !field.IsPrimaryKey && field.IsNormal { if scope.changeableField(field) && !field.IsPrimaryKey && field.IsNormal {
if field.HasDefaultValue { if field.HasDefaultValue {
if field.IsBlank { if field.IsBlank {
defaultValue := strings.Trim(parseTagSetting(field.Tag.Get("sql"))["DEFAULT"], "'") defaultValue := parseTagSetting(field.Tag.Get("sql"))["DEFAULT"]
sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), scope.AddToVars(defaultValue))) sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), escapeIfNeeded(scope, defaultValue)))
} else { } else {
sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface()))) sqls = append(sqls, fmt.Sprintf("%v = %v", scope.Quote(field.DBName), scope.AddToVars(field.Field.Interface())))
} }

View File

@ -51,7 +51,7 @@ func TestCreate(t *testing.T) {
DB.Model(user).Update("name", "create_user_new_name") DB.Model(user).Update("name", "create_user_new_name")
DB.First(&user, user.Id) 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") t.Errorf("CreatedAt should not be changed after update")
} }
} }