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.
func (s *Builder) Create(table string, callback func(bp *Blueprint)) error| Parameter | Type | Description |
|---|---|---|
table | string | Name of the table to create |
callback | func(bp *Blueprint) | Function that defines columns, indexes, and constraints |
Returns: error
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.
func (s *Builder) Alter(table string, callback func(bp *Blueprint)) error| Parameter | Type | Description |
|---|---|---|
table | string | Name of the table to alter |
callback | func(bp *Blueprint) | Function that defines modifications |
Returns: error
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.
func (s *Builder) Drop(table string) error| Parameter | Type | Description |
|---|---|---|
table | string | Name of the table to drop |
Returns: error
return s.Drop("posts")s.DropIfExists()
Drops a table only if it exists. Safe to use in Down methods.
func (s *Builder) DropIfExists(table string) errorReturns: error
return s.DropIfExists("posts")s.Rename()
Renames an existing table.
func (s *Builder) Rename(from string, to string) error| Parameter | Type | Description |
|---|---|---|
from | string | Current table name |
to | string | New table name |
Returns: error
return s.Rename("posts", "articles")s.HasTable()
Checks if a table exists in the database.
func (s *Builder) HasTable(table string) (bool, error)Returns: (bool, error)
exists, err := s.HasTable("users")
if err != nil {
return err
}
if exists {
// Table exists
}s.HasColumn()
Checks if a column exists in a table.
func (s *Builder) HasColumn(table string, column string) (bool, error)| Parameter | Type | Description |
|---|---|---|
table | string | Table name |
column | string | Column name |
Returns: (bool, error)
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.
func (s *Builder) RawExec(statements ...string) error| Parameter | Type | Description |
|---|---|---|
statements | ...string | One or more raw SQL statements to execute sequentially |
Returns: error
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.
| Method | Signature | Description |
|---|---|---|
ID | bp.ID() | Auto-incrementing unsigned big integer primary key named id |
String | bp.String(name string, length int) | Variable-length string (VARCHAR) |
Text | bp.Text(name string) | Unlimited-length text |
Integer | bp.Integer(name string) | 32-bit integer |
BigInteger | bp.BigInteger(name string) | 64-bit integer |
Boolean | bp.Boolean(name string) | Boolean true/false |
Timestamp | bp.Timestamp(name string) | Timestamp with date and time |
Date | bp.Date(name string) | Date without time |
Decimal | bp.Decimal(name string, precision int, scale int) | Fixed-point decimal |
Float | bp.Float(name string) | Floating-point number |
UUID | bp.UUID(name string) | UUID string |
JSON | bp.JSON(name string) | JSON data |
Binary | bp.Binary(name string) | Binary/blob data |
Enum | bp.Enum(name string, allowed []string) | Enumerated type with allowed values |
Char | bp.Char(name string, length int) | Fixed-length character string (CHAR(n)) |
LongText | bp.LongText(name string) | Long text (MySQL: LONGTEXT, others: TEXT) |
MediumText | bp.MediumText(name string) | Medium text (MySQL: MEDIUMTEXT, others: TEXT) |
TinyInt | bp.TinyInt(name string) | Tiny integer (MySQL: TINYINT, others: SMALLINT/INTEGER) |
SmallInt | bp.SmallInt(name string) | Small integer |
Timestamps | bp.Timestamps() | Adds nullable created_at and updated_at timestamps |
SoftDeletes | bp.SoftDeletes() | Adds a nullable deleted_at timestamp |
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.
| Modifier | Signature | Description |
|---|---|---|
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 |
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.
func (bp *Blueprint) DropColumn(name string)s.Alter("users", func(bp *schema.Blueprint) {
bp.DropColumn("phone")
})bp.RenameColumn()
Renames an existing column.
func (bp *Blueprint) RenameColumn(from string, to string)s.Alter("users", func(bp *schema.Blueprint) {
bp.RenameColumn("name", "full_name")
})bp.DropIndex()
Drops an index by name.
func (bp *Blueprint) DropIndex(name string)s.Alter("users", func(bp *schema.Blueprint) {
bp.DropIndex("idx_users_email")
})bp.DropForeign()
Drops a foreign key constraint by name.
func (bp *Blueprint) DropForeign(name string)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.
func (bp *Blueprint) Index(columns ...string) *IndexDefinition| Parameter | Type | Description |
|---|---|---|
columns | ...string | One or more column names |
// Single-column index
bp.Index("email")
// Composite index
bp.Index("user_id", "status")bp.UniqueIndex()
Creates a unique index on one or more columns.
func (bp *Blueprint) UniqueIndex(columns ...string) *IndexDefinitionbp.UniqueIndex("email")
bp.UniqueIndex("user_id", "plan_id")bp.FulltextIndex()
Creates a fulltext index on one or more columns.
func (bp *Blueprint) FulltextIndex(columns ...string) *IndexDefinitionbp.FulltextIndex("title", "body")bp.SpatialIndex()
Creates a spatial index on one or more columns.
func (bp *Blueprint) SpatialIndex(columns ...string) *IndexDefinitionbp.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.
func (idx *IndexDefinition) Named(name string) *IndexDefinitionbp.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.
func (bp *Blueprint) Foreign(column string) *ForeignKeyDefinitionChain methods:
| Method | Signature | Description |
|---|---|---|
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"
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
| Function | Description |
|---|---|
grammars.NewPostgresGrammar() | PostgreSQL grammar (default) |
grammars.NewMySQLGrammar() | MySQL grammar |
grammars.NewSQLiteGrammar() | SQLite grammar |
Pass a grammar to the migrator using migrator.WithGrammar():
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
| Method | Signature | Description |
|---|---|---|
Create | Create(table, callback) error | Create a new table |
Alter | Alter(table, callback) error | Modify an existing table |
Drop | Drop(table) error | Drop a table |
DropIfExists | DropIfExists(table) error | Drop a table if it exists |
Rename | Rename(from, to) error | Rename a table |
HasTable | HasTable(table) (bool, error) | Check if a table exists |
HasColumn | HasColumn(table, column) (bool, error) | Check if a column exists |
RawExec | RawExec(statements...) error | Execute raw SQL statements directly |
Quick Reference — Blueprint
| Method | Description |
|---|---|
ID, String, Text, Integer, BigInteger | Column types |
Boolean, Timestamp, Date, Decimal, Float | Column types |
UUID, JSON, Binary, Enum, Char | Column types |
LongText, MediumText, TinyInt, SmallInt | Column 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 |
Migrator
Complete package reference for the go-migration Migrator — all public methods with signatures, parameters, return types, and usage examples.
Seeder
Complete package reference for the go-migration Seeder interface, Runner, and dependency system — all public methods with signatures, parameters, return types, and usage examples.