added soft deleted
This commit is contained in:
@@ -31,7 +31,7 @@ func New[T any](client postgresql.Client, table, columns string, scan func(Scann
|
||||
}
|
||||
|
||||
func (r *Repository[T]) GetByID(ctx context.Context, id int64) (T, error) {
|
||||
row := r.client.QueryRow(ctx, `SELECT `+r.columns+` FROM `+r.table+` WHERE id = $1`, id)
|
||||
row := r.client.QueryRow(ctx, `SELECT `+r.columns+` FROM `+r.table+` WHERE id = $1 AND deleted_at IS NULL`, id)
|
||||
item, err := r.scan(row)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
var zero T
|
||||
@@ -44,11 +44,13 @@ func (r *Repository[T]) Delete(ctx context.Context, id int64) error {
|
||||
return Delete(ctx, r.client, r.table, id)
|
||||
}
|
||||
|
||||
// Delete runs the hard-delete-by-id pattern shared by every module that
|
||||
// Delete runs the soft-delete-by-id pattern shared by every module that
|
||||
// doesn't need the full Repository[T] (e.g. association tables, or entities
|
||||
// whose List/GetByID require joins genericrepo doesn't model).
|
||||
// whose List/GetByID require joins genericrepo doesn't model). Rows are never
|
||||
// hard-deleted so foreign keys pointing at them never break, and deletes are
|
||||
// recoverable.
|
||||
func Delete(ctx context.Context, client postgresql.Client, table string, id int64) error {
|
||||
tag, err := client.Exec(ctx, `DELETE FROM `+table+` WHERE id = $1`, id)
|
||||
tag, err := client.Exec(ctx, `UPDATE `+table+` SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -58,6 +60,15 @@ func Delete(ctx context.Context, client postgresql.Client, table string, id int6
|
||||
return nil
|
||||
}
|
||||
|
||||
// withDeletedAtFilter folds a mandatory "deleted_at IS NULL" condition into a
|
||||
// caller-supplied where clause (empty or starting with " WHERE ", see List).
|
||||
func withDeletedAtFilter(where string) string {
|
||||
if where == "" {
|
||||
return " WHERE deleted_at IS NULL"
|
||||
}
|
||||
return where + " AND deleted_at IS NULL"
|
||||
}
|
||||
|
||||
// List runs a paginated query. where must be empty or start with " WHERE "
|
||||
// (see province's buildListQuery for the convention); args are the
|
||||
// positional parameters referenced by where, in order. orderBy is the raw
|
||||
@@ -66,6 +77,7 @@ func (r *Repository[T]) List(ctx context.Context, where string, args []interface
|
||||
if orderBy == "" {
|
||||
orderBy = "id"
|
||||
}
|
||||
where = withDeletedAtFilter(where)
|
||||
|
||||
var count int64
|
||||
countQuery := `SELECT COUNT(*) FROM ` + r.table + where
|
||||
|
||||
Reference in New Issue
Block a user