Altering Tables
Learn how to modify existing database tables using the Schema Builder's s.Alter() method.
Altering Tables
The Alter method modifies an existing table. Like Create, it takes a table name and a Blueprint callback — but instead of defining a new table, you add or remove columns from an existing one.
Basic Usage
s.Alter("users", func(bp *schema.Blueprint) {
bp.String("phone", 20).Nullable()
})This adds a phone column to the users table.
Adding Columns
Use the same column methods you'd use in Create to add new columns:
package migrations
import (
"github.com/gopackx/go-migration/pkg/schema"
)
type AddProfileFieldsToUsers struct{}
func (m *AddProfileFieldsToUsers) Up(s *schema.Builder) error {
return s.Alter("users", func(bp *schema.Blueprint) {
bp.String("phone", 20).Nullable()
bp.Text("bio").Nullable()
bp.String("avatar_url", 500).Nullable()
bp.Date("date_of_birth").Nullable()
})
}
func (m *AddProfileFieldsToUsers) Down(s *schema.Builder) error {
return s.Alter("users", func(bp *schema.Blueprint) {
bp.DropColumn("phone")
bp.DropColumn("bio")
bp.DropColumn("avatar_url")
bp.DropColumn("date_of_birth")
})
}Dropping Columns
Use bp.DropColumn() to remove a column from the table:
s.Alter("users", func(bp *schema.Blueprint) {
bp.DropColumn("phone")
})You can drop multiple columns in a single Alter call:
s.Alter("users", func(bp *schema.Blueprint) {
bp.DropColumn("phone")
bp.DropColumn("bio")
bp.DropColumn("avatar_url")
})Dropping columns is a destructive operation. Make sure your Down method can recreate the column with the correct type and modifiers so rollbacks work properly.
Renaming Columns
Use bp.RenameColumn() to rename an existing column:
s.Alter("users", func(bp *schema.Blueprint) {
bp.RenameColumn("name", "full_name")
})The first argument is the current column name and the second is the new name.
Dropping Indexes and Foreign Keys
Drop an index by its name with bp.DropIndex(), or a foreign key constraint with bp.DropForeign():
s.Alter("users", func(bp *schema.Blueprint) {
bp.DropIndex("idx_users_email")
})
s.Alter("posts", func(bp *schema.Blueprint) {
bp.DropForeign("fk_posts_user_id")
})Index and foreign key names are generated automatically when they are created. Indexes use a type prefix (idx, uniq, ft, sp) followed by the table and column names, and foreign keys follow the fk_{table}_{column} pattern.
Adding Indexes and Foreign Keys
You can also add indexes and foreign keys in an Alter call:
s.Alter("posts", func(bp *schema.Blueprint) {
bp.String("category", 100).Nullable()
bp.Index("category")
})What's Next?
- Column Types — all available column types
- Column Modifiers — Nullable, Default, Unique, and more
- Indexes — single-column, composite, and unique indexes