Skip to content

Commit

Permalink
fix: migrator run with nil schema (#147)
Browse files Browse the repository at this point in the history
  • Loading branch information
black-06 committed May 19, 2023
1 parent 5acf810 commit 96a6bee
Showing 1 changed file with 26 additions and 21 deletions.
47 changes: 26 additions & 21 deletions migrator.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,37 +271,40 @@ func (m Migrator) BuildIndexOptions(opts []schema.IndexOption, stmt *gorm.Statem

func (m Migrator) CreateIndex(value interface{}, name string) error {
return m.RunWithValue(value, func(stmt *gorm.Statement) error {
if idx := stmt.Schema.LookIndex(name); idx != nil {
opts := m.BuildIndexOptions(idx.Fields, stmt)
values := []interface{}{clause.Column{Name: idx.Name}, clause.Table{Name: stmt.Table}, opts}
if stmt.Schema != nil {
if idx := stmt.Schema.LookIndex(name); idx != nil {
opts := m.BuildIndexOptions(idx.Fields, stmt)
values := []interface{}{clause.Column{Name: idx.Name}, clause.Table{Name: stmt.Table}, opts}

createIndexSQL := "CREATE "
if idx.Class != "" {
createIndexSQL += idx.Class + " "
}
createIndexSQL += "INDEX ?"
createIndexSQL := "CREATE "
if idx.Class != "" {
createIndexSQL += idx.Class + " "
}
createIndexSQL += "INDEX ?"

if idx.Type != "" {
createIndexSQL += " USING " + idx.Type
}
createIndexSQL += " ON ??"
if idx.Type != "" {
createIndexSQL += " USING " + idx.Type
}
createIndexSQL += " ON ??"

if idx.Where != "" {
createIndexSQL += " WHERE " + idx.Where
}
if idx.Where != "" {
createIndexSQL += " WHERE " + idx.Where
}

return m.DB.Exec(createIndexSQL, values...).Error
return m.DB.Exec(createIndexSQL, values...).Error
}
}

return fmt.Errorf("failed to create index with name %v", name)
})
}

func (m Migrator) HasIndex(value interface{}, name string) bool {
var count int
m.RunWithValue(value, func(stmt *gorm.Statement) error {
if idx := stmt.Schema.LookIndex(name); idx != nil {
name = idx.Name
if stmt.Schema != nil {
if idx := stmt.Schema.LookIndex(name); idx != nil {
name = idx.Name
}
}

if name != "" {
Expand All @@ -327,8 +330,10 @@ func (m Migrator) RenameIndex(value interface{}, oldName, newName string) error

func (m Migrator) DropIndex(value interface{}, name string) error {
return m.RunWithValue(value, func(stmt *gorm.Statement) error {
if idx := stmt.Schema.LookIndex(name); idx != nil {
name = idx.Name
if stmt.Schema != nil {
if idx := stmt.Schema.LookIndex(name); idx != nil {
name = idx.Name
}
}

return m.DB.Exec("DROP INDEX ?", clause.Column{Name: name}).Error
Expand Down

0 comments on commit 96a6bee

Please sign in to comment.