Fix create index

This commit is contained in:
Jinzhu 2020-04-03 07:57:52 +08:00
parent 511bd66490
commit d39bdc3513
3 changed files with 20 additions and 10 deletions

View File

@ -150,7 +150,7 @@ func (m Migrator) CreateTable(values ...interface{}) error {
for _, idx := range stmt.Schema.ParseIndexes() {
if m.CreateIndexAfterCreateTable {
tx.Migrator().CreateIndex(value, idx.Name)
defer tx.Migrator().CreateIndex(value, idx.Name)
} else {
createTableSQL += "INDEX ? ?,"
values = append(values, clause.Expr{SQL: idx.Name}, tx.Migrator().(BuildIndexOptionsInterface).BuildIndexOptions(idx.Fields, stmt))

View File

@ -26,7 +26,7 @@ type IndexOption struct {
func (schema *Schema) ParseIndexes() map[string]Index {
var indexes = map[string]Index{}
for _, field := range schema.FieldsByDBName {
for _, field := range schema.Fields {
if field.TagSettings["INDEX"] != "" || field.TagSettings["UNIQUE_INDEX"] != "" {
for _, index := range parseFieldIndexes(field) {
idx := indexes[index.Name]
@ -66,6 +66,10 @@ func parseFieldIndexes(field *Field) (indexes []Index) {
length, _ = strconv.Atoi(settings["LENGTH"])
)
if idx == -1 {
idx = len(tag)
}
if idx != -1 {
name = tag[0:idx]
}

View File

@ -9,13 +9,15 @@ import (
)
type UserIndex struct {
Name string `gorm:"index"`
Name2 string `gorm:"index:idx_name,unique"`
Name3 string `gorm:"index:,sort:desc,collate:utf8,type:btree,length:10,where:name3 != 'jinzhu'"`
Name4 string `gorm:"unique_index"`
Name5 int64 `gorm:"index:,class:FULLTEXT,comment:hello \\, world,where:age > 10"`
Name6 int64 `gorm:"index:profile,comment:hello \\, world,where:age > 10"`
Age int64 `gorm:"index:profile,expression:ABS(age)"`
Name string `gorm:"index"`
Name2 string `gorm:"index:idx_name,unique"`
Name3 string `gorm:"index:,sort:desc,collate:utf8,type:btree,length:10,where:name3 != 'jinzhu'"`
Name4 string `gorm:"unique_index"`
Name5 int64 `gorm:"index:,class:FULLTEXT,comment:hello \\, world,where:age > 10"`
Name6 int64 `gorm:"index:profile,comment:hello \\, world,where:age > 10"`
Age int64 `gorm:"index:profile,expression:ABS(age)"`
OID int64 `gorm:"index:idx_id"`
MemberNumber string `gorm:"index:idx_id"`
}
func TestParseIndex(t *testing.T) {
@ -64,6 +66,10 @@ func TestParseIndex(t *testing.T) {
Expression: "ABS(age)",
}},
},
"idx_id": {
Name: "idx_id",
Fields: []schema.IndexOption{{}, {}},
},
}
indices := user.ParseIndexes()
@ -71,7 +77,7 @@ func TestParseIndex(t *testing.T) {
for k, result := range results {
v, ok := indices[k]
if !ok {
t.Errorf("Failed to found index %v from parsed indices %+v", k, indices)
t.Fatalf("Failed to found index %v from parsed indices %+v", k, indices)
}
for _, name := range []string{"Name", "Class", "Type", "Where", "Comment"} {