schema

package
v0.26.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 13, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package schema provides a dialect-agnostic DSL for describing and executing database schema changes such as creating, altering, and dropping tables.

Operations are built with fluent builders that chain modifiers on column, index, and foreign-key builders, then executed against a database.DB with Run:

schema.Create("posts", func(table *schema.Blueprint) {
	table.Int("id").AutoIncrement().Primary()
	table.String("title").Size(255).NotNullable()
	table.Text("body").Nullable()
	table.DateTime("created_at").DefaultCurrentTime()
}).Run(ctx, tx)

Builders and the Runner contract

Create starts a new table, Table alters an existing one, and Drop and DropIfExists remove tables. Every operation implements Runner, whose Run method executes the change against a transaction. This is the contract the migrate package relies on: a migrate.Migration holds its Up and Down operations as schema.Runner values.

Within Create and Table the callback receives a *Blueprint, which collects columns (via shorthand methods such as String, Int, and Text, or OfType), indexes, foreign keys, primary keys, and, for Table, columns to drop.

Rendered through dialects

The builders describe tables as Blueprints and convert them into the dialect-neutral query types defined in the dialects package (CreateTableQuery, AlterTableQuery, and DropTableQuery). dialects.New picks a Dialect based on the database driver in use, which renders the final SQL. The same builder therefore produces SQLite, PostgreSQL, or MySQL statements without any code changes.

Generating migrations

migrate.CreateFromModel generates a Create builder from a model struct, and Migrations.update diffs a model against the current schema to produce Up and Down Table builders. The generated migration templates use GoString on the builders to serialize them back into Go source.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Blueprint

type Blueprint struct {
	// contains filtered or unexported fields
}

Blueprint describes a table: its columns, dropped columns, indexes, foreign keys, and primary key. A Blueprint is usually created with NewBlueprint and populated inside the callback passed to Create or Table.

func NewBlueprint

func NewBlueprint(name string) *Blueprint

NewBlueprint returns an empty Blueprint for the named table.

func (*Blueprint) AddColumn

func (t *Blueprint) AddColumn(c *ColumnBuilder) *Blueprint

AddColumn appends a column to the blueprint.

func (*Blueprint) Blob

func (t *Blueprint) Blob(name string) *ColumnBuilder

Blob adds a blob column and returns its builder.

func (*Blueprint) Bool

func (t *Blueprint) Bool(name string) *ColumnBuilder

Bool adds a boolean column and returns its builder.

func (*Blueprint) Date

func (t *Blueprint) Date(name string) *ColumnBuilder

Date adds a date column and returns its builder.

func (*Blueprint) DateTime

func (t *Blueprint) DateTime(name string) *ColumnBuilder

DateTime adds a date-time column and returns its builder.

func (*Blueprint) DropColumn

func (t *Blueprint) DropColumn(column string)

DropColumn marks a column to be dropped when the blueprint is executed.

func (*Blueprint) Float

func (t *Blueprint) Float(name string) *ColumnBuilder

Float adds a 32-bit floating point column and returns its builder.

func (*Blueprint) Float32

func (t *Blueprint) Float32(name string) *ColumnBuilder

Float32 adds a 32-bit floating point column and returns its builder.

func (*Blueprint) Float64

func (t *Blueprint) Float64(name string) *ColumnBuilder

Float64 adds a 64-bit floating point column and returns its builder.

func (*Blueprint) ForeignKey

func (t *Blueprint) ForeignKey(localKey, relatedTable, relatedKey string)

ForeignKey adds a foreign-key constraint making localKey reference relatedKey in relatedTable. The constraint is named "<localKey>-<relatedTable>-<relatedKey>".

func (*Blueprint) GetBlueprint

func (t *Blueprint) GetBlueprint() *Blueprint

GetBlueprint returns the Blueprint underlying the builder.

func (*Blueprint) GoString

func (b *Blueprint) GoString() string

GoString renders the blueprint as a Go function literal of the form "func(table *schema.Blueprint) { ... }".

func (*Blueprint) Index

func (t *Blueprint) Index(name string) *IndexBuilder

Index begins describing an index on the table and returns its builder. Add columns to the index with IndexBuilder.AddColumn, and call IndexBuilder.Unique for a unique index.

func (*Blueprint) Int

func (t *Blueprint) Int(name string) *ColumnBuilder

Int adds a 32-bit signed integer column and returns its builder.

func (*Blueprint) Int8

func (t *Blueprint) Int8(name string) *ColumnBuilder

Int8 adds an 8-bit signed integer column and returns its builder.

