schema

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package schema is a Laravel-style schema builder: you describe tables with a Blueprint, and a Grammar turns that description into DDL for the target database. Application code never writes SQL.

Index

Constants

View Source
const (
	TypeBigInteger   = "bigInteger"
	TypeInteger      = "integer"
	TypeSmallInteger = "smallInteger"
	TypeString       = "string"
	TypeText         = "text"
	TypeBoolean      = "boolean"
	TypeDecimal      = "decimal"
	TypeFloat        = "float"
	TypeDouble       = "double"
	TypeDate         = "date"
	TypeDateTime     = "dateTime"
	TypeTimestamp    = "timestamp"
	TypeJSON         = "json"
	TypeUUID         = "uuid"
	TypeBinary       = "binary"
	TypeEnum         = "enum"
)

Column type names.

Variables

View Source
var ErrUnsupported = errors.New("schema: operation not supported by this database")

ErrUnsupported is returned when the target database cannot perform an operation (for example dropping a foreign key on SQLite).

Functions

func ToAlterSQL

func ToAlterSQL(g Grammar, table string, fn func(t *Blueprint)) ([]string, error)

ToAlterSQL compiles a Table (alter) blueprint without executing it.

func ToSQL

func ToSQL(g Grammar, table string, fn func(t *Blueprint)) ([]string, error)

ToSQL compiles a Create blueprint without executing it. Handy for tests and documentation.

Types

type Blueprint

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

Blueprint collects the definition of one table.

func (*Blueprint) BigIncrements

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

BigIncrements adds an auto-incrementing BIGINT primary key.

func (*Blueprint) BigInteger

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

BigInteger adds a BIGINT column.

func (*Blueprint) Binary

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

Binary adds a binary (BLOB/BYTEA) column.

func (*Blueprint) Boolean

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

Boolean adds a boolean column.

func (*Blueprint) Date

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

Date adds a DATE column.

func (*Blueprint) DateTime

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

DateTime adds a DATETIME column.

func (*Blueprint) Decimal

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

Decimal adds a DECIMAL column. Optional arguments: precision, scale (default 8, 2).

func (*Blueprint) Double

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

Double adds a double-precision float column.

func (*Blueprint) DropColumn

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

DropColumn drops columns.

func (*Blueprint) DropForeign

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

DropForeign drops the foreign key created over cols.

func (*Blueprint) DropForeignNamed

func (b *Blueprint) DropForeignNamed(name string)

DropForeignNamed drops a foreign key by its exact name.

func (*Blueprint) DropIndex

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

DropIndex drops the plain index created over cols.

func (*Blueprint) DropIndexNamed

func (b *Blueprint) DropIndexNamed(name string)

DropIndexNamed drops an index by its exact name.

func (*Blueprint) DropUnique

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

DropUnique drops the unique index created over cols.

func (*Blueprint) Enum

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

Enum adds a column restricted to the allowed values.

func (*Blueprint) Float

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

Float adds a single-precision float column.

func (*Blueprint) Foreign

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

Foreign starts a foreign-key definition on cols.

func (*Blueprint) ForeignID

func (b *Blueprint) ForeignID(name string) *ForeignIDColumn

ForeignID adds a BIGINT UNSIGNED column intended as a foreign key.

t.ForeignID("user_id").Constrained().CascadeOnDelete()

func (*Blueprint) ID

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

ID adds an auto-incrementing BIGINT UNSIGNED primary key (default name "id").

func (*Blueprint) Increments

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

Increments adds an auto-incrementing INTEGER primary key.

func (*Blueprint) Index

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

Index adds an index over cols.

func (*Blueprint) Integer

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

Integer adds an INTEGER column.

func (*Blueprint) JSON

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

JSON adds a JSON column (JSONB on PostgreSQL, TEXT on SQLite).

func (*Blueprint) Primary

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

Primary declares a (composite) primary key over cols.

func (*Blueprint) RememberToken

func (b *Blueprint) RememberToken() *Column

RememberToken adds a nullable remember_token VARCHAR(100).

func (*Blueprint) RenameColumn

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

RenameColumn renames a column.

func (*Blueprint) SmallInteger

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

SmallInteger adds a SMALLINT column.

func (*Blueprint) SoftDeletes

func (b *Blueprint) SoftDeletes() *Column

SoftDeletes adds a nullable deleted_at column.

func (*Blueprint) String

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

String adds a VARCHAR column (default length 255).

func (*Blueprint) Table

func (b *Blueprint) Table() string

Table returns the table name.

func (*Blueprint) Text

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

Text adds a TEXT column.

func (*Blueprint) Timestamp

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

Timestamp adds a TIMESTAMP column.

func (*Blueprint) Timestamps

func (b *Blueprint) Timestamps()

Timestamps adds nullable created_at and updated_at columns.

func (*Blueprint) UUID

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

