prevent primary key updates (#95)

* prevent primary key updates

* better error to return

Co-authored-by: Jim Lambert <jimlambrt@Jims-MBP-3.home>
This commit is contained in:
JimandJim Lambert authored and GitHub committed 2020-06-03 09:51:34 -04:00
1 parent 1048673171
commit e3fdb493b8
2 files changed
+35

No files matched your search

+15
View File
@@ -249,6 +249,12 @@ func (rw *Db) Update(ctx context.Context, i interface{}, fieldMaskPaths []string
return NoRowsAffected, fmt.Errorf("update: primary key is not set")
}
for _, f := range scope.PrimaryFields() {
if contains(fieldMaskPaths, f.Name) {
return NoRowsAffected, fmt.Errorf("update: not allowed on primary key field %s: %w", f.Name, ErrInvalidFieldMask)
}
}
opts := GetOpts(opt...)
withDebug := opts.withDebug
withOplog := opts.withOplog
@@ -594,3 +600,12 @@ func isNil(i interface{}) bool {
}
return false
}
func contains(ss []string, t string) bool {
for _, s := range ss {
if strings.EqualFold(s, t) {
return true
}
}
return false
}
+20
View File
@@ -117,6 +117,26 @@ func TestDb_Update(t *testing.T) {
wantEmail: "",
wantPhoneNumber: "updated" + id,
},
{
name: "primary-key",
args: args{
i: &db_test.TestUser{
StoreTestUser: &db_test.StoreTestUser{
Name: "primary-key" + id,
Email: "updated" + id,
PhoneNumber: "updated" + id,
PublicId: publicId,
CreateTime: now,
UpdateTime: now,
},
},
fieldMaskPaths: []string{"Id"},
setToNullPaths: []string{"Email"},
},
want: 0,
wantErr: true,
wantErrMsg: "update: not allowed on primary key field Id: invalid field mask",
},
{
name: "both are missing",
args: args{