go-migrationGo Migration
Package Reference
Documentation

Schema Builder

Complete package reference for the Schema Builder, Blueprint, and Grammar — all public methods with signatures, parameters, return types, and usage examples.

Schema Builder API

The Schema Builder provides a fluent API for creating, altering, and inspecting database tables. It consists of three main components: the Builder, the Blueprint, and the Grammar.

Import path: github.com/gopackx/go-migration/pkg/schema

For conceptual documentation, see Schema Builder.


Builder Methods

The *schema.Builder is passed to your migration's Up and Down methods. It provides table-level operations.

s.Create()

Creates a new table with columns defined in the Blueprint callback.

go
func (s *Builder) Create(table string, callback func(bp *Blueprint)) error
ParameterTypeDescription
tablestringName of the table to create
callbackfunc(bp *Blueprint)Function that defines columns, indexes, and constraints

Returns: error

go
return s.Create("users", func(bp *schema.Blueprint) {
    bp.ID()
    bp.String("name", 255)
    bp.String("email", 255).Unique()
    bp.Timestamp("created_at").Nullable()
})

See Creating Tables.

s.Alter()

Modifies an existing table — add columns, drop columns, or add constraints.

go
func (s *Builder) Alter(table string, callback func(bp *Blueprint)) error
ParameterTypeDescription
tablestringName of the table to alter
callbackfunc(bp *Blueprint)Function that defines modifications

Returns: error

go
return s.Alter("users", func(bp *schema.Blueprint) {
    bp.String("phone", 20).Nullable()
})

See Altering Tables.

s.Drop()

Drops a table. Errors if the table does not exist.

go
func (s *Builder) Drop(table string) error
ParameterTypeDescription
tablestringName of the table to drop

Returns: error

go
return s.Drop("posts")

s.DropIfExists()

Drops a table only if it exists. Safe to use in Down methods.

go
func (s *Builder) DropIfExists(table string) error

Returns: error

go
return s.DropIfExists("posts")

s.Rename()

Renames an existing table.

go
func (s *Builder) Rename(from string, to string) error
ParameterTypeDescription
fromstringCurrent table name
tostringNew table name

Returns: error

go
return s.Rename("posts", "articles")

s.HasTable()

Checks if a table exists in the database.

go
func (s *Builder) HasTable(table string) (bool, error)

Returns: (bool, error)

go
exists, err := s.HasTable("users")
if err != nil {
    return err
}
if exists {
    // Table exists
}

s.HasColumn()

Checks if a column exists in a table.

go
func (s *Builder) HasColumn(table string, column string) (bool, error)
ParameterTypeDescription
tablestringTable name
columnstringColumn name

Returns: (bool, error)

go
exists, err := s.HasColumn("users", "phone")
if err != nil {
    return err
}
if !exists {
    return s.Alter("users", func(bp *schema.Blueprint) {
        bp.String("phone", 20).Nullable()
    })
}

See Utility Operations for more examples.

s.RawExec()

Executes one or more raw SQL statements directly, bypassing the fluent API. Useful for materialized views, custom DDL, extensions, triggers, or anything not covered by the Builder.

go
func (s *Builder) RawExec(statements ...string) error
ParameterTypeDescription
statements...stringOne or more raw SQL statements to execute sequentially

Returns: error

go
return s.RawExec(
    "CREATE EXTENSION IF NOT EXISTS pgcrypto",
    `CREATE MATERIALIZED VIEW monthly_sales AS
     SELECT date_trunc('month', created_at) AS month, SUM(amount) AS total
     FROM orders GROUP BY month`,
)

See Utility Operations for more examples.


Blueprint Methods — Column Types

The *schema.Blueprint is received inside Create and Alter callbacks. Column methods return a column definition that supports chaining with modifiers.

