DEV Community

Yasunori Tanaka
Yasunori Tanaka

Posted on

3 2

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.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay