-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.go
47 lines (40 loc) · 825 Bytes
/
update.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package db
import (
"github.com/serenize/snaker"
"github.com/uptrace/bun"
)
func UpdateDiff[T any](db *Db, prev, curr T) (columns []string, err error) {
columns = Diff(prev, curr)
if len(columns) > 0 {
for n, s := range columns {
columns[n] = snaker.CamelToSnake(s)
}
err = db.Update(&curr, func(q *bun.UpdateQuery) {
q.WherePK().Column(columns...)
})
}
return
}
type Updater[T any] struct {
db *Db
last T
}
func NewUpdater[T any](db *Db, v T) *Updater[T] {
return &Updater[T]{
db: db,
last: v,
}
}
func (o *Updater[T]) Update(v T) (columns []string, err error) {
columns, err = UpdateDiff(o.db, o.last, v)
if len(columns) > 0 && err == nil {
o.last = v
}
return
}
func (o *Updater[T]) Equal(v T) bool {
return Equal(o.last, v)
}
func (o *Updater[T]) Last() T {
return o.last
}