|
| 1 | +package types |
| 2 | + |
| 3 | +import ( |
| 4 | + "database/sql" |
| 5 | + "database/sql/driver" |
| 6 | + "encoding/json" |
| 7 | + "reflect" |
| 8 | + "time" |
| 9 | + |
| 10 | + "gorm.io/gorm" |
| 11 | + "gorm.io/gorm/clause" |
| 12 | + "gorm.io/gorm/schema" |
| 13 | +) |
| 14 | + |
| 15 | +// SoftDeletedAt is a nullable time type used as the DeletedAt field in |
| 16 | +// types.SoftDelete. It implements GORM's QueryClauses, UpdateClauses, and |
| 17 | +// DeleteClauses interfaces so that: |
| 18 | +// |
| 19 | +// - SELECT/UPDATE queries automatically gain WHERE deleted_at IS NULL. |
| 20 | +// - db.Delete() is converted to UPDATE SET deleted_at=NOW(), deleted=1 |
| 21 | +// instead of issuing a hard DELETE. |
| 22 | +// |
| 23 | +// Use db.Unscoped() to bypass the filter and see or hard-delete records. |
| 24 | +type SoftDeletedAt sql.NullTime |
| 25 | + |
| 26 | +// Scan implements the sql.Scanner interface. |
| 27 | +func (n *SoftDeletedAt) Scan(value interface{}) error { |
| 28 | + return (*sql.NullTime)(n).Scan(value) |
| 29 | +} |
| 30 | + |
| 31 | +// Value implements the driver.Valuer interface. |
| 32 | +func (n SoftDeletedAt) Value() (driver.Value, error) { |
| 33 | + if !n.Valid { |
| 34 | + return nil, nil |
| 35 | + } |
| 36 | + return n.Time, nil |
| 37 | +} |
| 38 | + |
| 39 | +// MarshalJSON implements json.Marshaler. |
| 40 | +func (n SoftDeletedAt) MarshalJSON() ([]byte, error) { |
| 41 | + if n.Valid { |
| 42 | + return json.Marshal(n.Time) |
| 43 | + } |
| 44 | + return json.Marshal(nil) |
| 45 | +} |
| 46 | + |
| 47 | +// UnmarshalJSON implements json.Unmarshaler. |
| 48 | +func (n *SoftDeletedAt) UnmarshalJSON(b []byte) error { |
| 49 | + if string(b) == "null" { |
| 50 | + n.Valid = false |
| 51 | + return nil |
| 52 | + } |
| 53 | + err := json.Unmarshal(b, &n.Time) |
| 54 | + if err == nil { |
| 55 | + n.Valid = true |
| 56 | + } |
| 57 | + return err |
| 58 | +} |
| 59 | + |
| 60 | +// GormDataType returns the GORM column data type. |
| 61 | +func (SoftDeletedAt) GormDataType() string { |
| 62 | + return "datetime" |
| 63 | +} |
| 64 | + |
| 65 | +// QueryClauses implements schema.QueryClausesInterface. |
| 66 | +// GORM calls this during schema parsing and registers the returned clauses |
| 67 | +// so that all SELECT statements gain WHERE deleted_at IS NULL automatically. |
| 68 | +func (SoftDeletedAt) QueryClauses(f *schema.Field) []clause.Interface { |
| 69 | + return []clause.Interface{softDeleteQueryClause{Field: f}} |
| 70 | +} |
| 71 | + |
| 72 | +// UpdateClauses implements schema.UpdateClausesInterface. |
| 73 | +// Ensures the WHERE deleted_at IS NULL filter is also applied on UPDATE. |
| 74 | +func (SoftDeletedAt) UpdateClauses(f *schema.Field) []clause.Interface { |
| 75 | + return []clause.Interface{softDeleteUpdateClause{Field: f}} |
| 76 | +} |
| 77 | + |
| 78 | +// DeleteClauses implements schema.DeleteClausesInterface. |
| 79 | +// Converts DELETE into UPDATE SET deleted_at=NOW(), deleted=1. |
| 80 | +func (SoftDeletedAt) DeleteClauses(f *schema.Field) []clause.Interface { |
| 81 | + return []clause.Interface{softDeleteDeleteClause{Field: f}} |
| 82 | +} |
| 83 | + |
| 84 | +// NullTime returns the underlying sql.NullTime. |
| 85 | +func (n SoftDeletedAt) NullTime() sql.NullTime { |
| 86 | + return sql.NullTime(n) |
| 87 | +} |
| 88 | + |
| 89 | +// TimeValue returns the time.Time value and whether it is valid (non-NULL). |
| 90 | +func (n SoftDeletedAt) TimeValue() (time.Time, bool) { |
| 91 | + return n.Time, n.Valid |
| 92 | +} |
| 93 | + |
| 94 | +// ---- query clause ------------------------------------------------------- |
| 95 | + |
| 96 | +type softDeleteQueryClause struct { |
| 97 | + Field *schema.Field |
| 98 | +} |
| 99 | + |
| 100 | +func (softDeleteQueryClause) Name() string { return "" } |
| 101 | +func (softDeleteQueryClause) Build(clause.Builder) {} |
| 102 | +func (softDeleteQueryClause) MergeClause(*clause.Clause) {} |
| 103 | + |
| 104 | +func (sd softDeleteQueryClause) ModifyStatement(stmt *gorm.Statement) { |
| 105 | + if _, ok := stmt.Clauses["soft_delete_enabled"]; ok || stmt.Statement.Unscoped { |
| 106 | + return |
| 107 | + } |
| 108 | + |
| 109 | + // Wrap existing OR conditions in AND to avoid logic errors when combined |
| 110 | + // with the soft-delete predicate (mirrors gorm.SoftDeleteQueryClause). |
| 111 | + if c, ok := stmt.Clauses["WHERE"]; ok { |
| 112 | + if where, ok := c.Expression.(clause.Where); ok && len(where.Exprs) >= 1 { |
| 113 | + for _, expr := range where.Exprs { |
| 114 | + if orCond, ok := expr.(clause.OrConditions); ok && len(orCond.Exprs) == 1 { |
| 115 | + where.Exprs = []clause.Expression{clause.And(where.Exprs...)} |
| 116 | + c.Expression = where |
| 117 | + stmt.Clauses["WHERE"] = c |
| 118 | + break |
| 119 | + } |
| 120 | + } |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + stmt.AddClause(clause.Where{Exprs: []clause.Expression{ |
| 125 | + clause.Eq{Column: clause.Column{Table: clause.CurrentTable, Name: sd.Field.DBName}, Value: nil}, |
| 126 | + }}) |
| 127 | + stmt.Clauses["soft_delete_enabled"] = clause.Clause{} |
| 128 | +} |
| 129 | + |
| 130 | +// ---- update clause ------------------------------------------------------- |
| 131 | + |
| 132 | +type softDeleteUpdateClause struct { |
| 133 | + Field *schema.Field |
| 134 | +} |
| 135 | + |
| 136 | +func (softDeleteUpdateClause) Name() string { return "" } |
| 137 | +func (softDeleteUpdateClause) Build(clause.Builder) {} |
| 138 | +func (softDeleteUpdateClause) MergeClause(*clause.Clause) {} |
| 139 | + |
| 140 | +func (sd softDeleteUpdateClause) ModifyStatement(stmt *gorm.Statement) { |
| 141 | + if stmt.SQL.Len() == 0 && !stmt.Statement.Unscoped { |
| 142 | + softDeleteQueryClause{Field: sd.Field}.ModifyStatement(stmt) |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +// ---- delete clause ------------------------------------------------------- |
| 147 | + |
| 148 | +type softDeleteDeleteClause struct { |
| 149 | + Field *schema.Field |
| 150 | +} |
| 151 | + |
| 152 | +func (softDeleteDeleteClause) Name() string { return "" } |
| 153 | +func (softDeleteDeleteClause) Build(clause.Builder) {} |
| 154 | +func (softDeleteDeleteClause) MergeClause(*clause.Clause) {} |
| 155 | + |
| 156 | +func (sd softDeleteDeleteClause) ModifyStatement(stmt *gorm.Statement) { |
| 157 | + if stmt.SQL.Len() != 0 || stmt.Statement.Unscoped { |
| 158 | + return |
| 159 | + } |
| 160 | + |
| 161 | + curTime := stmt.DB.NowFunc() |
| 162 | + nowSDA := SoftDeletedAt{Valid: true, Time: curTime} |
| 163 | + |
| 164 | + // Build a single SET clause with both assignments. |
| 165 | + // NOTE: In GORM v1.30+ clause.Set.MergeClause replaces rather than |
| 166 | + // appends, so we must pass both assignments in one AddClause call. |
| 167 | + set := clause.Set{{Column: clause.Column{Name: sd.Field.DBName}, Value: nowSDA}} |
| 168 | + if deletedField := sd.Field.Schema.LookUpField("Deleted"); deletedField != nil { |
| 169 | + set = append(set, clause.Assignment{Column: clause.Column{Name: deletedField.DBName}, Value: true}) |
| 170 | + stmt.SetColumn(deletedField.DBName, true, true) |
| 171 | + } |
| 172 | + stmt.AddClause(set) |
| 173 | + stmt.SetColumn(sd.Field.DBName, nowSDA, true) |
| 174 | + |
| 175 | + if stmt.Schema != nil { |
| 176 | + _, queryValues := schema.GetIdentityFieldValuesMap(stmt.Context, stmt.ReflectValue, stmt.Schema.PrimaryFields) |
| 177 | + column, values := schema.ToQueryValues(stmt.Table, stmt.Schema.PrimaryFieldDBNames, queryValues) |
| 178 | + |
| 179 | + if len(values) > 0 { |
| 180 | + stmt.AddClause(clause.Where{Exprs: []clause.Expression{clause.IN{Column: column, Values: values}}}) |
| 181 | + } |
| 182 | + |
| 183 | + if stmt.ReflectValue.CanAddr() && stmt.Dest != stmt.Model && stmt.Model != nil { |
| 184 | + _, queryValues = schema.GetIdentityFieldValuesMap(stmt.Context, reflect.ValueOf(stmt.Model), stmt.Schema.PrimaryFields) |
| 185 | + column, values = schema.ToQueryValues(stmt.Table, stmt.Schema.PrimaryFieldDBNames, queryValues) |
| 186 | + |
| 187 | + if len(values) > 0 { |
| 188 | + stmt.AddClause(clause.Where{Exprs: []clause.Expression{clause.IN{Column: column, Values: values}}}) |
| 189 | + } |
| 190 | + } |
| 191 | + } |
| 192 | + |
| 193 | + softDeleteQueryClause{Field: sd.Field}.ModifyStatement(stmt) |
| 194 | + stmt.AddClauseIfNotExists(clause.Update{}) |
| 195 | + stmt.Build(stmt.DB.Callback().Update().Clauses...) |
| 196 | +} |
0 commit comments