add restore api

This commit is contained in:
fuzengyao 2021-08-13 16:00:00 +08:00
parent 8c146f8981
commit a0d19fc26d
3 changed files with 21 additions and 6 deletions

View File

@ -641,13 +641,13 @@ func (db *DB) Restore(values interface{}) (tx *DB) {
tx.Statement.Unscoped = true
tx.Statement.Parse(values)
dest := make(map[string]interface{})
for _, c := range tx.Statement.Schema.DeleteClauses {
fieldName := c.(SoftDeleteDeleteClause).Field.DBName
dest[fieldName] = nil
}
tx.Statement.Dest = make(map[string]interface{})
tx.Statement.Dest = dest
for _, c := range tx.Statement.Schema.DeleteClauses {
if optimizer, ok := c.(UnDeleteDester); ok {
optimizer.SetUnDeleteDest(tx.Statement)
}
}
return tx.callbacks.Update().Execute(tx)
}

View File

@ -162,3 +162,13 @@ func (sd SoftDeleteDeleteClause) ModifyStatement(stmt *Statement) {
stmt.Build("UPDATE", "SET", "WHERE")
}
}
func (sd SoftDeleteDeleteClause) SetUnDeleteDest(stmt *Statement) {
if stmt.Unscoped {
if sd.Field.DefaultValue != "" {
stmt.SetColumn(sd.Field.DBName, clause.Expr{SQL: sd.Field.DefaultValue}, true)
} else {
stmt.SetColumn(sd.Field.DBName, nil, true)
}
}
}

View File

@ -57,6 +57,11 @@ type StatementModifier interface {
ModifyStatement(*Statement)
}
// UnDeleteDester set undelete dest interface
type UnDeleteDester interface {
SetUnDeleteDest(*Statement)
}
// WriteString write string
func (stmt *Statement) WriteString(str string) (int, error) {
return stmt.SQL.WriteString(str)