MCPcopy
hub / github.com/go-gorm/gorm / TestMigrate

Function TestMigrate

tests/migrate_test.go:26–84  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

24)
25
26func TestMigrate(t *testing.T) {
27 allModels := []interface{}{&User{}, &Account{}, &Pet{}, &Company{}, &Toy{}, &Language{}, &Tools{}, &Man{}}
28 rand.Seed(time.Now().UnixNano())
29 rand.Shuffle(len(allModels), func(i, j int) { allModels[i], allModels[j] = allModels[j], allModels[i] })
30 DB.Migrator().DropTable("user_speaks", "user_friends", "ccc")
31
32 if err := DB.Migrator().DropTable(allModels...); err != nil {
33 t.Fatalf("Failed to drop table, got error %v", err)
34 }
35
36 if err := DB.AutoMigrate(allModels...); err != nil {
37 t.Fatalf("Failed to auto migrate, got error %v", err)
38 }
39
40 if tables, err := DB.Migrator().GetTables(); err != nil {
41 t.Fatalf("Failed to get database all tables, but got error %v", err)
42 } else {
43 for _, t1 := range []string{"users", "accounts", "pets", "companies", "toys", "languages", "tools"} {
44 hasTable := false
45 for _, t2 := range tables {
46 if t2 == t1 {
47 hasTable = true
48 break
49 }
50 }
51 if !hasTable {
52 t.Fatalf("Failed to get table %v when GetTables", t1)
53 }
54 }
55 }
56
57 for _, m := range allModels {
58 if !DB.Migrator().HasTable(m) {
59 t.Fatalf("Failed to create table for %#v", m)
60 }
61 }
62
63 DB.Scopes(func(db *gorm.DB) *gorm.DB {
64 return db.Table("ccc")
65 }).Migrator().CreateTable(&Company{})
66
67 if !DB.Migrator().HasTable("ccc") {
68 t.Errorf("failed to create table ccc")
69 }
70
71 for _, indexes := range [][2]string{
72 {"user_speaks", "fk_user_speaks_user"},
73 {"user_speaks", "fk_user_speaks_language"},
74 {"user_friends", "fk_user_friends_user"},
75 {"user_friends", "fk_user_friends_friends"},
76 {"accounts", "fk_users_account"},
77 {"users", "fk_users_team"},
78 {"users", "fk_users_company"},
79 } {
80 if !DB.Migrator().HasConstraint(indexes[0], indexes[1]) {
81 t.Fatalf("Failed to find index for many2many for %v %v", indexes[0], indexes[1])
82 }
83 }

Callers

nothing calls this directly

Calls 9

DropTableMethod · 0.65
MigratorMethod · 0.65
AutoMigrateMethod · 0.65
GetTablesMethod · 0.65
HasTableMethod · 0.65
CreateTableMethod · 0.65
ScopesMethod · 0.65
TableMethod · 0.65
HasConstraintMethod · 0.65

Tested by

no test coverage detected