initialize.go 2.0 KB

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