migration

package
v1.16.5 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package migration provides database migration functionality.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateFileName

func GenerateFileName(version, name, direction string) string

GenerateFileName generates a migration filename. Format: {version}_{name}.{up|down}.sql

func GenerateVersion

func GenerateVersion() string

GenerateVersion generates a timestamp-based version string. Format: YYYYMMDDHHmmss (e.g., "20240101120000")

func HasMigrationFiles added in v1.16.0

func HasMigrationFiles(dir string) (bool, error)

HasMigrationFiles reports whether any *.up.sql files exist in dir.

func ReconstructSchemaFromMigrations added in v1.16.0

func ReconstructSchemaFromMigrations(dir string) (map[string]*schema.TableMetadata, error)

ReconstructSchemaFromMigrations replays all *.up.sql migration files in version order to reconstruct the current schema state. It is used as the offline baseline when no database connection is provided.

Types

type ColumnDiff

type ColumnDiff struct {
	ColumnName     string // Name of the column
	OldColumn      schema.ColumnMetadata
	NewColumn      schema.ColumnMetadata
	TypeChanged    bool // SQL type changed
	NullChanged    bool // Nullability changed
	DefaultChanged bool // Default value changed
}

ColumnDiff represents changes to a single column.

type Differ

type Differ struct{}

Differ compares schemas and generates diffs.

func NewDiffer

func NewDiffer() *Differ

NewDiffer creates a new schema differ.

func (*Differ) Compare

func (d *Differ) Compare(codeSchema, dbSchema map[string]*schema.TableMetadata) *SchemaDiff

Compare compares code schema (from structs) with database schema. codeSchema: TableMetadata from parsing Go structs dbSchema: TableMetadata from introspecting database

type EnumTypeDiff added in v1.8.7

type EnumTypeDiff struct {
	Name      string   // Enum type name
	OldValues []string // Existing values in database
	NewValues []string // New values to add
}

EnumTypeDiff represents changes to an enum type.

type Executor

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

Executor executes and tracks database migrations.

func NewExecutor

func NewExecutor(pool *pgxpool.Pool, migrationsDir string) *Executor

NewExecutor creates a new migration executor.

func (*Executor) Apply

func (e *Executor) Apply(ctx context.Context, migration Migration, dryRun bool) error

Apply executes a migration's up SQL.

func (*Executor) ApplyAll

func (e *Executor) ApplyAll(ctx context.Context, migrations []Migration, dryRun bool) error

ApplyAll applies all pending migrations.

func (*Executor) GetAllMigrations

func (e *Executor) GetAllMigrations(ctx context.Context) ([]MigrationRecord, error)

GetAllMigrations returns all migration records.

func (*Executor) GetAppliedMigrations

func (e *Executor) GetAppliedMigrations(ctx context.Context) ([]MigrationRecord, error)

GetAppliedMigrations returns all migrations that have been applied.

func (*Executor) GetStatus

func (e *Executor) GetStatus(ctx context.Context, migrations []Migration) ([]MigrationRecord, error)

GetStatus returns the status of all migrations.

func (*Executor) Initialize

func (e *Executor) Initialize(ctx context.Context) error

Initialize creates the schema_migrations table if it doesn't exist.

func (*Executor) IsMigrationApplied

func (e *Executor) IsMigrationApplied(ctx context.Context, version string) (bool, error)

IsMigrationApplied checks if a specific migration has been applied.

func (*Executor) Lock

func (e *Executor) Lock(ctx context.Context) error

Lock acquires an advisory lock to prevent concurrent migrations.

func (*Executor) Rollback

func (e *Executor) Rollback(ctx context.Context, migration Migration, dryRun bool) error

Rollback executes a migration's down SQL.

func (*Executor) RollbackLast

func (e *Executor) RollbackLast(ctx context.Context, migration Migration, dryRun bool) error

RollbackLast rolls back the most recently applied migration.

func (*Executor) RollbackTo

func (e *Executor) RollbackTo(ctx context.Context, targetVersion string, migrations []Migration, dryRun bool) error

RollbackTo rolls back all migrations after the specified version.

func (*Executor) TryLock

func (e *Executor) TryLock(ctx context.Context) (bool, error)

TryLock attempts to acquire an advisory lock without blocking.

func (*Executor) Unlock

func (e *Executor) Unlock(ctx context.Context) error

Unlock releases the advisory lock.

func (*Executor) Validate

func (e *Executor) Validate(ctx context.Context, migrations []Migration) error

Validate checks that all migrations in the database have corresponding files.

func (*Executor) WithLockID

func (e *Executor) WithLockID(lockID int64) *Executor

WithLockID sets a custom advisory lock ID.

func (*Executor) WithTransaction

func (e *Executor) WithTransaction(ctx context.Context, fn func(tx pgx.Tx) error) error

WithTransaction executes a function within a transaction.

type Generator

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

Generator generates migration files.

func NewGenerator

func NewGenerator(migrationsDir string) *Generator

NewGenerator creates a new migration file generator.

func (*Generator) Generate

func (g *Generator) Generate(name string, diff *SchemaDiff) (*MigrationFile, error)

Generate creates migration files from a schema diff.

func (*Generator) GenerateEmpty

func (g *Generator) GenerateEmpty(name string) (*MigrationFile, error)

GenerateEmpty creates empty migration files for manual editing.

func (*Generator) ListMigrations

