mysql.go 4.91 KiB
package mysql
import (
	"sync"
	"time"
	"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/configmdl"
	"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/errormdl"
	"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/loggermdl"
	_ "github.com/go-sql-driver/mysql"
	"github.com/gocraft/dbr"
// Hold a single global connection (pooling provided by sql driver)
var sqlConnections map[string]*dbr.Connection
var connectionError error
var sqlOnce sync.Once
var config tomlConfig
var defaultHost string
// MYSQLConnection -
type mysqlConnection struct {
	Server          string        `json:"server" bson:"server"`
	Username        string        `json:"username" bson:"username"`
	Password        string        `json:"password " bson:"password "`
	Protocol        string        `json:"protocol" bson:"protocol"`
	Database        string        `json:"database" bson:"database"`
	Parameters      []param       `json:"params" bson:"params"`
	MaxIdleConns    int           `json:"maxIdleConns" bson:"maxIdleConns"`
	MaxOpenConns    int           `json:"maxOpenConns" bson:"maxOpenConns"`
	ConnMaxLifetime time.Duration `json:"connMaxLifetime" bson:"connMaxLifetime"`
type param struct {
	ParamKey   string `json:"paramkey" bson:"paramkey"`
	ParamValue string `json:"paramvalue" bson:"paramvalue"`
type tomlConfig struct {
	MysqlHosts map[string]mysqlConnection
// Init initializes MYSQL Connections for given toml file
func Init(tomlFilepath string, defaultHostName string) (map[string]*dbr.Connection, error) {
	sqlOnce.Do(func() {
		sqlConnections = make(map[string]*dbr.Connection)
		_, err := configmdl.InitConfig(tomlFilepath, &config)
		if errormdl.CheckErr(err) != nil {
			loggermdl.LogError(err)
			connectionError = err
			return
		for connectionName, connectionDetails := range config.MysqlHosts {
			paramsString := ""
			if len(connectionDetails.Parameters) > 0 {
				for paramIndex, param := range connectionDetails.Parameters {
					if paramsString == "" {
						paramsString = "?"
					paramsString = paramsString + param.ParamKey + "=" + param.ParamValue
					hasNextParam := paramIndex+1 < len(connectionDetails.Parameters)
					if hasNextParam {
						paramsString = paramsString + "&"
			//connection, err := dbr.Open("mysql", "root:root@tcp(127.0.0.1:3306)/testdb?parseTime=true", nil)
			connection, err := dbr.Open("mysql", connectionDetails.Username+":"+connectionDetails.Password+"@"+connectionDetails.Protocol+"("+connectionDetails.Server+")/"+connectionDetails.Database+paramsString, nil)
			if errormdl.CheckErr1(err) != nil {
				loggermdl.LogError(err)
7172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
connectionError = err return } if connectionDetails.MaxIdleConns == 0 { connectionDetails.MaxIdleConns = 100 // default is 2 } if connectionDetails.MaxOpenConns == 0 { connectionDetails.MaxOpenConns = 5000 // default there's no limit } if connectionDetails.ConnMaxLifetime == 0 { duration := 3 * 24 * time.Hour connectionDetails.ConnMaxLifetime = duration } connection.SetMaxIdleConns(connectionDetails.MaxIdleConns) connection.SetMaxOpenConns(connectionDetails.MaxOpenConns) connection.SetConnMaxLifetime(connectionDetails.ConnMaxLifetime) sqlConnections[connectionName] = connection } defaultHost = defaultHostName }) return sqlConnections, errormdl.CheckErr2(connectionError) } //GetMYSQLConnection - func GetMYSQLConnection(connectionName string) (*dbr.Connection, error) { if errormdl.CheckBool(sqlConnections == nil) { return nil, errormdl.Wrap("MYSQL_INIT_NOT_DONE") } if connectionName == "" { if instance, keyExist := sqlConnections[defaultHost]; keyExist { return instance, nil } } if session, keyExist := sqlConnections[connectionName]; keyExist { return session, nil } return nil, errormdl.Wrap("Connection not found for host: " + connectionName) } // GetMultipleSQLConnection - /* func GetMultipleSQLConnection(tomlFilepath string) (map[string]*dbr.Connection, error) { sqlOnce.Do(func() { _, err := configmdl.InitConfig(tomlFilepath, &config) if errormdl.CheckErr(err) != nil { loggermdl.LogError(err) connectionError = err return } sqlConnections = make(map[string]*dbr.Connection) for connectionName, mysqlConnectionObj := range config.MysqlHosts { connection, err := dbr.Open("mysql", mysqlConnectionObj.Username+":"+mysqlConnectionObj.Password+"@"+mysqlConnectionObj.Protocol+"("+mysqlConnectionObj.Server+")/"+mysqlConnectionObj.Database, nil) if err != nil { connectionError = err } if mysqlConnectionObj.MaxIdleConns == 0 { connection.SetMaxIdleConns(100) // default is 2 } if mysqlConnectionObj.MaxOpenConns == 0 { connection.SetMaxOpenConns(5000) // default there's no limit } if mysqlConnectionObj.ConnMaxLifetime == 0 { duration := 3 * 24 * time.Hour connection.SetConnMaxLifetime(duration) } sqlConnections[connectionName] = connection } }) return sqlConnections, errormdl.CheckErr(connectionError) } */