mysql.go 5.03 KiB
Newer Older
Mayuri Shinde's avatar
Mayuri Shinde committed
package mysql

import (
	"sync"
	"time"

	"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/configmdl"
Mayuri Shinde's avatar
Mayuri Shinde committed
	"corelab.mkcl.org/MKCLOS/coredevelopmentplatform/corepkgv2/constantmdl"
Mayuri Shinde's avatar
Mayuri Shinde committed
	"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
Mayuri Shinde's avatar
Mayuri Shinde committed

// MYSQLConnection -
type mysqlConnection struct {
	Server          string        `json:"server" bson:"server"`
Mayuri Shinde's avatar
Mayuri Shinde committed
	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"`
Mayuri Shinde's avatar
Mayuri Shinde committed
	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"`
}
Mayuri Shinde's avatar
Mayuri Shinde committed

type tomlConfig struct {
	MysqlHosts map[string]mysqlConnection
Mayuri Shinde's avatar
Mayuri Shinde committed
}

// Init initializes MYSQL Connections for given toml file
func Init(tomlFilepath string, defaultHostName string) (map[string]*dbr.Connection, error) {
Mayuri Shinde's avatar
Mayuri Shinde committed
	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)
				connectionError = err
Mayuri Shinde's avatar
Mayuri Shinde committed
				return
			}
			if connectionDetails.MaxIdleConns == 0 {
Mayuri Shinde's avatar
Mayuri Shinde committed
				connectionDetails.MaxIdleConns = constantmdl.MAX_IDLE_CONNECTIONS // default is 2
			}
			if connectionDetails.MaxOpenConns == 0 {
Mayuri Shinde's avatar
Mayuri Shinde committed
				connectionDetails.MaxOpenConns = constantmdl.MAX_OPEN_CONNECTIONS // default there's no limit
			}
			if connectionDetails.ConnMaxLifetime == 0 {
Mayuri Shinde's avatar
Mayuri Shinde committed
				connectionDetails.ConnMaxLifetime = constantmdl.CONNECTION_MAX_LIFETIME
			}
			connection.SetMaxIdleConns(connectionDetails.MaxIdleConns)
			connection.SetMaxOpenConns(connectionDetails.MaxOpenConns)
			connection.SetConnMaxLifetime(connectionDetails.ConnMaxLifetime)
Mayuri Shinde's avatar
Mayuri Shinde committed
			sqlConnections[connectionName] = connection
		}
		defaultHost = defaultHostName
Mayuri Shinde's avatar
Mayuri Shinde committed
	})
	return sqlConnections, errormdl.CheckErr2(connectionError)
Mayuri Shinde's avatar
Mayuri Shinde committed
}

//GetMYSQLConnection -
func GetMYSQLConnection(connectionName string) (*dbr.Connection, error) {
	if errormdl.CheckBool(sqlConnections == nil) {
Mayuri Shinde's avatar
Mayuri Shinde committed
		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 {
Mayuri Shinde's avatar
Mayuri Shinde committed
		return session, nil
	}
	return nil, errormdl.Wrap("Connection not found for host: " + connectionName)
Mayuri Shinde's avatar
Mayuri Shinde committed
}

// GetMultipleSQLConnection -
/* func GetMultipleSQLConnection(tomlFilepath string) (map[string]*dbr.Connection, error) {
Mayuri Shinde's avatar
Mayuri Shinde committed
	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)
Mayuri Shinde's avatar
Mayuri Shinde committed
			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
Mayuri Shinde's avatar
Mayuri Shinde committed
		}
	})
	return sqlConnections, errormdl.CheckErr(connectionError)
} */