mirror of https://github.com/go-gorm/gorm.git
Fix Scopes with Migrator, close #4145
This commit is contained in:
parent
9fccb17d07
commit
912360097a
6
gorm.go
6
gorm.go
|
@ -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 {
|
if config.NamingStrategy == nil {
|
||||||
config.NamingStrategy = schema.NamingStrategy{}
|
config.NamingStrategy = schema.NamingStrategy{}
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,6 +7,13 @@ import (
|
||||||
|
|
||||||
// Migrator returns migrator
|
// Migrator returns migrator
|
||||||
func (db *DB) Migrator() 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{}))
|
return db.Dialector.Migrator(db.Session(&Session{}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -15,7 +15,7 @@ func TestMigrate(t *testing.T) {
|
||||||
rand.Seed(time.Now().UnixNano())
|
rand.Seed(time.Now().UnixNano())
|
||||||
rand.Shuffle(len(allModels), func(i, j int) { allModels[i], allModels[j] = allModels[j], allModels[i] })
|
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 {
|
if err := DB.Migrator().DropTable(allModels...); err != nil {
|
||||||
t.Fatalf("Failed to drop table, got error %v", err)
|
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{
|
for _, indexes := range [][2]string{
|
||||||
{"user_speaks", "fk_user_speaks_user"},
|
{"user_speaks", "fk_user_speaks_user"},
|
||||||
{"user_speaks", "fk_user_speaks_language"},
|
{"user_speaks", "fk_user_speaks_language"},
|
||||||
|
|
Loading…
Reference in New Issue