init.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. DisableForeignKeyConstraintWhenMigrating: true,
  45. NamingStrategy: schema.NamingStrategy{
  46. SingularTable: true,
  47. },
  48. Logger: New(
  49. logger.Config{
  50. SlowThreshold: time.Second,
  51. Colorful: true,
  52. LogLevel: logger.LogLevel(
  53. log.DefaultLogger.Options().Level.LevelForGorm()),
  54. },
  55. ),
  56. DisableAutomaticPing: true})
  57. if err != nil {
  58. log.Fatal(pkg.Red("mysql connect error :"), err)
  59. } else {
  60. log.Info(pkg.Green("mysql connect success !"))
  61. }
  62. DB = db
  63. e := mycasbin.Setup(db)
  64. sdk.Runtime.SetDb(toolsConfig.ApplicationConfig.Host, db)
  65. sdk.Runtime.SetCasbin(toolsConfig.ApplicationConfig.Host, e)
  66. }