Pg: Soft deletion

Created on 30 Dec 2017  路  5Comments  路  Source: go-pg/pg

Soft deletion was mentioned in #276.
Paranoid queries would be a really useful addition. Wondering whether someone is already working on a pull request.

Most helpful comment

tenor

All 5 comments

IMO go-pg should not couple with specific field of client code, eg. deleted_at or is_deleted.

And it's easy to implement it in client code:

type Base struct {
    DeletedAt *time.Time
}

func (b *Base) SoftDelete() {
    now := time.Now()
    b.DeletedAt = &now
}

func (b *Base) Undelete() {
    b.DeletedAt = nil
}

type User struct {
    Base
    ID       int
    Username string
}

tenor

I actually built this into my wrapper for pg-go since GORM had this. Put this into your model.go and just call it for deleting

func Delete(m Model, id int64) error {
    Read(m, id)
    deleted_at := time.Now()
    _, err := dbwrapper.DB().Model(m).Set("deleted_at = ?", deleted_at).Where("id = ?", id).Update(&deleted_at)
    return err
}

Also I should mention GORM checks to see if you have a deleted_at column. If not then it does a hard delete. So we could have both here.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bobobo1618 picture bobobo1618  路  3Comments

eicca picture eicca  路  3Comments

jayschwa picture jayschwa  路  4Comments

m-kad picture m-kad  路  3Comments

Labutin picture Labutin  路  3Comments