migrate

package
v1.2.17 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2026 License: BSD-2-Clause Imports: 21 Imported by: 348

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AddColumnOp added in v1.2.6

type AddColumnOp struct {
	TableName  string
	ColumnName string
	Column     sqlschema.Column
}

AddColumnOp adds a new column to the table.

func (*AddColumnOp) GetReverse added in v1.2.6

func (op *AddColumnOp) GetReverse() Operation

type AddForeignKeyOp added in v1.2.6

type AddForeignKeyOp struct {
	ForeignKey     sqlschema.ForeignKey
	ConstraintName string
}

AddForeignKey adds a new FOREIGN KEY constraint.

func (*AddForeignKeyOp) DependsOn added in v1.2.6

func (op *AddForeignKeyOp) DependsOn(another Operation) bool

func (*AddForeignKeyOp) GetReverse added in v1.2.6

func (op *AddForeignKeyOp) GetReverse() Operation

func (*AddForeignKeyOp) TableName added in v1.2.6

func (op *AddForeignKeyOp) TableName() string

type AddPrimaryKeyOp added in v1.2.6

type AddPrimaryKeyOp struct {
	TableName  string
	PrimaryKey sqlschema.PrimaryKey
}

AddPrimaryKeyOp adds a new PRIMARY KEY to the table.

func (*AddPrimaryKeyOp) DependsOn added in v1.2.6

func (op *AddPrimaryKeyOp) DependsOn(another Operation) bool

func (*AddPrimaryKeyOp) GetReverse added in v1.2.6

func (op *AddPrimaryKeyOp) GetReverse() Operation

type AddUniqueConstraintOp added in v1.2.6

type AddUniqueConstraintOp struct {
	TableName string
	Unique    sqlschema.Unique
}

AddUniqueConstraintOp adds new UNIQUE constraint to the table.

func (*AddUniqueConstraintOp) DependsOn added in v1.2.6

func (op *AddUniqueConstraintOp) DependsOn(another Operation) bool

func (*AddUniqueConstraintOp) GetReverse added in v1.2.6

func (op *AddUniqueConstraintOp) GetReverse() Operation

type AutoMigrator added in v1.2.6

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

AutoMigrator performs automated schema migrations.

It is designed to be a drop-in replacement for some Migrator functionality and supports all existing configuration options. Similarly to Migrator, it has methods to create SQL migrations, write them to a file, and apply them. Unlike Migrator, it detects the differences between the state defined by bun models and the current database schema automatically.

Usage:

  1. Generate migrations and apply them at once with AutoMigrator.Migrate().
  2. Create up- and down-SQL migration files and apply migrations using Migrator.Migrate().

While both methods produce complete, reversible migrations (with entries in the database and SQL migration files), prefer creating migrations and applying them separately for any non-trivial cases to ensure AutoMigrator detects expected changes correctly.

Limitations:

  • AutoMigrator only supports a subset of the possible ALTER TABLE modifications.
  • Some changes are not automatically reversible. For example, you would need to manually add a CREATE TABLE query to the .down migration file to revert a DROP TABLE migration.
  • Does not validate most dialect-specific constraints. For example, when changing column data type, make sure the data con be auto-casted to the new type.
  • Due to how the schema-state diff is calculated, it is not possible to rename a table and modify any of its columns' _data type_ in a single run. This will cause the AutoMigrator to drop and re-create the table under a different name; it is better to apply this change in 2 steps. Renaming a table and renaming its columns at the same time is possible.
  • Renaming table/column to an existing name, i.e. like this [A->B] [B->C], is not possible due to how AutoMigrator distinguishes "rename" and "unchanged" columns.

Dialect must implement both sqlschema.Inspector and sqlschema.Migrator to be used with AutoMigrator.

func NewAutoMigrator added in v1.2.6

func NewAutoMigrator(db *bun.DB, opts ...AutoMigratorOption) (*AutoMigrator, error)

