go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
37.02k stars 3.94k forks source link

the db.Save bug #7187

Closed jiaopengzi closed 2 months ago

jiaopengzi commented 2 months ago

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}
}

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.

github-actions[bot] commented 2 months ago

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.ioSearch Before Asking

jiaopengzi commented 2 months ago

After reviewing the documentation, this is the expected behavior. It is save all fields not upsert.