-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnection.go
106 lines (90 loc) · 2.41 KB
/
connection.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
105
106
package main
import (
"database/sql"
"fmt"
"strings"
"time"
_ "github.com/denisenkom/go-mssqldb"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
)
// Connection ...
type Connection struct {
Driver string `json:"driver"`
Server string `json:"server"`
Database string `json:"database"`
Dsn string `json:"dsn"`
Port int `json:"port"`
User string `json:"user"`
Password string `json:"password"`
Timezone string `json:"timezone"`
Max int `json:"max"`
db *sql.DB
location *time.Location
}
func connect(key string) *Connection {
connection, ok := config.Connections[key]
if !ok {
stop(fmt.Sprintf("Invalid connection key: '%s'", key), 1)
}
dsn := formatDsn(connection)
if dsn == "" {
stop(fmt.Sprintf("Invalid driver specified for connection: '%s'", key), 1)
}
if connection.db == nil {
var err error
connection.db, err = sql.Open(connection.Driver, dsn)
check(err)
err = connection.db.Ping()
if err != nil {
stop(fmt.Sprintf("Unable to establish connection to server \"%s\"", connection.Server), 3)
}
if connection.Max != 0 {
connection.db.SetMaxOpenConns(connection.Max)
}
if connection.Timezone != "" {
connection.location, err = time.LoadLocation(connection.Timezone)
check(err)
}
}
return connection
}
func disconnect() {
for _, connection := range config.Connections {
if connection.db != nil {
err := connection.db.Close()
check(err)
connection.db = nil
}
}
}
func formatDsn(connection *Connection) string {
if connection.Dsn != "" && !strings.HasPrefix(connection.Dsn, "...") {
return connection.Dsn
}
var dsn string
if connection.Driver == "mssql" {
dsn = fmt.Sprintf("server=%s;user id=%s;password=%s;port=%d",
connection.Server,
connection.User,
connection.Password,
connection.Port)
} else if connection.Driver == "postgres" {
dsn = fmt.Sprintf("host=%s user=%s password='%s' port=%d dbname=%s",
strings.Replace(connection.Server, " ", "\\ ", -1),
strings.Replace(connection.User, " ", "\\ ", -1),
strings.Replace(connection.Password, "'", "\\'", -1),
connection.Port,
strings.Replace(connection.Database, " ", "\\ ", -1))
} else if connection.Driver == "mysql" {
dsn = fmt.Sprintf("%s:%s@%s/%s",
connection.User,
connection.Password,
connection.Server,
connection.Database)
}
if strings.HasPrefix(connection.Dsn, "...") {
dsn += connection.Dsn[3:]
}
return dsn
}