forked from go-gorm/gorm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
soft_delete.go
85 lines (67 loc) · 2.1 KB
/
soft_delete.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package gorm
import (
"database/sql"
"database/sql/driver"
"reflect"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
)
type DeletedAt sql.NullTime
// Scan implements the Scanner interface.
func (n *DeletedAt) Scan(value interface{}) error {
return (*sql.NullTime)(n).Scan(value)
}
// Value implements the driver Valuer interface.
func (n DeletedAt) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.Time, nil
}
func (DeletedAt) QueryClauses() []clause.Interface {
return []clause.Interface{
clause.Where{Exprs: []clause.Expression{
clause.Eq{
Column: clause.Column{Table: clause.CurrentTable, Name: "deleted_at"},
Value: nil,
},
}},
}
}
func (DeletedAt) DeleteClauses() []clause.Interface {
return []clause.Interface{SoftDeleteClause{}}
}
type SoftDeleteClause struct {
}
func (SoftDeleteClause) Name() string {
return ""
}
func (SoftDeleteClause) Build(clause.Builder) {
}
func (SoftDeleteClause) MergeClause(*clause.Clause) {
}
func (SoftDeleteClause) ModifyStatement(stmt *Statement) {
if stmt.SQL.String() == "" {
stmt.AddClause(clause.Set{{Column: clause.Column{Name: "deleted_at"}, Value: stmt.DB.NowFunc()}})
if stmt.Schema != nil {
_, queryValues := schema.GetIdentityFieldValuesMap(stmt.ReflectValue, stmt.Schema.PrimaryFields)
column, values := schema.ToQueryValues(stmt.Table, stmt.Schema.PrimaryFieldDBNames, queryValues)
if len(values) > 0 {
stmt.AddClause(clause.Where{Exprs: []clause.Expression{clause.IN{Column: column, Values: values}}})
}
if stmt.Dest != stmt.Model && stmt.Model != nil {
_, queryValues = schema.GetIdentityFieldValuesMap(reflect.ValueOf(stmt.Model), stmt.Schema.PrimaryFields)
column, values = schema.ToQueryValues(stmt.Table, stmt.Schema.PrimaryFieldDBNames, queryValues)
if len(values) > 0 {
stmt.AddClause(clause.Where{Exprs: []clause.Expression{clause.IN{Column: column, Values: values}}})
}
}
}
if _, ok := stmt.Clauses["WHERE"]; !ok {
stmt.DB.AddError(ErrMissingWhereClause)
return
}
stmt.AddClauseIfNotExists(clause.Update{})
stmt.Build("UPDATE", "SET", "WHERE")
}
}