NewAutoMigrator creates an AutoMigrator that detects schema differences and generates migrations.

func (*AutoMigrator) CreateSQLMigrations added in v1.2.6

func (am *AutoMigrator) CreateSQLMigrations(ctx context.Context) ([]*MigrationFile, error)

CreateSQLMigration writes required changes to a new migration file. Use migrate.Migrator to apply the generated migrations.

func (*AutoMigrator) CreateTxSQLMigrations added in v1.2.6

func (am *AutoMigrator) CreateTxSQLMigrations(ctx context.Context) ([]*MigrationFile, error)

CreateTxSQLMigration writes required changes to a new migration file making sure they will be executed in a transaction when applied. Use migrate.Migrator to apply the generated migrations.

func (*AutoMigrator) Migrate added in v1.2.6

func (am *AutoMigrator) Migrate(ctx context.Context, opts ...MigrationOption) (*MigrationGroup, error)

Migrate writes required changes to a new migration file and runs the migration. This will create an entry in the migrations table, making it possible to revert the changes with Migrator.Rollback(). MigrationOptions are passed on to Migrator.Migrate().

type AutoMigratorOption added in v1.2.6

type AutoMigratorOption func(m *AutoMigrator)

AutoMigratorOption configures an AutoMigrator.

func WithExcludeForeignKeys added in v1.2.12

func WithExcludeForeignKeys(fks ...sqlschema.ForeignKey) AutoMigratorOption

WithExcludeForeignKeys tells AutoMigrator to exclude a foreign key constaint from the migration scope. This prevents AutoMigrator from dropping foreign keys that are defined manually via CreateTableQuery.ForeignKey().

func WithExcludeTable added in v1.2.6

func WithExcludeTable(tables ...string) AutoMigratorOption

WithExcludeTable tells AutoMigrator to exclude database tables from the migration scope. This prevents AutoMigrator from dropping tables which may exist in the schema but which are not used by the application.

Expressions may make use of the wildcards supported by the SQL LIKE operator:

  • % as a wildcard
  • _ as a single character

Do not exclude tables included via WithModel, as BunModelInspector ignores this setting.

func WithLocksTableNameAuto added in v1.2.6

func WithLocksTableNameAuto(table string) AutoMigratorOption

WithLocksTableNameAuto overrides default migration locks table name.

func WithMarkAppliedOnSuccessAuto added in v1.2.6

func WithMarkAppliedOnSuccessAuto(enabled bool) AutoMigratorOption

WithMarkAppliedOnSuccessAuto sets the migrator to only mark migrations as applied/unapplied when their up/down is successful.

func WithMigrationsDirectoryAuto added in v1.2.6

func WithMigrationsDirectoryAuto(directory string) AutoMigratorOption

WithMigrationsDirectoryAuto overrides the default directory for migration files.

func WithModel added in v1.2.6

func WithModel(models ...any) AutoMigratorOption

WithModel adds a bun.Model to the migration scope.

func WithSchemaName added in v1.2.6

func WithSchemaName(schemaName string) AutoMigratorOption

WithSchemaName sets the database schema to migrate objects in. By default, dialects' default schema is used.

func WithTableNameAuto added in v1.2.6

func WithTableNameAuto(table string) AutoMigratorOption

WithTableNameAuto overrides default migrations table name.

type ChangeColumnTypeOp added in v1.2.6

type ChangeColumnTypeOp struct {
	TableName string
	Column    string
	From      sqlschema.Column
	To        sqlschema.Column
}

ChangeColumnTypeOp set a new data type for the column. The two types should be such that the data can be auto-casted from one to another. E.g. reducing VARCHAR lenght is not possible in most dialects. AutoMigrator does not enforce or validate these rules.

func (*ChangeColumnTypeOp) GetReverse added in v1.2.6

func (op *ChangeColumnTypeOp) GetReverse() Operation

type ChangePrimaryKeyOp added in v1.2.6

