聊聊gorm的Unscoped

本文主要研究一下gorm的Unscopedgit

Unscoped

gorm.io/gorm@v1.20.11/chainable_api.gogithub

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.goapi

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.goui

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則執行的是物理刪除。code

doc

相關文章
相關標籤/搜索