Merge branch 'go-gorm:master' into master

This commit is contained in:
piyongcai 2021-12-02 11:33:07 +08:00 committed by GitHub
commit ebe8c925d4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 39 additions and 20 deletions

View File

@ -207,7 +207,7 @@ func SaveAfterAssociations(create bool) func(db *gorm.DB) {
} }
cacheKey := utils.ToStringKey(relPrimaryValues) cacheKey := utils.ToStringKey(relPrimaryValues)
if len(relPrimaryValues) == 0 || (len(relPrimaryValues) == len(rel.FieldSchema.PrimaryFields) && !identityMap[cacheKey]) { if len(relPrimaryValues) != len(rel.FieldSchema.PrimaryFields) || !identityMap[cacheKey] {
identityMap[cacheKey] = true identityMap[cacheKey] = true
if isPtr { if isPtr {
elems = reflect.Append(elems, elem) elems = reflect.Append(elems, elem)

View File

@ -83,7 +83,7 @@ func Create(config *Config) func(db *gorm.DB) {
) )
if db.AddError(err) == nil { if db.AddError(err) == nil {
gorm.Scan(rows, db, mode) gorm.Scan(rows, db, mode)
rows.Close() db.AddError(rows.Close())
} }
return return

View File

@ -168,7 +168,7 @@ func Delete(config *Config) func(db *gorm.DB) {
if rows, err := db.Statement.ConnPool.QueryContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...); db.AddError(err) == nil { if rows, err := db.Statement.ConnPool.QueryContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...); db.AddError(err) == nil {
gorm.Scan(rows, db, mode) gorm.Scan(rows, db, mode)
rows.Close() db.AddError(rows.Close())
} }
} }
} }

View File

@ -20,9 +20,8 @@ func Query(db *gorm.DB) {
db.AddError(err) db.AddError(err)
return return
} }
defer rows.Close()
gorm.Scan(rows, db, 0) gorm.Scan(rows, db, 0)
db.AddError(rows.Close())
} }
} }
} }

View File

@ -88,7 +88,7 @@ func Update(config *Config) func(db *gorm.DB) {
db.Statement.Dest = db.Statement.ReflectValue.Addr().Interface() db.Statement.Dest = db.Statement.ReflectValue.Addr().Interface()
gorm.Scan(rows, db, mode) gorm.Scan(rows, db, mode)
db.Statement.Dest = dest db.Statement.Dest = dest
rows.Close() db.AddError(rows.Close())
} }
} else { } else {
result, err := db.Statement.ConnPool.ExecContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...) result, err := db.Statement.ConnPool.ExecContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...)

View File