type ChangePrimaryKeyOp struct {
	TableName string
	Old       sqlschema.PrimaryKey
	New       sqlschema.PrimaryKey
}

ChangePrimaryKeyOp changes the PRIMARY KEY of the table.

func (*ChangePrimaryKeyOp) GetReverse added in v1.2.6

func (op *ChangePrimaryKeyOp) GetReverse() Operation

type CompareTypeFunc added in v1.2.6

type CompareTypeFunc func(sqlschema.Column, sqlschema.Column) bool

CompareTypeFunc compares two column definitions and reports whether they have the same SQL type.

type CreateTableOp added in v1.2.6

type CreateTableOp struct {
	TableName string
	Model     any
}

CreateTableOp creates a new table in the schema.

It does not report dependency on any other migration and may be executed first. Make sure the dialect does not include FOREIGN KEY constraints in the CREATE TABLE statement, as those may potentially reference not-yet-existing columns/tables.

func (*CreateTableOp) GetReverse added in v1.2.6

func (op *CreateTableOp) GetReverse() Operation

type DropColumnOp added in v1.2.6

type DropColumnOp struct {
	TableName  string
	ColumnName string
	Column     sqlschema.Column
}

DropColumnOp drop a column from the table.

While some dialects allow DROP CASCADE to drop dependent constraints, explicit handling on constraints is preferred for transparency and debugging. DropColumnOp depends on DropForeignKeyOp, DropPrimaryKeyOp, and ChangePrimaryKeyOp if any of the constraints is defined on this table.

func (*DropColumnOp) DependsOn added in v1.2.6

func (op *DropColumnOp) DependsOn(another Operation) bool

func (*DropColumnOp) GetReverse added in v1.2.6

func (op *DropColumnOp) GetReverse() Operation

type DropForeignKeyOp added in v1.2.6

type DropForeignKeyOp struct {
	ForeignKey     sqlschema.ForeignKey
	ConstraintName string
}

DropForeignKeyOp drops a FOREIGN KEY constraint.

func (*DropForeignKeyOp) GetReverse added in v1.2.6

func (op *DropForeignKeyOp) GetReverse() Operation

func (*DropForeignKeyOp) TableName added in v1.2.6

func (op *DropForeignKeyOp) TableName() string

type DropPrimaryKeyOp added in v1.2.6

type DropPrimaryKeyOp struct {
	TableName  string
	PrimaryKey sqlschema.PrimaryKey
}

DropPrimaryKeyOp drops the table's PRIMARY KEY.

func (*DropPrimaryKeyOp) GetReverse added in v1.2.6

func (op *DropPrimaryKeyOp) GetReverse() Operation

type DropTableOp added in v1.2.6

type DropTableOp struct {
	TableName string
}

DropTableOp drops a database table. This operation is not reversible.

func (*DropTableOp) DependsOn added in v1.2.6

func (op *DropTableOp) DependsOn(another Operation) bool

func (*DropTableOp) GetReverse added in v1.2.6

func (op *DropTableOp) GetReverse() Operation

GetReverse for a DropTable returns a no-op migration. Logically, CreateTable is the reverse, but DropTable does not have the table's definition to create one.

type DropUniqueConstraintOp added in v1.2.6

type DropUniqueConstraintOp struct {
	TableName string
	Unique    sqlschema.Unique
}

DropUniqueConstraintOp drops a UNIQUE constraint.

func (*DropUniqueConstraintOp) DependsOn added in v1.2.6

func (op *DropUniqueConstraintOp) DependsOn(another Operation) bool

func (*DropUniqueConstraintOp) GetReverse added in v1.2.6

func (op *DropUniqueConstraintOp) GetReverse() Operation

type GoMigrationOption added in v0.3.4

type GoMigrationOption func(cfg *goMigrationConfig)

GoMigrationOption configures Go migration file generation.

func WithGoTemplate added in v1.1.13

func WithGoTemplate(template string) GoMigrationOption

