init.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package db
  2. import (
  3. "gorm.io/driver/mysql"
  4. "gorm.io/gorm"
  5. "gorm.io/gorm/logger"
  6. "gorm.io/gorm/schema"
  7. "time"
  8. log "gogs.baozhida.cn/zoie/OAuth-core/logger"
  9. "gogs.baozhida.cn/zoie/OAuth-core/pkg"
  10. mycasbin "gogs.baozhida.cn/zoie/OAuth-core/pkg/casbin"
  11. "gogs.baozhida.cn/zoie/OAuth-core/sdk"
  12. toolsConfig "gogs.baozhida.cn/zoie/OAuth-core/sdk/config"
  13. toolsDB "gogs.baozhida.cn/zoie/OAuth-core/tools/database"
  14. . "gogs.baozhida.cn/zoie/OAuth-core/tools/gorm/logger"
  15. )
  16. var DB *gorm.DB
  17. // Setup 配置数据库
  18. func Setup() {
  19. c := toolsConfig.DatabaseConfig
  20. registers := make([]toolsDB.ResolverConfigure, len(c.Registers))
  21. for i := range c.Registers {
  22. registers[i] = toolsDB.NewResolverConfigure(
  23. c.Registers[i].Sources,
  24. c.Registers[i].Replicas,
  25. c.Registers[i].Policy,
  26. c.Registers[i].Tables)
  27. }
  28. //resolverConfig := toolsDB.NewConfigure(c.Source, c.MaxIdleConns, c.MaxOpenConns, c.ConnMaxIdleTime, c.ConnMaxLifeTime, registers)
  29. //db, err := resolverConfig.Init(&gorm.Config{
  30. // NamingStrategy: schema.NamingStrategy{
  31. // SingularTable: true,
  32. // },
  33. // Logger: New(
  34. // logger.Config{
  35. // SlowThreshold: time.Second,
  36. // Colorful: true,
  37. // LogLevel: logger.LogLevel(
  38. // log.DefaultLogger.Options().Level.LevelForGorm()),
  39. // },
  40. // ),
  41. // DisableAutomaticPing: true,
  42. //}, mysql.Open)
  43. db, err := gorm.Open(mysql.Open(c.Source), &gorm.Config{
  44. NamingStrategy: schema.NamingStrategy{
  45. SingularTable: true,
  46. },
  47. Logger: New(
  48. logger.Config{
  49. SlowThreshold: time.Second,
  50. Colorful: true,
  51. LogLevel: logger.LogLevel(
  52. log.DefaultLogger.Options().Level.LevelForGorm()),
  53. },
  54. ),
  55. DisableAutomaticPing: true})
  56. if err != nil {
  57. log.Fatal(pkg.Red("mysql connect error :"), err)
  58. } else {
  59. log.Info(pkg.Green("mysql connect success !"))
  60. }
  61. DB = db
  62. e := mycasbin.Setup(db)
  63. sdk.Runtime.SetDb(toolsConfig.ApplicationConfig.Host, db)
  64. sdk.Runtime.SetCasbin(toolsConfig.ApplicationConfig.Host, e)
  65. }