0
votes
import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    "server/config"
    "gorm.io/plugin/dbresolver"
)
    
func DB(config *config.Config) {
    var err error

    config.DB, err = gorm.Open("mysql", config.DBDSN)
    if err != nil {
        panic(err)
    }


    if !config.IsDev {
        config.DB.Use(dbresolver.Register(dbresolver.Config{
            Replicas: []gorm.Dialector{mysql.Open("mysql", config.DBDSN2)},
        }))
    }

}

I am trying to use GORM's DBresolver to make use of my cloud SQL instance's read replica. I think there is some versioning issue with the GORM package that I use and the DBresolver plugin. When I run the code above I get the following error:

  • config.DB.Use undefined (type *"github.com/jinzhu/gorm".DB has no field or method Use)
  • undefined: "github.com/jinzhu/gorm".Dialect

I could not find any reason for this online and there are very few online resources on GORM's advanced functionalities. I can easily get the replica to work if I create a separate connection to it, but that way I need to specify the DB every-time I interact with the database. I used the following to implement the code above: https://gorm.io/docs/dbresolver.html

1

1 Answers

2
votes

You are using the v1 import path for gorm, but DBResolver is a V2 feature. You'll want instead to use:

  • "gorm.io/gorm" for the main import package
  • "gorm.io/driver/mysql" for the driver import
  • gorm.Open with mysql.Open for creating the connections.
  • V2 is mostly backwards compatible, but you'll need to make sure any old code is tested to work on the new version.
import (
    "gorm.io/gorm"
    "gorm.io/driver/mysql"
    "gorm.io/plugin/dbresolver"
    "server/config"
)
    
func DB(config *config.Config) {
    var err error

    config.DB, err := gorm.Open(mysql.Open(config.DBDSN), &gorm.Config{})
    if err != nil {
        panic(err)
    }


    if !config.IsDev {
        config.DB.Use(dbresolver.Register(dbresolver.Config{
            Replicas: []gorm.Dialector{mysql.Open("mysql", config.DBDSN2)},
        }))
    }
}