Updating database field to NULL in GORM using struct
Background
When I was using GORM as the ORM in Go, I discovered that we cannot update a field into NULL
with struct, even though we use a pointer as the type.
For example, if we set nil
to the Name
and execute the Updates
method in GORM, the name field won't be updated into NULL
.
type User struct {
Id int64
Name *string
Age *int32
}
Solution
We can use sql.Null*
type for the field.
For instance, we can use sql.NullString
for supporting NULL
value for the string data type. We can use sql.NullBool
for boolean.
See the complete list in this package.
Example
Suppose we want to set the name
field into NULL
. We can create the struct as follows:
type User struct {
Id int64
Name sql.NullString
Age *int32
}
And then set the Name
with:
user := User{}
// setting Valid = false for updating the value into NULL
u.Name = sql.NullString{String: "", Valid: false}
db.Update(&user)
Trade-off
We need to map the field into sql.NullString
or other nullable types before updating data to the database.