db.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package lxDb
  2. import (
  3. "context"
  4. "fmt"
  5. "git.listensoft.net/tool/lxutils/lxzap"
  6. "github.com/gin-gonic/gin"
  7. "go.uber.org/zap"
  8. "gorm.io/driver/mysql"
  9. "gorm.io/gorm"
  10. "gorm.io/gorm/logger"
  11. "gorm.io/gorm/schema"
  12. "os"
  13. )
  14. // DB2.0 数据库连接 gorm2.0
  15. var DBS map[string]*gorm.DB //gs 数据库
  16. type DbConfig struct {
  17. Name string
  18. Host string
  19. Port string
  20. User string
  21. Password string
  22. Database string
  23. Charset string
  24. }
  25. func GetDB(c *gin.Context, dbName ...string) *gorm.DB {
  26. v, _ := c.Get("X-Span-ID")
  27. spanId := fmt.Sprintf("%v", v)
  28. ctx := context.WithValue(context.Background(), "X-Span-ID", spanId)
  29. d := "one"
  30. if len(dbName) != 0 {
  31. d = dbName[0]
  32. }
  33. return DBS[d].WithContext(ctx)
  34. }
  35. func GetDB2(dbName ...string) *gorm.DB {
  36. d := "one"
  37. if len(dbName) != 0 {
  38. d = dbName[0]
  39. }
  40. return DBS[d]
  41. }
  42. func InitDBS(env string, conf []DbConfig) {
  43. DBS = map[string]*gorm.DB{}
  44. if len(conf) == 1 {
  45. conf[0].Name = "one"
  46. }
  47. for _, config := range conf {
  48. InitDB(env, config)
  49. }
  50. }
  51. func InitDB(env string, conf DbConfig) {
  52. if conf.Name == "" {
  53. DBS = nil
  54. fmt.Println("db name 错误")
  55. return
  56. }
  57. if conf.Host == "" {
  58. DBS = nil
  59. fmt.Println("未配置Db连接")
  60. return
  61. }
  62. if conf.Charset == "" {
  63. conf.Charset = "utf8mb4"
  64. }
  65. dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
  66. conf.User, conf.Password, conf.Host, conf.Port, conf.Database, conf.Charset)
  67. if env == "dev" {
  68. db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
  69. Logger: logger.Default.LogMode(logger.Info),
  70. NamingStrategy: schema.NamingStrategy{
  71. SingularTable: true, // 使用单数表名,启用该选项,此时,`User` 的表名应该是 `user`
  72. },
  73. })
  74. if err != nil {
  75. fmt.Println(err.Error())
  76. os.Exit(-1)
  77. }
  78. DBS[conf.Name] = db
  79. } else {
  80. logger2 := lxzap.NewGormZap(zap.L())
  81. db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
  82. //Logger: logger.Default.LogMode(logger.Info),
  83. Logger: logger2,
  84. NamingStrategy: schema.NamingStrategy{
  85. SingularTable: true, // 使用单数表名,启用该选项,此时,`User` 的表名应该是 `user`
  86. },
  87. })
  88. if err != nil {
  89. fmt.Println(err.Error())
  90. os.Exit(-1)
  91. }
  92. DBS[conf.Name] = db
  93. }
  94. //db.AutoMigrate(TaskData{}, Task{}, Version{})
  95. }