Skip to content

Commit 6745db8

Browse files
#54: Add RenameIndex method + tests (#109)
1 parent 2a634ec commit 6745db8

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

schema.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ type column struct {
8383
Default *string
8484
ForeignKey *string
8585
IdxName string
86+
NewIdxName string
8687
Comment *string
8788
Collation *string
8889
Op string
@@ -231,11 +232,15 @@ func buildColumnOptions(col *column) (colSchema string) {
231232

232233
// build index for table on particular column depending on an index type
233234
func composeIndex(tblName string, col *column) string {
234-
if col.IsIndex {
235+
if col.IsIndex && col.NewIdxName == "" {
235236
return "CREATE INDEX " + applyIdxConcurrency(col.IsIdxConcurrent) + applyExistence(col.IfExists) +
236237
col.IdxName + " ON " + tblName + " (" + col.Name + ")" + applyIncludes(col.Includes)
237238
}
238239

240+
if col.NewIdxName != "" {
241+
return "ALTER INDEX " + col.IdxName + " RENAME TO " + col.NewIdxName
242+
}
243+
239244
if col.IsUnique {
240245
return "CREATE UNIQUE INDEX " + applyIdxConcurrency(col.IsIdxConcurrent) + applyExistence(col.IfExists) +
241246
col.IdxName + " ON " + tblName + " (" + col.Name + ")" + applyIncludes(col.Includes)
@@ -409,6 +414,13 @@ func (t *Table) Index(idxName string) *Table {
409414
return t
410415
}
411416

417+
// RenameIndex changes the name of a particular index
418+
func (t *Table) RenameIndex(idxName, newName string) *Table {
419+
t.columns = append(t.columns, &column{IdxName: idxName, IsIndex: true, NewIdxName: newName})
420+
421+
return t
422+
}
423+
412424
// Unique sets the last column to unique index
413425
func (t *Table) Unique(idxName string) *Table {
414426
t.columns[len(t.columns)-1].IdxName = idxName
@@ -591,9 +603,10 @@ func (r *DB) modifyTable(t *Table) (res sql.Result, err error) {
591603
query += composeDrop(t.tblName, col)
592604
} else { // create new column/comment/index or just add comments indices
593605
isCol, _ := r.HasColumns(DefaultSchema, t.tblName, col.Name)
594-
if !isCol {
606+
if !isCol && col.NewIdxName == "" {
595607
query += composeAddColumn(t.tblName, col)
596608
}
609+
597610
indices = append(indices, composeIndex(t.tblName, col))
598611
comments = append(comments, composeComment(t.tblName, col))
599612
}

schema_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ func TestTable_BigIncrements(t *testing.T) {
9494
table.String("title", 64).IfNotExists().Index("ttl_idx_if_not_exists").IfNotExists()
9595
table.DropIndex("idx_price")
9696
table.DropIndex("foo").IfExists()
97+
table.RenameIndex("ttl_idx_if_not_exists", "ttl_idx_renamed")
9798

9899
return nil
99100
})

0 commit comments

Comments
 (0)