Partial updates #467
-
What's the appropriate method for dynamic partial updates? I'm looking for something simple like this hypothetical approach: type MyParams struct {
ID int32
Value *string
}
func PartialNonNilUpdate(ctx context.Context, params MyParams) error {
sets := filterColumnAssignments(
maybeSetStringp(MyTable.Value, params.Value),
MyTable.UpdatedAt.SET(CURRENT_TIMESTAMP()),
)
stmt := MyTable.UPDATE().
SET(sets...). // type error
WHERE(MyTable.ID.EQ(Int32(params.ID)))
}
func filterColumnAssignments(sets ...ColumnAssigment) []ColumnAssigment {
return slices.DeleteFunc(
sets,
func(set ColumnAssigment) bool {
return set == nil
},
)
}
func maybeSetStringp(col ColumnString, v *string) ColumnAssigment {
if v == nil || *v == "" {
return nil
}
return col.SET(String(*v))
} Perhaps there's a way to make this work or another approach I should consider? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I usually do something like this: type MyParams struct {
ID int32
Value *string
}
func PartialNonNilUpdate(ctx context.Context, params MyParams) error {
var columns ColumnList
var myTable model.MyTable
if params.Value != nil {
myTable.Value = *params.Value
columns = append(columns, MyTable.Value)
}
// etc..., for the rest of params
stmt := MyTable.UPDATE(columns).
MODEL(myTable).
WHERE(MyTable.ID.EQ(Int32(params.ID)))
} To set UpdatedAt to CURRENT_TIMESTAMP I use database triggers, or sometimes myTable.UpdatedAt = time.Now(). SET(sets...). // type error To fix this type error, sets have to be of type []interface{}. |
Beta Was this translation helpful? Give feedback.
I usually do something like this:
To set UpdatedAt to CURRENT_TIMESTAMP I use database triggers, or sometimes myTable.UpdatedAt = time.Now().
If your params fields have the same name as your model fields, you can automate …