关于golang:聊聊gorm的Unscoped

33次阅读

共计 2502 个字符,预计需要花费 7 分钟才能阅读完成。

本文次要钻研一下 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 则执行的是物理删除。

doc

  • gorm

正文完
 0