Fix create unique index when creating table, close #3081
This commit is contained in:
		
							parent
							
								
									dd7caa9db0
								
							
						
					
					
						commit
						4201f7bdab
					
				| @ -175,6 +175,9 @@ func (m Migrator) CreateTable(values ...interface{}) error { | |||||||
| 						errr = tx.Migrator().CreateIndex(value, name) | 						errr = tx.Migrator().CreateIndex(value, name) | ||||||
| 					}(value, idx.Name) | 					}(value, idx.Name) | ||||||
| 				} else { | 				} else { | ||||||
|  | 					if idx.Class != "" { | ||||||
|  | 						createTableSQL += idx.Class + " " | ||||||
|  | 					} | ||||||
| 					createTableSQL += "INDEX ? ?," | 					createTableSQL += "INDEX ? ?," | ||||||
| 					values = append(values, clause.Expr{SQL: idx.Name}, tx.Migrator().(BuildIndexOptionsInterface).BuildIndexOptions(idx.Fields, stmt)) | 					values = append(values, clause.Expr{SQL: idx.Name}, tx.Migrator().(BuildIndexOptionsInterface).BuildIndexOptions(idx.Fields, stmt)) | ||||||
| 				} | 				} | ||||||
|  | |||||||
| @ -62,6 +62,23 @@ func TestMigrateWithComment(t *testing.T) { | |||||||
| 	} | 	} | ||||||
| } | } | ||||||
| 
 | 
 | ||||||
|  | func TestMigrateWithUniqueIndex(t *testing.T) { | ||||||
|  | 	type UserWithUniqueIndex struct { | ||||||
|  | 		ID   int | ||||||
|  | 		Name string    `gorm:"size:20;index:idx_name,unique"` | ||||||
|  | 		Date time.Time `gorm:"index:idx_name,unique"` | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	DB.Migrator().DropTable(&UserWithUniqueIndex{}) | ||||||
|  | 	if err := DB.AutoMigrate(&UserWithUniqueIndex{}); err != nil { | ||||||
|  | 		t.Fatalf("failed to migrate, got %v", err) | ||||||
|  | 	} | ||||||
|  | 
 | ||||||
|  | 	if !DB.Migrator().HasIndex(&UserWithUniqueIndex{}, "idx_name") { | ||||||
|  | 		t.Errorf("Failed to find created index") | ||||||
|  | 	} | ||||||
|  | } | ||||||
|  | 
 | ||||||
| func TestTable(t *testing.T) { | func TestTable(t *testing.T) { | ||||||
| 	type TableStruct struct { | 	type TableStruct struct { | ||||||
| 		gorm.Model | 		gorm.Model | ||||||
|  | |||||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user
	 Jinzhu
						Jinzhu