Passed
Push — main ( 6ef1c9...bfdedc )
by Christian
01:44 queued 16s
created

sqldb.*SQLProxy.Close   A

Complexity

Conditions 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 0
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
package sqldb
2
3
import (
4
	"context"
5
	"database/sql"
6
	"time"
7
8
	"github.com/cdleo/go-commons/logger"
9
	"github.com/cdleo/go-commons/sqlcommons"
10
)
11
12
type SQLProxy struct {
13
	connector  sqlcommons.SQLConnector
14
	translator sqlcommons.SQLAdapter
15
	logger     logger.Logger
16
	db         *sql.DB
17
}
18
19
func (s *SQLProxy) Open() (*sql.DB, error) {
20
	if db, err := s.connector.Open(s.logger, s.translator); err != nil {
21
		return nil, s.translator.ErrorHandler(err)
22
	} else {
23
		s.db = db
24
	}
25
26
	return s.db, nil
27
}
28
29
func (s *SQLProxy) IsOpen() error {
30
	if s.db == nil {
31
		return sqlcommons.DBNotInitialized
32
	}
33
34
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
35
	defer cancel()
36
37
	if stdErr := s.db.PingContext(ctx); stdErr != nil {
38
		s.Close()
39
		if _, err := s.Open(); err != nil {
40
			return s.translator.ErrorHandler(err)
41
		} else {
42
			ctxReconnect, cancelReconnect := context.WithTimeout(context.Background(), 1*time.Second)
43
			defer cancelReconnect()
44
			return s.db.PingContext(ctxReconnect)
45
		}
46
	}
47
	return nil
48
}
49
50
func (s *SQLProxy) Close() error {
51
52
	if s.db == nil {
53
		return sqlcommons.DBNotInitialized
54
	}
55
56
	err := s.db.Close()
57
	s.db = nil
58
	return err
59
}
60
61
func (s *SQLProxy) GetNextSequenceValue(ctx context.Context, sequenceName string) (int64, error) {
62
	if err := s.IsOpen(); err != nil {
63
		return 0, sqlcommons.ConnectionClosed
64
	}
65
66
	query := s.connector.GetNextSequenceQuery(sequenceName)
67
	row := s.db.QueryRowContext(ctx, query)
68
	var id int64
69
	if err := row.Scan(&id); err != nil {
70
		return 0, sqlcommons.NextValueFailed
71
	}
72
	return id, nil
73
}
74