Passed
Push — main ( 9e2022...6ef1c9 )
by Christian
02:04 queued 14s
created

adapter.*postgresAdapter.ErrorHandler   C

Complexity

Conditions 11

Size

Total Lines 26
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 23
nop 1
dl 0
loc 26
rs 5.4
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like adapter.*postgresAdapter.ErrorHandler often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
package adapter
2
3
import (
4
	"fmt"
5
	"regexp"
6
	"strings"
7
8
	"github.com/cdleo/go-commons/sqlcommons"
9
	"github.com/lib/pq"
10
)
11
12
type postgresAdapter struct {
13
	paramRegExp     *regexp.Regexp
14
	sourceSQLSintax string
15
}
16
17
func NewPostgresAdapter(sourceSQLSintax string) sqlcommons.SQLAdapter {
18
	return &postgresAdapter{
19
		regexp.MustCompile(":[1-9]"),
20
		sourceSQLSintax,
21
	}
22
}
23
24
func (s *postgresAdapter) Translate(query string) string {
25
26
	if s.sourceSQLSintax == "Oracle" {
27
		return s.paramRegExp.ReplaceAllStringFunc(query, func(m string) string {
28
			return strings.Replace(m, ":", "$", 1)
29
		})
30
	} else {
31
		return query
32
	}
33
}
34
35
func (s *postgresAdapter) ErrorHandler(err error) error {
36
	if err == nil {
37
		return nil
38
	}
39
40
	if pqError, ok := err.(*pq.Error); ok {
41
		switch pqError.Code {
42
		case "23505":
43
			return sqlcommons.UniqueConstraintViolation
44
		case "23503":
45
			return sqlcommons.IntegrityConstraintViolation
46
		case "22001":
47
			return sqlcommons.ValueTooLargeForColumn
48
		case "22003":
49
			return sqlcommons.ValueLargerThanPrecision
50
		case "23502":
51
			return sqlcommons.CannotSetNullColumn
52
		case "22P02":
53
			return sqlcommons.InvalidNumericValue
54
		case "21000":
55
			return sqlcommons.SubqueryReturnsMoreThanOneRow
56
		default:
57
			return fmt.Errorf("Unhandled PostgreSQL error. Code:[%s] Desc:[%s]", pqError.Code, pqError.Message)
58
		}
59
	} else {
60
		return err
61
	}
62
}
63