UUID adds a UUID column.

func (*Blueprint) Unique

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

Unique adds a unique index over cols.

type Builder

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

Builder is what migrations receive. It runs the DDL produced by a Grammar.

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

func NewBuilder

func NewBuilder(ctx context.Context, conn Conn, g Grammar) *Builder

NewBuilder creates a Builder that executes on conn.

func NewPretendBuilder

func NewPretendBuilder(ctx context.Context, g Grammar, log func(stmt string)) *Builder

NewPretendBuilder creates a Builder that never touches a database: every statement it would run is passed to log instead. Used by "migrate --pretend".

func (*Builder) Context

func (b *Builder) Context() context.Context

Context returns the context of the running migration.

func (*Builder) Create

func (b *Builder) Create(table string, fn func(t *Blueprint)) error

Create creates a table.

func (*Builder) Drop

func (b *Builder) Drop(table string) error

Drop drops a table; it fails if the table does not exist.

func (*Builder) DropAllTables

func (b *Builder) DropAllTables() error

DropAllTables drops every table in the current database. Pass a *sql.Conn (not a pooled *sql.DB) so that session settings such as FOREIGN_KEY_CHECKS apply to all statements.

func (*Builder) DropIfExists

func (b *Builder) DropIfExists(table string) error

DropIfExists drops a table if it exists.

func (*Builder) Grammar

func (b *Builder) Grammar() Grammar

Grammar returns the active grammar.

func (*Builder) HasColumn

func (b *Builder) HasColumn(table, column string) (bool, error)

HasColumn reports whether the column exists. In pretend mode it returns false.

func (*Builder) HasTable

func (b *Builder) HasTable(table string) (bool, error)

HasTable reports whether the table exists. In pretend mode it returns false.

func (*Builder) Rename

func (b *Builder) Rename(from, to string) error

Rename renames a table.

func (*Builder) Table

func (b *Builder) Table(table string, fn func(t *Blueprint)) error

Table alters an existing table.

type Column

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

Column describes one column. Instances are created by Blueprint methods and refined with the fluent modifiers below.

func (*Column) AutoIncrement

func (c *Column) AutoIncrement() *Column

AutoIncrement makes an integer column auto-increment.

func (*Column) Comment

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

Comment attaches a comment (MySQL and PostgreSQL; ignored by SQLite).

func (*Column) Default

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

Default sets the default value. Accepts strings, numbers, bools, nil, time.Time and schema.Raw.

func (*Column) Index

func (c *Column) Index() *Column

Index adds a plain index on this column.

func (*Column) Name

func (c *Column) Name() string

Name returns the column name.

func (*Column) Nullable

func (c *Column) Nullable(v ...bool) *Column

Nullable allows NULL. Columns are NOT NULL by default. Nullable(false) restores the default.

func (*Column) Primary

func (c *Column) Primary() *Column

Primary marks the column as (part of) the primary key.

func (*Column) Unique

func (c *Column) Unique() *Column

Unique adds a unique index on this column.

func (*Column) Unsigned

func (c *Column) Unsigned() *Column

Unsigned marks an integer column unsigned (MySQL only; ignored elsewhere).

func (*Column) UseCurrent

func (c *Column) UseCurrent() *Column

UseCurrent makes the default the current timestamp.

type Conn

type Conn interface {
	ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
	QueryRowContext(ctx context.Context, query string, args ...any) *sql.Row
}

Conn is the subset of *sql.DB, *sql.Tx and *sql.Conn that Builder needs.

type ForeignIDColumn

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

ForeignIDColumn is a BIGINT UNSIGNED column that can be turned into a foreign key in one call.

func (*ForeignIDColumn) Constrained

func (c *ForeignIDColumn) Constrained(table ...string) *ForeignKey

Constrained adds a foreign key to table (default: the column name without "_id", plus "s", so user_id -> users) referencing its id column.

func (*ForeignIDColumn) Nullable

func (c *ForeignIDColumn) Nullable(v ...bool) *ForeignIDColumn

Nullable allows NULL and keeps the chain on ForeignIDColumn.

type ForeignKey

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

ForeignKey describes a foreign-key constraint.

func (*ForeignKey) CascadeOnDelete

func (f *ForeignKey) CascadeOnDelete() *ForeignKey

CascadeOnDelete is shorthand for OnDelete("cascade").

func (*ForeignKey) Named

func (f *ForeignKey) Named(name string) *ForeignKey

Named overrides the generated constraint name.

func (*ForeignKey) NullOnDelete

func (f *ForeignKey) NullOnDelete() *ForeignKey

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

func (*ForeignKey) On

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

On sets the referenced table.

func (*ForeignKey) OnDelete

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

OnDelete sets the ON DELETE action: cascade, restrict, set null, no action or set default.

func (*ForeignKey) OnUpdate

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

