gomigrate

package module
v0.0.0-...-940b5b4 Latest Latest
Warning

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

Go to latest
Published: Jun 22, 2016 License: MIT Imports: 11 Imported by: 2

README

gomigrate

Build Status

A SQL database migration toolkit in Golang that supports migrations from multiple sources including in memory and files on disk.

Supported databases

  • PostgreSQL
  • MariaDB
  • MySQL
  • Sqlite3

Usage

First import the package:

import "github.com/hobeone/gomigrate"

Load Migrations from disk:

m, err = gomigrate.MigrationsFromPath(path, logger)
if err != nil {
  // deal with error
}

Given a database/sql database connection to a PostgreSQL database, db, and a directory to migration files, create a migrator:

migrator, _ := gomigrate.NewMigratorWithMigrations(db, gomigrate.Postgres{}, m)
migrator.Logger = logger

You may also specify a specific logger to use at creation time, such as logrus:

migrator, _ := gomigrate.NewMigratorWithLogger(db, gomigrate.Postgres{}, m, logrus.New())

To migrate the database, run:

err := migrator.Migrate()

To rollback the last migration, run:

err := migrator.Rollback()

Migration files

Migration files need to follow a standard format and must be present in the same directory. Given "up" and "down" steps for a migration, create a file for each by following this template:

{{ id }}_{{ name }}_{{ "up" or "down" }}.sql

For a given migration, the id and name fields must be the same. The id field is an integer that corresponds to the order in which the migration should run relative to the other migrations.

id should not be 0 as that value is used for internal validations.

Example

If I'm trying to add a "users" table to the database, I would create the following two files:

1_add_users_table_up.sql
CREATE TABLE users();
1_add_users_table_down.sql
DROP TABLE users;

Migrations from Memory

Migrations can also be embedded directly in your go code and passed into the Migrator. This can be useful for testdata fixtures or using go-bindata to build fixture data into your go binary.

	migrations := []*Migration{
		{
			ID:   100,
			Name: "FirstMigration",
			Up: `CREATE TABLE first_table (
				id INTEGER PRIMARY KEY
			)`,
			Down: `drop table "first_table"`,
		},
		{
			ID:   110,
			Name: "SecondMigration",
			Up: `CREATE TABLE second_table (
				id INTEGER PRIMARY KEY
			)`,
			Down: `drop table "second_table"`,
		},
	}
	migrator, _ := gomigrate.NewMigratorWithMigrations(db, gomigrate.Postgres{}, migrations)
	migrator.Migrate()

Copyright (c) 2014 David Huie. See LICENSE.txt for further details.

Documentation

Index

Constants

View Source
const (
	Inactive = iota
	Active
)

Migration statuses.

Variables

View Source
var (
	InvalidMigrationFile  = errors.New("Invalid migration file")
	InvalidMigrationPair  = errors.New("Invalid pair of migration files")
	InvalidMigrationType  = errors.New("Invalid migration type")
	ErrDuplicateMigration = errors.New("Duplicate migrations found")
)

Functions

This section is empty.

Types

type ErrInvalidMigration

type ErrInvalidMigration struct {
	ID   uint64
	Name string
	Err  string
}

ErrInvalidMigration encapsulates the reasons why a migration is invalid.

func (*ErrInvalidMigration) Error

func (e *ErrInvalidMigration) Error() string

type Logger

type Logger interface {
	Print(v ...interface{})
	Printf(format string, v ...interface{})
	Println(v ...interface{})
	Fatalf(format string, v ...interface{})
}

Logger represents the standard logging interface allows different logging implementations to be used.

type Mariadb

type Mariadb struct {
	Mysql
}

type Migratable

type Migratable interface {
	SelectMigrationTableSql() string
	CreateMigrationTableSql() string
	GetMigrationSql() string
	MigrationLogInsertSql() string
	MigrationLogDeleteSql() string
	GetMigrationCommands(string) []string
}

type Migration

type Migration struct {
	ID     uint64
	Name   string
	Status int
	Up     string
	Down   string
	Source string
}

Migration holds configuration information for a given migration.

func MigrationsFromPath

func MigrationsFromPath(migrationsPath string, logger Logger) ([]*Migration, error)

MigrationsFromPath loads migrations from the given path. Migration file naming and format requires two files per migration of the form: NUMBER_NAME_[UP|DOWN].sql

Example:

1_add_users_table_up.sql
1_add_users_table_down.sql

The name must match for each numbered pair.

