schema

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: May 15, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package schema provides a fluent table-builder DSL (Blueprint) and a driver-agnostic Builder that compiles blueprints into SQL via a Grammar implementation provided by the database driver.

Use the package as follows:

schema.Create("users", func(t *schema.Blueprint) {
    t.ID()
    t.String("name")
    t.String("email").Unique()
    t.Timestamps()
})

schema.Create returns a *Definition that the migration engine compiles to SQL using the connection's Grammar.

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 is the fluent table builder. Migrations construct it via schema.Create / schema.Table; users never instantiate it directly. The methods mutate the blueprint and return Column / Foreign pointers for chaining (Eloquent-style).

func NewBlueprint

func NewBlueprint(table string, create bool) *Blueprint

NewBlueprint returns an empty blueprint targeting the given table.

func (*Blueprint) AddIndex

func (b *Blueprint) AddIndex(cols ...string) *Index

AddIndex declares a multi-column plain index.

func (*Blueprint) BigIncrements

func (b *Blueprint) BigIncrements(name string) *Column

BigIncrements adds a big auto-increment primary key.

func (*Blueprint) BigInteger

func (b *Blueprint) BigInteger(name string) *Column

func (*Blueprint) Binary

func (b *Blueprint) Binary(name string) *Column

func (*Blueprint) Boolean

func (b *Blueprint) Boolean(name string) *Column

func (*Blueprint) Char

func (b *Blueprint) Char(name string, length ...int) *Column

func (*Blueprint) Charset

func (b *Blueprint) Charset(name string) *Blueprint

Charset sets the table charset.

func (*Blueprint) CharsetName

func (b *Blueprint) CharsetName() string

CharsetName returns the configured charset.

func (*Blueprint) Collation

func (b *Blueprint) Collation(name string) *Blueprint

Collation sets the table collation.

func (*Blueprint) CollationName

func (b *Blueprint) CollationName() string

CollationName returns the configured collation.

func (*Blueprint) Columns

func (b *Blueprint) Columns() []*Column

Columns returns all defined columns.

func (*Blueprint) Commands

func (b *Blueprint) Commands() []*Command

Commands returns deferred commands (drop column, rename column, etc).

func (*Blueprint) Comment

func (b *Blueprint) Comment(s string) *Blueprint

Comment attaches a table-level comment.

func (*Blueprint) CommentText

func (b *Blueprint) CommentText() string

CommentText returns the configured comment.

func (*Blueprint) Date

func (b *Blueprint) Date(name string) *Column

func (*Blueprint) DateTime

func (b *Blueprint) DateTime(name string) *Column

func (*Blueprint) Decimal

func (b *Blueprint) Decimal(name string, precisionScale ...int) *Column

func (*Blueprint) Double

func (b *Blueprint) Double(name string) *Column

func (*Blueprint) DropColumn

func (b *Blueprint) DropColumn(cols ...string)

DropColumn schedules columns for removal.

func (*Blueprint) DropForeign

func (b *Blueprint) DropForeign(name string)

DropForeign drops the named foreign key.

func (*Blueprint) DropIndex

func (b *Blueprint) DropIndex(name string)

DropIndex drops the named index.

func (*Blueprint) Engine

func (b *Blueprint) Engine(name string) *Blueprint

Engine sets the storage engine (MySQL).

func (*Blueprint) EngineName

func (b *Blueprint) EngineName() string

EngineName returns the configured engine, if any.

func (*Blueprint) Enum

func (b *Blueprint) Enum(name string, allowed ...string) *Column

func (*Blueprint) Float

func (b *Blueprint) Float(name string) *Column

func (*Blueprint) Foreign

func (b *Blueprint) Foreign(cols ...string) *Foreign

Foreign declares a foreign key on the given local columns.

func (*Blueprint) ForeignId

func (b *Blueprint) ForeignId(name string) *ForeignId

ForeignId adds an UNSIGNED BIG INTEGER column intended to reference another table's primary key. Use the returned *ForeignId to chain Constrained()/ References()/OnDelete()/OnUpdate().

func (*Blueprint) Foreigns

func (b *Blueprint) Foreigns() []*Foreign

Foreigns returns all defined foreign keys.

