0

I am using gorm to query and manage mysql. The function named SyncDB in the following snippet migrates the latest user schema found in the user.go file under schema directory.

    package db

    import (
       "my-server/db/schema"
       "github.com/jinzhu/gorm"
    )

    func SyncDB(db *gorm.DB) {

        db.AutoMigrate(&schema.User{})

    }

I have multiple files under the schema directory. I tried reading all the file names under the directory schema and have the filenames as an array which looks like:

filenames := []string{
   "user.go",
   "password.go",
   "profile.go",
}

Is there a way to use filenames array and dynamically call:

db.AutoMigrate(&schema.User{})

For example, &schema.User{} gets replaced by &schema.Password{} in the next call. How could I make this thing dynamic?

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

1 Answers1

0

There is not way to send the file. I would suggest to create slice of struct and pass that into AutoMigrate as mentioned below:

values := []interface{}{&schema.User{}, &profile.Profile{}, &password.Password{}}

if err := DB.AutoMigrate(values...).Error; err != nil {
    panic(fmt.Sprintf("No error should happen when create table, but got %+v", err))
}
Prakash Kumar
  • 2,554
  • 2
  • 18
  • 28
  • This is no different from directly passing to `AutoMigrate`. This does not have a solution with `gorm` but the question is if there is a way with `go`. – Suhail Gupta Jan 21 '20 at 08:01