Add support for sql expressions in struct tag default fileds, on update. Fixes create_test.go time comparison
This commit is contained in:
parent
40b51709ff
commit
5399fd879f
@ -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())))
|
||||
}
|
||||
|
@ -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")
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user