Fix Scopes with Migrator, close #4145

This commit is contained in:
Jinzhu 2021-03-11 10:29:52 +08:00
parent 9fccb17d07
commit 912360097a
3 changed files with 22 additions and 1 deletions

View File

@ -122,6 +122,12 @@ func Open(dialector Dialector, opts ...Option) (db *DB, err error) {
}
}
if d, ok := dialector.(interface{ Apply(*Config) error }); ok {
if err = d.Apply(config); err != nil {
return
}
}
if config.NamingStrategy == nil {
config.NamingStrategy = schema.NamingStrategy{}
}

View File

@ -7,6 +7,13 @@ import (
// Migrator returns migrator
func (db *DB) Migrator() Migrator {
// apply scopes to migrator
scopes := db.Statement.scopes
db.Statement.scopes = nil
for _, scope := range scopes {
db = scope(db)
}
return db.Dialector.Migrator(db.Session(&Session{}))
}

View File

@ -15,7 +15,7 @@ func TestMigrate(t *testing.T) {
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(allModels), func(i, j int) { allModels[i], allModels[j] = allModels[j], allModels[i] })
DB.Migrator().DropTable("user_speaks", "user_friends")
DB.Migrator().DropTable("user_speaks", "user_friends", "ccc")
if err := DB.Migrator().DropTable(allModels...); err != nil {
t.Fatalf("Failed to drop table, got error %v", err)
@ -31,6 +31,14 @@ func TestMigrate(t *testing.T) {
}
}
DB.Scopes(func(db *gorm.DB) *gorm.DB {
return db.Table("ccc")
}).Migrator().CreateTable(&Company{})
if !DB.Migrator().HasTable("ccc") {
t.Errorf("failed to create table ccc")
}
for _, indexes := range [][2]string{
{"user_speaks", "fk_user_speaks_user"},
{"user_speaks", "fk_user_speaks_language"},