AlesKas
AlesKas

Reputation: 91

GORM: upsert not inserting proper values

I am trying to find a way to UPSERT some values but I got some unexpected behavior. For example:

db.Clauses(clause.OnConflict{
    Columns:   []clause.Column{{Name: "name"}},
    DoUpdates: clause.AssignmentColumns([]string{"name", "email"}),
})

Returns

ON CONFLICT (name) DO UPDATE SET name = {excluded name %!s(bool=false)}, email = {excluded email %!s(bool=false)} RETURNING *

, which doesn't seems right.

I also tried building a map of names and expressions:

values := map[email:excluded.email name:excluded.name col3:table.col3+excluded.col3]

db.Clauses(clause.OnConflict{
    Columns:   []clause.Column{{Name: "name"}},
    DoUpdates: clause.Assignments(values),
})

Which generates

DO UPDATE SET "email"='excluded.email',"name"='excluded.name'

but I expect

DO UPDATE SET "email"="excluded.email","name"="excluded.name"

Gorm version: v1.20.6

Golang version: 1.12

Postgres 12

Upvotes: 2

Views: 5194

Answers (1)

appaquet
appaquet

Reputation: 94

Just ran into a similar issue where GORM wasn't updating the data of an associated table when upserting a model referencing this association (ex: upsert on a user table with an associated bill model where the bill data has changed and was expected to be save along the user's save).

It turns out GORM only updates fields that are making the association / foreign key, not the actual data. You need to turn on FullSaveAssociations session option in order to update all the fields. (see https://gorm.io/docs/session.html#FullSaveAssociations and https://github.com/go-gorm/gorm/issues/3506)

Upvotes: 3

Related Questions