Search code examples
postgresqlgoormgo-pg

go-pg, UpdateNotZero does not update nullable fields by design, how to do?


I'm having hard time trying to understand how to nullish a model field using go-pg and UpdateNotZero().

Example:

type Player struct {
  ID            int
  CreatedAt     time.Time `pg:"default:now(),notnull"`
  UpdatedAt     time.Time
  AccountID     *int
}

Let's say I have this player now:

+----+------------+------------+------------+
| ID | created_at | updated_at | account_id |
+----+------------+------------+------------+
|  1 | 2020-06-16 | NULL       |         12 |
+----+------------+------------+------------+

in my GO code I need to "remove" AccountID, I need to nullish it: from 12 to NULL.

If I use update() like this:

...
player.AccountID = nil
_, err := db.Model(player).WherePK().Update()

it gives me the error:

ERROR #23502 null value in column \"created_at\" violates not-null constraint"

If I use UpdateNotZero() like this:

...
player.AccountID = nil
_, err := db.Model(player).WherePK().UpdateNotZero()

it doesn't update AccountID at all.

How to do?


Related issues I think:


Solution

  • Limit the update to only the field you are trying to change:

    _, err := db.Model(player).WherePK().Set("account_id = NULL").Update()