func (*Blueprint) Int16

func (t *Blueprint) Int16(name string) *ColumnBuilder

Int16 adds a 16-bit signed integer column and returns its builder.

func (*Blueprint) Int32

func (t *Blueprint) Int32(name string) *ColumnBuilder

Int32 adds a 32-bit signed integer column and returns its builder.

func (*Blueprint) Int64

func (t *Blueprint) Int64(name string) *ColumnBuilder

Int64 adds a 64-bit signed integer column and returns its builder.

func (*Blueprint) JSON

func (t *Blueprint) JSON(name string) *ColumnBuilder

JSON adds a JSON column and returns its builder.

func (*Blueprint) Merge

func (t *Blueprint) Merge(newBlueprint *Blueprint)

Merge applies newBlueprint onto t. Columns marked with Change in newBlueprint replace existing columns by name, other columns are appended, and columns dropped in newBlueprint are removed. New foreign keys, indexes, and a primary key are taken from newBlueprint when present.

func (*Blueprint) OfType

func (t *Blueprint) OfType(datatype dialects.DataType, name string) *ColumnBuilder

OfType adds a column of the given datatype to the blueprint and returns its builder. The shorthand methods such as String and Int call this.

func (*Blueprint) PrimaryKey

func (t *Blueprint) PrimaryKey(columns ...string)

PrimaryKey sets the primary key of the table to the given columns. Use it for a composite primary key; for a single-column key, prefer ColumnBuilder.Primary.

func (*Blueprint) String

func (t *Blueprint) String(name string) *ColumnBuilder

String adds a string column and returns its builder.

func (*Blueprint) TableName

func (t *Blueprint) TableName() string

TableName returns the name of the table the blueprint describes.

func (*Blueprint) Text

func (t *Blueprint) Text(name string) *ColumnBuilder

Text adds a text column and returns its builder.

func (*Blueprint) UInt

func (t *Blueprint) UInt(name string) *ColumnBuilder

UInt adds a 32-bit unsigned integer column and returns its builder.

func (*Blueprint) UInt8

func (t *Blueprint) UInt8(name string) *ColumnBuilder

UInt8 adds an 8-bit unsigned integer column and returns its builder.

func (*Blueprint) UInt16

func (t *Blueprint) UInt16(name string) *ColumnBuilder

UInt16 adds a 16-bit unsigned integer column and returns its builder.

func (*Blueprint) UInt32

func (t *Blueprint) UInt32(name string) *ColumnBuilder

UInt32 adds a 32-bit unsigned integer column and returns its builder.

func (*Blueprint) UInt64

func (t *Blueprint) UInt64(name string) *ColumnBuilder

UInt64 adds a 64-bit unsigned integer column and returns its builder.

func (*Blueprint) Update

func (t *Blueprint) Update(oldBlueprint, newBlueprint *Blueprint) bool

Update rewrites t to describe the change from oldBlueprint to newBlueprint. Added columns are appended, modified columns are marked with Change, and columns that only exist in the old blueprint are dropped. New foreign keys and indexes are appended. It returns true if any change was detected.

Primary key changes, and the removal of existing foreign keys or indexes, are not yet supported.

type BlueprintType

type BlueprintType int

BlueprintType distinguishes a table creation from a table alteration.

const (
	// BlueprintTypeCreate marks a Blueprint used to create a table.
	BlueprintTypeCreate BlueprintType = iota
	// BlueprintTypeUpdate marks a Blueprint used to alter an existing table.
	BlueprintTypeUpdate
)

type Blueprinter

type Blueprinter interface {
	GetBlueprint() *Blueprint
	Type() BlueprintType
}

Blueprinter is implemented by table builders. Both CreateTableBuilder and UpdateTableBuilder satisfy it.

type ColumnBuilder

type ColumnBuilder struct {
	// contains filtered or unexported fields
}

ColumnBuilder describes a single column and collects its modifiers. It is created by the Blueprint shorthand methods or NewColumn, and modifiers such as Nullable and Default mutate it and return it so calls can be chained.

func NewColumn

func NewColumn(name string, datatype dialects.DataType) *ColumnBuilder

NewColumn returns a column builder with the given name and datatype.

func (*ColumnBuilder) After

func (b *ColumnBuilder) After(column string) *ColumnBuilder

After positions the column after the named column. It is only supported by MySQL.

func (*ColumnBuilder) AutoIncrement

func (b *ColumnBuilder) AutoIncrement() *ColumnBuilder

AutoIncrement makes the database populate the column automatically on insert. It is typically combined with Primary.

