12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package database
- import (
- "time"
- log "github.com/go-admin-team/go-admin-core/logger"
- "github.com/go-admin-team/go-admin-core/sdk"
- toolsConfig "github.com/go-admin-team/go-admin-core/sdk/config"
- "github.com/go-admin-team/go-admin-core/sdk/pkg"
- mycasbin "github.com/go-admin-team/go-admin-core/sdk/pkg/casbin"
- toolsDB "github.com/go-admin-team/go-admin-core/tools/database"
- . "github.com/go-admin-team/go-admin-core/tools/gorm/logger"
- "github.com/uptrace/opentelemetry-go-extra/otelgorm"
- "gorm.io/gorm"
- "gorm.io/gorm/logger"
- "gorm.io/gorm/schema"
- "go-admin/common/global"
- )
- // Setup 配置数据库
- func Setup() {
- for k := range toolsConfig.DatabasesConfig {
- setupSimpleDatabase(k, toolsConfig.DatabasesConfig[k], true)
- }
- }
- func SetupWithoutOtel() {
- for k := range toolsConfig.DatabasesConfig {
- setupSimpleDatabase(k, toolsConfig.DatabasesConfig[k], false)
- }
- }
- func setupSimpleDatabase(host string, c *toolsConfig.Database, otel bool) {
- if global.Driver == "" {
- global.Driver = c.Driver
- }
- log.Debugf("%s => %s", host, pkg.Green(c.Source))
- registers := make([]toolsDB.ResolverConfigure, len(c.Registers))
- for i := range c.Registers {
- registers[i] = toolsDB.NewResolverConfigure(
- c.Registers[i].Sources,
- c.Registers[i].Replicas,
- c.Registers[i].Policy,
- c.Registers[i].Tables)
- }
- resolverConfig := toolsDB.NewConfigure(c.Source, c.MaxIdleConns, c.MaxOpenConns, c.ConnMaxIdleTime, c.ConnMaxLifeTime, registers)
- db, err := resolverConfig.Init(&gorm.Config{
- NamingStrategy: schema.NamingStrategy{
- SingularTable: true,
- },
- Logger: New(
- logger.Config{
- SlowThreshold: time.Second,
- Colorful: true,
- LogLevel: logger.LogLevel(
- log.DefaultLogger.Options().Level.LevelForGorm()),
- },
- ),
- }, opens[c.Driver])
- if otel {
- db.Use(otelgorm.NewPlugin())
- }
- if err != nil {
- log.Fatal(pkg.Red(c.Driver+" connect error :"), err)
- } else {
- log.Info(pkg.Green(c.Driver + " connect success !"))
- }
- e := mycasbin.Setup(db, "")
- sdk.Runtime.SetDb(host, db)
- sdk.Runtime.SetCasbin(host, e)
- }
|