I'm using go-gorm with a postgres 11 DB and facing an issue where I need to remove the RETURNING clause entirely when creating records (that statement seems to be included by default). I just want to insert records and get nothing back, except for errors. I have some complex relations on the database that won't support RETURNING statements, so when I try to insert like this: (made code simpler for brevity)
type Cargo struct {
Id int64 `gorm:"primaryKey"`
Name string
}
dsnString := fmt.Sprintf("host=%s ...")
db, _ := gorm.Open(postgres.New(postgres.Config{DSN: dsnString}), &gorm.Config{})
cargo := Cargo{Name: "test"}
db.Create(cargo)
I get the error "ERROR: cannot perform INSERT RETURNING on relation Cargo".
I tried creating the db connection with the parameter WithoutReturning: true:
db, _ := gorm.Open(postgres.New(postgres.Config{DSN: dsnString, , WithoutReturning: true}), &gorm.Config{})
But then when I try db.Create(cargo)
I get a different error: "LastInsertId is not supported by this driver". It seems to be still trying to get the last inserted id anyway.
In go-pg I could use db.Model(x).Returning("null").Insert(cargo)
but I couldn't find a way to do it with go-gorm. Any help is greatly appreciated.
The only two ways that I can get gorm to not use the RETURNING
clause with postgres are
That means getting rid of the field that is named ID/Id
or any tagged gorm:"primaryKey"
.
type Cargo struct {
Name string
}
db.Create(&Cargo{Name: "Test"})
Table()
In this case you would represent your model as a map[string]interface{}
instead of as a struct and use it like this:
db.Table("cargos").Create(map[string]interface{}{
"name": "Test",
})
As it stands gorm doesn't support this use case very well. If you can't restructure your views to support RETURNING and these options aren't doing it for you, I suggest adding a feature request in the gorm repo.