-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
241 lines (200 loc) · 6.07 KB
/
database.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Package database provides support for access the database.
package database
import (
"context"
"errors"
"fmt"
"github.com/fadhilijuma/images/foundation/web"
"net/url"
"strings"
"time"
"github.com/jmoiron/sqlx"
"github.com/lib/pq" // Calls init function.
"go.uber.org/zap"
)
// lib/pq errorCodeNames
// https://github.com/lib/pq/blob/master/error.go#L178
const uniqueViolation = "23505"
// Set of error variables for CRUD operations.
var (
ErrDBNotFound = errors.New("not found")
ErrDBDuplicatedEntry = errors.New("duplicated entry")
)
// Config is the required properties to use the database.
type Config struct {
User string
Password string
Host string
Name string
MaxIdleConns int
MaxOpenConns int
DisableTLS bool
}
// Open knows how to open a database connection based on the configuration.
func Open(cfg Config) (*sqlx.DB, error) {
sslMode := "require"
if cfg.DisableTLS {
sslMode = "disable"
}
q := make(url.Values)
q.Set("sslmode", sslMode)
q.Set("timezone", "utc")
u := url.URL{
Scheme: "postgres",
User: url.UserPassword(cfg.User, cfg.Password),
Host: cfg.Host,
Path: cfg.Name,
RawQuery: q.Encode(),
}
db, err := sqlx.Open("postgres", u.String())
if err != nil {
return nil, err
}
db.SetMaxIdleConns(cfg.MaxIdleConns)
db.SetMaxOpenConns(cfg.MaxOpenConns)
return db, nil
}
// StatusCheck returns nil if it can successfully talk to the database. It
// returns a non-nil error otherwise.
func StatusCheck(ctx context.Context, db *sqlx.DB) error {
// First check we can ping the database.
var pingError error
for attempts := 1; ; attempts++ {
pingError = db.Ping()
if pingError == nil {
break
}
time.Sleep(time.Duration(attempts) * 100 * time.Millisecond)
if ctx.Err() != nil {
return ctx.Err()
}
}
// Make sure we didn't timeout or be cancelled.
if ctx.Err() != nil {
return ctx.Err()
}
// Run a simple query to determine connectivity. Running this query forces a
// round trip through the database.
const q = `SELECT true`
var tmp bool
return db.QueryRowContext(ctx, q).Scan(&tmp)
}
// Transactor interface needed to begin transaction.
type Transactor interface {
Beginx() (*sqlx.Tx, error)
}
// WithinTran runs passed function and do commit/rollback at the end.
func WithinTran(ctx context.Context, log *zap.SugaredLogger, db Transactor, fn func(sqlx.ExtContext) error) error {
traceID := web.GetTraceID(ctx)
// Begin the transaction.
log.Infow("begin tran", "traceid", traceID)
tx, err := db.Beginx()
if err != nil {
return fmt.Errorf("begin tran: %w", err)
}
// Mark to the defer function a rollback is required.
mustRollback := true
// Set up a defer function for rolling back the transaction. If
// mustRollback is true it means the call to fn failed, and we
// need to roll back the transaction.
defer func() {
if mustRollback {
log.Infow("rollback tran", "traceid", traceID)
if err := tx.Rollback(); err != nil {
log.Errorw("unable to rollback tran", "traceid", traceID, "ERROR", err)
}
}
}()
// Execute the code inside the transaction. If the function
// fails, return the error and the defer function will roll back.
if err := fn(tx); err != nil {
// Checks if the error is of code 23505 (unique_violation).
if pqerr, ok := err.(*pq.Error); ok && pqerr.Code == uniqueViolation {
return ErrDBDuplicatedEntry
}
return fmt.Errorf("exec tran: %w", err)
}
// Disarm the deferred rollback.
mustRollback = false
// Commit the transaction.
log.Infow("commit tran", "traceid", traceID)
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit tran: %w", err)
}
return nil
}
// NamedExecContext is a helper function to execute a CUD operation with
// logging and tracing.
func NamedExecContext(ctx context.Context, log *zap.SugaredLogger, db sqlx.ExtContext, query string, data any) error {
q := queryString(query, data)
log.Infow("database.NamedExecContext", "traceid", web.GetTraceID(ctx), "query", q)
if _, err := sqlx.NamedExecContext(ctx, db, query, data); err != nil {
// Checks if the error is of code 23505 (unique_violation).
if pqerr, ok := err.(*pq.Error); ok && pqerr.Code == uniqueViolation {
return ErrDBDuplicatedEntry
}
return err
}
return nil
}
// NamedQuerySlice is a helper function for executing queries that return a
// collection of data to be unmarshalled into a slice.
func NamedQuerySlice[T any](ctx context.Context, log *zap.SugaredLogger, db sqlx.ExtContext, query string, data any, dest *[]T) error {
q := queryString(query, data)
log.Infow("database.NamedQuerySlice", "traceid", web.GetTraceID(ctx), "query", q)
rows, err := sqlx.NamedQueryContext(ctx, db, query, data)
if err != nil {
return err
}
defer rows.Close()
var slice []T
for rows.Next() {
v := new(T)
if err := rows.StructScan(v); err != nil {
return err
}
slice = append(slice, *v)
}
*dest = slice
return nil
}
// NamedQueryStruct is a helper function for executing queries that return a
// single value to be unmarshalled into a struct type.
func NamedQueryStruct(ctx context.Context, log *zap.SugaredLogger, db sqlx.ExtContext, query string, data any, dest any) error {
q := queryString(query, data)
log.Infow("database.NamedQueryStruct", "traceid", web.GetTraceID(ctx), "query", q)
rows, err := sqlx.NamedQueryContext(ctx, db, query, data)
if err != nil {
return err
}
defer rows.Close()
if !rows.Next() {
return ErrDBNotFound
}
if err := rows.StructScan(dest); err != nil {
return err
}
return nil
}
// queryString provides a pretty print version of the query and parameters.
func queryString(query string, args ...any) string {
query, params, err := sqlx.Named(query, args)
if err != nil {
return err.Error()
}
for _, param := range params {
var value string
switch v := param.(type) {
case string:
value = fmt.Sprintf("%q", v)
case []byte:
value = fmt.Sprintf("%q", string(v))
default:
value = fmt.Sprintf("%v", v)
}
query = strings.Replace(query, "?", value, 1)
}
query = strings.ReplaceAll(query, "\t", "")
query = strings.ReplaceAll(query, "\n", " ")
return strings.Trim(query, " ")
}