-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconn.go
More file actions
50 lines (39 loc) · 1.03 KB
/
Copy pathconn.go
File metadata and controls
50 lines (39 loc) · 1.03 KB
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
package qube
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
)
type Conn struct {
db *sql.DB
raw *sql.Conn
}
func (conn *Conn) Exec(query string, args ...any) (sql.Result, error) {
// Avoid "bad connection".
return conn.withRetry(context.Background(), query, args...)
}
func (conn *Conn) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) {
// Avoid "bad connection".
return conn.withRetry(ctx, query, args...)
}
func (conn *Conn) withRetry(ctx context.Context, query string, args ...any) (sql.Result, error) {
res, err := conn.raw.ExecContext(ctx, query, args...)
if errors.Is(err, driver.ErrBadConn) || errors.Is(err, sql.ErrConnDone) {
if !errors.Is(err, sql.ErrConnDone) {
conn.raw.Close()
}
raw, err := conn.db.Conn(ctx)
if err != nil {
return nil, fmt.Errorf("failed to reopen DB connection (%w)", err)
}
conn.raw = raw
return conn.raw.ExecContext(ctx, query, args...)
}
return res, err
}
func (conn *Conn) Close() {
conn.raw.Close()
conn.db.Close()
}