GORM Playground Link
https://github.com/go-gorm/playground/pull/587
Description
From what I understand about gorm, struct fields that are equal to their zero values should be automatically omitted when inserting into a database. Specifically, if the primary key of a struct is equal to its zero value, gorm should not attempt to insert that value. This was the case prior to v1.20.4, which contains this commit, breaking the described functionality.
For example...
import "github.com/google/uuid"
type Person struct {
ID uuid.UUID
FirstName string
LastName string
}
function CreatePerson(db *gorm.DB) (Person, error) {
person := {
FirstName: "John",
LastName: "Doe",
}
tx := db.Debug().Create(&person)
// EXPECTED debug output: INSERT INTO "persons" ("first_name", "last_name") VALUES ('John', 'Doe')
// ACTUAL debug output: INSERT INTO "persons" ("id", "first_name", "last_name") VALUES ('00000000-0000-0000-0000-000000000000', 'John', 'Doe')
return person, tx.Error
}
Comment From: TheDhejavu
Hey @chad-bekmezian-snap
try this:
import "github.com/google/uuid"
type Person struct {
ID uuid.UUID
FirstName string
LastName string
}
func (p *Person) BeforeCreate(tx *gorm.DB) (err error) {
p.ID = uuid.New()
return
}
func CreatePerson(db *gorm.DB) (Person, error) {
person := {
FirstName: "John",
LastName: "Doe",
}
tx := db.Debug().Create(&person)
return person, tx.Error
}
Comment From: chad-bekmezian-snap
Hey @chad-bekmezian-snap
try this:
```go import "github.com/google/uuid"
type Person struct { ID uuid.UUID FirstName string LastName string }
func (p Person) BeforeCreate(tx gorm.DB) (err error) { p.ID = uuid.New() return }
func CreatePerson(db *gorm.DB) (Person, error) { person := { FirstName: "John", LastName: "Doe", }
tx := db.Debug().Create(&person)
return person, tx.Error } ```
That does of course work, however it does not change the fact that prior to v1.24.4 empty ids were not inserted, as is consistent with Gorm's behavior. Additionally, our enterprise database is generating the uuid, since Gorm omits the zeroed ID field--until now.
Comment From: a631807682
cc @jinzhu
Comment From: efournival
@jinzhu I'm facing this issue too, that looks like a regression. Would you accept a PR?
Comment From: manicar2093
Maybe adding test for this stage can be a useful way to avoid delete this code. 😃 I'm with the same issue 😢
Comment From: manicar2093
Hi! Sorry, is there any change attached to this issue? 😮
Comment From: martinmunillas
I'm facing this too :(
I've managed to find a workaround for now. If you tell gorm there is a default (which can be empty) it wont send the zero value
type Model struct {
ID uuid.UUID `gorm:"default:"`
}
Of course this, first, looks ugly and second, makes it prone to error and forget adding it
Comment From: martinmunillas
I just opened a PR to solve this, go give it some love https://github.com/go-gorm/gorm/pull/6970
Comment From: jinzhu
https://github.com/go-gorm/gorm/pull/6970#issuecomment-2076668010