WithGoTemplate sets the Go template string used for generated migration files.

func WithPackageName added in v0.3.4

func WithPackageName(name string) GoMigrationOption

WithPackageName sets the Go package name used in generated migration files.

type Migration

type Migration struct {
	bun.BaseModel

	ID         int64 `bun:",pk,autoincrement"`
	Name       string
	Comment    string `bun:"-"`
	GroupID    int64
	MigratedAt time.Time `bun:",notnull,nullzero,default:current_timestamp"`

	Up   internalMigrationFunc `bun:"-"`
	Down internalMigrationFunc `bun:"-"`
}

Migration represents a single database migration with up and down functions.

func (Migration) IsApplied added in v0.3.1

func (m Migration) IsApplied() bool

IsApplied reports whether the migration has been applied.

func (Migration) String added in v0.3.0

func (m Migration) String() string

String returns the migration name and comment.

type MigrationFile added in v0.3.0

type MigrationFile struct {
	Name    string
	Path    string
	Content string
}

MigrationFile represents a generated migration file on disk.

type MigrationFunc

type MigrationFunc func(ctx context.Context, db *bun.DB) error

MigrationFunc is a function that executes a migration against a database.

type MigrationGroup added in v0.3.0

type MigrationGroup struct {
	ID         int64
	Migrations MigrationSlice
}

MigrationGroup is a group of migrations that were applied together in a single Migrate call.

func (MigrationGroup) IsZero added in v0.3.1

func (g MigrationGroup) IsZero() bool

IsZero reports whether the group is empty.

func (MigrationGroup) String added in v0.3.0

func (g MigrationGroup) String() string

type MigrationHook added in v1.2.16

type MigrationHook func(ctx context.Context, db bun.IConn, migration *Migration) error

MigrationHook is a callback invoked before or after each migration runs.

type MigrationOption added in v0.3.1

type MigrationOption func(cfg *migrationConfig)

MigrationOption configures how a migration is executed.

func WithNopMigration added in v0.3.1

func WithNopMigration() MigrationOption

WithNopMigration creates a no-op migration that marks itself as applied without running.

type MigrationSlice added in v0.3.0

type MigrationSlice []Migration

MigrationSlice is a slice of migrations that provides helper methods for filtering and grouping.

func (MigrationSlice) Applied added in v0.3.1

func (ms MigrationSlice) Applied() MigrationSlice

Applied returns applied migrations in descending order (the order is important and is used in Rollback).

func (MigrationSlice) LastGroup added in v0.3.1

func (ms MigrationSlice) LastGroup() *MigrationGroup

LastGroup returns the last applied migration group.

func (MigrationSlice) LastGroupID added in v0.3.1

func (ms MigrationSlice) LastGroupID() int64

LastGroupID returns the last applied migration group id. The id is 0 when there are no migration groups.

func (MigrationSlice) String added in v0.3.0

func (ms MigrationSlice) String() string

func (MigrationSlice) Unapplied added in v0.3.1

func (ms MigrationSlice) Unapplied() MigrationSlice

Unapplied returns unapplied migrations in ascending order (the order is important and is used in Migrate).

type Migrations

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

Migrations is a collection of registered migrations.

func NewMigrations

func NewMigrations(opts ...MigrationsOption) *Migrations

NewMigrations creates a new collection of migrations.

func (*Migrations) Add added in v0.4.1

func (m *Migrations) Add(migration Migration)

Add appends a migration to the collection.

func (*Migrations) Discover

func (m *Migrations) Discover(fsys fs.FS) error

Discover discovers SQL migration files in the given filesystem.

func (*Migrations) DiscoverCaller

func (m *Migrations) DiscoverCaller() error

DiscoverCaller discovers SQL migration files in the caller's directory.

func (*Migrations) MustRegister

func (m *Migrations) MustRegister(up, down MigrationFunc)

MustRegister is like Register but panics on error.

