engines.*sqlite3Conn.ErrorHandler   C
last analyzed

Complexity

Conditions 11

Size

Total Lines 31
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

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

How to fix   Complexity   

Complexity

Complex classes like engines.*sqlite3Conn.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/mattn/go-sqlite3"
12
)
13
14
type sqlite3Conn struct {
15
	url string
16
}
17
18
const sqlite3_DriverName = "sqlite3-adapter"
19
20
func NewSqlite3Connector(url string) adapter.SQLEngineConnector {
21
	return &sqlite3Conn{
22
		url,
23
	}
24
}
25
26
func (s *sqlite3Conn) Open() (*sql.DB, error) {
27
	return sql.Open(sqlite3_DriverName, s.url)
28
}
29
30
func (s *sqlite3Conn) DriverName() string {
31
	return sqlite3_DriverName
32
}
33
34
func (s *sqlite3Conn) Driver() driver.Driver {
35
	return &sqlite3.SQLiteDriver{}
36
}
37
38
func (s *sqlite3Conn) ErrorHandler(err error) error {
39
	if err == nil {
40
		return nil
41
	}
42
43
	if sqliteError, ok := err.(sqlite3.Error); ok {
44
45
		if sqliteError.Code == 18 { //SQLITE_TOOBIG
46
			return sqlcommons.ValueTooLargeForColumn
47
48
		} else if sqliteError.Code == 19 { //SQLITE_CONSTRAINT
49
			if sqliteError.ExtendedCode == 787 || /*SQLITE_CONSTRAINT_FOREIGNKEY*/
50
				sqliteError.ExtendedCode == 1555 || /*SQLITE_CONSTRAINT_PRIMARYKEY*/
51
				sqliteError.ExtendedCode == 1811 /*SQLITE_CONSTRAINT_TRIGGER*/ {
52
				return sqlcommons.IntegrityConstraintViolation
53
54
			} else if sqliteError.ExtendedCode == 1299 { //SQLITE_CONSTRAINT_NOTNULL
55
				return sqlcommons.CannotSetNullColumn
56
57
			} else if sqliteError.ExtendedCode == 2067 { //SQLITE_CONSTRAINT_UNIQUE
58
				return sqlcommons.UniqueConstraintViolation
59
60
			}
61
		} else if sqliteError.Code == 25 { //SQLITE_RANGE
62
			return sqlcommons.InvalidNumericValue
63
		}
64
65
		return fmt.Errorf("Unhandled SQLite3 error. Code:[%s] Extended:[%s] Desc:[%s]", sqliteError.Code, sqliteError.ExtendedCode, sqliteError.Error())
66
67
	} else {
68
		return err
69
	}
70
}
71