/
driver.go
89 lines (79 loc) · 1.92 KB
/
driver.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
package xpg
import (
"net"
"github.com/go-pg/pg/v10"
"github.com/kucjac/cleango/cgerrors"
"github.com/kucjac/cleango/xservice"
)
var defaultDriver = NewDriver()
// Compile time check for the xservice.Driver implementation.
var _ xservice.Driver = (*PGDriver)(nil)
// PGDriver is an implementation of the xservice.Driver for the go-pg.
type PGDriver struct {
mp map[string]cgerrors.ErrorCode
}
// NewDriver creates a new driver implementation for the go-pg.
func NewDriver() *PGDriver {
mp := map[string]cgerrors.ErrorCode{}
for k, v := range errorMap {
mp[k] = v
}
return &PGDriver{mp: mp}
}
// CustomErrorCode overwrites default error map for given class, which would result in given code.
func (p *PGDriver) CustomErrorCode(class string, code cgerrors.ErrorCode) {
p.mp[class] = code
}
// ErrorCode implements xservice.Driver interface.
func (p *PGDriver) ErrorCode(err error) cgerrors.ErrorCode {
switch err {
case pg.ErrNoRows:
return cgerrors.ErrorCode_NotFound
case pg.ErrMultiRows, pg.ErrTxDone:
return cgerrors.ErrorCode_Internal
}
e, ok := err.(pg.Error)
if !ok {
return cgerrors.ErrorCode_Unknown
}
class := e.Field('C')
if class == "" {
return cgerrors.ErrorCode_Unknown
}
code, ok := p.mp[class]
if ok {
return code
}
if len(class) < 2 {
return cgerrors.ErrorCode_Unknown
}
code, ok = p.mp[class[:2]]
if !ok {
return cgerrors.ErrorCode_Internal
}
return code
}
// CanRetry implements xservice.Driver interface.
func (p *PGDriver) CanRetry(err error) bool {
switch e := err.(type) {
case pg.Error:
class := e.Field('C')
if len(class) >= 2 {
return class[:2] == "08"
}
return false
case *net.OpError:
return true
}
return false
}
// Err converts given error into a cgerrors.Error.
func (p *PGDriver) Err(err error) *cgerrors.Error {
if err == nil {
return nil
}
if e, ok := err.(*cgerrors.Error); ok {
return e
}
return cgerrors.New("", err.Error(), p.ErrorCode(err))
}