gorm-plus icon indicating copy to clipboard operation
gorm-plus copied to clipboard

support multiple gorm

Open philhuan opened this issue 1 year ago • 4 comments

We need to connect to multiple databases in our project, but gplus's gorm as a global variable. can gplus support multi gorm??

philhuan avatar Feb 02 '24 00:02 philhuan

Good idea, we can add it later, or if you're interested, you can submit pr

afumu avatar Feb 02 '24 01:02 afumu

我们需要连接到项目中的多个数据库,但 gplus 的 gorm 是一个全局变量。 gplus 可以支持 multi gorm 吗?

这个似乎和plus没有太大的关系我写了个方法在有需要的地方自己去切换数据源。类似这样: var gormDb *gorm.DB var gormDbMap = make(map[string]*gorm.DB)

func DbChange(tag string){ // gplus的连接的数据库 gormDb := gormDbMap[tag] gplus.Init(gormDb) } func DbInit(tag string,url string) { var err error gormDb, err = gorm.Open(mysql.Open(url+"?charset=utf8mb4&parseTime=True&loc=Local"), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), NamingStrategy: schema.NamingStrategy{ TablePrefix: "", // 数据库表前缀 SingularTable: true, // 不用给表名加复数 NoLowerCase: false, // 要不要把表名全小写 }, // Logger: logger.Discard, // 不输出日志 }) if err != nil { log.Println(err) } gormDbMap[tag] = gormDb }

MrYZhou avatar Feb 25 '24 15:02 MrYZhou

In actual projects, multiple data sources must be used concurrently at the same time, so the value of global variables cannot be switched through one method.

We can provide API of gplus through the methods of an object, and then distinguish different data sources through the attribute values ​​​​of the object.

For example:


gorm1Db, _ = gorm.Open()
gorm2Db, _ = gorm.Open()

gplus1Db = gplus.New(gorm1Db)
gplus2Db = gplus.New(gorm2Db)


users1, resultDb := gplus1Db.SelectList[User](nil)
users2, resultDb := gplus2Db.SelectList[User](nil)

However, this will change the API of gplus.

philhuan avatar Feb 25 '24 16:02 philhuan

For example:


gorm1Db, _ = gorm.Open()
gorm2Db, _ = gorm.Open()

gplus1Db = gplus.New(gorm1Db)
gplus2Db = gplus.New(gorm2Db)


users1, resultDb := gplus1Db.SelectList[User](nil)
users2, resultDb := gplus2Db.SelectList[User](nil)

So far, go doesn't support generic methods.

timandy avatar Sep 09 '24 08:09 timandy