MethodSignatureDescription
IDbp.ID()Auto-incrementing unsigned big integer primary key named id
Stringbp.String(name string, length int)Variable-length string (VARCHAR)
Textbp.Text(name string)Unlimited-length text
Integerbp.Integer(name string)32-bit integer
BigIntegerbp.BigInteger(name string)64-bit integer
Booleanbp.Boolean(name string)Boolean true/false
Timestampbp.Timestamp(name string)Timestamp with date and time
Datebp.Date(name string)Date without time
Decimalbp.Decimal(name string, precision int, scale int)Fixed-point decimal
Floatbp.Float(name string)Floating-point number
UUIDbp.UUID(name string)UUID string
JSONbp.JSON(name string)JSON data
Binarybp.Binary(name string)Binary/blob data
Enumbp.Enum(name string, allowed []string)Enumerated type with allowed values
Charbp.Char(name string, length int)Fixed-length character string (CHAR(n))
LongTextbp.LongText(name string)Long text (MySQL: LONGTEXT, others: TEXT)
MediumTextbp.MediumText(name string)Medium text (MySQL: MEDIUMTEXT, others: TEXT)
TinyIntbp.TinyInt(name string)Tiny integer (MySQL: TINYINT, others: SMALLINT/INTEGER)
SmallIntbp.SmallInt(name string)Small integer
Timestampsbp.Timestamps()Adds nullable created_at and updated_at timestamps
SoftDeletesbp.SoftDeletes()Adds a nullable deleted_at timestamp
go
s.Create("products", func(bp *schema.Blueprint) {
    bp.ID()
    bp.String("name", 255)
    bp.Decimal("price", 10, 2)
    bp.Integer("stock").Default(0)
    bp.Boolean("active").Default(true)
    bp.JSON("metadata").Nullable()
    bp.Timestamps()
})

Timestamps() and SoftDeletes() return nothing — they add columns directly to the Blueprint rather than returning a chainable column definition.

See Column Types for detailed usage of each type.


Blueprint Methods — Column Modifiers

Modifiers are chainable methods called on the column definition returned by any column type method.

ModifierSignatureDescription
Nullable.Nullable()Allow NULL values
Default.Default(value any)Set a default value
DefaultRaw.DefaultRaw(expression string)Set a raw SQL expression as the default value
Primary.Primary()Set as primary key
Unique.Unique()Add a unique constraint
Unsigned.Unsigned()Make numeric column unsigned
AutoIncrement.AutoIncrement()Enable auto-increment
go
bp.String("email", 255).Unique()
bp.Integer("age").Unsigned().Nullable()
bp.Boolean("active").Default(true)
bp.Timestamp("created_at").DefaultRaw("CURRENT_TIMESTAMP")
bp.BigInteger("id").AutoIncrement().Primary()

See Column Modifiers.


Blueprint Methods — Alter Operations

These methods queue commands inside Alter callbacks.

bp.DropColumn()

Removes a column from the table.

go
func (bp *Blueprint) DropColumn(name string)
go
s.Alter("users", func(bp *schema.Blueprint) {
    bp.DropColumn("phone")
})

bp.RenameColumn()

Renames an existing column.

go
func (bp *Blueprint) RenameColumn(from string, to string)
go
s.Alter("users", func(bp *schema.Blueprint) {
    bp.RenameColumn("name", "full_name")
})

bp.DropIndex()

Drops an index by name.

go
func (bp *Blueprint) DropIndex(name string)
go
s.Alter("users", func(bp *schema.Blueprint) {
    bp.DropIndex("idx_users_email")
})

bp.DropForeign()

Drops a foreign key constraint by name.

go
func (bp *Blueprint) DropForeign(name string)
go
s.Alter("posts", func(bp *schema.Blueprint) {
    bp.DropForeign("fk_posts_user_id")
})

Blueprint Methods — Indexes

Index names are generated automatically from the table and column names, so the index methods take only column names. The generated name uses a type prefix: idx (regular), uniq (unique), ft (fulltext), and sp (spatial). Each index method returns an *IndexDefinition, whose .Named() method overrides the generated name.

bp.Index()

Creates an index on one or more columns.

go
func (bp *Blueprint) Index(columns ...string) *IndexDefinition
ParameterTypeDescription
columns...stringOne or more column names
go
// Single-column index
bp.Index("email")

// Composite index
bp.Index("user_id", "status")

bp.UniqueIndex()

