db_migrator

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 15, 2026 License: MIT Imports: 14 Imported by: 2

README

Compogo DB Migrator 📦

Compogo DB Migrator — компонент для управления миграциями базы данных, построенный на базе golang-migrate. Полностью интегрируется с экосистемой Compogo.

🚀 Установка

go get github.com/Compogo/db-migrator
📦 Быстрый старт
package main

import (
    "github.com/Compogo/compogo"
    "github.com/Compogo/db-client"
    "github.com/Compogo/db-migrator"
    _ "github.com/Compogo/postgres" // ваш драйвер БД
)

func main() {
    app := compogo.NewApp("myapp",
        compogo.WithOsSignalCloser(),
        db_client.Component,      // выбираем драйвер через --db.driver
        db_migrator.Component,    // мигратор автоматически подхватит тот же драйвер
        compogo.WithComponents(
            // ... ваши компоненты
        ),
    )

    if err := app.Serve(); err != nil {
        panic(err)
    }
}
✨ Возможности
🔌 Плагинная архитектура драйверов

Драйверы БД сами регистрируют свою реализацию для мигратора:

// В драйвере postgres
func init() {
    db_migrator.Registration(Postgres, NewPostgresMigrationDriver)
}
📁 Умный путь к миграциям

Путь к файлам миграций может содержать плейсхолдер {db.driver}:

--migrator.source="file://./migrations/{db.driver}"

При использовании драйвера postgres путь автоматически станет file://./migrations/postgres.

🚦 Автоматические миграции
./myapp --migrator.auto=true

Миграции выполняются в фазе Execute до запуска основных сервисов.

⏱️ Бесконечный таймаут

Миграции — критическая операция, которую нельзя прерывать. Компонент устанавливает таймаут = 0, позволяя миграциям выполняться столько, сколько нужно.

🔗 Интеграция с драйверами

Драйверы должны зарегистрировать свою реализацию database.Driver для мигратора:

type PostgresMigrationDriver struct {
    // ...
}

func NewPostgresMigrationDriver(container container.Container) (database.Driver, error) {
    var db *sql.DB
    if err := container.Invoke(func(sqlDB *sql.DB) { db = sqlDB }); err != nil {
        return nil, err
    }
    return postgres.WithConnection(db), nil
}

func init() {
    db_migrator.Registration(Postgres, NewPostgresMigrationDriver)
}

Documentation

Index

Constants

View Source
const (
	PathFieldName        = "migrator.source"
	AutoMigrateFieldName = "migrator.auto"

	DriverReplacement = "{db.driver}"

	PathDefault        = "file://./migrations/" + DriverReplacement
	AutoMigrateDefault = false
)

Variables

View Source
var Component = &component.Component{
	Init: component.StepFunc(func(container container.Container) error {
		return container.Provides(
			NewConfig,
			NewMigrator,
		)
	}),
	BindFlags: component.BindFlags(func(flagSet flag.FlagSet, container container.Container) error {
		return container.Invoke(func(config *Config) {
			flagSet.StringVar(&config.Path, PathFieldName, PathDefault, "path to migrations directory")
			flagSet.BoolVar(&config.AutoMigrate, AutoMigrateFieldName, AutoMigrateDefault, "automatically migrate")
		})
	}),
	Configuration: component.StepFunc(func(container container.Container) error {
		return container.Invoke(Configuration)
	}),
	ExecuteDuration: component.GetDurationFunc(func() time.Duration {
		return 0
	}),
	Execute: component.StepFunc(func(container container.Container) error {
		return container.Invoke(func(config *Config, migrator *migrate.Migrate, informer logger.Informer) error {
			if !config.AutoMigrate {
				return nil
			}

			err := migrator.Up()
			if err != nil && !errors.Is(err, migrate.ErrNoChange) {
				return err
			}

			if errors.Is(err, migrate.ErrNoChange) {
				return nil
			}

			version, _, err := migrator.Version()

			informer.Infof("[db-migrator]: up to '%d' version", version)

			return nil
		})
	}),
}

Component is a ready-to-use Compogo component that provides database migrations. It automatically:

  • Registers Config and Migrator in the DI container
  • Adds command-line flags for migration configuration
  • Applies configuration during Configuration phase
  • Runs migrations (if enabled) during Execute phase with no timeout

Usage:

compogo.WithComponents(
    db_client.Component,      // database client (provides driver name)
    db_migrator.Component,    // migrations
    // ... driver components (postgres, mysql, etc.)
)

The driver name is automatically taken from db-client configuration and used to select the appropriate migration driver.

Functions

func NewMigrator

func NewMigrator(config *Config, container container.Container, informer logger.Informer) (*migrate.Migrate, error)

NewMigrator creates a new golang-migrate instance based on the configuration. It performs the following steps:

  1. Replaces {db.driver} placeholder in the path with actual driver name
  2. Looks up the Getter for the configured driver
  3. Creates the migration driver instance
  4. Returns a configured migrate.Migrate instance

The migrator is not started automatically — use the Component for lifecycle management.

func Registration

func Registration(d driver.Driver, getter Getter)

Registration registers a new database driver constructor for migrations. This function should be called during driver package initialization. The driver will then be available for use via the migrator component.

Example (in postgres driver):

func init() {
    db_migrator.Registration(Postgres, NewPostgresMigrationDriver)
}

Types

type Config

type Config struct {
	Path        string
	AutoMigrate bool
	Driver      driver.Driver
}

func Configuration

func Configuration(config *Config, configurator configurator.Configurator) *Config

func NewConfig

func NewConfig() *Config

type Getter

type Getter func(container container.Container) (database.Driver, error)

Getter is a function type that creates a new migration driver instance. It receives the DI container which may contain dependencies like config or logger, and returns a database.Driver compatible with golang-migrate.

Jump to

Keyboard shortcuts

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