Skip to content

Commit 49bbaa6

Browse files
authored
use map look-up for indexes (#7242)
1 parent b0d70a2 commit 49bbaa6

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

schema/index.go

+6-8
Original file line numberDiff line numberDiff line change
@@ -76,11 +76,12 @@ func (schema *Schema) ParseIndexes() map[string]Index {
7676
func (schema *Schema) LookIndex(name string) *Index {
7777
if schema != nil {
7878
indexes := schema.ParseIndexes()
79-
for _, index := range indexes {
80-
if index.Name == name {
81-
return &index
82-
}
8379

80+
if index, found := indexes[name]; found {
81+
return &index
82+
}
83+
84+
for _, index := range indexes {
8485
for _, field := range index.Fields {
8586
if field.Name == name {
8687
return &index
@@ -111,10 +112,7 @@ func parseFieldIndexes(field *Field) (indexes []Index, err error) {
111112
idx = len(tag)
112113
}
113114

114-
if idx != -1 {
115-
name = tag[0:idx]
116-
}
117-
115+
name = tag[0:idx]
118116
if name == "" {
119117
subName := field.Name
120118
const key = "COMPOSITE"

schema/index_test.go

+13-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ type UserIndex struct {
2121
Name7 string `gorm:"index:type"`
2222
Name8 string `gorm:"index:,length:10;index:,collate:utf8"`
2323

24+
CompName1 string `gorm:"index:,unique,composite:idx_compname_1,option:NULLS NOT DISTINCT;not null"`
25+
CompName2 string `gorm:"index:,composite:idx_compname_1"`
26+
2427
// Composite Index: Flattened structure.
2528
Data0A string `gorm:"index:,composite:comp_id0"`
2629
Data0B string `gorm:"index:,composite:comp_id0"`
@@ -154,6 +157,15 @@ func TestParseIndex(t *testing.T) {
154157
Field: &schema.Field{Name: "Data2B"},
155158
}},
156159
},
160+
"idx_user_indices_idx_compname_1": {
161+
Class: "UNIQUE",
162+
Name: "idx_user_indices_idx_compname_1",
163+
Option: "NULLS NOT DISTINCT",
164+
Fields: []schema.IndexOption{
165+
{Field: &schema.Field{Name: "CompName1", NotNull: true}},
166+
{Field: &schema.Field{Name: "CompName2"}},
167+
},
168+
},
157169
}
158170

159171
CheckIndices(t, results, user.ParseIndexes())
@@ -253,7 +265,7 @@ func CheckIndices(t *testing.T, expected, actual map[string]schema.Index) {
253265
}
254266
for i, ef := range ei.Fields {
255267
af := ai.Fields[i]
256-
tests.AssertObjEqual(t, af, ef, "Name", "Unique", "UniqueIndex", "Expression", "Sort", "Collate", "Length")
268+
tests.AssertObjEqual(t, af, ef, "Name", "Unique", "UniqueIndex", "Expression", "Sort", "Collate", "Length", "NotNull")
257269
}
258270
})
259271
delete(actual, k)

0 commit comments

Comments
 (0)