-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdb.go
More file actions
45 lines (36 loc) · 742 Bytes
/
db.go
File metadata and controls
45 lines (36 loc) · 742 Bytes
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
package main
import (
"context"
"errors"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
func newDB(config Config) (*pgxpool.Pool, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
pool, err := pgxpool.New(ctx, config.PgDsn)
if err != nil {
return nil, err
}
_, err = pool.Exec(ctx, "select 1;")
return pool, err
}
func (h *handler) tx(ctx context.Context, fn func(tx pgx.Tx) error) error {
tx, err := h.db.Begin(ctx)
if err != nil {
return err
}
defer func() {
rec := recover()
if rec != nil {
tx.Rollback(ctx)
panic(rec)
}
}()
err = fn(tx)
if err != nil {
return errors.Join(err, tx.Rollback(ctx))
}
return tx.Commit(ctx)
}