If for whatever readon my someModel is not found in my first query below, the delete statement then deletes the entire table.
delete from somemodels
What is the best way to prevent this?
someModel := &SomeModel{}
db.Where("some_id = ? and other_id = ?", someModel.UserId, someModel.Id).First(&someModel)
db.Delete(&someModel)
Currently I am not checking if the model actually was found and returned from the database, and I know I should be checking but what is the best way to do this?
Just check if it is not nil? model.Id > 0 ?
According to the doc, you need to check whether the primary id is blank. I'm not sure what your model looks like but I guess you should check modle.ID
is not blank.
As you have surmised, it deletes the entire table because the record was not found, i.e. there is nothing in the model that it can use as a criteria, and therefore leaves the criteria blank and removes the entire table.
You can check if the record was found, without checking the model itself.
For instance:
if !db.Where("some_id = ? and other_id = ?", someModel.UserId, someModel.Id).First(&someModel).RecordNotFound {
db.Delete(&someModel)
}
if err := db.Where("some_id = ? and other_id = ?", someModel.UserId, someModel.Id).First(&someModel).Error; err != nil {
if gorm.IsRecordNotFoundError(err) {
// record not found
} else {
// something else went wrong
}
} else {
db.Delete(&someModel)
}