问题描述:
最近在使用gorm时,发现db文件在某些情况下会多出来几行重复的数据。
type Sip struct {
SipPoolID uint
Sip string `json:"-" gorm:"primary_key"`
NetSegment string `json:"-" gorm:"primary_key"`
}
使用以上结构体,通过gorm创建出来的表会出现如下情况:
诊断:
经过一番操作和观察,发现在某行数据主键为空值的时候,这行数据会重复出现。然后去看源码,发现了这么一段代码:
// Save update value in database, if the value doesn't have primary key, will insert it
func (s *DB) Save(value interface{}) *DB {
scope := s.NewScope(value)
if !scope.PrimaryKeyZero() {
newDB := scope.callCallbacks(s.parent.callbacks.updates).db
if newDB.Error == nil && newDB.RowsAffected == 0 {