func (g *Generator) ListMigrations() ([]MigrationFile, error)

ListMigrations lists all migration files in the migrations directory.

func (*Generator) ReadMigration

func (g *Generator) ReadMigration(file MigrationFile) (*Migration, error)

ReadMigration reads the SQL content from a migration file.

type Introspector

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

Introspector inspects database schema.

func NewIntrospector

func NewIntrospector(pool *pgxpool.Pool) *Introspector

NewIntrospector creates a new database introspector.

func (*Introspector) IntrospectSchema

func (i *Introspector) IntrospectSchema(ctx context.Context) (map[string]*schema.TableMetadata, error)

IntrospectSchema introspects the entire database schema.

func (*Introspector) IntrospectTable

func (i *Introspector) IntrospectTable(ctx context.Context, tableName string) (*schema.TableMetadata, error)

IntrospectTable introspects a single table.

type Migration

type Migration struct {
	Version   string    // Version/timestamp (e.g., "20240101120000")
	Name      string    // Migration name (e.g., "create_users_table")
	UpSQL     string    // SQL for applying the migration
	DownSQL   string    // SQL for rolling back the migration
	AppliedAt time.Time // When the migration was applied
}

Migration represents a database migration.

type MigrationFile

type MigrationFile struct {
	Version  string // Version/timestamp
	Name     string // Migration name
	UpPath   string // Path to .up.sql file
	DownPath string // Path to .down.sql file
}

MigrationFile represents a migration file on disk.

type MigrationPlan

type MigrationPlan struct {
	Migrations []Migration // Migrations to apply in order
	DryRun     bool        // Whether this is a dry run
}

MigrationPlan represents a plan for applying migrations.

type MigrationRecord

type MigrationRecord struct {
	Version   string          // Migration version
	Name      string          // Migration name
	Status    MigrationStatus // Current status
	AppliedAt *time.Time      // When applied (nil if not applied)
	Error     *string         // Error message if failed
}

MigrationRecord represents a migration in the tracking table.

type MigrationStatus

type MigrationStatus string

MigrationStatus represents the status of a migration.

const (
	// StatusPending means the migration has not been applied.
	StatusPending MigrationStatus = "pending"
	// StatusApplied means the migration has been applied.
	StatusApplied MigrationStatus = "applied"
	// StatusFailed means the migration failed to apply.
	StatusFailed MigrationStatus = "failed"
)

type Planner

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

Planner generates SQL migration statements from schema diffs.

func NewPlanner

func NewPlanner() *Planner

NewPlanner creates a new migration planner with default options.

func NewPlannerWithOptions added in v1.4.0

func NewPlannerWithOptions(opts PlannerOptions) *Planner

NewPlannerWithOptions creates a new migration planner with custom options.

func (*Planner) GenerateMigration

func (p *Planner) GenerateMigration(diff *SchemaDiff) (upSQL, downSQL string)

GenerateMigration generates up and down SQL from a schema diff.

type PlannerOptions added in v1.4.0

type PlannerOptions struct {
	// IfNotExists adds IF NOT EXISTS to CREATE TABLE statements.
	// This makes migrations idempotent and safe to run multiple times.
	// Default: true (safe by default)
	IfNotExists bool
}

PlannerOptions configures migration generation behavior.

type PrimaryKeyChange

type PrimaryKeyChange struct {
	Old *schema.PrimaryKeyMetadata
	New *schema.PrimaryKeyMetadata
}

PrimaryKeyChange represents a change to the primary key.

type SchemaDiff

type SchemaDiff struct {
	TablesAdded       []schema.TableMetadata // Tables to create
	TablesDropped     []schema.TableMetadata // Tables to drop (full metadata for down migration)
	TablesModified    []TableDiff            // Tables with changes
	EnumTypesAdded    []schema.EnumType      // Enum types to create
	EnumTypesDropped  []schema.EnumType      // Enum types to drop (full metadata for down migration)
	EnumTypesModified []EnumTypeDiff         // Enum types with new values
}

SchemaDiff represents differences between two schemas.

func (*SchemaDiff) HasChanges

func (d *SchemaDiff) HasChanges() bool

HasChanges returns true if there are any schema differences.

type TableDiff

type TableDiff struct {
	TableName          string                      // Name of the table
	ColumnsAdded       []schema.ColumnMetadata     // Columns to add
	ColumnsDropped     []schema.ColumnMetadata     // Columns to drop (full metadata for down migration)
	ColumnsModified    []ColumnDiff                // Columns with changes
	IndexesAdded       []schema.IndexMetadata      // Indexes to create
	IndexesDropped     []schema.IndexMetadata      // Indexes to drop (full metadata for down migration)
	ForeignKeysAdded   []schema.ForeignKeyMetadata // Foreign keys to add
	ForeignKeysDropped []schema.ForeignKeyMetadata // Foreign keys to drop (full metadata for down migration)
	ConstraintsAdded   []schema.ConstraintMetadata // Constraints to add
	ConstraintsDropped []schema.ConstraintMetadata // Constraints to drop (full metadata for down migration)
	PrimaryKeyChanged  *PrimaryKeyChange           // Primary key modification
}

TableDiff represents changes to a single table.

func (*TableDiff) HasChanges

func (t *TableDiff) HasChanges() bool

HasChanges returns true if the table has any changes.

Jump to

Keyboard shortcuts

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