initialize.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package database
  2. import (
  3. log "github.com/go-admin-team/go-admin-core/logger"
  4. "github.com/go-admin-team/go-admin-core/sdk"
  5. toolsConfig "github.com/go-admin-team/go-admin-core/sdk/config"
  6. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  7. mycasbin "github.com/go-admin-team/go-admin-core/sdk/pkg/casbin"
  8. toolsDB "github.com/go-admin-team/go-admin-core/tools/database"
  9. // . "github.com/go-admin-team/go-admin-core/tools/gorm/logger"
  10. "github.com/uptrace/opentelemetry-go-extra/otelgorm"
  11. "gorm.io/gorm"
  12. // "gorm.io/gorm/logger"
  13. "gorm.io/gorm/schema"
  14. "go-admin/common/global"
  15. )
  16. // Setup 配置数据库
  17. func Setup() {
  18. for k := range toolsConfig.DatabasesConfig {
  19. setupSimpleDatabase(k, toolsConfig.DatabasesConfig[k], true)
  20. }
  21. }
  22. func SetupWithoutOtel() {
  23. for k := range toolsConfig.DatabasesConfig {
  24. setupSimpleDatabase(k, toolsConfig.DatabasesConfig[k], false)
  25. }
  26. }
  27. func setupSimpleDatabase(host string, c *toolsConfig.Database, otel bool) {
  28. if global.Driver == "" {
  29. global.Driver = c.Driver
  30. }
  31. log.Debugf("%s => %s", host, pkg.Green(c.Source))
  32. registers := make([]toolsDB.ResolverConfigure, len(c.Registers))
  33. for i := range c.Registers {
  34. registers[i] = toolsDB.NewResolverConfigure(
  35. c.Registers[i].Sources,
  36. c.Registers[i].Replicas,
  37. c.Registers[i].Policy,
  38. c.Registers[i].Tables)
  39. }
  40. resolverConfig := toolsDB.NewConfigure(c.Source, c.MaxIdleConns, c.MaxOpenConns, c.ConnMaxIdleTime, c.ConnMaxLifeTime, registers)
  41. db, err := resolverConfig.Init(&gorm.Config{
  42. NamingStrategy: schema.NamingStrategy{
  43. SingularTable: true,
  44. },
  45. // Logger: New(
  46. // logger.Config{
  47. // SlowThreshold: time.Second,
  48. // Colorful: true,
  49. // LogLevel: logger.LogLevel(
  50. // log.DefaultLogger.Options().Level.LevelForGorm()),
  51. // },
  52. // ),
  53. }, opens[c.Driver])
  54. if err != nil {
  55. log.Fatal(pkg.Red(c.Driver+" connect error :"), err)
  56. } else {
  57. log.Info(pkg.Green(c.Driver + " connect success !"))
  58. }
  59. if otel {
  60. db.Use(otelgorm.NewPlugin())
  61. }
  62. sdk.Runtime.SetDb(host, db)
  63. if host == "*" { // 更改了框架的默认行为,*代表mysql库,存储框架相关表,其它为pg, ck,不存储框架相关表
  64. e := mycasbin.Setup(db, "")
  65. sdk.Runtime.SetCasbin(host, e)
  66. }
  67. }