func (*Blueprint) ID

func (b *Blueprint) ID(name ...string) *Column

ID adds a big auto-incrementing primary key column. Default name "id".

func (*Blueprint) Increments

func (b *Blueprint) Increments(name string) *Column

Increments adds a 32-bit auto-increment primary key.

func (*Blueprint) Indexes

func (b *Blueprint) Indexes() []*Index

Indexes returns all defined indexes.

func (*Blueprint) Integer

func (b *Blueprint) Integer(name string) *Column

func (*Blueprint) IsCreate

func (b *Blueprint) IsCreate() bool

IsCreate reports whether this is CREATE TABLE (vs ALTER TABLE).

func (*Blueprint) IsTemporary

func (b *Blueprint) IsTemporary() bool

IsTemporary reports whether the blueprint is temporary.

func (*Blueprint) JSON

func (b *Blueprint) JSON(name string) *Column

func (*Blueprint) JSONB

func (b *Blueprint) JSONB(name string) *Column

func (*Blueprint) LongText

func (b *Blueprint) LongText(name string) *Column

func (*Blueprint) MediumText

func (b *Blueprint) MediumText(name string) *Column

func (*Blueprint) Primary

func (b *Blueprint) Primary(cols ...string) *Index

Primary declares a composite primary key.

func (*Blueprint) RenameColumn

func (b *Blueprint) RenameColumn(from, to string)

RenameColumn renames a column.

func (*Blueprint) RenameTo

func (b *Blueprint) RenameTo(name string)

RenameTo renames the table.

func (*Blueprint) Set

func (b *Blueprint) Set(name string, allowed ...string) *Column

func (*Blueprint) SmallInteger

func (b *Blueprint) SmallInteger(name string) *Column

func (*Blueprint) SoftDeletes

func (b *Blueprint) SoftDeletes() *Column

SoftDeletes adds a nullable deleted_at column conventionally used by the ORM's soft-delete behavior.

func (*Blueprint) String

func (b *Blueprint) String(name string, length ...int) *Column

func (*Blueprint) Table

func (b *Blueprint) Table() string

Table returns the table name.

func (*Blueprint) Temporary

func (b *Blueprint) Temporary() *Blueprint

Temporary marks the table as TEMPORARY.

func (*Blueprint) Text

func (b *Blueprint) Text(name string) *Column

func (*Blueprint) Time

func (b *Blueprint) Time(name string) *Column

func (*Blueprint) Timestamp

func (b *Blueprint) Timestamp(name string) *Column

func (*Blueprint) TimestampTz

func (b *Blueprint) TimestampTz(name string) *Column

func (*Blueprint) Timestamps

func (b *Blueprint) Timestamps()

Timestamps adds nullable created_at and updated_at columns.

func (*Blueprint) TimestampsTz

func (b *Blueprint) TimestampsTz()

TimestampsTz adds the same as Timestamps but with TZ.

func (*Blueprint) TinyInteger

func (b *Blueprint) TinyInteger(name string) *Column

func (*Blueprint) UUID

func (b *Blueprint) UUID(name string) *Column

UUID adds a UUID column (no default generator).

func (*Blueprint) Unique

func (b *Blueprint) Unique(cols ...string) *Index

Unique declares a multi-column unique index.

func (*Blueprint) UnsignedBigInteger

func (b *Blueprint) UnsignedBigInteger(name string) *Column

func (*Blueprint) UnsignedInteger

func (b *Blueprint) UnsignedInteger(name string) *Column

type Column

type Column struct {
	Name       string
	Kind       ColumnKind
	Length     int
	Precision  int
	Scale      int
	NullableV  bool
	HasDefault bool
	DefaultV   any
	IsUnique   bool
	IsIndex    bool
	IsPrimary  bool
	UnsignedV  bool
	AutoInc    bool
	CommentV   string
	AfterV     string
	FirstV     bool
	Allowed    []string // for ENUM/SET
	Change     bool     // true when used inside Table() to alter
	Renamed    bool
	OldName    string // when renaming
	Drop       bool
	UseCurrent bool
}

Column is the fluent builder returned by Blueprint methods. The fluent methods set modifiers and return the same pointer for chaining.

