Skip to content

Commit 60668f8

Browse files
authored
feat(store): add a helper that marks rows as deleted (#1959)
1 parent af7634f commit 60668f8

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

‎internal/store/postgres/postgres.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,12 @@ func live(table string) exp.BooleanExpression {
2929
return goqu.I(table + ".deleted_at").IsNull()
3030
}
3131

32+
// softDelete marks rows as deleted instead of removing them. It skips rows
33+
// that are already deleted, so the first delete time is kept.
34+
func softDelete(table string) *goqu.UpdateDataset {
35+
return dialect.Update(table).Set(goqu.Record{"deleted_at": goqu.L("now()")}).Where(live(table))
36+
}
37+
3238
// fromLive reads only the rows that are not soft-deleted.
3339
func fromLive(table string) *goqu.SelectDataset {
3440
return dialect.From(table).Where(live(table))
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package postgres
2+
3+
import (
4+
"testing"
5+
6+
"github.com/doug-martin/goqu/v9"
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
func TestSoftDelete(t *testing.T) {
11+
tests := []struct {
12+
name string
13+
stmt *goqu.UpdateDataset
14+
wantSQL string
15+
wantParams []any
16+
}{
17+
{
18+
name: "marks the live rows of the table",
19+
stmt: softDelete(TABLE_DOMAINS),
20+
wantSQL: `UPDATE "domains" SET "deleted_at"=now() WHERE ("domains"."deleted_at" IS NULL)`,
21+
wantParams: []any{},
22+
},
23+
{
24+
name: "joins the caller's filter with AND",
25+
stmt: softDelete(TABLE_DOMAINS).Where(goqu.Ex{"id": "8f2d5b1e-3c4a-4d6b-9e7f-1a2b3c4d5e6f"}),
26+
wantSQL: `UPDATE "domains" SET "deleted_at"=now() WHERE (("domains"."deleted_at" IS NULL) AND ("id" = $1))`,
27+
wantParams: []any{"8f2d5b1e-3c4a-4d6b-9e7f-1a2b3c4d5e6f"},
28+
},
29+
}
30+
31+
for _, tt := range tests {
32+
t.Run(tt.name, func(t *testing.T) {
33+
gotSQL, gotParams, err := tt.stmt.Prepared(true).ToSQL()
34+
assert.NoError(t, err)
35+
assert.Equal(t, tt.wantSQL, gotSQL)
36+
assert.Equal(t, tt.wantParams, gotParams)
37+
})
38+
}
39+
}

0 commit comments

Comments
 (0)