GORM – Golang Change Database at Runtime

Issue

In the UI you can select different options in a dropdown, which relate to data held in different databases. I have created models for the data, and as the table schemas are the same between the DBs, I would like to simply switch between the DBs according to which option the user has selected.

How can this be achieved in GORM 2.0? I would prefer to avoid specifying the "database.tableName" in the queries, as I have frequently used the

db.Model(&model).Where...

pattern.

I have figured out a method, but I was interested to see if there was a way of handling this in the gorm.DB object (or more elegantly at all!).

Current solution:

In the repository, before executing any database operation use the following:

r.db.Exec("use " + utils.GetDB())

and use the API middleware to pick up any changes to the dropdown and set a global variable pertaining to the required database.

Many thanks in advance.

Solution

In the absence of other answers, here is a guide to the solution I decided to use:

var db map[string]*gorm.DB

db = make(map[string]*gorm.DB)
db["db1"], err = gorm.Open(mysql.Open(config.DbURL()), &gorm.Config{})
db["db2"], err = gorm.Open(mysql.Open(config.DbURL()), &gorm.Config{})
db["db3"], err = gorm.Open(mysql.Open(config.DbURL()), &gorm.Config{})

and then when required have a function to return the required database name, returning the instance you wish to use.

db[dbname].Table("table1").Select....

Answered By – CatchingMonkey

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.