func (*Migrations) Register

func (m *Migrations) Register(up, down MigrationFunc) error

Register registers up and down migration functions derived from the caller's file name.

func (*Migrations) Sorted added in v0.3.1

func (m *Migrations) Sorted() MigrationSlice

Sorted returns a copy of the migrations sorted by name in ascending order.

type MigrationsOption

type MigrationsOption func(m *Migrations)

MigrationsOption configures a Migrations instance.

func WithMigrationsDirectory added in v0.3.0

func WithMigrationsDirectory(directory string) MigrationsOption

WithMigrationsDirectory sets the directory where migration files are stored.

type Migrator added in v0.3.0

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

Migrator manages the lifecycle of database migrations.

func NewMigrator added in v0.3.0

func NewMigrator(db *bun.DB, migrations *Migrations, opts ...MigratorOption) *Migrator

NewMigrator creates a new Migrator for the given database and migrations.

func (*Migrator) AppliedMigrations added in v1.1.8

func (m *Migrator) AppliedMigrations(ctx context.Context) (MigrationSlice, error)

AppliedMigrations returns applied (applied) migrations in descending order.

func (*Migrator) CreateGoMigration added in v0.3.4

func (m *Migrator) CreateGoMigration(
	ctx context.Context, name string, opts ...GoMigrationOption,
) (*MigrationFile, error)

CreateGoMigration creates a Go migration file.

func (*Migrator) CreateSQLMigrations added in v0.3.4

func (m *Migrator) CreateSQLMigrations(ctx context.Context, name string) ([]*MigrationFile, error)

CreateSQLMigrations creates up and down SQL migration files.

func (*Migrator) CreateTxSQLMigrations added in v1.1.17

func (m *Migrator) CreateTxSQLMigrations(ctx context.Context, name string) ([]*MigrationFile, error)

CreateTxSQLMigration creates transactional up and down SQL migration files.

func (*Migrator) DB added in v0.3.1

func (m *Migrator) DB() *bun.DB

DB returns the underlying bun.DB.

func (*Migrator) Init added in v0.3.0

func (m *Migrator) Init(ctx context.Context) error

Init creates the migration tables if they do not already exist.

func (*Migrator) Lock added in v0.3.0

func (m *Migrator) Lock(ctx context.Context) error

Lock acquires an advisory lock on the migration table to prevent concurrent migrations.

func (*Migrator) MarkApplied added in v0.3.1

func (m *Migrator) MarkApplied(ctx context.Context, migration *Migration) error

MarkApplied marks the migration as applied (completed).

func (*Migrator) MarkUnapplied added in v0.3.1

func (m *Migrator) MarkUnapplied(ctx context.Context, migration *Migration) error

MarkUnapplied marks the migration as unapplied (new).

func (*Migrator) Migrate added in v0.3.0

func (m *Migrator) Migrate(ctx context.Context, opts ...MigrationOption) (*MigrationGroup, error)

Migrate runs unapplied migrations. If a migration fails, migrate immediately exits.

func (*Migrator) MigrationsWithStatus added in v0.3.1

func (m *Migrator) MigrationsWithStatus(ctx context.Context) (MigrationSlice, error)

MigrationsWithStatus returns migrations with status in ascending order.

func (*Migrator) MissingMigrations added in v1.1.8

func (m *Migrator) MissingMigrations(ctx context.Context) (MigrationSlice, error)

MissingMigrations returns applied migrations that can no longer be found.

func (*Migrator) Reset added in v0.4.1

func (m *Migrator) Reset(ctx context.Context) error

Reset drops and re-creates the migration tables.

func (*Migrator) Rollback added in v0.3.0

func (m *Migrator) Rollback(ctx context.Context, opts ...MigrationOption) (*MigrationGroup, error)

Rollback rolls back the last migration group.

func (*Migrator) RunMigration added in v1.2.17

func (m *Migrator) RunMigration(
	ctx context.Context, migrationName string, opts ...MigrationOption,
) error