@ -457,12 +457,12 @@ func (db *DB) Scan(dest interface{}) (tx *DB) {
tx.Config = &config tx.Config = &config
if rows, err := tx.Rows(); err == nil { if rows, err := tx.Rows(); err == nil {
defer rows.Close()
if rows.Next() { if rows.Next() {
tx.ScanRows(rows, dest) tx.ScanRows(rows, dest)
} else { } else {
tx.RowsAffected = 0 tx.RowsAffected = 0
} }
tx.AddError(rows.Close())
} }
currentLogger.Trace(tx.Statement.Context, newLogger.BeginAt, func() (string, int64) { currentLogger.Trace(tx.Statement.Context, newLogger.BeginAt, func() (string, int64) {

View File

@ -430,13 +430,15 @@ func (m Migrator) MigrateColumn(value interface{}, field *schema.Field, columnTy
// ColumnTypes return columnTypes []gorm.ColumnType and execErr error // ColumnTypes return columnTypes []gorm.ColumnType and execErr error
func (m Migrator) ColumnTypes(value interface{}) ([]gorm.ColumnType, error) { func (m Migrator) ColumnTypes(value interface{}) ([]gorm.ColumnType, error) {
columnTypes := make([]gorm.ColumnType, 0) columnTypes := make([]gorm.ColumnType, 0)
execErr := m.RunWithValue(value, func(stmt *gorm.Statement) error { execErr := m.RunWithValue(value, func(stmt *gorm.Statement) (err error) {
rows, err := m.DB.Session(&gorm.Session{}).Table(stmt.Table).Limit(1).Rows() rows, err := m.DB.Session(&gorm.Session{}).Table(stmt.Table).Limit(1).Rows()
if err != nil { if err != nil {
return err return err
} }
defer rows.Close() defer func() {
err = rows.Close()
}()
var rawColumnTypes []*sql.ColumnType var rawColumnTypes []*sql.ColumnType
rawColumnTypes, err = rows.ColumnTypes() rawColumnTypes, err = rows.ColumnTypes()
@ -448,7 +450,7 @@ func (m Migrator) ColumnTypes(value interface{}) ([]gorm.ColumnType, error) {
columnTypes = append(columnTypes, c) columnTypes = append(columnTypes, c)
} }
return nil return
}) })
return columnTypes, execErr return columnTypes, execErr

View File

@ -132,6 +132,13 @@ func TestBelongsToAssociation(t *testing.T) {
AssertAssociationCount(t, user2, "Company", 0, "after clear") AssertAssociationCount(t, user2, "Company", 0, "after clear")
AssertAssociationCount(t, user2, "Manager", 0, "after clear") AssertAssociationCount(t, user2, "Manager", 0, "after clear")
// unexist company id
unexistCompanyID := company.ID + 9999999
user = User{Name: "invalid-user-with-invalid-belongs-to-foreign-key", CompanyID: &unexistCompanyID}
if err := DB.Create(&user).Error; err == nil {
t.Errorf("should have gotten foreign key violation error")
}
} }
func TestBelongsToAssociationForSlice(t *testing.T) { func TestBelongsToAssociationForSlice(t *testing.T) {

View File

@ -179,12 +179,8 @@ func TestForeignKeyConstraintsBelongsTo(t *testing.T) {
func TestFullSaveAssociations(t *testing.T) { func TestFullSaveAssociations(t *testing.T) {
coupon := &Coupon{ coupon := &Coupon{
ID: "full-save-association-coupon1",
AppliesToProduct: []*CouponProduct{ AppliesToProduct: []*CouponProduct{
{ {ProductId: "full-save-association-product1"},
CouponId: "full-save-association-coupon1",
ProductId: "full-save-association-product1",
},
}, },
AmountOff: 10, AmountOff: 10,
PercentOff: 0.0, PercentOff: 0.0,
@ -198,11 +194,11 @@ func TestFullSaveAssociations(t *testing.T) {
t.Errorf("Failed, got error: %v", err) t.Errorf("Failed, got error: %v", err)
} }
if DB.First(&Coupon{}, "id = ?", "full-save-association-coupon1").Error != nil { if DB.First(&Coupon{}, "id = ?", coupon.ID).Error != nil {
t.Errorf("Failed to query saved coupon") t.Errorf("Failed to query saved coupon")
} }
if DB.First(&CouponProduct{}, "coupon_id = ? AND product_id = ?", "full-save-association-coupon1", "full-save-association-product1").Error != nil { if DB.First(&CouponProduct{}, "coupon_id = ? AND product_id = ?", coupon.ID, "full-save-association-product1").Error != nil {
t.Errorf("Failed to query saved association") t.Errorf("Failed to query saved association")
} }
@ -210,4 +206,18 @@ func TestFullSaveAssociations(t *testing.T) {
if err := DB.Create(&orders).Error; err != nil { if err := DB.Create(&orders).Error; err != nil {
t.Errorf("failed to create orders, got %v", err) t.Errorf("failed to create orders, got %v", err)
} }
coupon2 := Coupon{
AppliesToProduct: []*CouponProduct{{Desc: "coupon-description"}},
}
DB.Session(&gorm.Session{FullSaveAssociations: true}).Create(&coupon2)
var result Coupon
if err := DB.Preload("AppliesToProduct").First(&result, "id = ?", coupon2.ID).Error; err != nil {
t.Errorf("Failed to create coupon w/o name, got error: %v", err)
}
if len(result.AppliesToProduct) != 1 {
t.Errorf("Failed to preload AppliesToProduct")
}
} }

View File

@ -62,15 +62,16 @@ type Language struct {
} }
type Coupon struct { type Coupon struct {
ID string `gorm:"primarykey; size:255"` ID int `gorm:"primarykey; size:255"`
AppliesToProduct []*CouponProduct `gorm:"foreignKey:CouponId;constraint:OnDelete:CASCADE"` AppliesToProduct []*CouponProduct `gorm:"foreignKey:CouponId;constraint:OnDelete:CASCADE"`
AmountOff uint32 `gorm:"amount_off"` AmountOff uint32 `gorm:"amount_off"`
PercentOff float32 `gorm:"percent_off"` PercentOff float32 `gorm:"percent_off"`
} }
type CouponProduct struct { type CouponProduct struct {
CouponId string `gorm:"primarykey; size:255"` CouponId int `gorm:"primarykey;size:255"`
ProductId string `gorm:"primarykey;size:255"` ProductId string `gorm:"primarykey;size:255"`
Desc string
} }
type Order struct { type Order struct {