OnUpdate sets the ON UPDATE action (same values as OnDelete).

func (*ForeignKey) References

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

References sets the referenced columns (default: id).

func (*ForeignKey) RestrictOnDelete

func (f *ForeignKey) RestrictOnDelete() *ForeignKey

RestrictOnDelete is shorthand for OnDelete("restrict").

type Grammar

type Grammar interface {
	// Name is the canonical driver name: postgres, mysql or sqlite.
	Name() string
	CompileCreate(bp *Blueprint) ([]string, error)
	CompileAlter(bp *Blueprint) ([]string, error)
	CompileDrop(table string) string
	CompileDropIfExists(table string) string
	CompileRename(from, to string) string
	CompileHasTable(table string) (string, []any)
	CompileHasColumn(table, column string) (string, []any)
	CompileListTables() string
	CompileDropAll(tables []string) []string
}

Grammar turns a Blueprint into DDL for one database. It is the only place in dbkit where SQL text is produced. Implement it to add a new database.

func GrammarFor

func GrammarFor(driver string) (Grammar, error)

GrammarFor returns the Grammar for a driver name. Aliases such as pgx, postgresql, mariadb and sqlite3 are accepted.

type Index

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

Index is a (non-primary) index or a primary-key declaration.

func (*Index) Named

func (i *Index) Named(name string) *Index

Named overrides the generated index name.

type MySQL

type MySQL struct{}

MySQL compiles DDL for MySQL 8+ and MariaDB.

func (MySQL) CompileAlter

func (g MySQL) CompileAlter(bp *Blueprint) ([]string, error)

func (MySQL) CompileCreate

func (g MySQL) CompileCreate(bp *Blueprint) ([]string, error)

func (MySQL) CompileDrop

func (MySQL) CompileDrop(table string) string

func (MySQL) CompileDropAll

func (MySQL) CompileDropAll(tables []string) []string

func (MySQL) CompileDropIfExists

func (MySQL) CompileDropIfExists(table string) string

func (MySQL) CompileHasColumn

func (MySQL) CompileHasColumn(table, column string) (string, []any)

func (MySQL) CompileHasTable

func (MySQL) CompileHasTable(table string) (string, []any)

func (MySQL) CompileListTables

func (MySQL) CompileListTables() string

func (MySQL) CompileRename

func (MySQL) CompileRename(from, to string) string

func (MySQL) Name

func (MySQL) Name() string

type Postgres

type Postgres struct{}

Postgres compiles DDL for PostgreSQL.

func (Postgres) CompileAlter

func (g Postgres) CompileAlter(bp *Blueprint) ([]string, error)

func (Postgres) CompileCreate

func (g Postgres) CompileCreate(bp *Blueprint) ([]string, error)

func (Postgres) CompileDrop

func (Postgres) CompileDrop(table string) string

func (Postgres) CompileDropAll

func (Postgres) CompileDropAll(tables []string) []string

func (Postgres) CompileDropIfExists

func (Postgres) CompileDropIfExists(table string) string

func (Postgres) CompileHasColumn

func (Postgres) CompileHasColumn(table, column string) (string, []any)

func (Postgres) CompileHasTable

func (Postgres) CompileHasTable(table string) (string, []any)

func (Postgres) CompileListTables

func (Postgres) CompileListTables() string

func (Postgres) CompileRename

func (Postgres) CompileRename(from, to string) string

func (Postgres) Name

func (Postgres) Name() string

type Raw

type Raw string

Raw is a value written into the DDL verbatim (for example a function call used as a column default). Use it sparingly and never with user input.

t.Timestamp("seen_at").Default(schema.Raw("CURRENT_TIMESTAMP"))

type SQLite

type SQLite struct{}

SQLite compiles DDL for SQLite 3.35+.

SQLite cannot add or drop foreign keys or primary keys on an existing table; those operations return ErrUnsupported. Declare them in Create.

func (SQLite) CompileAlter

func (g SQLite) CompileAlter(bp *Blueprint) ([]string, error)

func (SQLite) CompileCreate

func (g SQLite) CompileCreate(bp *Blueprint) ([]string, error)

func (SQLite) CompileDrop

func (SQLite) CompileDrop(table string) string

func (SQLite) CompileDropAll

func (SQLite) CompileDropAll(tables []string) []string

func (SQLite) CompileDropIfExists

func (SQLite) CompileDropIfExists(table string) string

func (SQLite) CompileHasColumn

func (SQLite) CompileHasColumn(table, column string) (string, []any)

func (SQLite) CompileHasTable

func (SQLite) CompileHasTable(table string) (string, []any)

func (SQLite) CompileListTables

func (SQLite) CompileListTables() string

func (SQLite) CompileRename

func (SQLite) CompileRename(from, to string) string

func (SQLite) Name

func (SQLite) Name() string

Jump to

Keyboard shortcuts

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