func (*Column) After

func (c *Column) After(name string) *Column

After positions the column after another (MySQL).

func (*Column) Allow

func (c *Column) Allow(values ...string) *Column

Allow installs allowed values for ENUM/SET.

func (*Column) AutoIncrement

func (c *Column) AutoIncrement() *Column

AutoIncrement marks the column auto-incrementing.

func (*Column) Comment

func (c *Column) Comment(s string) *Column

Comment attaches an inline column comment.

func (*Column) Default

func (c *Column) Default(v any) *Column

Default sets a literal default value.

func (*Column) Equal

func (c *Column) Equal(o *Column) bool

Equal performs deep equality between two columns (used by tests).

func (*Column) First

func (c *Column) First() *Column

First places the column first (MySQL).

func (*Column) Index

func (c *Column) Index() *Column

Index requests a single-column index.

func (*Column) NotNull

func (c *Column) NotNull() *Column

NotNull explicitly marks the column NOT NULL (default).

func (*Column) Nullable

func (c *Column) Nullable() *Column

Nullable marks the column NULLABLE.

func (*Column) Primary

func (c *Column) Primary() *Column

Primary marks the column as primary key.

func (*Column) Unique

func (c *Column) Unique() *Column

Unique adds a UNIQUE constraint.

func (*Column) Unsigned

func (c *Column) Unsigned() *Column

Unsigned marks an integer column unsigned.

func (*Column) UseCurrentDefault

func (c *Column) UseCurrentDefault() *Column

UseCurrent uses CURRENT_TIMESTAMP as the default (timestamp columns).

type ColumnKind

type ColumnKind string

ColumnKind enumerates portable column kinds. Drivers translate kinds to dialect-specific SQL via database.Grammar.CompileType.

const (
	KindBigIncrements ColumnKind = "bigIncrements"
	KindIncrements    ColumnKind = "increments"
	KindBigInteger    ColumnKind = "bigInteger"
	KindInteger       ColumnKind = "integer"
	KindSmallInteger  ColumnKind = "smallInteger"
	KindTinyInteger   ColumnKind = "tinyInteger"
	KindUnsignedBig   ColumnKind = "unsignedBigInteger"
	KindUnsignedInt   ColumnKind = "unsignedInteger"
	KindFloat         ColumnKind = "float"
	KindDouble        ColumnKind = "double"
	KindDecimal       ColumnKind = "decimal"
	KindBoolean       ColumnKind = "boolean"
	KindString        ColumnKind = "string"
	KindChar          ColumnKind = "char"
	KindText          ColumnKind = "text"
	KindMediumText    ColumnKind = "mediumText"
	KindLongText      ColumnKind = "longText"
	KindBinary        ColumnKind = "binary"
	KindUUID          ColumnKind = "uuid"
	KindJSON          ColumnKind = "json"
	KindJSONB         ColumnKind = "jsonb"
	KindDate          ColumnKind = "date"
	KindDateTime      ColumnKind = "dateTime"
	KindTime          ColumnKind = "time"
	KindTimestamp     ColumnKind = "timestamp"
	KindTimestampTZ   ColumnKind = "timestampTz"
	KindEnum          ColumnKind = "enum"
	KindSet           ColumnKind = "set"
	KindIPAddress     ColumnKind = "ipAddress"
	KindMACAddress    ColumnKind = "macAddress"
)

type Command

type Command struct {
	Type CommandType
	Args []string
}

Command is a deferred ALTER operation.

type CommandType

type CommandType string

CommandType enumerates deferred blueprint commands.

const (
	CmdDropColumn   CommandType = "dropColumn"
	CmdRenameColumn CommandType = "renameColumn"
	CmdDropIndex    CommandType = "dropIndex"
	CmdDropUnique   CommandType = "dropUnique"
	CmdDropForeign  CommandType = "dropForeign"
	CmdDropPrimary  CommandType = "dropPrimary"
	CmdRenameTable  CommandType = "renameTable"
)

type Compiler

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

Compiler compiles a blueprint into one or more Statements. It is a thin orchestrator on top of database.Grammar — the grammar handles type rendering and identifier quoting; the compiler walks the blueprint and assembles DDL.