func (*Migration) Validate

func (m *Migration) Validate() error

Validate checks that a migration is properly formed and named.

type Migrator

type Migrator struct {
	DB             *sql.DB
	MigrationsPath string

	Logger Logger
	// contains filtered or unexported fields
}

Migrator contains the information needed to migrate a database schema.

func NewMigrator

func NewMigrator(db *sql.DB, adapter Migratable, migrationsPath string) (*Migrator, error)

NewMigrator is the previous api for gomigrate. It loads migrations from disk and return a new migrator.

func NewMigratorWithLogger

func NewMigratorWithLogger(db *sql.DB, adapter Migratable, migrationsPath string, logger Logger) (*Migrator, error)

NewMigratorWithLogger is the previous api for gomigrate. It loads migrations from disk and you can provide a Logger object.

func NewMigratorWithMigrations

func NewMigratorWithMigrations(db *sql.DB, adapter Migratable, migrations []*Migration) (*Migrator, error)

NewMigratorWithMigrations returns a new Migrator setup with the given migrations. It validates the migrations (i.e. no duplicates) but doesn't connect to the database. All changes happen in the Migrate() function.

func (*Migrator) ApplyMigration

func (m *Migrator) ApplyMigration(migration *Migration, mType migrationType) error

ApplyMigration applies a single migration in the given direction.

func (*Migrator) CreateMigrationsTable

func (m *Migrator) CreateMigrationsTable() error

CreateMigrationsTable creates the migrations table if it doesn't exist.

func (*Migrator) Migrate

func (m *Migrator) Migrate() error

Migrate runs the given migrations against the database. It will also create the migration meta table if needed and will only run migrations that haven't already been run.

func (*Migrator) MigrationTableExists

func (m *Migrator) MigrationTableExists() (bool, error)

MigrationTableExists returns true if the migration table already exists.

func (*Migrator) Migrations

func (m *Migrator) Migrations(status int) []*Migration

Migrations returns a sorted list of migration ids for a given status. -1 returns all migrations.

func (*Migrator) Rollback

func (m *Migrator) Rollback() error

Rollback rolls back the last migration.

func (*Migrator) RollbackAll

func (m *Migrator) RollbackAll() error

RollbackAll rolls back all migrations.

func (*Migrator) RollbackN

func (m *Migrator) RollbackN(n int) error

RollbackN rolls back N migrations.

type Mysql

type Mysql struct{}

func (Mysql) CreateMigrationTableSql

func (m Mysql) CreateMigrationTableSql() string

func (Mysql) GetMigrationCommands

func (m Mysql) GetMigrationCommands(sql string) []string

func (Mysql) GetMigrationSql

func (m Mysql) GetMigrationSql() string

func (Mysql) MigrationLogDeleteSql

func (m Mysql) MigrationLogDeleteSql() string

func (Mysql) MigrationLogInsertSql

func (m Mysql) MigrationLogInsertSql() string

func (Mysql) SelectMigrationTableSql

func (m Mysql) SelectMigrationTableSql() string

type Postgres

type Postgres struct{}

func (Postgres) CreateMigrationTableSql

func (p Postgres) CreateMigrationTableSql() string

func (Postgres) GetMigrationCommands

func (p Postgres) GetMigrationCommands(sql string) []string

func (Postgres) GetMigrationSql

func (p Postgres) GetMigrationSql() string

func (Postgres) MigrationLogDeleteSql

func (p Postgres) MigrationLogDeleteSql() string

func (Postgres) MigrationLogInsertSql

func (p Postgres) MigrationLogInsertSql() string

func (Postgres) SelectMigrationTableSql

func (p Postgres) SelectMigrationTableSql() string

type Sqlite3

type Sqlite3 struct{}

func (Sqlite3) CreateMigrationTableSql

func (s Sqlite3) CreateMigrationTableSql() string

func (Sqlite3) GetMigrationCommands

func (s Sqlite3) GetMigrationCommands(sql string) []string

func (Sqlite3) GetMigrationSql

func (s Sqlite3) GetMigrationSql() string

func (Sqlite3) MigrationLogDeleteSql

func (s Sqlite3) MigrationLogDeleteSql() string

func (Sqlite3) MigrationLogInsertSql

func (s Sqlite3) MigrationLogInsertSql() string

func (Sqlite3) SelectMigrationTableSql

func (s Sqlite3) SelectMigrationTableSql() string

Jump to

Keyboard shortcuts

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