github.com/keysonZZZ/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgSql/DbConfig.go (about)

     1  package kmgSql
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/bronze1man/kmg/encoding/kmgYaml"
     7  	"github.com/bronze1man/kmg/kmgConfig"
     8  	"github.com/bronze1man/kmg/kmgFile"
     9  )
    10  
    11  type DbConfig struct {
    12  	Username string // example: root
    13  	Password string // example: password
    14  	Host     string // example: 127.0.0.1
    15  	DbName   string // example: kmg_test
    16  }
    17  
    18  func (config *DbConfig) GetDsn() string {
    19  	return fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8&timeout=5s",
    20  		config.Username,
    21  		config.Password,
    22  		config.Host,
    23  		config.DbName)
    24  }
    25  
    26  func (config *DbConfig) GetDsnWithoutDbName() string {
    27  	return fmt.Sprintf("%s:%s@tcp(%s:3306)/?charset=utf8&timeout=5s",
    28  		config.Username,
    29  		config.Password,
    30  		config.Host)
    31  }
    32  
    33  var defaultDbConfig *DbConfig
    34  
    35  func SetDefaultDbConfig(conf *DbConfig) {
    36  	dbLock.Lock()
    37  	defer dbLock.Unlock()
    38  	if db.DB != nil {
    39  		db.DB.Close()
    40  		db = DB{}
    41  	}
    42  	defaultDbConfig = conf
    43  }
    44  
    45  func GetDefaultDbConfig() *DbConfig {
    46  	dbLock.Lock()
    47  	defer dbLock.Unlock()
    48  	if defaultDbConfig == nil {
    49  		panic("you need use SetDefaultDbConfig to set the config")
    50  	}
    51  	return defaultDbConfig
    52  }
    53  
    54  type TestDbConf struct {
    55  	Db *DbConfig
    56  }
    57  
    58  func HasTestConfig() bool {
    59  	return kmgFile.MustFileExist(kmgConfig.DefaultEnv().PathInConfig("Test.yml"))
    60  }
    61  
    62  func HasProdConfig() bool {
    63  	return kmgFile.MustFileExist(kmgConfig.DefaultEnv().PathInConfig("Prod.yml"))
    64  }
    65  func MustLoadTestConfig() {
    66  	mustLoadConfigByFilename("Test.yml")
    67  }
    68  
    69  func MustLoadProdConfig() {
    70  	mustLoadConfigByFilename("Prod.yml")
    71  }
    72  
    73  func LoadConfigWithDbName(dbname string) {
    74  	SetDefaultDbConfig(&DbConfig{
    75  		Username: "root",
    76  		Password: "",
    77  		Host:     "127.0.0.1",
    78  		DbName:   dbname,
    79  	})
    80  }
    81  
    82  func mustLoadConfigByFilename(filename string) {
    83  	conf := TestDbConf{}
    84  	err := kmgYaml.ReadFile(kmgConfig.DefaultEnv().PathInConfig(filename), &conf)
    85  	if err != nil {
    86  		panic(err)
    87  	}
    88  	SetDefaultDbConfig(conf.Db)
    89  }