func (*ColumnBuilder) Change

func (b *ColumnBuilder) Change() *ColumnBuilder

Change marks the column as a modification of an existing column when used with an UpdateTableBuilder, producing ALTER TABLE ... MODIFY instead of ADD.

func (*ColumnBuilder) ColumnDefinition

func (b *ColumnBuilder) ColumnDefinition() *dialects.ColumnDefinition

ColumnDefinition converts the column into its dialects.ColumnDefinition, the query-level representation that a dialect encodes into SQL.

func (*ColumnBuilder) Default

func (b *ColumnBuilder) Default(v any) *ColumnBuilder

Default sets a constant default value for the column.

func (*ColumnBuilder) DefaultCurrentTime

func (b *ColumnBuilder) DefaultCurrentTime() *ColumnBuilder

DefaultCurrentTime sets the column default to CURRENT_TIMESTAMP.

func (*ColumnBuilder) Equals

func (b *ColumnBuilder) Equals(newB *ColumnBuilder) bool

Equals reports whether b describes the same column definition as newB. It compares the name, datatype, nullability, auto-increment, primary-key, and index settings.

func (*ColumnBuilder) GoString

func (b *ColumnBuilder) GoString() string

GoString renders the column's modifiers as a chain of Go method calls.

func (*ColumnBuilder) Index

func (b *ColumnBuilder) Index() *ColumnBuilder

Index creates an index on the column.

func (*ColumnBuilder) Name

func (b *ColumnBuilder) Name() string

Name returns the column name.

func (*ColumnBuilder) NotNullable

func (b *ColumnBuilder) NotNullable() *ColumnBuilder

NotNullable forbids NULL in the column. Columns are not nullable by default.

func (*ColumnBuilder) Nullable

func (b *ColumnBuilder) Nullable() *ColumnBuilder

Nullable allows the column to store NULL.

func (*ColumnBuilder) Primary

func (b *ColumnBuilder) Primary() *ColumnBuilder

Primary marks the column as the primary key. For a composite primary key, use Blueprint.PrimaryKey.

func (*ColumnBuilder) Size

func (b *ColumnBuilder) Size(s int) *ColumnBuilder

Size sets the column size, for example the length of a string column.

func (*ColumnBuilder) Type

func (b *ColumnBuilder) Type(datatype dialects.DataType) *ColumnBuilder

Type overrides the column's data type.

func (*ColumnBuilder) Unique

func (b *ColumnBuilder) Unique() *ColumnBuilder

Unique adds a unique constraint to the column.

type CreateTableBuilder

type CreateTableBuilder struct {
	// contains filtered or unexported fields
}

CreateTableBuilder builds a CREATE TABLE operation. Create returns one, and it may be configured with IfNotExists or Temporary before Run executes it. It implements Blueprinter and Runner.

func Create

func Create(name string, cb func(b *Blueprint)) *CreateTableBuilder

Create starts a CREATE TABLE operation for the named table. The callback populates the table's Blueprint with columns, indexes, and constraints.

func (*CreateTableBuilder) AddColumns

func (b *CreateTableBuilder) AddColumns(columns ...*ColumnBuilder) *CreateTableBuilder

AddColumns appends the given columns to the blueprint.

func (*CreateTableBuilder) Columns

func (b *CreateTableBuilder) Columns(columns ...*ColumnBuilder) *CreateTableBuilder

Columns replaces the blueprint's columns with the given ones.

func (*CreateTableBuilder) CreateTableQuery

func (b *CreateTableBuilder) CreateTableQuery() *dialects.CreateTableQuery

CreateTableQuery converts the builder into a dialects.CreateTableQuery that a dialect can encode into SQL.

func (*CreateTableBuilder) GetBlueprint

func (b *CreateTableBuilder) GetBlueprint() *Blueprint

GetBlueprint returns the Blueprint describing the table.

func (*CreateTableBuilder) GoString

func (b *CreateTableBuilder) GoString() string

GoString renders the operation as a schema.Create(...) call.

func (*CreateTableBuilder) IfNotExists

func (b *CreateTableBuilder) IfNotExists() *CreateTableBuilder

IfNotExists causes the statement to be generated with IF NOT EXISTS.

func (*CreateTableBuilder) Run

Run selects the dialect for the transaction's driver and executes the rendered CREATE TABLE statement.

func (*CreateTableBuilder) Temporary

func (b *CreateTableBuilder) Temporary() *CreateTableBuilder

Temporary causes a temporary table to be created.