func NewCompiler

func NewCompiler(g database.Grammar) *Compiler

NewCompiler builds a compiler bound to the given grammar.

func (*Compiler) Compile

func (c *Compiler) Compile(def *Definition) ([]Statement, error)

Compile returns all statements for a Definition.

type Definition

type Definition struct {
	Blueprint *Blueprint
	Op        Operation
}

Definition pairs a blueprint with the kind of statement it represents.

func Create

func Create(table string, fn func(t *Blueprint)) *Definition

Create builds a CREATE TABLE definition.

func CreateIfNotExists

func CreateIfNotExists(table string, fn func(t *Blueprint)) *Definition

CreateIfNotExists is the IF NOT EXISTS variant.

func Drop

func Drop(table string) *Definition

Drop schedules DROP TABLE.

func DropIfExists

func DropIfExists(table string) *Definition

DropIfExists schedules DROP TABLE IF EXISTS.

func Rename

func Rename(from, to string) *Definition

Rename schedules RENAME TABLE from → to.

func Table

func Table(table string, fn func(t *Blueprint)) *Definition

Table builds an ALTER TABLE definition.

type Foreign

type Foreign struct {
	Name            string
	Columns         []string
	ReferencesTable string
	ReferencesCols  []string
	OnDeleteAction  string
	OnUpdateAction  string
	Drop            bool
}

Foreign describes a foreign-key constraint.

func (*Foreign) CascadeOnDelete

func (f *Foreign) CascadeOnDelete() *Foreign

CascadeOnDelete is sugar for OnDelete("cascade").

func (*Foreign) NullOnDelete

func (f *Foreign) NullOnDelete() *Foreign

NullOnDelete is sugar for OnDelete("set null").

func (*Foreign) On

func (f *Foreign) On(table string) *Foreign

On targets the referenced table.

func (*Foreign) OnDelete

func (f *Foreign) OnDelete(action string) *Foreign

OnDelete sets ON DELETE behavior ("cascade", "restrict", "set null", "no action").

func (*Foreign) OnUpdate

func (f *Foreign) OnUpdate(action string) *Foreign

OnUpdate sets ON UPDATE behavior.

func (*Foreign) References

func (f *Foreign) References(cols ...string) *Foreign

References sets the referenced columns.

func (*Foreign) RestrictOnDelete

func (f *Foreign) RestrictOnDelete() *Foreign

RestrictOnDelete is sugar for OnDelete("restrict").

type ForeignId

type ForeignId struct {
	*Column
	// contains filtered or unexported fields
}

ForeignId is the fluent chain used in Laravel-style declarations:

table.ForeignId("user_id").Constrained("users").OnDelete("cascade")

func (*ForeignId) Cascade

func (f *ForeignId) Cascade(table ...string) *Foreign

Cascade is a convenience: Constrained() + OnDelete("cascade").

func (*ForeignId) Constrained

func (f *ForeignId) Constrained(table ...string) *Foreign

Constrained creates a FK on this column referencing the given table's "id". If table is empty it is inferred from the column name ("user_id" → "users").

func (*ForeignId) References

func (f *ForeignId) References(cols ...string) *Foreign

References starts a FK targeting the named referenced columns. Pair with .On().

type Index

type Index struct {
	Name    string
	Type    IndexType
	Columns []string
	Algo    string // optional: btree/hash/gin/gist (Postgres)
	Drop    bool
}

Index describes a table index.

type IndexType

type IndexType string

IndexType enumerates supported index types.

const (
	IndexPlain   IndexType = "index"
	IndexUnique  IndexType = "unique"
	IndexPrimary IndexType = "primary"
	IndexSpatial IndexType = "spatial"
	IndexFull    IndexType = "fulltext"
)

type Operation

type Operation int

Operation enumerates schema operations.

const (
	OpCreate Operation = iota
	OpCreateIfNotExists
	OpAlter
	OpDrop
	OpDropIfExists
	OpRename
)

type Statement

type Statement struct {
	SQL  string
	Args []any
}

Statement is a compiled SQL string with optional positional args. Most schema statements have no args, but driver-specific code (e.g. comments on Postgres) may emit them.

Jump to

Keyboard shortcuts

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