dialect/sql: add alter-index for renaming psql indexes (#301)

This commit is contained in:
Ariel Mashraki
2020-01-20 18:13:55 -05:00
committed by GitHub
parent ba189b5f33
commit 4c89190e8a
2 changed files with 50 additions and 0 deletions

View File

@@ -289,6 +289,39 @@ func (t *TableAlter) Query() (string, []interface{}) {
return t.String(), t.args
}
// IndexAlter is a query builder for `ALTER INDEX` statement.
type IndexAlter struct {
Builder
name string // index to alter.
Queries []Querier // alter options.
}
// AlterIndex returns a query builder for the `ALTER INDEX` statement.
//
// AlterIndex("old_key").
// Rename("new_key")
//
func AlterIndex(name string) *IndexAlter { return &IndexAlter{name: name} }
// Rename appends the `RENAME TO` clause to the `ALTER INDEX` statement.
func (i *IndexAlter) Rename(name string) *IndexAlter {
i.Queries = append(i.Queries, Raw(fmt.Sprintf("RENAME TO %s", i.Quote(name))))
return i
}
// Query returns query representation of the `ALTER INDEX` statement.
//
// ALTER INDEX name
// [alter_specification]
//
func (i *IndexAlter) Query() (string, []interface{}) {
i.WriteString("ALTER INDEX ")
i.Ident(i.name)
i.Pad()
i.JoinComma(i.Queries...)
return i.String(), i.args
}
// ForeignKeyBuilder is the builder for the foreign-key constraint clause.
type ForeignKeyBuilder struct {
Builder
@@ -2000,6 +2033,18 @@ func (d *DialectBuilder) AlterTable(name string) *TableAlter {
return b
}
// AlterIndex creates an IndexAlter for the configured dialect.
//
// Dialect(dialect.Postgres).
// AlterIndex("old").
// Rename("new")
//
func (d *DialectBuilder) AlterIndex(name string) *IndexAlter {
b := AlterIndex(name)
b.SetDialect(d.dialect)
return b
}
// Column creates a ColumnBuilder for the configured dialect.
//
// Dialect(dialect.Postgres)..

View File

@@ -195,6 +195,11 @@ func TestBuilder(t *testing.T) {
input: AlterTable("users").RenameIndex("old", "new"),
wantQuery: "ALTER TABLE `users` RENAME INDEX `old` TO `new`",
},
{
input: Dialect(dialect.Postgres).AlterIndex("old").
Rename("new"),
wantQuery: `ALTER INDEX "old" RENAME TO "new"`,
},
{
input: Insert("users").Columns("age").Values(1),
wantQuery: "INSERT INTO `users` (`age`) VALUES (?)",