Creates a unique index on one or more columns.

go
func (bp *Blueprint) UniqueIndex(columns ...string) *IndexDefinition
go
bp.UniqueIndex("email")
bp.UniqueIndex("user_id", "plan_id")

bp.FulltextIndex()

Creates a fulltext index on one or more columns.

go
func (bp *Blueprint) FulltextIndex(columns ...string) *IndexDefinition
go
bp.FulltextIndex("title", "body")

bp.SpatialIndex()

Creates a spatial index on one or more columns.

go
func (bp *Blueprint) SpatialIndex(columns ...string) *IndexDefinition
go
bp.SpatialIndex("location")

idx.Named()

Overrides the auto-generated index name. Chainable on the value returned by any index method. An empty string is ignored, leaving the generated name intact.

go
func (idx *IndexDefinition) Named(name string) *IndexDefinition
go
bp.Index("email").Named("idx_users_email_lower")
bp.UniqueIndex("user_id", "plan_id").Named("uq_subscription")

The custom name is what you pass to bp.DropIndex() when removing the index.

See Indexes.


Blueprint Methods — Foreign Keys

bp.Foreign()

Starts a foreign key constraint definition. Returns a chainable builder.

go
func (bp *Blueprint) Foreign(column string) *ForeignKeyDefinition

Chain methods:

MethodSignatureDescription
References.References(column string)The referenced column
On.On(table string)The referenced table
OnDeleteAction.OnDeleteAction(action string)Action on parent deletion
OnUpdateAction.OnUpdateAction(action string)Action on parent update

Actions: "CASCADE", "SET NULL", "RESTRICT", "NO ACTION"

go
bp.Foreign("user_id").References("id").On("users").OnDeleteAction("CASCADE")
bp.Foreign("category_id").References("id").On("categories").OnDeleteAction("SET NULL").OnUpdateAction("CASCADE")

See Foreign Keys.


Grammar Interface

Grammars translate Blueprint definitions into database-specific SQL. Three built-in grammars are available.

Import path: github.com/gopackx/go-migration/pkg/schema/grammars

FunctionDescription
grammars.NewPostgresGrammar()PostgreSQL grammar (default)
grammars.NewMySQLGrammar()MySQL grammar
grammars.NewSQLiteGrammar()SQLite grammar

Pass a grammar to the migrator using migrator.WithGrammar():

go
import (
    "github.com/gopackx/go-migration/pkg/schema/grammars"
    "github.com/gopackx/go-migration/pkg/migrator"
)

// MySQL
m := migrator.New(db, migrator.WithGrammar(grammars.NewMySQLGrammar()))

// SQLite
m := migrator.New(db, migrator.WithGrammar(grammars.NewSQLiteGrammar()))

See Database Grammars for type mapping details across all three grammars.


Quick Reference — Builder

MethodSignatureDescription
CreateCreate(table, callback) errorCreate a new table
AlterAlter(table, callback) errorModify an existing table
DropDrop(table) errorDrop a table
DropIfExistsDropIfExists(table) errorDrop a table if it exists
RenameRename(from, to) errorRename a table
HasTableHasTable(table) (bool, error)Check if a table exists
HasColumnHasColumn(table, column) (bool, error)Check if a column exists
RawExecRawExec(statements...) errorExecute raw SQL statements directly

Quick Reference — Blueprint

MethodDescription
ID, String, Text, Integer, BigIntegerColumn types
Boolean, Timestamp, Date, Decimal, FloatColumn types
UUID, JSON, Binary, Enum, CharColumn types
LongText, MediumText, TinyInt, SmallIntColumn types
Timestamps(), SoftDeletes()Convenience column groups
.Nullable(), .Default(), .DefaultRaw(), .Primary()Column modifiers
.Unique(), .Unsigned(), .AutoIncrement()Column modifiers
DropColumn(name), RenameColumn(from, to)Alter operations
DropIndex(name), DropForeign(name)Alter operations
Index(columns...), UniqueIndex(columns...)Create an index
FulltextIndex(columns...), SpatialIndex(columns...)Create an index
Foreign(column)Start a foreign key definition