RunMigration runs the up migration with the given name and marks it as applied. It runs the migration even if it is already marked as applied. The migration is added as a new applied record, creating a separate migration group.

func (*Migrator) TruncateTable added in v1.1.8

func (m *Migrator) TruncateTable(ctx context.Context) error

TruncateTable removes all rows from the migrations table.

func (*Migrator) Unlock added in v0.3.0

func (m *Migrator) Unlock(ctx context.Context) error

Unlock releases the advisory lock on the migration table.

type MigratorOption added in v0.3.0

type MigratorOption func(m *Migrator)

MigratorOption configures a Migrator.

func AfterMigration added in v1.2.16

func AfterMigration(hook MigrationHook) MigratorOption

AfterMigration registers a hook that runs after each migration.

func BeforeMigration added in v1.2.16

func BeforeMigration(hook MigrationHook) MigratorOption

BeforeMigration registers a hook that runs before each migration.

func WithLocksTableName

func WithLocksTableName(table string) MigratorOption

WithLocksTableName overrides default migration locks table name.

func WithMarkAppliedOnSuccess added in v1.1.6

func WithMarkAppliedOnSuccess(enabled bool) MigratorOption

WithMarkAppliedOnSuccess sets the migrator to only mark migrations as applied/unapplied when their up/down is successful.

func WithTableName

func WithTableName(table string) MigratorOption

WithTableName overrides default migrations table name.

func WithTemplateData added in v1.2.12

func WithTemplateData(data any) MigratorOption

WithTemplateData sets data passed to SQL migration templates during rendering.

func WithUpsert added in v1.2.17

func WithUpsert(enabled bool) MigratorOption

WithUpsert enables upsert (ON CONFLICT / ON DUPLICATE KEY / MERGE) in MarkApplied. This is required when re-running already-applied migrations via RunMigration. Init automatically creates a unique index on the name column.

type Operation added in v1.2.6

type Operation interface {
	GetReverse() Operation
}

Operation encapsulates the request to change a database definition and knowns which operation can revert it.

It is useful to define "monolith" Operations whenever possible, even though they a dialect may require several distinct steps to apply them. For example, changing a primary key involves first dropping the old constraint before generating the new one. Yet, this is only an implementation detail and passing a higher-level ChangePrimaryKeyOp will give the dialect more information about the applied change.

Some operations might be irreversible due to technical limitations. Returning a *comment from GetReverse() will add an explanatory note to the generate migration file.

To declare dependency on another Operation, operations should implement { DependsOn(Operation) bool } interface, which Changeset will use to resolve dependencies.

type RenameColumnOp added in v1.2.6

type RenameColumnOp struct {
	TableName string
	OldName   string
	NewName   string
}

RenameColumnOp renames a column in the table. If the changeset includes a rename operation for the column's table, it should be executed first.

func (*RenameColumnOp) DependsOn added in v1.2.6

func (op *RenameColumnOp) DependsOn(another Operation) bool

func (*RenameColumnOp) GetReverse added in v1.2.6

func (op *RenameColumnOp) GetReverse() Operation

type RenameTableOp added in v1.2.6

type RenameTableOp struct {
	TableName string
	NewName   string
}

RenameTableOp renames the table. Changing the "schema" part of the table's FQN (moving tables between schemas) is not allowed.

func (*RenameTableOp) GetReverse added in v1.2.6

func (op *RenameTableOp) GetReverse() Operation

type Unimplemented added in v1.2.12

type Unimplemented string

Unimplemented denotes an Operation that cannot be executed.

Operations, which cannot be reversed due to current technical limitations, may have their GetReverse() return &Unimplemented with a helpful message.

When applying operations, changelog should skip it or output as a log message, and write it as an SQL Unimplemented when creating migration files.

func (*Unimplemented) GetReverse added in v1.2.12

func (reason *Unimplemented) GetReverse() Operation

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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