序
本文主要研究一下gorm的Unscoped
Unscoped
gorm.io/gorm@v1.20.11/chainable_api.go
func (db *DB) Unscoped() (tx *DB) {
tx = db.getInstance()
tx.Statement.Unscoped = true
return
}
Unscoped方法设置tx.Statement.Unscoped为true
Delete
gorm.io/gorm@v1.20.11/callbacks/delete.go
func Delete(db *gorm.DB) {
if db.Error == nil {
if db.Statement.Schema != nil && !db.Statement.Unscoped {
for _, c := range db.Statement.Schema.DeleteClauses {
db.Statement.AddClause(c)
}
}
if db.Statement.SQL.String() == "" {
db.Statement.SQL.Grow(100)
db.Statement.AddClauseIfNotExists(clause.Delete{})
if db.Statement.Schema != nil {
_, queryValues := schema.GetIdentityFieldValuesMap(db.Statement.ReflectValue, db.Statement.Schema.PrimaryFields)
column, values := schema.ToQueryValues(db.Statement.Table, db.Statement.Schema.PrimaryFieldDBNames, queryValues)
if len(values) > 0 {
db.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.IN{Column: column, Values: values}}})
}
if db.Statement.ReflectValue.CanAddr() && db.Statement.Dest != db.Statement.Model && db.Statement.Model != nil {
_, queryValues = schema.GetIdentityFieldValuesMap(reflect.ValueOf(db.Statement.Model), db.Statement.Schema.PrimaryFields)
column, values = schema.ToQueryValues(db.Statement.Table, db.Statement.Schema.PrimaryFieldDBNames, queryValues)
if len(values) > 0 {
db.Statement.AddClause(clause.Where{Exprs: []clause.Expression{clause.IN{Column: column, Values: values}}})
}
}
}
db.Statement.AddClauseIfNotExists(clause.From{})
db.Statement.Build("DELETE", "FROM", "WHERE")
}
if _, ok := db.Statement.Clauses["WHERE"]; !db.AllowGlobalUpdate && !ok && db.Error == nil {
db.AddError(gorm.ErrMissingWhereClause)
return
}
if !db.DryRun && db.Error == nil {
result, err := db.Statement.ConnPool.ExecContext(db.Statement.Context, db.Statement.SQL.String(), db.Statement.Vars...)
if err == nil {
db.RowsAffected, _ = result.RowsAffected()
} else {
db.AddError(err)
}
}
}
}
callbacks的Delete方法在db.Statement.Unscoped为false的时候才追加db.Statement.Schema.DeleteClauses
DeleteClauses
gorm.io/gorm@v1.20.11/soft_delete.go
func (DeletedAt) DeleteClauses(f *schema.Field) []clause.Interface {
return []clause.Interface{SoftDeleteDeleteClause{Field: f}}
}
针对带有DeletedAt会执行软删除,其db.Statement.Schema.DeleteClauses为SoftDeleteDeleteClause,即设置deleted_at为指定的时间戳
实例
type DemoEntity struct {
gorm.Model
Name string `gorm:"column:name"`
}
func unscopedDemo(db *gorm.DB) {
if err := db.Debug().Unscoped().Where("id = ?", 5).Delete(&DemoEntity{}).Error; err != nil {
panic(err)
}
}
小结
gorm的Unscoped方法设置tx.Statement.Unscoped为true;针对软删除会追加SoftDeleteDeleteClause,即设置deleted_at为指定的时间戳;而callbacks的Delete方法在db.Statement.Unscoped为false的时候才追加db.Statement.Schema.DeleteClauses,而Unscoped则执行的是物理删除。