Skip to content

Commit 60a0587

Browse files
authored
Fix index (#88)
* index where tag fix go-gorm/gorm#6070 * without debug
1 parent 0f54846 commit 60a0587

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

migrator.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,34 @@ func (m Migrator) ColumnTypes(value interface{}) ([]gorm.ColumnType, error) {
285285
return columnTypes, execErr
286286
}
287287

288+
func (m Migrator) CreateIndex(value interface{}, name string) error {
289+
return m.RunWithValue(value, func(stmt *gorm.Statement) error {
290+
idx := stmt.Schema.LookIndex(name)
291+
if idx == nil {
292+
return fmt.Errorf("failed to create index with name %s", name)
293+
}
294+
295+
opts := m.BuildIndexOptions(idx.Fields, stmt)
296+
values := []interface{}{clause.Column{Name: idx.Name}, m.CurrentTable(stmt), opts}
297+
298+
createIndexSQL := "CREATE "
299+
if idx.Class != "" {
300+
createIndexSQL += idx.Class + " "
301+
}
302+
createIndexSQL += "INDEX ? ON ??"
303+
304+
if idx.Where != "" {
305+
createIndexSQL += " WHERE " + idx.Where
306+
}
307+
308+
if idx.Option != "" {
309+
createIndexSQL += " " + idx.Option
310+
}
311+
312+
return m.DB.Exec(createIndexSQL, values...).Error
313+
})
314+
}
315+
288316
func (m Migrator) HasIndex(value interface{}, name string) bool {
289317
var count int
290318
m.RunWithValue(value, func(stmt *gorm.Statement) error {

migrator_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,3 +96,22 @@ func TestAutomigrateTablesWithoutDefaultSchema(t *testing.T) {
9696
}
9797

9898
}
99+
100+
type Testtable6 struct {
101+
ID string `gorm:"index:unique_id,class:UNIQUE,where:id IS NOT NULL"`
102+
}
103+
104+
func (*Testtable6) TableName() string { return "testtable" }
105+
106+
func TestCreateIndex(t *testing.T) {
107+
db, err := gorm.Open(sqlserver.Open(sqlserverDSN))
108+
if err != nil {
109+
t.Error(err)
110+
}
111+
if err = db.AutoMigrate(&Testtable6{}); err != nil {
112+
t.Error("couldn't create table at user default schema", err)
113+
}
114+
if tx := db.Exec("drop table testtable"); tx.Error != nil {
115+
t.Error("couldn't drop table testtable", tx.Error)
116+
}
117+
}

0 commit comments

Comments
 (0)