mirror of
https://github.com/go-admin-team/go-admin.git
synced 2026-09-20 17:57:54 +00:00
setupSimpleDatabase runs once per configured database - one per host in the multi-tenant configuration - and passed the same empty key to mycasbin.Setup every time. Setup caches per key, so every host after the first was handed the enforcer built from the first host's database and was authorized against a casbin_rule table that was not its own. Takes effect with the go-admin-core release that keys the cache; before it, Setup ignored the argument entirely.
75 lines
2.1 KiB
Go
75 lines
2.1 KiB
Go
package database
|
|
|
|
import (
|
|
"time"
|
|
|
|
mycasbin "github.com/go-admin-team/go-admin-core/v2/casbin"
|
|
log "github.com/go-admin-team/go-admin-core/v2/logger"
|
|
"github.com/go-admin-team/go-admin-core/v2/sdk"
|
|
toolsConfig "github.com/go-admin-team/go-admin-core/v2/sdk/config"
|
|
"github.com/go-admin-team/go-admin-core/v2/sdk/pkg"
|
|
toolsDB "github.com/go-admin-team/go-admin-core/v2/tools/database"
|
|
. "github.com/go-admin-team/go-admin-core/v2/tools/gorm/gormlog"
|
|
"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])
|
|
}
|
|
}
|
|
|
|
func setupSimpleDatabase(host string, c *toolsConfig.Database) {
|
|
if global.Driver == "" {
|
|
global.Driver = c.Driver
|
|
}
|
|
log.Infof("%s => %s", host, pkg.Green(redactDSN(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)
|
|
}
|
|
open, err := openerFor(c.Driver)
|
|
if err != nil {
|
|
log.Fatal(pkg.Red(err.Error()))
|
|
}
|
|
|
|
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()),
|
|
},
|
|
),
|
|
}, open)
|
|
|
|
if err != nil {
|
|
log.Fatal(pkg.Red(c.Driver+" connect error :"), err)
|
|
} else {
|
|
log.Info(pkg.Green(c.Driver + " connect success !"))
|
|
}
|
|
|
|
// Keyed by host, matching the database this enforcer reads from. Passing
|
|
// the same key for every host would hand each one the enforcer built from
|
|
// whichever database was configured first, and the rest would be decided
|
|
// by a casbin_rule table that is not theirs.
|
|
e := mycasbin.Setup(db, host)
|
|
|
|
sdk.Runtime.SetDbByTenant(host, db)
|
|
sdk.Runtime.SetCasbinByTenant(host, e)
|
|
}
|