-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
100 lines (79 loc) · 1.71 KB
/
db.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
package main
import (
"context"
"database/sql"
"fmt"
"log"
"time"
_ "github.com/lib/pq"
)
type DB struct {
db *sql.DB
ctx context.Context // background context
cancel func() // cancel background context
// Datasource name.
DSN string
// Returns the current time. Defaults to time.Now().
// Can be mocked for tests.
Now func() time.Time
}
// New ...
func New(ctx context.Context, dsn string) *DB {
db := &DB{
DSN: dsn,
Now: time.Now,
}
db.ctx, db.cancel = context.WithCancel(ctx)
return db
}
// Open a connection on the underlying server
func (db *DB) Open() (err error) {
// Ensure a DSN is set before attempting to open the database.
if db.DSN == "" {
return fmt.Errorf("dsn required")
}
log.Println("opening database connection")
db.db, err = sql.Open("postgres", db.DSN)
if err != nil {
return err
}
for i := 1; i < 10; i++ {
time.Sleep(5 * time.Millisecond)
if err == nil {
log.Printf("pinging %d", i)
err := db.Ping()
if err == nil {
return nil
}
}
}
db.db.SetMaxOpenConns(60)
db.db.SetMaxIdleConns(30)
db.db.SetConnMaxLifetime(15 * time.Minute)
return fmt.Errorf("failed to connect to database")
}
func (db *DB) Close() {
db.cancel()
db.db.Close()
}
func (db *DB) Ping() error {
return db.db.Ping()
}
// Tx wraps the SQL Tx object to provide a timestamp at the start of the transaction.
type Tx struct {
*sql.Tx
db *DB
Now time.Time
}
func (db *DB) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
tx, err := db.db.BeginTx(ctx, opts)
if err != nil {
return nil, err
}
// Return wrapper Tx that includes the transaction start time.
return &Tx{
Tx: tx,
db: db,
Now: db.Now().UTC().Truncate(time.Second),
}, nil
}