dbhelper.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * @description:
  3. * @Author: CP
  4. * @Date: 2020-08-20 22:25:17
  5. * @FilePath: \construction_management\datasource\dbhelper.go
  6. */
  7. package datasource
  8. import (
  9. "fmt"
  10. "log"
  11. "sync"
  12. _ "github.com/go-sql-driver/mysql"
  13. "github.com/go-xorm/xorm"
  14. "github.com/spf13/viper"
  15. "go.mod/conf"
  16. )
  17. //互斥锁
  18. var dbLock sync.Mutex
  19. var masterInstance *xorm.Engine
  20. //单例模式
  21. func InstanceDbMaster() *xorm.Engine {
  22. if masterInstance != nil {
  23. return masterInstance
  24. }
  25. dbLock.Lock()
  26. defer dbLock.Unlock()
  27. if masterInstance != nil {
  28. return masterInstance
  29. }
  30. return NewDbMaster()
  31. }
  32. func GetEnvInfo(env string) bool {
  33. viper.AutomaticEnv()
  34. return viper.GetBool(env)
  35. }
  36. func NewDbMaster() *xorm.Engine {
  37. debug := GetEnvInfo("Debug")
  38. configFilePrefix := "config"
  39. configFileName := fmt.Sprintf("%s-pro.yaml", configFilePrefix)
  40. if debug {
  41. configFileName = fmt.Sprintf("%s-debug.yaml", configFilePrefix)
  42. }
  43. v := viper.New()
  44. v.SetConfigFile(configFileName)
  45. if err := v.ReadInConfig(); err != nil {
  46. log.Fatal("读取配置文件出错:", err)
  47. return nil
  48. }
  49. if err := v.Unmarshal(&conf.MysqlConfig); err != nil {
  50. panic(err)
  51. }
  52. sourcename := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8",
  53. conf.MysqlConfig.User,
  54. conf.MysqlConfig.Pwd,
  55. conf.MysqlConfig.Host,
  56. conf.MysqlConfig.Port,
  57. conf.MysqlConfig.Datebase)
  58. instance, err := xorm.NewEngine(conf.DriverName, sourcename)
  59. if err != nil {
  60. log.Fatal("dbhelper.NewDbMaster NewEngine error ", err)
  61. return nil
  62. }
  63. //展示执行的sql语句
  64. instance.ShowSQL(true)
  65. masterInstance = instance
  66. return instance
  67. }