I use Go-GORM to connect to a cockrouch DB cluster. I wrote a helper function to handle the connection and auto migrate part. Everything works fine, except when I want to auto migrate more than 1 model.
err = helperdb.HandleMigrate(db, models.Resource{}, models.Right{})
if err != nil {
helperlog.Log("Clavem", "HandleMigrate", "Error migrating resource:"+err.Error())
return
}
This is the helper function:
// HandleMigrate ...
func HandleMigrate(db *gorm.DB, models ...interface{}) error {
// this need to be checked
err := db.AutoMigrate(models).Error
if err != nil {
fmt.Println("Error HandleMigrate:" + err.Error())
return err
}
return nil
}
I get the following error:
pq: empty table name: "\"\""
When I call gorm.DB.AutoMigrate(&models.Resurce{}, models.Right{})
directly I get no error.
I realise that I do not need a helper function, but I would like to know why the helper functions does not work, especially since it is my first time working my variadic functions.
Thanks :)
Pretty sure you just need to do:
err := db.AutoMigrate(models...).Error
Variadic functions receive the arguments as a slice of the type. In this case your function receives a []interface{}
named models
. When you pass that argument to db.AutoMigrate
, you are passing it as a single argument of type []interface{}
.
What you really want is to pass each value in args as a separate argument (the same way you received them). To do this you must use the ...
syntax.
You just need to pass the models as a variadic arg to your automigrate call. Automigrate accepts multiple model parameters (as in db.AutoMigrate(model1{}, model2{}, model3{})
), not an array.
I threw together an analog example printing strings in the playground here: https://play.golang.org/p/qPTLqBvsen
You need to make this modification:
// HandleMigrate ...
func HandleMigrate(db *gorm.DB, models ...interface{}) error {
// this need to be checked
err := db.AutoMigrate(models...).Error
if err != nil {
fmt.Println("Error HandleMigrate:" + err.Error())
return err
}
return nil
}