-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection_handler.go
104 lines (84 loc) · 2.27 KB
/
connection_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package gotabase
import (
"database/sql"
"errors"
"github.com/KowalskiPiotr98/gotabase/logger"
)
var connection *connectionHandler
type connectionHandler struct {
database *sql.DB
}
var _ Connector = (*connectionHandler)(nil)
var (
connectionNotInitialisedErr = errors.New("database connection has not been initialised")
connectionAlreadyInitialised = errors.New("database connection has already been set")
)
func (c *connectionHandler) QueryRow(sql string, args ...interface{}) (Row, error) {
if connection == nil {
return nil, connectionNotInitialisedErr
}
result := c.database.QueryRow(sql, args...)
return result, result.Err()
}
func (c *connectionHandler) QueryRows(sql string, args ...interface{}) (Rows, error) {
if connection == nil {
return nil, connectionNotInitialisedErr
}
return c.database.Query(sql, args...)
}
func (c *connectionHandler) Exec(sql string, args ...interface{}) (Result, error) {
if connection == nil {
return nil, connectionNotInitialisedErr
}
return c.database.Exec(sql, args...)
}
func InitialiseConnection(connectionString string, driver string) error {
if connection != nil {
return connectionAlreadyInitialised
}
logger.LogInfo("Initialising database connection...")
database, err := sql.Open(driver, connectionString)
if err != nil {
logger.LogWarn("Failed to open database connection: %v", err)
return err
}
err = database.Ping()
if err != nil {
logger.LogWarn("Failed to ping database: %v", err)
database.Close()
return err
}
logger.LogInfo("Database connection established")
connection = &connectionHandler{
database: database,
}
return nil
}
func GetConnection() Connector {
if connection == nil {
logger.LogPanic(connectionNotInitialisedErr.Error())
}
return connection
}
func BeginTransaction() (*Transaction, error) {
if connection == nil {
logger.LogPanic(connectionNotInitialisedErr.Error())
}
tx, err := connection.database.Begin()
if err != nil {
logger.LogWarn("Failed to begin transaction: %v", err)
return nil, err
}
return newTransaction(tx), nil
}
func CloseConnection() error {
if connection == nil {
return nil
}
if err := connection.database.Close(); err != nil {
logger.LogWarn("Failed to close database connection: %v", err)
return err
}
connection = nil
return nil
}