initialize.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package database
  2. import (
  3. log2 "git.cestong.com.cn/cecf/cecf-golib/pkg/log"
  4. "git.cestong.com.cn/cecf/config-center-server/common/global"
  5. log "github.com/go-admin-team/go-admin-core/logger"
  6. "github.com/go-admin-team/go-admin-core/sdk"
  7. toolsConfig "github.com/go-admin-team/go-admin-core/sdk/config"
  8. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  9. mycasbin "github.com/go-admin-team/go-admin-core/sdk/pkg/casbin"
  10. toolsDB "github.com/go-admin-team/go-admin-core/tools/database"
  11. "gorm.io/gorm"
  12. "gorm.io/gorm/schema"
  13. )
  14. // Setup 配置数据库
  15. func Setup() {
  16. for k := range toolsConfig.DatabasesConfig {
  17. setupSimpleDatabase(k, toolsConfig.DatabasesConfig[k])
  18. }
  19. }
  20. func setupSimpleDatabase(host string, c *toolsConfig.Database) {
  21. if global.Driver == "" {
  22. global.Driver = c.Driver
  23. }
  24. log.Infof("%s => %s", host, pkg.Green(c.Source))
  25. registers := make([]toolsDB.ResolverConfigure, len(c.Registers))
  26. for i := range c.Registers {
  27. registers[i] = toolsDB.NewResolverConfigure(
  28. c.Registers[i].Sources,
  29. c.Registers[i].Replicas,
  30. c.Registers[i].Policy,
  31. c.Registers[i].Tables)
  32. }
  33. resolverConfig := toolsDB.NewConfigure(c.Source, c.MaxIdleConns, c.MaxOpenConns, c.ConnMaxIdleTime, c.ConnMaxLifeTime, registers)
  34. db, err := resolverConfig.Init(&gorm.Config{
  35. NamingStrategy: schema.NamingStrategy{
  36. SingularTable: true,
  37. },
  38. //DisableForeignKeyConstraintWhenMigrating: true,
  39. Logger: log2.NewGormLogger(),
  40. }, opens[c.Driver])
  41. if err != nil {
  42. log.Fatal(pkg.Red(c.Driver+" connect error :"), err)
  43. } else {
  44. log.Info(pkg.Green(c.Driver + " connect success !"))
  45. }
  46. e := mycasbin.Setup(db, "sys_")
  47. sdk.Runtime.SetDb(host, db)
  48. sdk.Runtime.SetCasbin(host, e)
  49. }