Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support multiple gorm #79

Open
philhuan opened this issue Feb 2, 2024 · 4 comments
Open

support multiple gorm #79

philhuan opened this issue Feb 2, 2024 · 4 comments

Comments

@philhuan
Copy link

philhuan commented Feb 2, 2024

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

@afumu
Copy link
Member

afumu commented Feb 2, 2024

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

@MrYZhou
Copy link

MrYZhou commented Feb 25, 2024

我们需要连接到项目中的多个数据库,但 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
}

@philhuan
Copy link
Author

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.

@timandy
Copy link

timandy commented Sep 9, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants