hello
package main
import (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func main() {
// TestTable
type TestTable struct {
gorm.Model
Field1 uint64 `gorm:"column:field1;type:bigint"`
Field2 string `gorm:"column:field2;type:varchar(255)"`
}
// change to your database information
dsn := "host=10.10.10.109 user=uroot password=123456 dbname=db_blog port=5432"
// Connect to the database
db, _ := gorm.Open(postgres.New(postgres.Config{DSN: dsn}))
// Execute migration
_ = db.AutoMigrate(&TestTable{})
v1 := TestTable{
Model: gorm.Model{
ID: 1,
},
Field1: 1,
Field2: "test1",
}
// First db.Save
db.Save(&v1)
// Retrieve data with Field1: 1
var result1 TestTable
db.Where("id = ?", 1).First(&result1)
fmt.Printf("result1:%v\n", result1)
// result1:{{1 2024-09-10 09:35:10.785883 +0800 CST 2024-09-10 09:35:10.78346 +0800 CST {0001-01-01 00:00:00 +0000 UTC false}} 1 test1}
v2 := TestTable{
Model: gorm.Model{
ID: 1,
},
Field1: 2,
Field2: "test2",
}
// Second db.Save
db.Save(&v2)
// Retrieve data with Field1: 1 again
var result2 TestTable
db.Where("id = ?", 1).First(&result2)
fmt.Printf("result2:%v\n", result2)
//result2:{{1 0001-01-01 08:00:00 +0800 CST 2024-09-10 09:35:10.808792 +0800 CST {0001-01-01 00:00:00 +0000 UTC false}} 2 test2}
}
- go version go1.23.0 windows/amd64
- gorm.io/driver/postgres v1.5.9
- gorm.io/gorm v1.25.11
- postgres:16.3
In the above code, when using db.Save, if there is a created_at field, it is only correct during the first execution of the upsert. Subsequent executions of db.Save will use the zero value to overwrite created_at. I believe this is a bug.
Comment From: github-actions[bot]
The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking ✨
Comment From: jiaopengzi
After reviewing the documentation, this is the expected behavior. It is save all fields not upsert.