Skip to content

Commit

Permalink
This commit provides mysql migrations the ability to add a column bef…
Browse files Browse the repository at this point in the history
…ore or after another column
  • Loading branch information
alexsante committed Mar 1, 2018
1 parent a3ee1c5 commit c77e4af
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
2 changes: 2 additions & 0 deletions fizz/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ Any other type passed it will be be passed straight through to the underlying da
* `null` - By default columns are not allowed to be `null`.
* `default` - The default value you want for this column. By default this is `null`.
* `default_raw` - The default value defined as a database function.
* `before` - Add a column before another column in the table. *Mysql Only*
* `after` - Add a column after another column in the table. *Mysql Only*

## Drop a Table

Expand Down
13 changes: 13 additions & 0 deletions fizz/translators/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,19 @@ func (p *MySQL) AddColumn(t fizz.Table) (string, error) {
if len(t.Columns) == 0 {
return "", errors.New("Not enough columns supplied!")
}

if val, ok := t.Options["before"]; ok {
c := t.Columns[0]
s := fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s BEFORE %s;", t.Name, p.buildColumn(c), val)
return s, nil
}

if val, ok := t.Options["after"]; ok {
c := t.Columns[0]
s := fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s AFTER %s;", t.Name, p.buildColumn(c), val)
return s, nil
}

c := t.Columns[0]
s := fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s;", t.Name, p.buildColumn(c))
return s, nil
Expand Down
18 changes: 18 additions & 0 deletions fizz/translators/mysql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,24 @@ func (p *MySQLSuite) Test_MySQL_AddColumn() {
r.Equal(ddl, res)
}

func (p *MySQLSuite) Test_MySQL_AddColumnBefore() {
r := p.Require()
ddl := `ALTER TABLE users ADD COLUMN mycolumn VARCHAR (50) NOT NULL DEFAULT 'foo' BEFORE created_at;`

res, _ := fizz.AString(`add_column("users", "mycolumn", "string", {"default": "foo", "size": 50, "before":"created_at"})`, myt)

r.Equal(ddl, res)
}

func (p *MySQLSuite) Test_MySQL_AddColumnAfter() {
r := p.Require()
ddl := `ALTER TABLE users ADD COLUMN mycolumn VARCHAR (50) NOT NULL DEFAULT 'foo' AFTER created_at;`

res, _ := fizz.AString(`add_column("users", "mycolumn", "string", {"default": "foo", "size": 50, "after":"created_at"})`, myt)

r.Equal(ddl, res)
}

func (p *MySQLSuite) Test_MySQL_DropColumn() {
r := p.Require()
ddl := `ALTER TABLE users DROP COLUMN mycolumn;`
Expand Down

0 comments on commit c77e4af

Please sign in to comment.