Total Lines | 60 |
Duplicated Lines | 0 % |
Changes | 0 |
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 | } |
||
63 |