Allow updating only specific columns

This commit is contained in:
Deluan
2021-06-02 18:40:29 -04:00
parent 9da9d73c1d
commit bebfe296a5
2 changed files with 15 additions and 12 deletions
+1 -1
View File
@@ -48,7 +48,7 @@ func (r *shareRepository) Put(s *model.Share) error {
func (r *shareRepository) Update(entity interface{}, cols ...string) error { func (r *shareRepository) Update(entity interface{}, cols ...string) error {
s := entity.(*model.Share) s := entity.(*model.Share)
_, err := r.put(s.ID, s) _, err := r.put(s.ID, s, cols...)
if err == model.ErrNotFound { if err == model.ErrNotFound {
return rest.ErrNotFound return rest.ErrNotFound
} }
+14 -11
View File
@@ -6,6 +6,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/navidrome/navidrome/utils"
. "github.com/Masterminds/squirrel" . "github.com/Masterminds/squirrel"
"github.com/astaxie/beego/orm" "github.com/astaxie/beego/orm"
"github.com/google/uuid" "github.com/google/uuid"
@@ -184,30 +186,31 @@ func (r sqlRepository) count(countQuery SelectBuilder, options ...model.QueryOpt
return res.Count, err return res.Count, err
} }
func (r sqlRepository) put(id string, m interface{}) (newId string, err error) { func (r sqlRepository) put(id string, m interface{}, colsToUpdate ...string) (newId string, err error) {
values, _ := toSqlArgs(m) values, _ := toSqlArgs(m)
// Remove created_at from args and save it for later, if needed for insert // If there's an ID, try to update first
createdAt := values["created_at"]
delete(values, "created_at")
if id != "" { if id != "" {
update := Update(r.tableName).Where(Eq{"id": id}).SetMap(values) updateValues := map[string]interface{}{}
for k, v := range values {
if len(colsToUpdate) == 0 || utils.StringInSlice(k, colsToUpdate) {
updateValues[k] = v
}
}
delete(updateValues, "created_at")
update := Update(r.tableName).Where(Eq{"id": id}).SetMap(updateValues)
count, err := r.executeSQL(update) count, err := r.executeSQL(update)
if err != nil { if err != nil {
return "", err return "", err
} }
if count > 0 { if count > 0 {
return id, err return id, nil
} }
} }
// If does not have an id OR could not update (new record with predefined id) // If does not have an ID OR the ID was not found (when it is a new record with predefined id)
if id == "" { if id == "" {
id = uuid.NewString() id = uuid.NewString()
values["id"] = id values["id"] = id
} }
// It is a insert. if there was a created_at, add it back to args
if createdAt != nil {
values["created_at"] = createdAt
}
insert := Insert(r.tableName).SetMap(values) insert := Insert(r.tableName).SetMap(values)
_, err = r.executeSQL(insert) _, err = r.executeSQL(insert)
return id, err return id, err