func (*CreateTableBuilder) Type

Type returns BlueprintTypeCreate.

type ForeignKeyBuilder

type ForeignKeyBuilder struct {
	// contains filtered or unexported fields
}

ForeignKeyBuilder describes a foreign-key constraint created with Blueprint.ForeignKey, referencing a column in another table.

func (*ForeignKeyBuilder) ForeignKey

func (b *ForeignKeyBuilder) ForeignKey() *dialects.ForeignKey

ForeignKey converts the builder into its dialects.ForeignKey representation. The constraint has a column on localKey referencing relatedKey in the related table and is named "<localKey>-<relatedTable>-<relatedKey>".

type IndexBuilder

type IndexBuilder struct {
	// contains filtered or unexported fields
}

IndexBuilder describes an index on a table. Create one with Blueprint.Index and chain AddColumn, and optionally Unique, on it.

func (*IndexBuilder) AddColumn

func (b *IndexBuilder) AddColumn(c string) *IndexBuilder

AddColumn adds a column to the index.

func (*IndexBuilder) GoString

func (b *IndexBuilder) GoString() string

GoString renders the index's modifiers as a chain of Go method calls.

func (*IndexBuilder) Index

func (b *IndexBuilder) Index() *dialects.Index

Index converts the builder into its dialects.Index representation that a dialect encodes into SQL.

func (*IndexBuilder) Unique

func (b *IndexBuilder) Unique() *IndexBuilder

Unique makes the index enforce uniqueness.

type Raw

type Raw string

Raw is a schema operation containing a raw SQL statement to execute as-is.

func (Raw) Run

func (v Raw) Run(ctx context.Context, tx database.DB) error

Run implements Runner.

type Runner

type Runner interface {
	Run(ctx context.Context, tx database.DB) error
}

Runner is any database schema change that executes against a database.DB, usually a transaction. Create and Table operations, the results of Drop and DropIfExists, View, and Raw all implement it.

func Drop

func Drop(table string) Runner

Drop returns a Runner that drops the named table.

func DropIfExists

func DropIfExists(table string) Runner

DropIfExists returns a Runner that drops the named table if it exists.

func Run

func Run(f RunnerFunc) Runner

Run wraps f as a Runner so it can be used anywhere a schema operation is expected.

type RunnerFunc

type RunnerFunc func(ctx context.Context, tx database.DB) error

RunnerFunc adapts a function to the Runner interface.

func (RunnerFunc) Run

func (f RunnerFunc) Run(ctx context.Context, tx database.DB) error

Run implements Runner.

type UpdateTableBuilder

type UpdateTableBuilder struct {
	// contains filtered or unexported fields
}

UpdateTableBuilder builds an ALTER TABLE operation. Table returns one and Run executes it. Columns not marked with Change are added, columns marked with Change are modified, DropColumn names columns to remove, and ForeignKey and Index append new constraints. It implements Blueprinter and Runner.

func Table

func Table(name string, cb func(table *Blueprint)) *UpdateTableBuilder

Table starts an ALTER TABLE operation for the named table. The callback populates the Blueprint with the changes to apply.

func (*UpdateTableBuilder) AlterTableQuery

func (b *UpdateTableBuilder) AlterTableQuery() *dialects.AlterTableQuery

AlterTableQuery converts the builder into a dialects.AlterTableQuery that a dialect can encode into SQL.

func (*UpdateTableBuilder) GetBlueprint

func (b *UpdateTableBuilder) GetBlueprint() *Blueprint

GetBlueprint returns the Blueprint describing the changes.

func (*UpdateTableBuilder) GoString

func (b *UpdateTableBuilder) GoString() string

GoString renders the operation as a schema.Table(...) call.

func (*UpdateTableBuilder) Run

Run selects the dialect for the transaction's driver and executes the rendered ALTER TABLE statement.

func (*UpdateTableBuilder) Type

Type returns BlueprintTypeUpdate.

type ViewBuilder

type ViewBuilder struct {
	// Name is the name of the view.
	Name string
	// Query is the SELECT statement that defines the view.
	Query string
}

ViewBuilder builds a CREATE VIEW operation.

func View

func View(name string, query string) *ViewBuilder

View returns a ViewBuilder for a view named name backed by the given query.

func (*ViewBuilder) GoString

func (b *ViewBuilder) GoString() string

GoString renders the builder as a schema.View(...) call.

func (*ViewBuilder) Run

func (b *ViewBuilder) Run(ctx context.Context, tx database.DB) error

Run executes the CREATE VIEW statement against the transaction.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL