migrator

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2025 License: MIT Imports: 11 Imported by: 1

README

Migrator

Go Reference Go Version License

A lightweight, SQL-based database migration tool for Go applications.

Features

  • Simple and efficient SQL migration management
  • Supports both UP and DOWN migrations
  • Version-based migration tracking
  • Transaction-based migrations for safety
  • Detailed logging with customizable log levels
  • Automatic migration table creation
  • Compatible with PostgreSQL (extensible for other databases)

Installation

go get github.com/AlonMell/migrator

Usage

Basic Usage
package main

import (
	"context"
	"database/sql"
	"log"

	"github.com/AlonMell/migrator"
	_ "github.com/lib/pq"
)

func main() {
	// Connect to the database
	db, err := sql.Open("postgres", "postgres://user:password@localhost:5432/dbname?sslmode=disable")
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}
	defer db.Close()

	// Create a new migrator
	// Parameters: database connection, logger, major version, minor version,
	// migrations table name, migrations directory path
	m := migrator.New(db, nil, 1, 0, "migrations", "./migrations")

	// Run migrations
	ctx := context.Background()
	if err := m.Migrate(ctx); err != nil {
		log.Fatalf("Migration failed: %v", err)
	}
}
With Custom Logger
package main

import (
	"context"
	"database/sql"
	"log/slog"
	"os"

	"github.com/AlonMell/grovelog"
	"github.com/AlonMell/migrator"
	_ "github.com/lib/pq"
)

func main() {
	// Setup logger
	opts := grovelog.NewOptions(slog.LevelDebug, "", grovelog.Color)
	logger := grovelog.NewLogger(os.Stdout, opts)

	// Connect to database
	db, err := sql.Open("postgres", "postgres://user:password@localhost:5432/dbname?sslmode=disable")
	if err != nil {
		logger.Error("Failed to connect to database", err)
		os.Exit(1)
	}
	defer db.Close()

	// Create migrator with custom logger
	m := migrator.New(db, logger, 1, 0, "migrations", "./migrations")

	// Run migrations
	ctx := context.Background()
	if err := m.Migrate(ctx); err != nil {
		logger.Error("Migration failed", err)
		os.Exit(1)
	}
}

Migration File Format

Migration files must follow this naming convention:

nnnn.mm.nn[.comment].(up|down).sql

Where:

  • nnnn - File number (4 digits)
  • mm - Major version (2 digits)
  • nn - Minor version (2 digits)
  • [.comment] - Optional comment/description
  • (up|down) - Migration direction (up = apply, down = rollback)

Examples:

  • 0001.00.00.baseline.up.sql - Initial schema creation
  • 0001.00.00.baseline.down.sql - Rollback for initial schema
  • 0002.00.01.create_users.up.sql - Create users table
  • 0002.00.01.create_users.down.sql - Drop users table

Version Control

The migrator uses a version system with major and minor components:

  • Major version (mm) - For significant schema changes
  • Minor version (nn) - For smaller, incremental changes

When running the migrator, specify the target version (major.minor) you want to migrate to:

  • To upgrade: specify a higher version than current
  • To downgrade: specify a lower version than current

Development

Requirements
  • Go 1.24+
  • PostgreSQL
  • Docker (for integration tests)
Testing

Run integration tests with Docker:

make test
Building
make build
Other Commands
make help  # Show available commands

License

MIT License - See LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Last ver.Version = ver.Version{Major: 99, Minor: 99, FileNumber: 9999}
View Source
var Zero ver.Version = ver.Version{Major: -1, Minor: -1, FileNumber: -1}

Functions

func NewDefaultLogger

func NewDefaultLogger() *slog.Logger

Types

type Logger

type Logger interface {
	DebugContext(ctx context.Context, msg string, args ...any)
	InfoContext(ctx context.Context, msg string, args ...any)
	WarnContext(ctx context.Context, msg string, args ...any)
	ErrorContext(ctx context.Context, msg string, args ...any)
}

type Migrator

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

func New

func New(
	db *sql.DB, logger Logger,
	major, minor int,
	table, path string,
) *Migrator

func (*Migrator) Execute

func (m *Migrator) Execute(ctx context.Context, files []*parser.FileInfo) error

func (*Migrator) FetchCurrentVersion

func (m *Migrator) FetchCurrentVersion(ctx context.Context) (ver.Version, error)

func (*Migrator) InitMigrationTable

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

func (*Migrator) Migrate

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

Migrate performs database migration from the current version to the target version

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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