Debian Codegraph @

tests/migrate_test.go

raw
1 package tests_test
2
3 import (
4 "context"
5 "database/sql"
6 "fmt"
7 "math/rand"
8 "reflect"
9 "strconv"
10 "strings"
11 "testing"
12 "time"
13
14 "github.com/stretchr/testify/assert"
15 "gorm.io/driver/gaussdb"
16 "gorm.io/driver/postgres"
17
18 "gorm.io/gorm"
19 "gorm.io/gorm/clause"
20 "gorm.io/gorm/migrator"
21 "gorm.io/gorm/schema"
22 "gorm.io/gorm/utils"
23 . "gorm.io/gorm/utils/tests"
24 )
25
26 func 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 }
84 }
85
86 func TestAutoMigrateInt8PGAndGaussDB(t *testing.T) {
87 if DB.Dialector.Name() != "postgres" && DB.Dialector.Name() != "gaussdb" {
88 return
89 }
90
91 type Smallint int8
92
93 type MigrateInt struct {
94 Int8 Smallint
95 }
96
97 tracer := Tracer{
98 Logger: DB.Config.Logger,
99 Test: func(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
100 sql, _ := fc()
101 if strings.HasPrefix(sql, "ALTER TABLE \"migrate_ints\" ALTER COLUMN \"int8\" TYPE smallint") {
102 t.Fatalf("shouldn't execute ALTER COLUMN TYPE if such type is already existed in DB schema: sql: %s",
103 sql)
104 }
105 },
106 }
107
108 DB.Migrator().DropTable(&MigrateInt{})
109
110 // The first AutoMigrate to make table with field with correct type
111 if err := DB.AutoMigrate(&MigrateInt{}); err != nil {
112 t.Fatalf("Failed to auto migrate: error: %v", err)
113 }
114
115 // make new session to set custom logger tracer
116 session := DB.Session(&gorm.Session{Logger: tracer})
117
118 // The second AutoMigrate to catch an error
119 if err := session.AutoMigrate(&MigrateInt{}); err != nil {
120 t.Fatalf("Failed to auto migrate: error: %v", err)
121 }
122 }
123
124 func TestAutoMigrateSelfReferential(t *testing.T) {
125 type MigratePerson struct {
126 ID uint
127 Name string
128 ManagerID *uint
129 Manager *MigratePerson
130 }
131
132 DB.Migrator().DropTable(&MigratePerson{})
133
134 if err := DB.AutoMigrate(&MigratePerson{}); err != nil {
135 t.Fatalf("Failed to auto migrate, but got error %v", err)
136 }
137
138 if !DB.Migrator().HasConstraint("migrate_people", "fk_migrate_people_manager") {
139 t.Fatalf("Failed to find has one constraint between people and managers")
140 }
141 }
142
143 func TestAutoMigrateNullable(t *testing.T) {
144 type MigrateNullableColumn struct {
145 ID uint
146 Bonus float64 `gorm:"not null"`
147 Stock float64
148 }
149
150 DB.Migrator().DropTable(&MigrateNullableColumn{})
151
152 DB.AutoMigrate(&MigrateNullableColumn{})
153
154 type MigrateNullableColumn2 struct {
155 ID uint
156 Bonus float64
157 Stock float64 `gorm:"not null"`
158 }
159
160 if err := DB.Table("migrate_nullable_columns").AutoMigrate(&MigrateNullableColumn2{}); err != nil {
161 t.Fatalf("failed to auto migrate, got error: %v", err)
162 }
163
164 columnTypes, err := DB.Table("migrate_nullable_columns").Migrator().ColumnTypes(&MigrateNullableColumn{})
165 if err != nil {
166 t.Fatalf("failed to get column types, got error: %v", err)
167 }
168
169 for _, columnType := range columnTypes {
170 switch columnType.Name() {
171 case "bonus":
172 // allow to change non-nullable to nullable
173 if nullable, _ := columnType.Nullable(); !nullable {
174 t.Fatalf("bonus's nullable should be true, bug got %t", nullable)
175 }
176 case "stock":
177 // do not allow to change nullable to non-nullable
178 if nullable, _ := columnType.Nullable(); !nullable {
179 t.Fatalf("stock's nullable should be true, bug got %t", nullable)
180 }
181 }
182 }
183 }
184
185 func TestSmartMigrateColumn(t *testing.T) {
186 fullSupported := map[string]bool{"mysql": true, "postgres": true, "gaussdb": true}[DB.Dialector.Name()]
187
188 type UserMigrateColumn struct {
189 ID uint
190 Name string
191 Salary float64
192 Birthday time.Time `gorm:"precision:4"`
193 }
194
195 DB.Migrator().DropTable(&UserMigrateColumn{})
196
197 DB.AutoMigrate(&UserMigrateColumn{})
198
199 type UserMigrateColumn2 struct {
200 ID uint
201 Name string `gorm:"size:128"`
202 Salary float64 `gorm:"precision:2"`
203 Birthday time.Time `gorm:"precision:2"`
204 NameIgnoreMigration string `gorm:"size:100"`
205 }
206
207 if err := DB.Table("user_migrate_columns").AutoMigrate(&UserMigrateColumn2{}); err != nil {
208 t.Fatalf("failed to auto migrate, got error: %v", err)
209 }
210
211 columnTypes, err := DB.Table("user_migrate_columns").Migrator().ColumnTypes(&UserMigrateColumn{})
212 if err != nil {
213 t.Fatalf("failed to get column types, got error: %v", err)
214 }
215
216 for _, columnType := range columnTypes {
217 switch columnType.Name() {
218 case "name":
219 if length, _ := columnType.Length(); (fullSupported || length != 0) && length != 128 {
220 t.Fatalf("name's length should be 128, but got %v", length)
221 }
222 case "salary":
223 if precision, o, _ := columnType.DecimalSize(); (fullSupported || precision != 0) && precision != 2 {
224 t.Fatalf("salary's precision should be 2, but got %v %v", precision, o)
225 }
226 case "birthday":
227 if precision, _, _ := columnType.DecimalSize(); (fullSupported || precision != 0) && precision != 2 {
228 t.Fatalf("birthday's precision should be 2, but got %v", precision)
229 }
230 }
231 }
232
233 type UserMigrateColumn3 struct {
234 ID uint
235 Name string `gorm:"size:256"`
236 Salary float64 `gorm:"precision:3"`
237 Birthday time.Time `gorm:"precision:3"`
238 NameIgnoreMigration string `gorm:"size:128;-:migration"`
239 }
240
241 if err := DB.Table("user_migrate_columns").AutoMigrate(&UserMigrateColumn3{}); err != nil {
242 t.Fatalf("failed to auto migrate, got error: %v", err)
243 }
244
245 columnTypes, err = DB.Table("user_migrate_columns").Migrator().ColumnTypes(&UserMigrateColumn{})
246 if err != nil {
247 t.Fatalf("failed to get column types, got error: %v", err)
248 }
249
250 for _, columnType := range columnTypes {
251 switch columnType.Name() {
252 case "name":
253 if length, _ := columnType.Length(); (fullSupported || length != 0) && length != 256 {
254 t.Fatalf("name's length should be 128, but got %v", length)
255 }
256 case "salary":
257 if precision, _, _ := columnType.DecimalSize(); (fullSupported || precision != 0) && precision != 3 {
258 t.Fatalf("salary's precision should be 2, but got %v", precision)
259 }
260 case "birthday":
261 if precision, _, _ := columnType.DecimalSize(); (fullSupported || precision != 0) && precision != 3 {
262 t.Fatalf("birthday's precision should be 2, but got %v", precision)
263 }
264 case "name_ignore_migration":
265 if length, _ := columnType.Length(); (fullSupported || length != 0) && length != 100 {
266 t.Fatalf("name_ignore_migration's length should still be 100 but got %v", length)
267 }
268 }
269 }
270 }
271
272 func TestSmartMigrateColumnGaussDB(t *testing.T) {
273 fullSupported := map[string]bool{"mysql": true, "gaussdb": true}[DB.Dialector.Name()]
274
275 type UserMigrateColumn struct {
276 ID uint
277 Name string
278 Salary float64
279 Birthday time.Time `gorm:"precision:4"`
280 }
281
282 DB.Migrator().DropTable(&UserMigrateColumn{})
283
284 DB.AutoMigrate(&UserMigrateColumn{})
285
286 type UserMigrateColumn2 struct {
287 ID uint
288 Name string `gorm:"size:128"`
289 Salary float64 `gorm:"precision:2"`
290 Birthday time.Time `gorm:"precision:2"`
291 NameIgnoreMigration string `gorm:"size:100"`
292 }
293
294 if err := DB.Table("user_migrate_columns").AutoMigrate(&UserMigrateColumn2{}); err != nil {
295 t.Fatalf("failed to auto migrate, got error: %v", err)
296 }
297
298 columnTypes, err := DB.Table("user_migrate_columns").Migrator().ColumnTypes(&UserMigrateColumn{})
299 if err != nil {
300 t.Fatalf("failed to get column types, got error: %v", err)
301 }
302
303 for _, columnType := range columnTypes {
304 switch columnType.Name() {
305 case "name":
306 if length, _ := columnType.Length(); (fullSupported || length != 0) && length != 128 {
307 t.Fatalf("name's length should be 128, but got %v", length)
308 }
309 case "salary":
310 if precision, o, _ := columnType.DecimalSize(); (fullSupported || precision != 0) && precision != 2 {
311 t.Fatalf("salary's precision should be 2, but got %v %v", precision, o)
312 }
313 case "birthday":
314 if precision, _, _ := columnType.DecimalSize(); (fullSupported || precision != 0) && precision != 2 {
315 t.Fatalf("birthday's precision should be 2, but got %v", precision)
316 }
317 }
318 }
319
320 type UserMigrateColumn3 struct {
321 ID uint
322 Name string `gorm:"size:256"`
323 Salary float64 `gorm:"precision:3"`
324 Birthday time.Time `gorm:"precision:3"`
325 NameIgnoreMigration string `gorm:"size:128;-:migration"`
326 }
327
328 if err := DB.Table("user_migrate_columns").AutoMigrate(&UserMigrateColumn3{}); err != nil {
329 t.Fatalf("failed to auto migrate, got error: %v", err)
330 }
331
332 columnTypes, err = DB.Table("user_migrate_columns").Migrator().ColumnTypes(&UserMigrateColumn{})
333 if err != nil {
334 t.Fatalf("failed to get column types, got error: %v", err)
335 }
336
337 for _, columnType := range columnTypes {
338 switch columnType.Name() {
339 case "name":
340 if length, _ := columnType.Length(); (fullSupported || length != 0) && length != 256 {
341 t.Fatalf("name's length should be 128, but got %v", length)
342 }
343 case "salary":
344 if precision, _, _ := columnType.DecimalSize(); (fullSupported || precision != 0) && precision != 3 {
345 t.Fatalf("salary's precision should be 2, but got %v", precision)
346 }
347 case "birthday":
348 if precision, _, _ := columnType.DecimalSize(); (fullSupported || precision != 0) && precision != 3 {
349 t.Fatalf("birthday's precision should be 2, but got %v", precision)
350 }
351 case "name_ignore_migration":
352 if length, _ := columnType.Length(); (fullSupported || length != 0) && length != 100 {
353 t.Fatalf("name_ignore_migration's length should still be 100 but got %v", length)
354 }
355 }
356 }
357 }
358
359 func TestMigrateWithColumnComment(t *testing.T) {
360 type UserWithColumnComment struct {
361 gorm.Model
362 Name string `gorm:"size:111;comment:this is a 字段"`
363 }
364
365 if err := DB.Migrator().DropTable(&UserWithColumnComment{}); err != nil {
366 t.Fatalf("Failed to drop table, got error %v", err)
367 }
368
369 if err := DB.AutoMigrate(&UserWithColumnComment{}); err != nil {
370 t.Fatalf("Failed to auto migrate, but got error %v", err)
371 }
372 }
373
374 func TestMigrateWithIndexComment(t *testing.T) {
375 if DB.Dialector.Name() != "mysql" {
376 t.Skip()
377 }
378
379 type UserWithIndexComment struct {
380 gorm.Model
381 Name string `gorm:"size:111;index:,comment:这是一个index"`
382 }
383
384 if err := DB.Migrator().DropTable(&UserWithIndexComment{}); err != nil {
385 t.Fatalf("Failed to drop table, got error %v", err)
386 }
387
388 if err := DB.AutoMigrate(&UserWithIndexComment{}); err != nil {
389 t.Fatalf("Failed to auto migrate, but got error %v", err)
390 }
391 }
392
393 func TestMigrateWithUniqueIndex(t *testing.T) {
394 type UserWithUniqueIndex struct {
395 ID int
396 Name string `gorm:"size:20;index:idx_name,unique"`
397 Date time.Time `gorm:"index:idx_name,unique"`
398 UName string `gorm:"uniqueIndex;size:255"`
399 }
400
401 DB.Migrator().DropTable(&UserWithUniqueIndex{})
402 if err := DB.AutoMigrate(&UserWithUniqueIndex{}); err != nil {
403 t.Fatalf("failed to migrate, got %v", err)
404 }
405
406 if !DB.Migrator().HasIndex(&UserWithUniqueIndex{}, "idx_name") {
407 t.Errorf("Failed to find created index")
408 }
409
410 if !DB.Migrator().HasIndex(&UserWithUniqueIndex{}, "idx_user_with_unique_indices_u_name") {
411 t.Errorf("Failed to find created index")
412 }
413
414 if err := DB.AutoMigrate(&UserWithUniqueIndex{}); err != nil {
415 t.Fatalf("failed to migrate, got %v", err)
416 }
417
418 if !DB.Migrator().HasIndex(&UserWithUniqueIndex{}, "idx_user_with_unique_indices_u_name") {
419 t.Errorf("Failed to find created index")
420 }
421 }
422
423 func TestMigrateTable(t *testing.T) {
424 type TableStruct struct {
425 gorm.Model
426 Name string
427 }
428
429 DB.Migrator().DropTable(&TableStruct{})
430 DB.AutoMigrate(&TableStruct{})
431
432 if !DB.Migrator().HasTable(&TableStruct{}) {
433 t.Fatalf("should found created table")
434 }
435
436 type NewTableStruct struct {
437 gorm.Model
438 Name string
439 }
440
441 if err := DB.Migrator().RenameTable(&TableStruct{}, &NewTableStruct{}); err != nil {
442 t.Fatalf("Failed to rename table, got error %v", err)
443 }
444
445 if !DB.Migrator().HasTable("new_table_structs") {
446 t.Fatal("should found renamed table")
447 }
448
449 DB.Migrator().DropTable("new_table_structs")
450
451 if DB.Migrator().HasTable(&NewTableStruct{}) {
452 t.Fatal("should not found dropped table")
453 }
454 }
455
456 func TestMigrateWithQuotedIndex(t *testing.T) {
457 if DB.Dialector.Name() != "mysql" {
458 t.Skip()
459 }
460
461 type QuotedIndexStruct struct {
462 gorm.Model
463 Name string `gorm:"size:255;index:AS"` // AS is one of MySQL reserved words
464 }
465
466 if err := DB.Migrator().DropTable(&QuotedIndexStruct{}); err != nil {
467 t.Fatalf("Failed to drop table, got error %v", err)
468 }
469
470 if err := DB.AutoMigrate(&QuotedIndexStruct{}); err != nil {
471 t.Fatalf("Failed to auto migrate, but got error %v", err)
472 }
473 }
474
475 func TestMigrateIndexes(t *testing.T) {
476 type IndexStruct struct {
477 gorm.Model
478 Name string `gorm:"size:255;index"`
479 }
480
481 DB.Migrator().DropTable(&IndexStruct{})
482 DB.AutoMigrate(&IndexStruct{})
483
484 if err := DB.Migrator().DropIndex(&IndexStruct{}, "Name"); err != nil {
485 t.Fatalf("Failed to drop index for user's name, got err %v", err)
486 }
487
488 if err := DB.Migrator().CreateIndex(&IndexStruct{}, "Name"); err != nil {
489 t.Fatalf("Got error when tried to create index: %+v", err)
490 }
491
492 if !DB.Migrator().HasIndex(&IndexStruct{}, "Name") {
493 t.Fatalf("Failed to find index for user's name")
494 }
495
496 if err := DB.Migrator().DropIndex(&IndexStruct{}, "Name"); err != nil {
497 t.Fatalf("Failed to drop index for user's name, got err %v", err)
498 }
499
500 if DB.Migrator().HasIndex(&IndexStruct{}, "Name") {
501 t.Fatalf("Should not find index for user's name after delete")
502 }
503
504 if err := DB.Migrator().CreateIndex(&IndexStruct{}, "Name"); err != nil {
505 t.Fatalf("Got error when tried to create index: %+v", err)
506 }
507
508 if err := DB.Migrator().RenameIndex(&IndexStruct{}, "idx_index_structs_name", "idx_users_name_1"); err != nil {
509 t.Fatalf("no error should happen when rename index, but got %v", err)
510 }
511
512 if !DB.Migrator().HasIndex(&IndexStruct{}, "idx_users_name_1") {
513 t.Fatalf("Should find index for user's name after rename")
514 }
515
516 if err := DB.Migrator().DropIndex(&IndexStruct{}, "idx_users_name_1"); err != nil {
517 t.Fatalf("Failed to drop index for user's name, got err %v", err)
518 }
519
520 if DB.Migrator().HasIndex(&IndexStruct{}, "idx_users_name_1") {
521 t.Fatalf("Should not find index for user's name after delete")
522 }
523 }
524
525 func TestTiDBMigrateColumns(t *testing.T) {
526 if !isTiDB() {
527 t.Skip()
528 }
529
530 // TiDB can't change column constraint and has auto_random feature
531 type ColumnStruct struct {
532 ID int `gorm:"primarykey;default:auto_random()"`
533 Name string
534 Age int `gorm:"default:18;comment:my age"`
535 Code string `gorm:"unique;comment:my code;"`
536 Code2 string
537 Code3 string `gorm:"unique"`
538 }
539
540 DB.Migrator().DropTable(&ColumnStruct{})
541
542 if err := DB.AutoMigrate(&ColumnStruct{}); err != nil {
543 t.Errorf("Failed to migrate, got %v", err)
544 }
545
546 type ColumnStruct2 struct {
547 ID int `gorm:"primarykey;default:auto_random()"`
548 Name string `gorm:"size:100"`
549 Code string `gorm:"unique;comment:my code2;default:hello"`
550 Code2 string `gorm:"comment:my code2;default:hello"`
551 }
552
553 if err := DB.Table("column_structs").Migrator().AlterColumn(&ColumnStruct{}, "Name"); err != nil {
554 t.Fatalf("no error should happened when alter column, but got %v", err)
555 }
556
557 if err := DB.Table("column_structs").AutoMigrate(&ColumnStruct2{}); err != nil {
558 t.Fatalf("no error should happened when auto migrate column, but got %v", err)
559 }
560
561 if columnTypes, err := DB.Migrator().ColumnTypes(&ColumnStruct{}); err != nil {
562 t.Fatalf("no error should returns for ColumnTypes")
563 } else {
564 stmt := &gorm.Statement{DB: DB}
565 stmt.Parse(&ColumnStruct2{})
566
567 for _, columnType := range columnTypes {
568 switch columnType.Name() {
569 case "id":
570 if v, ok := columnType.PrimaryKey(); !ok || !v {
571 t.Fatalf("column id primary key should be correct, name: %v, column: %#v", columnType.Name(),
572 columnType)
573 }
574 case "name":
575 dataType := DB.Dialector.DataTypeOf(stmt.Schema.LookUpField(columnType.Name()))
576 if !strings.Contains(strings.ToUpper(dataType), strings.ToUpper(columnType.DatabaseTypeName())) {
577 t.Fatalf("column name type should be correct, name: %v, length: %v, expects: %v, column: %#v",
578 columnType.Name(), columnType.DatabaseTypeName(), dataType, columnType)
579 }
580 if length, ok := columnType.Length(); !ok || length != 100 {
581 t.Fatalf("column name length should be correct, name: %v, length: %v, expects: %v, column: %#v",
582 columnType.Name(), length, 100, columnType)
583 }
584 case "age":
585 if v, ok := columnType.DefaultValue(); !ok || v != "18" {
586 t.Fatalf("column age default value should be correct, name: %v, column: %#v", columnType.Name(),
587 columnType)
588 }
589 if v, ok := columnType.Comment(); !ok || v != "my age" {
590 t.Fatalf("column age comment should be correct, name: %v, column: %#v", columnType.Name(),
591 columnType)
592 }
593 case "code":
594 if v, ok := columnType.Unique(); !ok || !v {
595 t.Fatalf("column code unique should be correct, name: %v, column: %#v", columnType.Name(),
596 columnType)
597 }
598 if v, ok := columnType.DefaultValue(); !ok || v != "hello" {
599 t.Fatalf("column code default value should be correct, name: %v, column: %#v, default value: %v",
600 columnType.Name(), columnType, v)
601 }
602 if v, ok := columnType.Comment(); !ok || v != "my code2" {
603 t.Fatalf("column code comment should be correct, name: %v, column: %#v", columnType.Name(),
604 columnType)
605 }
606 case "code2":
607 // Code2 string `gorm:"comment:my code2;default:hello"`
608 if v, ok := columnType.DefaultValue(); !ok || v != "hello" {
609 t.Fatalf("column code default value should be correct, name: %v, column: %#v, default value: %v",
610 columnType.Name(), columnType, v)
611 }
612 if v, ok := columnType.Comment(); !ok || v != "my code2" {
613 t.Fatalf("column code comment should be correct, name: %v, column: %#v", columnType.Name(),
614 columnType)
615 }
616 }
617 }
618 }
619
620 type NewColumnStruct struct {
621 gorm.Model
622 Name string
623 NewName string
624 }
625
626 if err := DB.Table("column_structs").Migrator().AddColumn(&NewColumnStruct{}, "NewName"); err != nil {
627 t.Fatalf("Failed to add column, got %v", err)
628 }
629
630 if !DB.Table("column_structs").Migrator().HasColumn(&NewColumnStruct{}, "NewName") {
631 t.Fatalf("Failed to find added column")
632 }
633
634 if err := DB.Table("column_structs").Migrator().DropColumn(&NewColumnStruct{}, "NewName"); err != nil {
635 t.Fatalf("Failed to add column, got %v", err)
636 }
637
638 if DB.Table("column_structs").Migrator().HasColumn(&NewColumnStruct{}, "NewName") {
639 t.Fatalf("Found deleted column")
640 }
641
642 if err := DB.Table("column_structs").Migrator().AddColumn(&NewColumnStruct{}, "NewName"); err != nil {
643 t.Fatalf("Failed to add column, got %v", err)
644 }
645
646 if err := DB.Table("column_structs").Migrator().RenameColumn(&NewColumnStruct{}, "NewName",
647 "new_new_name"); err != nil {
648 t.Fatalf("Failed to add column, got %v", err)
649 }
650
651 if !DB.Table("column_structs").Migrator().HasColumn(&NewColumnStruct{}, "new_new_name") {
652 t.Fatalf("Failed to found renamed column")
653 }
654
655 if err := DB.Table("column_structs").Migrator().DropColumn(&NewColumnStruct{}, "new_new_name"); err != nil {
656 t.Fatalf("Failed to add column, got %v", err)
657 }
658
659 if DB.Table("column_structs").Migrator().HasColumn(&NewColumnStruct{}, "new_new_name") {
660 t.Fatalf("Found deleted column")
661 }
662 }
663
664 func TestMigrateColumns(t *testing.T) {
665 tidbSkip(t, "use another test case")
666
667 sqlite := DB.Dialector.Name() == "sqlite"
668 sqlserver := DB.Dialector.Name() == "sqlserver"
669
670 type ColumnStruct struct {
671 gorm.Model
672 Name string
673 Age int `gorm:"default:18;comment:my age"`
674 Code string `gorm:"unique;comment:my code;"`
675 Code2 string
676 Code3 string `gorm:"unique"`
677 }
678
679 DB.Migrator().DropTable(&ColumnStruct{})
680
681 if err := DB.AutoMigrate(&ColumnStruct{}); err != nil {
682 t.Errorf("Failed to migrate, got %v", err)
683 }
684
685 type ColumnStruct2 struct {
686 gorm.Model
687 Name string `gorm:"size:100"`
688 Code string `gorm:"unique;comment:my code2;default:hello"`
689 Code2 string `gorm:"unique"`
690 // Code3 string
691 }
692
693 if err := DB.Table("column_structs").Migrator().AlterColumn(&ColumnStruct{}, "Name"); err != nil {
694 t.Fatalf("no error should happened when alter column, but got %v", err)
695 }
696
697 if err := DB.Table("column_structs").AutoMigrate(&ColumnStruct2{}); err != nil {
698 t.Fatalf("no error should happened when auto migrate column, but got %v", err)
699 }
700
701 if columnTypes, err := DB.Migrator().ColumnTypes(&ColumnStruct{}); err != nil {
702 t.Fatalf("no error should returns for ColumnTypes")
703 } else {
704 stmt := &gorm.Statement{DB: DB}
705 stmt.Parse(&ColumnStruct2{})
706
707 for _, columnType := range columnTypes {
708 switch columnType.Name() {
709 case "id":
710 if v, ok := columnType.PrimaryKey(); !ok || !v {
711 t.Fatalf("column id primary key should be correct, name: %v, column: %#v", columnType.Name(),
712 columnType)
713 }
714 case "name":
715 dataType := DB.Dialector.DataTypeOf(stmt.Schema.LookUpField(columnType.Name()))
716 if !strings.Contains(strings.ToUpper(dataType), strings.ToUpper(columnType.DatabaseTypeName())) {
717 t.Fatalf("column name type should be correct, name: %v, length: %v, expects: %v, column: %#v",
718 columnType.Name(), columnType.DatabaseTypeName(), dataType, columnType)
719 }
720 if length, ok := columnType.Length(); !sqlite && (!ok || length != 100) {
721 t.Fatalf("column name length should be correct, name: %v, length: %v, expects: %v, column: %#v",
722 columnType.Name(), length, 100, columnType)
723 }
724 case "age":
725 if v, ok := columnType.DefaultValue(); !ok || v != "18" {
726 t.Fatalf("column age default value should be correct, name: %v, column: %#v", columnType.Name(),
727 columnType)
728 }
729 if v, ok := columnType.Comment(); !sqlite && !sqlserver && (!ok || v != "my age") {
730 t.Fatalf("column age comment should be correct, name: %v, column: %#v", columnType.Name(),
731 columnType)
732 }
733 case "code":
734 if v, ok := columnType.Unique(); !ok || !v {
735 t.Fatalf("column code unique should be correct, name: %v, column: %#v", columnType.Name(),
736 columnType)
737 }
738 if v, ok := columnType.DefaultValue(); !sqlserver && (!ok || v != "hello") {
739 t.Fatalf("column code default value should be correct, name: %v, column: %#v, default value: %v",
740 columnType.Name(), columnType, v)
741 }
742 if v, ok := columnType.Comment(); !sqlite && !sqlserver && (!ok || v != "my code2") {
743 t.Fatalf("column code comment should be correct, name: %v, column: %#v", columnType.Name(),
744 columnType)
745 }
746 case "code2":
747 if v, ok := columnType.Unique(); !sqlserver && (!ok || !v) {
748 t.Fatalf("column code2 unique should be correct, name: %v, column: %#v", columnType.Name(),
749 columnType)
750 }
751 case "code3":
752 // TODO
753 // if v, ok := columnType.Unique(); !ok || v {
754 // t.Fatalf("column code unique should be correct, name: %v, column: %#v", columnType.Name(), columnType)
755 // }
756 }
757 }
758 }
759
760 type NewColumnStruct struct {
761 gorm.Model
762 Name string
763 NewName string
764 }
765
766 if err := DB.Table("column_structs").Migrator().AddColumn(&NewColumnStruct{}, "NewName"); err != nil {
767 t.Fatalf("Failed to add column, got %v", err)
768 }
769
770 if !DB.Table("column_structs").Migrator().HasColumn(&NewColumnStruct{}, "NewName") {
771 t.Fatalf("Failed to find added column")
772 }
773
774 if err := DB.Table("column_structs").Migrator().DropColumn(&NewColumnStruct{}, "NewName"); err != nil {
775 t.Fatalf("Failed to add column, got %v", err)
776 }
777
778 if DB.Table("column_structs").Migrator().HasColumn(&NewColumnStruct{}, "NewName") {
779 t.Fatalf("Found deleted column")
780 }
781
782 if err := DB.Table("column_structs").Migrator().AddColumn(&NewColumnStruct{}, "NewName"); err != nil {
783 t.Fatalf("Failed to add column, got %v", err)
784 }
785
786 if err := DB.Table("column_structs").Migrator().RenameColumn(&NewColumnStruct{}, "NewName",
787 "new_new_name"); err != nil {
788 t.Fatalf("Failed to add column, got %v", err)
789 }
790
791 if !DB.Table("column_structs").Migrator().HasColumn(&NewColumnStruct{}, "new_new_name") {
792 t.Fatalf("Failed to found renamed column")
793 }
794
795 if err := DB.Table("column_structs").Migrator().DropColumn(&NewColumnStruct{}, "new_new_name"); err != nil {
796 t.Fatalf("Failed to add column, got %v", err)
797 }
798
799 if DB.Table("column_structs").Migrator().HasColumn(&NewColumnStruct{}, "new_new_name") {
800 t.Fatalf("Found deleted column")
801 }
802 }
803
804 func TestMigrateConstraint(t *testing.T) {
805 names := []string{"Account", "fk_users_account", "Pets", "fk_users_pets", "Company", "fk_users_company", "Team", "fk_users_team", "Languages", "fk_users_languages"}
806
807 for _, name := range names {
808 if !DB.Migrator().HasConstraint(&User{}, name) {
809 DB.Migrator().CreateConstraint(&User{}, name)
810 }
811
812 if err := DB.Migrator().DropConstraint(&User{}, name); err != nil {
813 t.Fatalf("failed to drop constraint %v, got error %v", name, err)
814 }
815
816 if DB.Migrator().HasConstraint(&User{}, name) {
817 t.Fatalf("constraint %v should been deleted", name)
818 }
819
820 if err := DB.Migrator().CreateConstraint(&User{}, name); err != nil {
821 t.Fatalf("failed to create constraint %v, got error %v", name, err)
822 }
823
824 if !DB.Migrator().HasConstraint(&User{}, name) {
825 t.Fatalf("failed to found constraint %v", name)
826 }
827 }
828 }
829
830 type DynamicUser struct {
831 gorm.Model
832 Name string
833 CompanyID string `gorm:"index"`
834 }
835
836 // To test auto migrate crate indexes for dynamic table name
837 // https://github.com/go-gorm/gorm/issues/4752
838 func TestMigrateIndexesWithDynamicTableName(t *testing.T) {
839 // Create primary table
840 if err := DB.AutoMigrate(&DynamicUser{}); err != nil {
841 t.Fatalf("AutoMigrate create table error: %#v", err)
842 }
843
844 // Create sub tables
845 for _, v := range []string{"01", "02", "03"} {
846 tableName := "dynamic_users_" + v
847 m := DB.Scopes(func(db *gorm.DB) *gorm.DB {
848 return db.Table(tableName)
849 }).Migrator()
850
851 if err := m.AutoMigrate(&DynamicUser{}); err != nil {
852 t.Fatalf("AutoMigrate create table error: %#v", err)
853 }
854
855 if !m.HasTable(tableName) {
856 t.Fatalf("AutoMigrate expected %#v exist, but not.", tableName)
857 }
858
859 if !m.HasIndex(&DynamicUser{}, "CompanyID") {
860 t.Fatalf("Should have index on %s", "CompanyI.")
861 }
862
863 if !m.HasIndex(&DynamicUser{}, "DeletedAt") {
864 t.Fatalf("Should have index on deleted_at.")
865 }
866 }
867 }
868
869 // check column order after migration, flaky test
870 // https://github.com/go-gorm/gorm/issues/4351
871 func TestMigrateColumnOrder(t *testing.T) {
872 type UserMigrateColumn struct {
873 ID uint
874 }
875 DB.Migrator().DropTable(&UserMigrateColumn{})
876 DB.AutoMigrate(&UserMigrateColumn{})
877
878 type UserMigrateColumn2 struct {
879 ID uint
880 F1 string
881 F2 string
882 F3 string
883 F4 string
884 F5 string
885 F6 string
886 F7 string
887 F8 string
888 F9 string
889 F10 string
890 F11 string
891 F12 string
892 F13 string
893 F14 string
894 F15 string
895 F16 string
896 F17 string
897 F18 string
898 F19 string
899 F20 string
900 F21 string
901 F22 string
902 F23 string
903 F24 string
904 F25 string
905 F26 string
906 F27 string
907 F28 string
908 F29 string
909 F30 string
910 F31 string
911 F32 string
912 F33 string
913 F34 string
914 F35 string
915 }
916 if err := DB.Table("user_migrate_columns").AutoMigrate(&UserMigrateColumn2{}); err != nil {
917 t.Fatalf("failed to auto migrate, got error: %v", err)
918 }
919
920 columnTypes, err := DB.Table("user_migrate_columns").Migrator().ColumnTypes(&UserMigrateColumn2{})
921 if err != nil {
922 t.Fatalf("failed to get column types, got error: %v", err)
923 }
924 typ := reflect.Indirect(reflect.ValueOf(&UserMigrateColumn2{})).Type()
925 numField := typ.NumField()
926 if numField != len(columnTypes) {
927 t.Fatalf("column's number not match struct and ddl, %d != %d", numField, len(columnTypes))
928 }
929 namer := schema.NamingStrategy{}
930 for i := 0; i < numField; i++ {
931 expectName := namer.ColumnName("", typ.Field(i).Name)
932 if columnTypes[i].Name() != expectName {
933 t.Fatalf("column order not match struct and ddl, idx %d: %s != %s",
934 i, columnTypes[i].Name(), expectName)
935 }
936 }
937 }
938
939 // https://github.com/go-gorm/gorm/issues/5047
940 func TestMigrateSerialColumn(t *testing.T) {
941 if DB.Dialector.Name() != "postgres" && DB.Dialector.Name() != "gaussdb" {
942 return
943 }
944
945 type Event struct {
946 ID uint `gorm:"primarykey"`
947 UID uint32
948 }
949
950 type Event1 struct {
951 ID uint `gorm:"primarykey"`
952 UID uint32 `gorm:"not null;autoIncrement"`
953 }
954
955 type Event2 struct {
956 ID uint `gorm:"primarykey"`
957 UID uint16 `gorm:"not null;autoIncrement"`
958 }
959
960 var err error
961 err = DB.Migrator().DropTable(&Event{})
962 if err != nil {
963 t.Errorf("DropTable err:%v", err)
964 }
965
966 // create sequence
967 err = DB.Table("events").AutoMigrate(&Event1{})
968 if err != nil {
969 t.Errorf("AutoMigrate err:%v", err)
970 }
971
972 // delete sequence
973 err = DB.Table("events").AutoMigrate(&Event{})
974 if err != nil {
975 t.Errorf("AutoMigrate err:%v", err)
976 }
977
978 // update sequence
979 err = DB.Table("events").AutoMigrate(&Event1{})
980 if err != nil {
981 t.Errorf("AutoMigrate err:%v", err)
982 }
983 err = DB.Table("events").AutoMigrate(&Event2{})
984 if err != nil {
985 t.Errorf("AutoMigrate err:%v", err)
986 }
987
988 DB.Table("events").Save(&Event2{})
989 DB.Table("events").Save(&Event2{})
990 DB.Table("events").Save(&Event2{})
991
992 events := make([]*Event, 0)
993 DB.Table("events").Find(&events)
994
995 AssertEqual(t, 3, len(events))
996 for _, v := range events {
997 AssertEqual(t, v.ID, v.UID)
998 }
999 }
1000
1001 // https://github.com/go-gorm/gorm/issues/5300
1002 func TestMigrateWithSpecialName(t *testing.T) {
1003 var err error
1004 err = DB.AutoMigrate(&Coupon{})
1005 if err != nil {
1006 t.Fatalf("AutoMigrate err:%v", err)
1007 }
1008 err = DB.Table("coupon_product_1").AutoMigrate(&CouponProduct{})
1009 if err != nil {
1010 t.Fatalf("AutoMigrate err:%v", err)
1011 }
1012 err = DB.Table("coupon_product_2").AutoMigrate(&CouponProduct{})
1013 if err != nil {
1014 t.Fatalf("AutoMigrate err:%v", err)
1015 }
1016
1017 AssertEqual(t, true, DB.Migrator().HasTable("coupons"))
1018 AssertEqual(t, true, DB.Migrator().HasTable("coupon_product_1"))
1019 AssertEqual(t, true, DB.Migrator().HasTable("coupon_product_2"))
1020 }
1021
1022 // https://github.com/go-gorm/gorm/issues/4760
1023 func TestMigrateAutoIncrement(t *testing.T) {
1024 type AutoIncrementStruct struct {
1025 ID int64 `gorm:"primarykey;autoIncrement"`
1026 Field1 uint32 `gorm:"column:field1"`
1027 Field2 float32 `gorm:"column:field2"`
1028 }
1029
1030 if err := DB.AutoMigrate(&AutoIncrementStruct{}); err != nil {
1031 t.Fatalf("AutoMigrate err: %v", err)
1032 }
1033
1034 const ROWS = 10
1035 for idx := 0; idx < ROWS; idx++ {
1036 if err := DB.Create(&AutoIncrementStruct{}).Error; err != nil {
1037 t.Fatalf("create auto_increment_struct fail, err: %v", err)
1038 }
1039 }
1040
1041 rows := make([]*AutoIncrementStruct, 0, ROWS)
1042 if err := DB.Order("id ASC").Find(&rows).Error; err != nil {
1043 t.Fatalf("find auto_increment_struct fail, err: %v", err)
1044 }
1045
1046 ids := make([]int64, 0, len(rows))
1047 for _, row := range rows {
1048 ids = append(ids, row.ID)
1049 }
1050 lastID := ids[len(ids)-1]
1051
1052 if err := DB.Where("id IN (?)", ids).Delete(&AutoIncrementStruct{}).Error; err != nil {
1053 t.Fatalf("delete auto_increment_struct fail, err: %v", err)
1054 }
1055
1056 newRow := &AutoIncrementStruct{}
1057 if err := DB.Create(newRow).Error; err != nil {
1058 t.Fatalf("create auto_increment_struct fail, err: %v", err)
1059 }
1060
1061 AssertEqual(t, newRow.ID, lastID+1)
1062 }
1063
1064 // https://github.com/go-gorm/gorm/issues/5320
1065 func TestPrimarykeyID(t *testing.T) {
1066 if DB.Dialector.Name() != "postgres" {
1067 return
1068 }
1069
1070 type MissPKLanguage struct {
1071 ID string `gorm:"type:uuid;default:uuid_generate_v4()"`
1072 Name string
1073 }
1074
1075 type MissPKUser struct {
1076 ID string `gorm:"type:uuid;default:uuid_generate_v4()"`
1077 MissPKLanguages []MissPKLanguage `gorm:"many2many:miss_pk_user_languages;"`
1078 }
1079
1080 var err error
1081 err = DB.Migrator().DropTable(&MissPKUser{}, &MissPKLanguage{})
1082 if err != nil {
1083 t.Fatalf("DropTable err:%v", err)
1084 }
1085
1086 DB.Exec(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp";`)
1087
1088 err = DB.AutoMigrate(&MissPKUser{}, &MissPKLanguage{})
1089 if err != nil {
1090 t.Fatalf("AutoMigrate err:%v", err)
1091 }
1092
1093 // patch
1094 err = DB.AutoMigrate(&MissPKUser{}, &MissPKLanguage{})
1095 if err != nil {
1096 t.Fatalf("AutoMigrate err:%v", err)
1097 }
1098 }
1099
1100 func TestPrimarykeyIDGaussDB(t *testing.T) {
1101 t.Skipf("This test case skipped, because of gaussdb not support uuid-ossp plugin (SQLSTATE 58P01)")
1102 if DB.Dialector.Name() != "gaussdb" {
1103 return
1104 }
1105
1106 type MissPKLanguage struct {
1107 ID string `gorm:"type:uuid;default:uuid_generate_v4()"`
1108 Name string
1109 }
1110
1111 type MissPKUser struct {
1112 ID string `gorm:"type:uuid;default:uuid_generate_v4()"`
1113 MissPKLanguages []MissPKLanguage `gorm:"many2many:miss_pk_user_languages;"`
1114 }
1115
1116 var err error
1117 err = DB.Migrator().DropTable(&MissPKUser{}, &MissPKLanguage{})
1118 if err != nil {
1119 t.Fatalf("DropTable err:%v", err)
1120 }
1121 // TODO: ERROR: could not open extension control file: No such file or directory (SQLSTATE 58P01)
1122 DB.Exec(`CREATE EXTENSION IF NOT EXISTS "uuid-ossp";`)
1123
1124 err = DB.AutoMigrate(&MissPKUser{}, &MissPKLanguage{})
1125 if err != nil {
1126 t.Fatalf("AutoMigrate err:%v", err)
1127 }
1128
1129 // patch
1130 err = DB.AutoMigrate(&MissPKUser{}, &MissPKLanguage{})
1131 if err != nil {
1132 t.Fatalf("AutoMigrate err:%v", err)
1133 }
1134 }
1135
1136 func TestCurrentTimestamp(t *testing.T) {
1137 if DB.Dialector.Name() != "mysql" {
1138 return
1139 }
1140 type CurrentTimestampTest struct {
1141 ID string `gorm:"primary_key"`
1142 TimeAt *time.Time `gorm:"type:datetime;not null;default:CURRENT_TIMESTAMP;unique"`
1143 }
1144 var err error
1145 err = DB.Migrator().DropTable(&CurrentTimestampTest{})
1146 if err != nil {
1147 t.Errorf("DropTable err:%v", err)
1148 }
1149 err = DB.AutoMigrate(&CurrentTimestampTest{})
1150 if err != nil {
1151 t.Fatalf("AutoMigrate err:%v", err)
1152 }
1153
1154 err = DB.AutoMigrate(&CurrentTimestampTest{})
1155 if err != nil {
1156 t.Fatalf("AutoMigrate err:%v", err)
1157 }
1158 AssertEqual(t, true, DB.Migrator().HasConstraint(&CurrentTimestampTest{}, "uni_current_timestamp_tests_time_at"))
1159 AssertEqual(t, false, DB.Migrator().HasIndex(&CurrentTimestampTest{}, "time_at"))
1160 AssertEqual(t, false, DB.Migrator().HasIndex(&CurrentTimestampTest{}, "time_at_2"))
1161 }
1162
1163 func TestUniqueColumn(t *testing.T) {
1164 if DB.Dialector.Name() != "mysql" {
1165 return
1166 }
1167
1168 type UniqueTest struct {
1169 ID string `gorm:"primary_key"`
1170 Name string `gorm:"unique"`
1171 }
1172
1173 type UniqueTest2 struct {
1174 ID string `gorm:"primary_key"`
1175 Name string `gorm:"unique;default:NULL"`
1176 }
1177
1178 type UniqueTest3 struct {
1179 ID string `gorm:"primary_key"`
1180 Name string `gorm:"unique;default:''"`
1181 }
1182
1183 type UniqueTest4 struct {
1184 ID string `gorm:"primary_key"`
1185 Name string `gorm:"unique;default:'123'"`
1186 }
1187
1188 var err error
1189 err = DB.Migrator().DropTable(&UniqueTest{})
1190 if err != nil {
1191 t.Errorf("DropTable err:%v", err)
1192 }
1193
1194 err = DB.AutoMigrate(&UniqueTest{})
1195 if err != nil {
1196 t.Fatalf("AutoMigrate err:%v", err)
1197 }
1198
1199 // null -> null
1200 err = DB.AutoMigrate(&UniqueTest{})
1201 if err != nil {
1202 t.Fatalf("AutoMigrate err:%v", err)
1203 }
1204
1205 ct, err := findColumnType(&UniqueTest{}, "name")
1206 if err != nil {
1207 t.Fatalf("findColumnType err:%v", err)
1208 }
1209
1210 value, ok := ct.DefaultValue()
1211 AssertEqual(t, "", value)
1212 AssertEqual(t, false, ok)
1213
1214 // null -> null
1215 err = DB.Table("unique_tests").AutoMigrate(&UniqueTest2{})
1216 if err != nil {
1217 t.Fatalf("AutoMigrate err:%v", err)
1218 }
1219
1220 // not trigger alert column
1221 AssertEqual(t, true, DB.Migrator().HasConstraint(&UniqueTest{}, "uni_unique_tests_name"))
1222 AssertEqual(t, false, DB.Migrator().HasIndex(&UniqueTest{}, "name"))
1223 AssertEqual(t, false, DB.Migrator().HasIndex(&UniqueTest{}, "name_1"))
1224 AssertEqual(t, false, DB.Migrator().HasIndex(&UniqueTest{}, "name_2"))
1225
1226 ct, err = findColumnType(&UniqueTest{}, "name")
1227 if err != nil {
1228 t.Fatalf("findColumnType err:%v", err)
1229 }
1230
1231 value, ok = ct.DefaultValue()
1232 AssertEqual(t, "", value)
1233 AssertEqual(t, false, ok)
1234
1235 tidbSkip(t, "can't change column constraint")
1236
1237 // null -> empty string
1238 err = DB.Table("unique_tests").AutoMigrate(&UniqueTest3{})
1239 if err != nil {
1240 t.Fatalf("AutoMigrate err:%v", err)
1241 }
1242
1243 ct, err = findColumnType(&UniqueTest{}, "name")
1244 if err != nil {
1245 t.Fatalf("findColumnType err:%v", err)
1246 }
1247
1248 value, ok = ct.DefaultValue()
1249 AssertEqual(t, "", value)
1250 AssertEqual(t, true, ok)
1251
1252 // empty string -> 123
1253 err = DB.Table("unique_tests").AutoMigrate(&UniqueTest4{})
1254 if err != nil {
1255 t.Fatalf("AutoMigrate err:%v", err)
1256 }
1257
1258 ct, err = findColumnType(&UniqueTest{}, "name")
1259 if err != nil {
1260 t.Fatalf("findColumnType err:%v", err)
1261 }
1262
1263 value, ok = ct.DefaultValue()
1264 AssertEqual(t, "123", value)
1265 AssertEqual(t, true, ok)
1266
1267 // 123 -> null
1268 err = DB.Table("unique_tests").AutoMigrate(&UniqueTest2{})
1269 if err != nil {
1270 t.Fatalf("AutoMigrate err:%v", err)
1271 }
1272
1273 ct, err = findColumnType(&UniqueTest{}, "name")
1274 if err != nil {
1275 t.Fatalf("findColumnType err:%v", err)
1276 }
1277
1278 value, ok = ct.DefaultValue()
1279 AssertEqual(t, "", value)
1280 AssertEqual(t, false, ok)
1281 }
1282
1283 func findColumnType(dest interface{}, columnName string) (
1284 foundColumn gorm.ColumnType, err error,
1285 ) {
1286 columnTypes, err := DB.Migrator().ColumnTypes(dest)
1287 if err != nil {
1288 err = fmt.Errorf("ColumnTypes err:%v", err)
1289 return
1290 }
1291
1292 for _, c := range columnTypes {
1293 if c.Name() == columnName {
1294 foundColumn = c
1295 break
1296 }
1297 }
1298 return
1299 }
1300
1301 func TestInvalidCachedPlanSimpleProtocol(t *testing.T) {
1302 if DB.Dialector.Name() != "postgres" {
1303 return
1304 }
1305
1306 db, err := gorm.Open(postgres.Open(postgresDSN), &gorm.Config{})
1307 if err != nil {
1308 t.Errorf("Open err:%v", err)
1309 }
1310
1311 type Object1 struct{}
1312 type Object2 struct {
1313 Field1 string
1314 }
1315 type Object3 struct {
1316 Field2 string
1317 }
1318 db.Migrator().DropTable("objects")
1319
1320 err = db.Table("objects").AutoMigrate(&Object1{})
1321 if err != nil {
1322 t.Errorf("AutoMigrate err:%v", err)
1323 }
1324
1325 err = db.Table("objects").AutoMigrate(&Object2{})
1326 if err != nil {
1327 t.Errorf("AutoMigrate err:%v", err)
1328 }
1329
1330 err = db.Table("objects").AutoMigrate(&Object3{})
1331 if err != nil {
1332 t.Errorf("AutoMigrate err:%v", err)
1333 }
1334 }
1335
1336 // TODO: ERROR: must have at least one column (SQLSTATE 0A000)
1337 func TestInvalidCachedPlanSimpleProtocolGaussDB(t *testing.T) {
1338 t.Skipf("This test case skipped, because of gaussdb not support creaing empty table(SQLSTATE 0A000)")
1339 if DB.Dialector.Name() != "gaussdb" {
1340 return
1341 }
1342
1343 db, err := gorm.Open(gaussdb.Open(gaussdbDSN), &gorm.Config{})
1344 if err != nil {
1345 t.Errorf("Open err:%v", err)
1346 }
1347
1348 type Object1 struct{}
1349 type Object2 struct {
1350 Field1 string
1351 }
1352 type Object3 struct {
1353 Field2 string
1354 }
1355 db.Migrator().DropTable("objects")
1356
1357 err = db.Table("objects").AutoMigrate(&Object1{})
1358 if err != nil {
1359 t.Errorf("AutoMigrate err:%v", err)
1360 }
1361
1362 err = db.Table("objects").AutoMigrate(&Object2{})
1363 if err != nil {
1364 t.Errorf("AutoMigrate err:%v", err)
1365 }
1366
1367 err = db.Table("objects").AutoMigrate(&Object3{})
1368 if err != nil {
1369 t.Errorf("AutoMigrate err:%v", err)
1370 }
1371 }
1372
1373 func TestDifferentTypeWithoutDeclaredLength(t *testing.T) {
1374 type DiffType struct {
1375 ID uint
1376 Name string `gorm:"type:varchar(20)"`
1377 }
1378
1379 type DiffType1 struct {
1380 ID uint
1381 Name string `gorm:"type:text"`
1382 }
1383
1384 var err error
1385 DB.Migrator().DropTable(&DiffType{})
1386
1387 err = DB.AutoMigrate(&DiffType{})
1388 if err != nil {
1389 t.Errorf("AutoMigrate err:%v", err)
1390 }
1391
1392 ct, err := findColumnType(&DiffType{}, "name")
1393 if err != nil {
1394 t.Errorf("findColumnType err:%v", err)
1395 }
1396
1397 AssertEqual(t, "varchar", strings.ToLower(ct.DatabaseTypeName()))
1398
1399 err = DB.Table("diff_types").AutoMigrate(&DiffType1{})
1400 if err != nil {
1401 t.Errorf("AutoMigrate err:%v", err)
1402 }
1403
1404 ct, err = findColumnType(&DiffType{}, "name")
1405 if err != nil {
1406 t.Errorf("findColumnType err:%v", err)
1407 }
1408
1409 AssertEqual(t, "text", strings.ToLower(ct.DatabaseTypeName()))
1410 }
1411
1412 func TestMigrateArrayTypeModel(t *testing.T) {
1413 if DB.Dialector.Name() != "postgres" && DB.Dialector.Name() != "gaussdb" {
1414 return
1415 }
1416
1417 type ArrayTypeModel struct {
1418 ID uint
1419 Number string `gorm:"type:varchar(51);NOT NULL"`
1420 TextArray []string `gorm:"type:text[];NOT NULL"`
1421 NestedTextArray [][]string `gorm:"type:text[][]"`
1422 NestedIntArray [][]int64 `gorm:"type:integer[3][3]"`
1423 }
1424
1425 var err error
1426 DB.Migrator().DropTable(&ArrayTypeModel{})
1427
1428 err = DB.AutoMigrate(&ArrayTypeModel{})
1429 AssertEqual(t, nil, err)
1430
1431 ct, err := findColumnType(&ArrayTypeModel{}, "number")
1432 AssertEqual(t, nil, err)
1433 AssertEqual(t, "varchar", ct.DatabaseTypeName())
1434
1435 ct, err = findColumnType(&ArrayTypeModel{}, "text_array")
1436 AssertEqual(t, nil, err)
1437 AssertEqual(t, "text[]", ct.DatabaseTypeName())
1438
1439 ct, err = findColumnType(&ArrayTypeModel{}, "nested_text_array")
1440 AssertEqual(t, nil, err)
1441 AssertEqual(t, "text[]", ct.DatabaseTypeName())
1442
1443 ct, err = findColumnType(&ArrayTypeModel{}, "nested_int_array")
1444 AssertEqual(t, nil, err)
1445 AssertEqual(t, "integer[]", ct.DatabaseTypeName())
1446 }
1447
1448 type mockMigrator struct {
1449 gorm.Migrator
1450 }
1451
1452 func (mm mockMigrator) AlterColumn(dst interface{}, field string) error {
1453 err := mm.Migrator.AlterColumn(dst, field)
1454 if err != nil {
1455 return err
1456 }
1457 return fmt.Errorf("trigger alter column error, field: %s", field)
1458 }
1459
1460 func TestMigrateDonotAlterColumn(t *testing.T) {
1461 wrapMockMigrator := func(m gorm.Migrator) mockMigrator {
1462 return mockMigrator{
1463 Migrator: m,
1464 }
1465 }
1466 m := DB.Migrator()
1467 mockM := wrapMockMigrator(m)
1468
1469 type NotTriggerUpdate struct {
1470 ID uint
1471 F1 uint16
1472 F2 uint32
1473 F3 int
1474 F4 int64
1475 F5 string
1476 F6 float32
1477 F7 float64
1478 F8 time.Time
1479 F9 bool
1480 F10 []byte
1481 }
1482
1483 var err error
1484 err = mockM.DropTable(&NotTriggerUpdate{})
1485 AssertEqual(t, err, nil)
1486 err = mockM.AutoMigrate(&NotTriggerUpdate{})
1487 AssertEqual(t, err, nil)
1488 err = mockM.AutoMigrate(&NotTriggerUpdate{})
1489 AssertEqual(t, err, nil)
1490 }
1491
1492 func TestMigrateSameEmbeddedFieldName(t *testing.T) {
1493 type UserStat struct {
1494 GroundDestroyCount int
1495 }
1496
1497 type GameUser struct {
1498 gorm.Model
1499 StatAb UserStat `gorm:"embedded;embeddedPrefix:stat_ab_"`
1500 }
1501
1502 type UserStat1 struct {
1503 GroundDestroyCount string
1504 }
1505
1506 type GroundRate struct {
1507 GroundDestroyCount int
1508 }
1509
1510 type GameUser1 struct {
1511 gorm.Model
1512 StatAb UserStat1 `gorm:"embedded;embeddedPrefix:stat_ab_"`
1513 GroundRateRb GroundRate `gorm:"embedded;embeddedPrefix:rate_ground_rb_"`
1514 }
1515
1516 DB.Migrator().DropTable(&GameUser{})
1517 err := DB.AutoMigrate(&GameUser{})
1518 AssertEqual(t, nil, err)
1519
1520 err = DB.Table("game_users").AutoMigrate(&GameUser1{})
1521 AssertEqual(t, nil, err)
1522
1523 _, err = findColumnType(&GameUser{}, "stat_ab_ground_destroy_count")
1524 AssertEqual(t, nil, err)
1525
1526 _, err = findColumnType(&GameUser{}, "rate_ground_rb_ground_destroy_count")
1527 AssertEqual(t, nil, err)
1528 }
1529
1530 func TestMigrateWithDefaultValue(t *testing.T) {
1531 if DB.Dialector.Name() == "sqlserver" {
1532 // sqlserver driver treats NULL and 'NULL' the same
1533 t.Skip("skip sqlserver")
1534 }
1535
1536 type NullModel struct {
1537 ID uint
1538 Content string `gorm:"default:null"`
1539 }
1540
1541 type NullStringModel struct {
1542 ID uint
1543 Content string `gorm:"default:'null'"`
1544 Active bool `gorm:"default:false"`
1545 }
1546
1547 tableName := "null_string_model"
1548
1549 DB.Migrator().DropTable(tableName)
1550
1551 err := DB.Table(tableName).AutoMigrate(&NullModel{})
1552 AssertEqual(t, err, nil)
1553
1554 // default null -> 'null'
1555 err = DB.Table(tableName).AutoMigrate(&NullStringModel{})
1556 AssertEqual(t, err, nil)
1557
1558 columnType, err := findColumnType(tableName, "content")
1559 AssertEqual(t, err, nil)
1560
1561 defVal, ok := columnType.DefaultValue()
1562 AssertEqual(t, defVal, "null")
1563 AssertEqual(t, ok, true)
1564
1565 columnType2, err := findColumnType(tableName, "active")
1566 AssertEqual(t, err, nil)
1567
1568 defVal, ok = columnType2.DefaultValue()
1569 bv, _ := strconv.ParseBool(defVal)
1570 AssertEqual(t, bv, false)
1571 AssertEqual(t, ok, true)
1572
1573 // default 'null' -> 'null'
1574 session := DB.Session(&gorm.Session{Logger: Tracer{
1575 Logger: DB.Config.Logger,
1576 Test: func(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
1577 sql, _ := fc()
1578 if strings.HasPrefix(sql, "ALTER TABLE") {
1579 t.Errorf("shouldn't execute: sql=%s", sql)
1580 }
1581 },
1582 }})
1583 err = session.Table(tableName).AutoMigrate(&NullStringModel{})
1584 AssertEqual(t, err, nil)
1585
1586 columnType, err = findColumnType(tableName, "content")
1587 AssertEqual(t, err, nil)
1588
1589 defVal, ok = columnType.DefaultValue()
1590 AssertEqual(t, defVal, "null")
1591 AssertEqual(t, ok, true)
1592
1593 // default 'null' -> null
1594 err = DB.Table(tableName).AutoMigrate(&NullModel{})
1595 AssertEqual(t, err, nil)
1596
1597 columnType, err = findColumnType(tableName, "content")
1598 AssertEqual(t, err, nil)
1599
1600 defVal, ok = columnType.DefaultValue()
1601 AssertEqual(t, defVal, "")
1602 AssertEqual(t, ok, false)
1603 }
1604
1605 func TestMigrateMySQLWithCustomizedTypes(t *testing.T) {
1606 if DB.Dialector.Name() != "mysql" {
1607 t.Skip()
1608 }
1609
1610 type MyTable struct {
1611 Def string `gorm:"size:512;index:idx_def,unique"`
1612 Abc string `gorm:"size:65000000"`
1613 }
1614
1615 DB.Migrator().DropTable("my_tables")
1616
1617 sql := "CREATE TABLE `my_tables` (`def` varchar(512),`abc` longtext,UNIQUE INDEX `idx_def` (`def`))"
1618 if err := DB.Exec(sql).Error; err != nil {
1619 t.Errorf("Failed, got error: %v", err)
1620 }
1621
1622 session := DB.Session(&gorm.Session{Logger: Tracer{
1623 Logger: DB.Config.Logger,
1624 Test: func(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
1625 sql, _ := fc()
1626 if strings.HasPrefix(sql, "ALTER TABLE") {
1627 t.Errorf("shouldn't execute: sql=%s", sql)
1628 }
1629 },
1630 }})
1631
1632 if err := session.AutoMigrate(&MyTable{}); err != nil {
1633 t.Errorf("Failed, got error: %v", err)
1634 }
1635 }
1636
1637 func TestMigrateIgnoreRelations(t *testing.T) {
1638 type RelationModel1 struct {
1639 ID uint
1640 }
1641 type RelationModel2 struct {
1642 ID uint
1643 }
1644 type RelationModel3 struct {
1645 ID uint
1646 RelationModel1ID uint
1647 RelationModel1 *RelationModel1
1648 RelationModel2ID uint
1649 RelationModel2 *RelationModel2 `gorm:"-:migration"`
1650 }
1651
1652 var err error
1653 _ = DB.Migrator().DropTable(&RelationModel1{}, &RelationModel2{}, &RelationModel3{})
1654
1655 tx := DB.Session(&gorm.Session{})
1656 tx.IgnoreRelationshipsWhenMigrating = true
1657
1658 err = tx.AutoMigrate(&RelationModel3{})
1659 if err != nil {
1660 t.Errorf("AutoMigrate err:%v", err)
1661 }
1662
1663 // RelationModel3 should be existed
1664 _, err = findColumnType(&RelationModel3{}, "id")
1665 AssertEqual(t, nil, err)
1666
1667 // RelationModel1 should not be existed
1668 _, err = findColumnType(&RelationModel1{}, "id")
1669 if err == nil {
1670 t.Errorf("RelationModel1 should not be migrated")
1671 }
1672
1673 // RelationModel2 should not be existed
1674 _, err = findColumnType(&RelationModel2{}, "id")
1675 if err == nil {
1676 t.Errorf("RelationModel2 should not be migrated")
1677 }
1678
1679 tx.IgnoreRelationshipsWhenMigrating = false
1680
1681 err = tx.AutoMigrate(&RelationModel3{})
1682 if err != nil {
1683 t.Errorf("AutoMigrate err:%v", err)
1684 }
1685
1686 // RelationModel3 should be existed
1687 _, err = findColumnType(&RelationModel3{}, "id")
1688 AssertEqual(t, nil, err)
1689
1690 // RelationModel1 should be existed
1691 _, err = findColumnType(&RelationModel1{}, "id")
1692 AssertEqual(t, nil, err)
1693
1694 // RelationModel2 should not be existed
1695 _, err = findColumnType(&RelationModel2{}, "id")
1696 if err == nil {
1697 t.Errorf("RelationModel2 should not be migrated")
1698 }
1699 }
1700
1701 func TestMigrateView(t *testing.T) {
1702 DB.Save(GetUser("joins-args-db", Config{Pets: 2}))
1703
1704 if err := DB.Migrator().CreateView("invalid_users_pets",
1705 gorm.ViewOption{Query: nil}); err != gorm.ErrSubQueryRequired {
1706 t.Fatalf("no view should be created, got %v", err)
1707 }
1708
1709 query := DB.Model(&User{}).
1710 Select("users.id as users_id, users.name as users_name, pets.id as pets_id, pets.name as pets_name").
1711 Joins("inner join pets on pets.user_id = users.id")
1712
1713 if err := DB.Migrator().CreateView("users_pets", gorm.ViewOption{Query: query}); err != nil {
1714 t.Fatalf("Failed to crate view, got %v", err)
1715 }
1716
1717 var count int64
1718 if err := DB.Table("users_pets").Count(&count).Error; err != nil {
1719 t.Fatalf("should found created view")
1720 }
1721
1722 if err := DB.Migrator().DropView("users_pets"); err != nil {
1723 t.Fatalf("Failed to drop view, got %v", err)
1724 }
1725
1726 query = DB.Model(&User{}).Where("age > ?", 20)
1727 if err := DB.Migrator().CreateView("users_view", gorm.ViewOption{Query: query}); err != nil {
1728 t.Fatalf("Failed to crate view, got %v", err)
1729 }
1730 if err := DB.Migrator().DropView("users_view"); err != nil {
1731 t.Fatalf("Failed to drop view, got %v", err)
1732 }
1733 }
1734
1735 func TestMigrateExistingBoolColumnPGAndGaussDB(t *testing.T) {
1736 if DB.Dialector.Name() != "postgres" && DB.Dialector.Name() != "gaussdb" {
1737 return
1738 }
1739
1740 type ColumnStruct struct {
1741 gorm.Model
1742 Name string
1743 StringBool string
1744 SmallintBool int `gorm:"type:smallint"`
1745 }
1746
1747 type ColumnStruct2 struct {
1748 gorm.Model
1749 Name string
1750 StringBool bool // change existing boolean column from string to boolean
1751 SmallintBool bool // change existing boolean column from smallint or other to boolean
1752 }
1753
1754 DB.Migrator().DropTable(&ColumnStruct{})
1755
1756 if err := DB.AutoMigrate(&ColumnStruct{}); err != nil {
1757 t.Errorf("Failed to migrate, got %v", err)
1758 }
1759
1760 if err := DB.Table("column_structs").AutoMigrate(&ColumnStruct2{}); err != nil {
1761 t.Fatalf("no error should happened when auto migrate column, but got %v", err)
1762 }
1763
1764 if columnTypes, err := DB.Migrator().ColumnTypes(&ColumnStruct{}); err != nil {
1765 t.Fatalf("no error should returns for ColumnTypes")
1766 } else {
1767 stmt := &gorm.Statement{DB: DB}
1768 stmt.Parse(&ColumnStruct2{})
1769
1770 for _, columnType := range columnTypes {
1771 switch columnType.Name() {
1772 case "id":
1773 if v, ok := columnType.PrimaryKey(); !ok || !v {
1774 t.Fatalf("column id primary key should be correct, name: %v, column: %#v", columnType.Name(),
1775 columnType)
1776 }
1777 case "string_bool":
1778 dataType := DB.Dialector.DataTypeOf(stmt.Schema.LookUpField(columnType.Name()))
1779 if !strings.Contains(strings.ToUpper(dataType), strings.ToUpper(columnType.DatabaseTypeName())) {
1780 t.Fatalf("column name type should be correct, name: %v, length: %v, expects: %v, column: %#v",
1781 columnType.Name(), columnType.DatabaseTypeName(), dataType, columnType)
1782 }
1783 case "smallint_bool":
1784 dataType := DB.Dialector.DataTypeOf(stmt.Schema.LookUpField(columnType.Name()))
1785 if !strings.Contains(strings.ToUpper(dataType), strings.ToUpper(columnType.DatabaseTypeName())) {
1786 t.Fatalf("column name type should be correct, name: %v, length: %v, expects: %v, column: %#v",
1787 columnType.Name(), columnType.DatabaseTypeName(), dataType, columnType)
1788 }
1789 }
1790 }
1791 }
1792 }
1793
1794 func TestTableType(t *testing.T) {
1795 // currently it is only supported for mysql driver
1796 if !isMysql() {
1797 return
1798 }
1799
1800 const tblName = "cities"
1801 const tblSchema = "gorm"
1802 const tblType = "BASE TABLE"
1803 const tblComment = "foobar comment"
1804
1805 type City struct {
1806 gorm.Model
1807 Name string `gorm:"unique"`
1808 }
1809
1810 DB.Migrator().DropTable(&City{})
1811
1812 if err := DB.Set("gorm:table_options",
1813 fmt.Sprintf("ENGINE InnoDB COMMENT '%s'", tblComment)).AutoMigrate(&City{}); err != nil {
1814 t.Fatalf("failed to migrate cities tables, got error: %v", err)
1815 }
1816
1817 tableType, err := DB.Table("cities").Migrator().TableType(&City{})
1818 if err != nil {
1819 t.Fatalf("failed to get table type, got error %v", err)
1820 }
1821
1822 if tableType.Schema() != tblSchema {
1823 t.Fatalf("expected tblSchema to be %s but got %s", tblSchema, tableType.Schema())
1824 }
1825
1826 if tableType.Name() != tblName {
1827 t.Fatalf("expected table name to be %s but got %s", tblName, tableType.Name())
1828 }
1829
1830 if tableType.Type() != tblType {
1831 t.Fatalf("expected table type to be %s but got %s", tblType, tableType.Type())
1832 }
1833
1834 comment, ok := tableType.Comment()
1835 if !ok || comment != tblComment {
1836 t.Fatalf("expected comment %s got %s", tblComment, comment)
1837 }
1838 }
1839
1840 func TestMigrateWithUniqueIndexAndUnique(t *testing.T) {
1841 const table = "unique_struct"
1842
1843 checkField := func(model interface{}, fieldName string, unique bool, uniqueIndex string) {
1844 stmt := &gorm.Statement{DB: DB}
1845 err := stmt.Parse(model)
1846 if err != nil {
1847 t.Fatalf("%v: failed to parse schema, got error: %v", utils.FileWithLineNum(), err)
1848 }
1849 _ = stmt.Schema.ParseIndexes()
1850 field := stmt.Schema.LookUpField(fieldName)
1851 if field == nil {
1852 t.Fatalf("%v: failed to find column %q", utils.FileWithLineNum(), fieldName)
1853 }
1854 if field.Unique != unique {
1855 t.Fatalf("%v: %q column %q unique should be %v but got %v", utils.FileWithLineNum(), stmt.Schema.Table, fieldName, unique, field.Unique)
1856 }
1857 if field.UniqueIndex != uniqueIndex {
1858 t.Fatalf("%v: %q column %q uniqueIndex should be %v but got %v", utils.FileWithLineNum(), stmt.Schema, fieldName, uniqueIndex, field.UniqueIndex)
1859 }
1860 }
1861
1862 type ( // not unique
1863 UniqueStruct1 struct {
1864 Name string `gorm:"size:10"`
1865 }
1866 UniqueStruct2 struct {
1867 Name string `gorm:"size:20"`
1868 }
1869 )
1870 checkField(&UniqueStruct1{}, "name", false, "")
1871 checkField(&UniqueStruct2{}, "name", false, "")
1872
1873 type ( // unique
1874 UniqueStruct3 struct {
1875 Name string `gorm:"size:30;unique"`
1876 }
1877 UniqueStruct4 struct {
1878 Name string `gorm:"size:40;unique"`
1879 }
1880 )
1881 checkField(&UniqueStruct3{}, "name", true, "")
1882 checkField(&UniqueStruct4{}, "name", true, "")
1883
1884 type ( // uniqueIndex
1885 UniqueStruct5 struct {
1886 Name string `gorm:"size:50;uniqueIndex"`
1887 }
1888 UniqueStruct6 struct {
1889 Name string `gorm:"size:60;uniqueIndex"`
1890 }
1891 UniqueStruct7 struct {
1892 Name string `gorm:"size:70;uniqueIndex:idx_us6_all_names"`
1893 NickName string `gorm:"size:70;uniqueIndex:idx_us6_all_names"`
1894 }
1895 )
1896 checkField(&UniqueStruct5{}, "name", false, "idx_unique_struct5_name")
1897 checkField(&UniqueStruct6{}, "name", false, "idx_unique_struct6_name")
1898
1899 checkField(&UniqueStruct7{}, "name", false, "")
1900 checkField(&UniqueStruct7{}, "nick_name", false, "")
1901 checkField(&UniqueStruct7{}, "nick_name", false, "")
1902
1903 type UniqueStruct8 struct { // unique and uniqueIndex
1904 Name string `gorm:"size:60;unique;index:my_us8_index,unique;"`
1905 }
1906 checkField(&UniqueStruct8{}, "name", true, "my_us8_index")
1907
1908 type TestCase struct {
1909 name string
1910 from, to interface{}
1911 checkFunc func(t *testing.T)
1912 }
1913
1914 checkColumnType := func(t *testing.T, fieldName string, unique bool) {
1915 columnTypes, err := DB.Migrator().ColumnTypes(table)
1916 if err != nil {
1917 t.Fatalf("%v: failed to get column types, got error: %v", utils.FileWithLineNum(), err)
1918 }
1919 var found gorm.ColumnType
1920 for _, columnType := range columnTypes {
1921 if columnType.Name() == fieldName {
1922 found = columnType
1923 }
1924 }
1925 if found == nil {
1926 t.Fatalf("%v: failed to find column type %q", utils.FileWithLineNum(), fieldName)
1927 }
1928 if actualUnique, ok := found.Unique(); !ok || actualUnique != unique {
1929 t.Fatalf("%v: column %q unique should be %v but got %v", utils.FileWithLineNum(), fieldName, unique, actualUnique)
1930 }
1931 }
1932
1933 checkIndex := func(t *testing.T, expected []gorm.Index) {
1934 indexes, err := DB.Migrator().GetIndexes(table)
1935 if err != nil {
1936 t.Fatalf("%v: failed to get indexes, got error: %v", utils.FileWithLineNum(), err)
1937 }
1938 assert.ElementsMatch(t, expected, indexes)
1939 }
1940
1941 uniqueIndex := &migrator.Index{TableName: table, NameValue: DB.Config.NamingStrategy.IndexName(table, "name"), ColumnList: []string{"name"}, PrimaryKeyValue: sql.NullBool{Bool: false, Valid: true}, UniqueValue: sql.NullBool{Bool: true, Valid: true}}
1942 myIndex := &migrator.Index{TableName: table, NameValue: "my_us8_index", ColumnList: []string{"name"}, PrimaryKeyValue: sql.NullBool{Bool: false, Valid: true}, UniqueValue: sql.NullBool{Bool: true, Valid: true}}
1943 mulIndex := &migrator.Index{TableName: table, NameValue: "idx_us6_all_names", ColumnList: []string{"name", "nick_name"}, PrimaryKeyValue: sql.NullBool{Bool: false, Valid: true}, UniqueValue: sql.NullBool{Bool: true, Valid: true}}
1944
1945 var checkNotUnique, checkUnique, checkUniqueIndex, checkMyIndex, checkMulIndex func(t *testing.T)
1946 // UniqueAffectedByUniqueIndex is true
1947 if DB.Dialector.Name() == "mysql" {
1948 uniqueConstraintIndex := &migrator.Index{TableName: table, NameValue: DB.Config.NamingStrategy.UniqueName(table, "name"), ColumnList: []string{"name"}, PrimaryKeyValue: sql.NullBool{Bool: false, Valid: true}, UniqueValue: sql.NullBool{Bool: true, Valid: true}}
1949 checkNotUnique = func(t *testing.T) {
1950 checkColumnType(t, "name", false)
1951 checkIndex(t, nil)
1952 }
1953 checkUnique = func(t *testing.T) {
1954 checkColumnType(t, "name", true)
1955 checkIndex(t, []gorm.Index{uniqueConstraintIndex})
1956 }
1957 checkUniqueIndex = func(t *testing.T) {
1958 checkColumnType(t, "name", true)
1959 checkIndex(t, []gorm.Index{uniqueIndex})
1960 }
1961 checkMyIndex = func(t *testing.T) {
1962 checkColumnType(t, "name", true)
1963 checkIndex(t, []gorm.Index{uniqueConstraintIndex, myIndex})
1964 }
1965 checkMulIndex = func(t *testing.T) {
1966 checkColumnType(t, "name", false)
1967 checkColumnType(t, "nick_name", false)
1968 checkIndex(t, []gorm.Index{mulIndex})
1969 }
1970 } else {
1971 checkNotUnique = func(t *testing.T) { checkColumnType(t, "name", false) }
1972 checkUnique = func(t *testing.T) { checkColumnType(t, "name", true) }
1973 checkUniqueIndex = func(t *testing.T) {
1974 checkColumnType(t, "name", false)
1975 checkIndex(t, []gorm.Index{uniqueIndex})
1976 }
1977 checkMyIndex = func(t *testing.T) {
1978 checkColumnType(t, "name", true)
1979 if !DB.Migrator().HasIndex(table, myIndex.Name()) {
1980 t.Errorf("%v: should has index %s but not", utils.FileWithLineNum(), myIndex.Name())
1981 }
1982 }
1983 checkMulIndex = func(t *testing.T) {
1984 checkColumnType(t, "name", false)
1985 checkColumnType(t, "nick_name", false)
1986 if !DB.Migrator().HasIndex(table, mulIndex.Name()) {
1987 t.Errorf("%v: should has index %s but not", utils.FileWithLineNum(), mulIndex.Name())
1988 }
1989 }
1990 }
1991
1992 tests := []TestCase{
1993 {name: "notUnique to notUnique", from: &UniqueStruct1{}, to: &UniqueStruct2{}, checkFunc: checkNotUnique},
1994 {name: "notUnique to unique", from: &UniqueStruct1{}, to: &UniqueStruct3{}, checkFunc: checkUnique},
1995 {name: "notUnique to uniqueIndex", from: &UniqueStruct1{}, to: &UniqueStruct5{}, checkFunc: checkUniqueIndex},
1996 {name: "notUnique to uniqueAndUniqueIndex", from: &UniqueStruct1{}, to: &UniqueStruct8{}, checkFunc: checkMyIndex},
1997 {name: "unique to unique", from: &UniqueStruct3{}, to: &UniqueStruct4{}, checkFunc: checkUnique},
1998 {name: "unique to uniqueIndex", from: &UniqueStruct3{}, to: &UniqueStruct5{}, checkFunc: checkUniqueIndex},
1999 {name: "unique to uniqueAndUniqueIndex", from: &UniqueStruct3{}, to: &UniqueStruct8{}, checkFunc: checkMyIndex},
2000 {name: "uniqueIndex to uniqueIndex", from: &UniqueStruct5{}, to: &UniqueStruct6{}, checkFunc: checkUniqueIndex},
2001 {name: "uniqueIndex to uniqueAndUniqueIndex", from: &UniqueStruct5{}, to: &UniqueStruct8{}, checkFunc: checkMyIndex},
2002 {name: "uniqueIndex to multi uniqueIndex", from: &UniqueStruct5{}, to: &UniqueStruct7{}, checkFunc: checkMulIndex},
2003 }
2004 for _, test := range tests {
2005 t.Run(test.name, func(t *testing.T) {
2006 if err := DB.Migrator().DropTable(table); err != nil {
2007 t.Fatalf("failed to drop table, got error: %v", err)
2008 }
2009 if err := DB.Table(table).AutoMigrate(test.from); err != nil {
2010 t.Fatalf("failed to migrate table, got error: %v", err)
2011 }
2012 if err := DB.Table(table).AutoMigrate(test.to); err != nil {
2013 t.Fatalf("failed to migrate table, got error: %v", err)
2014 }
2015 test.checkFunc(t)
2016 })
2017 }
2018
2019 if DB.Dialector.Name() != "sqlserver" {
2020 // In SQLServer, If an index or constraint depends on the column,
2021 // this column will not be able to run ALTER
2022 // see https://stackoverflow.com/questions/19460912/the-object-df-is-dependent-on-column-changing-int-to-double/19461205#19461205
2023 // may we need to create another PR to fix it, see https://github.com/go-gorm/sqlserver/pull/106
2024 tests = []TestCase{
2025 {name: "unique to notUnique", from: &UniqueStruct3{}, to: &UniqueStruct1{}, checkFunc: checkNotUnique},
2026 {name: "uniqueIndex to notUnique", from: &UniqueStruct5{}, to: &UniqueStruct2{}, checkFunc: checkNotUnique},
2027 {name: "uniqueIndex to unique", from: &UniqueStruct5{}, to: &UniqueStruct3{}, checkFunc: checkUnique},
2028 }
2029 }
2030
2031 if DB.Dialector.Name() == "mysql" {
2032 compatibilityTests := []TestCase{
2033 {name: "oldUnique to notUnique", to: UniqueStruct1{}, checkFunc: checkNotUnique},
2034 {name: "oldUnique to unique", to: UniqueStruct3{}, checkFunc: checkUnique},
2035 {name: "oldUnique to uniqueIndex", to: UniqueStruct5{}, checkFunc: checkUniqueIndex},
2036 {name: "oldUnique to uniqueAndUniqueIndex", to: UniqueStruct8{}, checkFunc: checkMyIndex},
2037 }
2038 for _, test := range compatibilityTests {
2039 t.Run(test.name, func(t *testing.T) {
2040 if err := DB.Migrator().DropTable(table); err != nil {
2041 t.Fatalf("failed to drop table, got error: %v", err)
2042 }
2043 if err := DB.Exec("CREATE TABLE ? (`name` varchar(10) UNIQUE)", clause.Table{Name: table}).Error; err != nil {
2044 t.Fatalf("failed to create table, got error: %v", err)
2045 }
2046 if err := DB.Table(table).AutoMigrate(test.to); err != nil {
2047 t.Fatalf("failed to migrate table, got error: %v", err)
2048 }
2049 test.checkFunc(t)
2050 })
2051 }
2052 }
2053 }
2054
2055 func testAutoMigrateDecimal(t *testing.T, model1, model2 any) []string {
2056 tracer := Tracer{
2057 Logger: DB.Config.Logger,
2058 Test: func(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
2059 sql, _ := fc()
2060 if strings.HasPrefix(sql, "ALTER TABLE ") {
2061 t.Fatalf("shouldn't execute ALTER COLUMN TYPE if decimal is not change: sql: %s", sql)
2062 }
2063 },
2064 }
2065 session := DB.Session(&gorm.Session{Logger: tracer})
2066
2067 DB.Migrator().DropTable(model1)
2068 var modifySql []string
2069 if err := session.AutoMigrate(model1); err != nil {
2070 t.Fatalf("failed to auto migrate, got error: %v", err)
2071 }
2072 if err := session.AutoMigrate(model1); err != nil {
2073 t.Fatalf("failed to auto migrate, got error: %v", err)
2074 }
2075 tracer2 := Tracer{
2076 Logger: DB.Config.Logger,
2077 Test: func(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error) {
2078 sql, _ := fc()
2079 modifySql = append(modifySql, sql)
2080 },
2081 }
2082 session2 := DB.Session(&gorm.Session{Logger: tracer2})
2083 err := session2.Table("migrate_decimal_columns").Migrator().AutoMigrate(model2)
2084 if err != nil {
2085 t.Fatalf("failed to get column types, got error: %v", err)
2086 }
2087 return modifySql
2088 }
2089
2090 func decimalColumnsTest[T, T2 any](t *testing.T, expectedSql []string) {
2091 var t1 T
2092 var t2 T2
2093 modSql := testAutoMigrateDecimal(t, t1, t2)
2094 var alterSQL []string
2095 for _, sql := range modSql {
2096 if strings.HasPrefix(sql, "ALTER TABLE ") {
2097 alterSQL = append(alterSQL, sql)
2098 }
2099 }
2100
2101 if len(alterSQL) != 3 {
2102 t.Fatalf("decimal changed error,expected: %+v,got: %+v.", expectedSql, alterSQL)
2103 }
2104 for i := range alterSQL {
2105 if alterSQL[i] != expectedSql[i] {
2106 t.Fatalf("decimal changed error,expected: %+v,got: %+v.", expectedSql, alterSQL)
2107 }
2108 }
2109 }
2110
2111 func TestAutoMigrateDecimal(t *testing.T) {
2112 if DB.Dialector.Name() == "sqlserver" { // database/sql will replace numeric to decimal. so only support decimal.
2113 type MigrateDecimalColumn struct {
2114 RecID1 int64 `gorm:"column:recid1;type:decimal(9,0);not null" json:"recid1"`
2115 RecID2 int64 `gorm:"column:recid2;type:decimal(8);not null" json:"recid2"`
2116 RecID3 int64 `gorm:"column:recid3;type:decimal(8,1);not null" json:"recid3"`
2117 }
2118 type MigrateDecimalColumn2 struct {
2119 RecID1 int64 `gorm:"column:recid1;type:decimal(8);not null" json:"recid1"`
2120 RecID2 int64 `gorm:"column:recid2;type:decimal(9,1);not null" json:"recid2"`
2121 RecID3 int64 `gorm:"column:recid3;type:decimal(9,2);not null" json:"recid3"`
2122 }
2123 expectedSql := []string{
2124 `ALTER TABLE "migrate_decimal_columns" ALTER COLUMN "recid1" decimal(8) NOT NULL`,
2125 `ALTER TABLE "migrate_decimal_columns" ALTER COLUMN "recid2" decimal(9,1) NOT NULL`,
2126 `ALTER TABLE "migrate_decimal_columns" ALTER COLUMN "recid3" decimal(9,2) NOT NULL`,
2127 }
2128 decimalColumnsTest[MigrateDecimalColumn, MigrateDecimalColumn2](t, expectedSql)
2129 } else if DB.Dialector.Name() == "postgres" || DB.Dialector.Name() == "gaussdb" {
2130 type MigrateDecimalColumn struct {
2131 RecID1 int64 `gorm:"column:recid1;type:numeric(9,0);not null" json:"recid1"`
2132 RecID2 int64 `gorm:"column:recid2;type:numeric(8);not null" json:"recid2"`
2133 RecID3 int64 `gorm:"column:recid3;type:numeric(8,1);not null" json:"recid3"`
2134 }
2135 type MigrateDecimalColumn2 struct {
2136 RecID1 int64 `gorm:"column:recid1;type:numeric(8);not null" json:"recid1"`
2137 RecID2 int64 `gorm:"column:recid2;type:numeric(9,1);not null" json:"recid2"`
2138 RecID3 int64 `gorm:"column:recid3;type:numeric(9,2);not null" json:"recid3"`
2139 }
2140 expectedSql := []string{
2141 `ALTER TABLE "migrate_decimal_columns" ALTER COLUMN "recid1" TYPE numeric(8) USING "recid1"::numeric(8)`,
2142 `ALTER TABLE "migrate_decimal_columns" ALTER COLUMN "recid2" TYPE numeric(9,1) USING "recid2"::numeric(9,1)`,
2143 `ALTER TABLE "migrate_decimal_columns" ALTER COLUMN "recid3" TYPE numeric(9,2) USING "recid3"::numeric(9,2)`,
2144 }
2145 decimalColumnsTest[MigrateDecimalColumn, MigrateDecimalColumn2](t, expectedSql)
2146 } else if DB.Dialector.Name() == "mysql" {
2147 type MigrateDecimalColumn struct {
2148 RecID1 int64 `gorm:"column:recid1;type:decimal(9,0);not null" json:"recid1"`
2149 RecID2 int64 `gorm:"column:recid2;type:decimal(8);not null" json:"recid2"`
2150 RecID3 int64 `gorm:"column:recid3;type:decimal(8,1);not null" json:"recid3"`
2151 }
2152 type MigrateDecimalColumn2 struct {
2153 RecID1 int64 `gorm:"column:recid1;type:decimal(8);not null" json:"recid1"`
2154 RecID2 int64 `gorm:"column:recid2;type:decimal(9,1);not null" json:"recid2"`
2155 RecID3 int64 `gorm:"column:recid3;type:decimal(9,2);not null" json:"recid3"`
2156 }
2157 expectedSql := []string{
2158 "ALTER TABLE `migrate_decimal_columns` MODIFY COLUMN `recid1` decimal(8) NOT NULL",
2159 "ALTER TABLE `migrate_decimal_columns` MODIFY COLUMN `recid2` decimal(9,1) NOT NULL",
2160 "ALTER TABLE `migrate_decimal_columns` MODIFY COLUMN `recid3` decimal(9,2) NOT NULL",
2161 }
2162 decimalColumnsTest[MigrateDecimalColumn, MigrateDecimalColumn2](t, expectedSql)
2163 }
2164 }