DEV Community

Yasunori Tanaka
Yasunori Tanaka

Posted on

Prevent updating query updates all records in GORM

Finally, I found that prevent updating all records when I forget with a primary ID in GORM.

Sometimes, we forget primary ID for updating a record in a query. This query will occur the problem that all records in the table will be updated because the query does not specify a primary ID.

A query below will update one record with a company ID.

var db *gorm.DB
db, err = gorm.Open("mysql")

company := &Company{
   Model: gorm.Model{ID: companyID},
   Name:  request.Name,
}

_, err := db.Model(&company).Update(company)
if err != nil {
   ...
}

This query works well wholly.

In contrast, the blow query without a primary ID will update all records.

var db *gorm.DB
db, err = gorm.Open("mysql")

company := &Company{
   Name:  request.Name,
}

_, err := db.Model(&company).Update(company)
if err != nil {
   ...
}

If this code is deployed to production service with no test, I don't want to imagine that it will do to our database.

So we can prevent this behavior with func (*DB) BlockGlobalUpdate.

var db *gorm.DB
db, err = gorm.Open("mysql")

db.BlockGlobalUpdate(true)
...

Again, the same query with not primary ID.

company := &Company{
   Name:  request.Name,
}

_, err := db.Model(&company).Update(company)

If we forget primary ID like that, we will get an error from GORM like below.

2020-08-03T07:45:14.011Z  ERROR  logger/logger.go:58  missing WHERE clause while updating

BlockGlobalUpdate() can prevent updating all records in a table.

Wrapping up, we should use BlockGlobalUpdate() when we create a gorm DB instance. Otherwise, someday your query could destroy your user's data entirely.

Top comments (0)