'Is there a way to remove the RETURNING clause while creating records with go-gorm?
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.
Solution 1:[1]
The only two ways that I can get gorm to not use the RETURNING clause with postgres are
A model that does not declare a primary key
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"})
Using Create from map with 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.
Solution 2:[2]
You can modify the default returning behavior with
db.Clauses(clause.Returning{}).Create(&cargo)
Here the doc link: https://gorm.io/docs/update.html#Returning-Data-From-Modified-Rows
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ezequiel Muns |
| Solution 2 | Pioz |
