-
Notifications
You must be signed in to change notification settings - Fork 12
/
db.go
238 lines (201 loc) · 6.58 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
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
// Copyright 2022 The searKing Author. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sql
import (
"context"
"database/sql"
"errors"
"fmt"
"log/slog"
"net/url"
"runtime"
"strconv"
"strings"
"time"
"github.com/jmoiron/sqlx"
"github.com/searKing/golang/go/database/dsn"
slog_ "github.com/searKing/golang/go/log/slog"
time_ "github.com/searKing/golang/go/time"
)
var (
ErrRegister = errors.New("register db driver")
)
// DB represents a connection to a SQL database.
//
//go:generate go-option -type "DB"
type DB struct {
DSN string
db *sqlx.DB
driverName string
driverPackage string
logger *slog.Logger
// options
opts struct {
// UseTracedDriver will make it so that a wrapped driver is used that supports the opentracing API.
// Deprecated: remove trace options.
UseTracedDriver bool
// if TraceOrphans is set to true, then spans with no parent will be traced anyway, if false, they will not be.
// Deprecated: remove trace options.
TraceOrphans bool
// if OmitArgs is set to true, then query arguments are omitted from tracing spans.
// Deprecated: remove trace options.
OmitArgs bool
// ForcedDriverName is specifically for writing tests as you can't register a driver with the same name more than once.
// Deprecated: remove trace options.
ForcedDriverName string
}
}
// Open returns a new DB.
func Open(dsn string, opts ...DBOption) (*DB, error) {
connection := &DB{DSN: dsn}
connection.ApplyOptions(opts...)
return connection, nil
}
func cleanURLQuery(in url.Values) (out url.Values) {
out, _ = url.ParseQuery(in.Encode())
out.Del("max_conns")
out.Del("max_idle_conns")
out.Del("max_conn_lifetime")
out.Del("parseTime")
return out
}
func (db *DB) fieldLogger() *slog.Logger {
if db.logger == nil {
return slog.Default()
}
return db.logger
}
// GetDatabaseRetry tries to connect to a database and fails after failAfter.
func (db *DB) GetDatabaseRetry(ctx context.Context, maxWait time.Duration, failAfter time.Duration) (*sqlx.DB, error) {
// how long to sleep on retry failure
var tempDelay = time_.NewDefaultExponentialBackOff(
time_.WithExponentialBackOffOptionMaxInterval(maxWait),
time_.WithExponentialBackOffOptionMaxElapsedDuration(failAfter))
var err error
for {
db.db, err = db.GetDatabase()
if err != nil {
if errors.Is(err, ErrRegister) {
db.fieldLogger().ErrorContext(ctx, "database: Register", slog_.Error(err))
return nil, err
}
delay, ok := tempDelay.NextBackOff()
if !ok {
db.fieldLogger().ErrorContext(ctx, fmt.Sprintf("database: Connect; retried canceled as time exceed(%s)",
tempDelay.GetMaxElapsedDuration()), slog_.Error(err))
return nil, err
}
db.fieldLogger().WarnContext(ctx, fmt.Sprintf("database: Connect; retrying in (%v)", delay), slog_.Error(err))
time.Sleep(delay)
continue
}
return db.db, nil
}
}
// GetDatabase returns a database instance.
func (db *DB) GetDatabase() (*sqlx.DB, error) {
if db.db != nil {
return db.db, nil
}
driverName, driverPackage, err := db.registerDriver()
if err != nil {
return nil, fmt.Errorf("could not register driver: %w", err)
}
dsn_, err := dsnForSqlOpen(db.DSN)
if err != nil {
return nil, err
}
classifiedDSN := dsn.Masking(dsn_)
logger := db.fieldLogger().With("dsn", classifiedDSN)
logger.Info("Establishing connection with SQL database backend")
db_, err := sql.Open(driverName, dsn_)
if err != nil {
logger.Error("Unable to open SQL connection", slog_.Error(err))
return nil, fmt.Errorf("could not open SQL connection: %w", err)
}
db.db = sqlx.NewDb(db_, driverPackage) // This must be clean.Scheme otherwise things like `Rebind()` won't work
if err := db.db.Ping(); err != nil {
logger.Error("Unable to ping SQL database backend", slog_.Error(err))
return nil, fmt.Errorf("could not ping SQL connection: %w", err)
}
logger.Info("Successfully connected to SQL database backend")
_, _, query := dsn.Split(dsn_)
maxConns := maxParallelism() * 2
if v := query.Get("max_conns"); v != "" {
s, err := strconv.ParseInt(v, 10, 32)
if err != nil {
logger.Warn(fmt.Sprintf(`Query parameter "max_conns" value %v could not be parsed to int, falling back to default value %d`, v, maxConns), slog_.Error(err))
} else {
maxConns = int(s)
}
}
maxIdleConns := maxParallelism()
if v := query.Get("max_idle_conns"); v != "" {
s, err := strconv.ParseInt(v, 10, 32)
if err != nil {
logger.Warn(fmt.Sprintf("max_idle_conns value %s could not be parsed to int: %s", v, err))
logger.Warn(fmt.Sprintf(`Query parameter "max_idle_conns" value %v could not be parsed to int, falling back to default value %d`, v, maxIdleConns), slog_.Error(err))
} else {
maxIdleConns = int(s)
}
}
maxConnLifetime := time.Duration(0)
if v := query.Get("max_conn_lifetime"); v != "" {
s, err := time.ParseDuration(v)
if err != nil {
logger.Warn(fmt.Sprintf(`Query parameter "max_conn_lifetime" value %v could not be parsed to int, falling back to default value %d`, v, maxConnLifetime), slog_.Error(err))
} else {
maxConnLifetime = s
}
}
db.db.SetMaxOpenConns(maxConns)
db.db.SetMaxIdleConns(maxIdleConns)
db.db.SetConnMaxLifetime(maxConnLifetime)
return db.db, nil
}
func maxParallelism() int {
maxProcs := runtime.GOMAXPROCS(0)
numCPU := runtime.NumCPU()
if maxProcs < numCPU {
return maxProcs
}
return numCPU
}
func dsnForSqlOpen(dsn_ string) (string, error) {
scheme, connect, query := dsn.Split(dsn_)
query = cleanURLQuery(query)
// special case, remove scheme for mysql*
if strings.HasPrefix(scheme, "mysql") {
query.Set("parseTime", "true")
scheme = ""
}
if scheme == "cockroach" {
scheme = "postgres"
}
return dsn.Join(scheme, connect, query), nil
}
// registerDriver checks if tracing is enabled and registers a custom "instrumented-sql-driver" driver that internally
// wraps the proper driver (mysql/postgres) with an instrumented driver.
func (db *DB) registerDriver() (string, string, error) {
if db.driverName != "" {
return db.driverName, db.driverPackage, nil
}
scheme, _, _ := dsn.Split(db.DSN)
driverName := scheme
driverPackage := scheme
if driverName == "cockroach" || driverName == "postgres" {
// If we're not using the instrumented driver, we need to replace "cockroach" with "postgres"
driverName = "pgx"
}
switch scheme {
case "cockroach":
driverPackage = "postgres"
}
db.driverName = driverName
db.driverPackage = driverPackage
if driverName == "" {
return "", "", fmt.Errorf("unsupported scheme (%s) in DSN : %w", scheme, ErrRegister)
}
return driverName, driverPackage, nil
}