engines.*pgSqlConn.ErrorHandler   C
last analyzed

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 engines.*pgSqlConn.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 engines
2
3
import (
4
	"database/sql"
5
	"database/sql/driver"
6
	"fmt"
7
8
	adapter "github.com/cdleo/go-sql-adapter"
9
10
	"github.com/cdleo/go-commons/sqlcommons"
11
	"github.com/lib/pq"
12
)
13
14
type pgSqlConn struct {
15
	url      string
16
	user     string
17
	password string
18
	database string
19
}
20
21
const postgresql_DriverName = "postgres"
22
23
func NewPostgreSqlConnector(host string, port int, user string, password string, database string) adapter.SQLEngineConnector {
24
25
	return &pgSqlConn{
26
		url:      fmt.Sprintf("%s:%d", host, port),
27
		user:     user,
28
		password: password,
29
		database: database,
30
	}
31
}
32
33
func (s *pgSqlConn) Open() (*sql.DB, error) {
34
	dataSourceName := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable", s.user, s.password, s.url, s.database)
35
	return sql.Open(postgresql_DriverName, dataSourceName)
36
}
37
38
func (s *pgSqlConn) DriverName() string {
39
	return postgresql_DriverName
40
}
41
42
func (s *pgSqlConn) Driver() driver.Driver {
43
44
	if conn, err := pq.NewConnector("postgres://"); err == nil {
45
		return conn.Driver()
46
	}
47
	return nil
48
}
49
50
func (s *pgSqlConn) ErrorHandler(err error) error {
51
	if err == nil {
52
		return nil
53
	}
54
55
	if pqError, ok := err.(*pq.Error); ok {
56
		switch pqError.Code {
57
		case "23505":
58
			return sqlcommons.UniqueConstraintViolation
59
		case "23503":
60
			return sqlcommons.IntegrityConstraintViolation
61
		case "22001":
62
			return sqlcommons.ValueTooLargeForColumn
63
		case "22003":
64
			return sqlcommons.ValueLargerThanPrecision
65
		case "23502":
66
			return sqlcommons.CannotSetNullColumn
67
		case "22P02":
68
			return sqlcommons.InvalidNumericValue
69
		case "21000":
70
			return sqlcommons.SubqueryReturnsMoreThanOneRow
71
		default:
72
			return fmt.Errorf("Unhandled PostgreSQL error. Code:[%s] Desc:[%s]", pqError.Code, pqError.Message)
73
		}
74
	} else {
75
		return err
76
	}
77
}
78