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?

6
  • Definitely there is no way with GORM (I could find any documentation) but the question if we could do this with GO? Commented Jan 21, 2020 at 8:09
  • You can't get types (or values of those types) by their string names. Commented Jan 21, 2020 at 8:11
  • @icza AutoMigrate accepts the interface type. Could we utilize the behavior? Commented Jan 21, 2020 at 8:49
  • No, you need to pass values of your type (or pointers), and that you cannot get just by their string names in Go. Commented Jan 21, 2020 at 9:03
  • @icza Does casting work with Go? Commented Jan 21, 2020 at 9:16

1 Answer 1

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))
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.