Skip to content

Commit

Permalink
sql/mysql: allow attaching RENAME to ALTER commands (#2652)
Browse files Browse the repository at this point in the history
  • Loading branch information
a8m authored Mar 31, 2024
1 parent 0ca58f8 commit f95ac0a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
9 changes: 8 additions & 1 deletion sql/mysql/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,12 +375,19 @@ func (s *state) modifyTable(modify *schema.ModifyTable) error {
func (s *state) alterTable(t *schema.Table, changes []schema.Change) error {
var (
reverse []schema.Change
name = t.Name
reversible = true
)
build := func(changes []schema.Change) (string, error) {
b := s.Build("ALTER TABLE").Table(t)
b := s.Build("ALTER TABLE").SchemaResource(t.Schema, name)
err := b.MapCommaErr(changes, func(i int, b *sqlx.Builder) error {
switch change := changes[i].(type) {
case *schema.RenameTable:
b.P("RENAME TO").Table(change.To)
// Next time "build" is called, it
// will refer to the new table name.
name = change.To.Name
reverse = append(reverse, &schema.RenameTable{From: change.To, To: change.From})
case *schema.AddColumn:
b.P("ADD COLUMN")
if err := s.column(b, t, change.C); err != nil {
Expand Down
37 changes: 37 additions & 0 deletions sql/mysql/migrate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,43 @@ func TestPlanChanges(t *testing.T) {
},
},
},
{
changes: []schema.Change{
&schema.ModifyTable{
T: schema.NewTable("users").AddColumns(schema.NewIntColumn("id", "int")),
Changes: []schema.Change{
&schema.RenameTable{From: schema.NewTable("users"), To: schema.NewTable("accounts")},
}},
},
wantPlan: &migrate.Plan{
Reversible: true,
Changes: []*migrate.Change{
{
Cmd: "ALTER TABLE `users` RENAME TO `accounts`",
Reverse: "ALTER TABLE `accounts` RENAME TO `users`",
},
},
},
},
{
changes: []schema.Change{
&schema.ModifyTable{
T: schema.NewTable("users").AddColumns(schema.NewIntColumn("id", "int"), schema.NewStringColumn("name", "varchar(255)")),
Changes: []schema.Change{
&schema.RenameTable{From: schema.NewTable("users"), To: schema.NewTable("accounts")},
&schema.AddColumn{C: schema.NewStringColumn("name", "varchar(255)")},
}},
},
wantPlan: &migrate.Plan{
Reversible: true,
Changes: []*migrate.Change{
{
Cmd: "ALTER TABLE `users` RENAME TO `accounts`, ADD COLUMN `name` varchar(255) NOT NULL",
Reverse: "ALTER TABLE `accounts` DROP COLUMN `name`, RENAME TO `users`",
},
},
},
},
{
changes: []schema.Change{
func() schema.Change {
Expand Down

0 comments on commit f95ac0a

Please sign in to comment.