Soft delete
Embed fusion.DeletedAt to hide deleted rows, restore them, or bypass the machinery with Unscoped.
Soft delete turns Delete into an UPDATE of a timestamp column and hides
rows whose column is set. The whole feature is driven by one field type:
fusion.DeletedAt.
The type
// DeletedAt is a nullable soft-delete timestamp. Its zero value means the row
// is live; Value renders it as NULL so the default query condition is
// "deleted_at IS NULL".type DeletedAt struct {
Time time.Time
Valid bool
}DeletedAt implements driver.Valuer and sql.Scanner (soft_delete.go:24,
soft_delete.go:32). The zero value — Valid == false — is written as
NULL, which is what makes the default query condition work:
... WHERE "deleted_at" IS NULLA deleted row has Valid == true and renders its timestamp.
Embed it in a model
Add a DeletedAt field — the base models already carry one:
type Model struct {
ID uint64 `fusion:"pk,autoincrement"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt DeletedAt `fusion:"index"`
}Or declare it yourself:
type softUser struct {
ID int64 `fusion:"pk,autoincrement"`
Name string
DeletedAt DeletedAt
}The schema layer detects the field type at parse time and records it as the table's soft-delete field. No other wiring is needed.
What changes
Delete becomes an UPDATE
rewriteSoftDelete removes the delete clause and adds an UPDATE that
sets the soft-delete column (soft_delete.go:191). For a DeletedAt field the
written value is the session's NowFunc() timestamp:
user := exampleSoftUser{Name: "Ada"}
db.Create(&user)
db.Delete(&exampleSoftUser{}, user.ID)UPDATE "example_soft_users" SET "deleted_at" = ? WHERE "id" = ? AND "deleted_at" IS NULLEvery read and count gains the live-row filter
Query builders inject the predicate through injectSoftDeleteFilter
(soft_delete.go:135). The filter is appended as an AND condition, and the
injection is idempotent — a condition that already carries the same
expression is not duplicated (soft_delete.go:145).
The filter is ANDed across OR groups
A top-level OR in your conditions would bind tighter than the appended
AND — "a OR b AND deleted_at IS NULL" — letting deleted rows back in.
The injection regroups caller conditions first, so the predicate renders
"(a OR b) AND deleted_at IS NULL" (soft_delete.go:148-166):
// A top-level OR in the caller's conditions would bind tighter than the
// appended AND ("a OR b AND deleted_at IS NULL"), letting deleted rows
// back in — regroup everything so it renders "(a OR b) AND deleted...".Unscoped
Unscoped is a chainable that sets the fusion:unscoped statement setting
(chainable_api.go:80). With it set, the live-row filter is not injected and
Delete stays a real DELETE (soft_delete.go:136, soft_delete.go:192). It
also applies to relation preloads issued from the chain.
var hidden softUser
if err := db.Unscoped().First(&hidden, all[0].ID).Error; err != nil {
t.Fatalf("Unscoped First: %v", err)
}
if !hidden.DeletedAt.Valid {
t.Error("deleted_at not populated")
}Unscoped().First returns the deleted row with DeletedAt.Valid == true —
the timestamp came back from the scan.
Counts agree with finds
Count goes through the same builder, so a scoped count and a scoped
Find always see the same rows. Unscoped().Model(...).Count(&n) counts
deleted rows too.
Restore
Restore(value) undeletes rows matched by primary key: it chains an
Unscoped session, finds each row by PK, and updates the soft-delete column
back to its zero value (soft_delete.go:227). For a DeletedAt field the
zero value is NULL.
if err := db.Restore(&softUser{ID: all[0].ID}).Error; err != nil {
t.Fatalf("Restore: %v", err)
}Restore errors with ErrInvalidValue when the model has no soft-delete
field or no primary key (soft_delete.go:237, soft_delete.go:247).
Custom zero and delete values
You do not have to use a timestamp. Any field can be the soft-delete column
if it carries the softdelete tag; zerovalue sets the "live" value and
deletevalue the "deleted" value. A boolean flag is the common shape:
type softFlag struct {
ID int64 `fusion:"pk,autoincrement"`
Name string
Removed bool `fusion:"softdelete,zerovalue:false,deletevalue:true"`
}With this model, Delete writes removed = true and queries filter on
removed = false — a live-row condition of = ? instead of IS NULL
(soft_delete.go:91). Deleting works exactly like the timestamp version:
db.Delete(&softFlag{}, 1)
// scoped Count sees 0 rows; Unscoped count sees 1Values are parsed to the field's kind — bool, integer, unsigned, or float —
and fall back to the raw string (soft_delete.go:63). For untagged fields the
defaults by kind are: bool true, integers 1, strings "deleted", and
anything else the session's NowFunc() (soft_delete.go:103).
The full round trip
db.Model(&softUser{}).Find(&all) // 2 live rows
db.Delete(&softUser{}, all[0].ID) // UPDATE ... SET deleted_at
db.Model(&softUser{}).Find(&live) // 1 row; the deleted one is hidden
db.Unscoped().First(&hidden, all[0].ID) // 1 row; DeletedAt.Valid == true
db.Restore(&softUser{ID: all[0].ID}) // back to 2 live rowsEnd to end
func ExampleDB_Unscoped() {
e := newExample()
defer e.close()
exampleMust(e.AutoMigrateExample(&exampleSoftUser{}))
user := exampleSoftUser{Name: "Ada"}
exampleMust(e.session.Create(&user).Error)
exampleMust(e.session.Delete(&exampleSoftUser{}, user.ID).Error)
var visible, all int64
exampleMust(e.session.Model(&exampleSoftUser{}).Count(&visible).Error)
exampleMust(e.session.Unscoped().Model(&exampleSoftUser{}).Count(&all).Error)
fmt.Println(visible, all)
// Output: 0 1
}The executed statements, in order:
UPDATE "example_soft_users" SET "deleted_at" = ? WHERE "id" = ? AND "deleted_at" IS NULLSELECT count(*) FROM "example_soft_users" WHERE "deleted_at" IS NULL