/
base.go
116 lines (96 loc) · 2.16 KB
/
base.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package postgres
import (
"context"
"database/sql"
"github.com/friendsofgo/errors"
"github.com/mr-linch/go-tg-bot/internal/store"
"github.com/mr-linch/go-tg-bot/internal/store/postgres/shared"
"github.com/volatiletech/sqlboiler/v4/boil"
)
// baseStore define base store
type baseStore struct {
*sql.DB
store.Txier
}
func (bs *baseStore) getExecutor(ctx context.Context) boil.ContextExecutor {
return shared.GetExecutorOrDefault(ctx, bs)
}
// type deletableRow interface {
// Delete(
// ctx context.Context,
// exec boil.ContextExecutor,
// ) (int64, error)
// }
// func (bs *BaseStore) deleteOne(
// ctx context.Context,
// row deletableRow,
// notFoundErr error,
// ) error {
// return bs.Txier(ctx, func(ctx context.Context) error {
// count, err := row.Delete(
// ctx,
// bs.getExecutor(ctx),
// )
// if err != nil {
// return errors.Wrap(err, "exec")
// }
// switch {
// case count == 0:
// return notFoundErr
// case count > 1:
// return store.ErrTooManyAffectedRows
// }
// return nil
// })
// }
type updatetableRow interface {
Update(
ctx context.Context,
exec boil.ContextExecutor,
columns boil.Columns,
) (int64, error)
}
type insertableRow interface {
Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error
}
func (bs *baseStore) insertOne(
ctx context.Context,
row insertableRow,
) error {
return row.Insert(ctx, bs.getExecutor(ctx), boil.Infer())
}
func (bs *baseStore) updateOne(
ctx context.Context,
row updatetableRow,
notFoundErr error,
fields ...string,
) error {
return bs.Txier(ctx, func(ctx context.Context) error {
columns := boil.Infer()
if len(fields) > 0 {
columns = boil.Whitelist(fields...)
}
count, err := row.Update(
ctx,
bs.getExecutor(ctx),
columns,
)
if err != nil {
return errors.Wrap(err, "exec")
}
switch {
case count == 0:
return notFoundErr
case count > 1:
return store.ErrTooManyAffectedRows
}
return nil
})
}
// func isPostgresErrorConstraint(err error, constraint string) bool {
// var pqErr *pq.Error
// if errors.As(err, &pqErr) {
// return pqErr.Constraint == constraint
// }
// return false
// }