/
rdbms.go
52 lines (46 loc) · 1.72 KB
/
rdbms.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
package utils
import (
"database/sql"
"fmt"
"log"
"strconv"
"time"
)
type RDBMSConfig struct {
DriverName string // Name of the SQL driver viz., mysql, postgres, sqlite etc
HostName string // Hostname of the SQL server
Port int64 // Port number of the SQL server
Database string // Name of the database to connect to on the SQL server
UserName string // Username part of the SQL server credentials
Password string // Password for the afore-defined UserName
MaxOpenConns int // Maximum number of connections to be opened
MaxIdleConns int // Maximum number of idle connections to be kept
MaxLifeTimeConn int // Maximum life of connection (in seconds)
}
func (c *RDBMSConfig) Values(driverName, hostName string, port int64, database, userName, password string, maxOpenconns, maxIdleConns, maxLifeTimeConn int) {
c.DriverName = driverName
c.HostName = hostName
c.Port = port
c.Database = database
c.UserName = userName
c.Password = password
c.MaxOpenConns = maxOpenconns
c.MaxIdleConns = maxIdleConns
c.MaxLifeTimeConn = maxLifeTimeConn
}
func (c *RDBMSConfig) DSN() string {
return c.UserName + ":" + c.Password + "@tcp(" + c.HostName + ":" + strconv.FormatInt(c.Port, 10) + ")/" + c.Database
}
func (c *RDBMSConfig) String() string {
return fmt.Sprintf("DBConfig = %#v", c)
}
func (c *RDBMSConfig) Connect() (*sql.DB, error) {
db, err := sql.Open(c.DriverName, c.DSN())
if err == nil {
db.SetMaxOpenConns(c.MaxOpenConns)
db.SetMaxIdleConns(c.MaxIdleConns)
db.SetConnMaxLifetime(time.Duration(c.MaxLifeTimeConn) * time.Second)
log.Printf("Successfully connected to: %s", c.DSN())
}
return db, err
}