clair/vendor/github.com/remind101/migrate
2017-05-05 11:46:41 -04:00
..
.gitignore vendor: regenerate vendor directory with glide 2017-05-05 11:46:41 -04:00
.travis.yml vendor: regenerate vendor directory with glide 2017-05-05 11:46:41 -04:00
example_test.go vendor: regenerate vendor directory with glide 2017-05-05 11:46:41 -04:00
LICENSE vendor: regenerate vendor directory with glide 2017-05-05 11:46:41 -04:00
migrate_test.go vendor: regenerate vendor directory with glide 2017-05-05 11:46:41 -04:00
migrate.go vendor: regenerate vendor directory with glide 2017-05-05 11:46:41 -04:00
README.md vendor: regenerate vendor directory with glide 2017-05-05 11:46:41 -04:00

Migrate

Build Status

Migrate is a Go library for doing migrations. It's stupidly simple and gets out of your way.

Features

  • It's only dependency is database/sql.
  • It supports any type of migration you want to run (e.g. raw sql, or Go code).
  • It doesn't provide a command. It's designed to be embedded in projects and used exclusively as a library.

Usage

migrations := []migrate.Migration{
	{
		ID: 1,
		Up: func(tx *sql.Tx) error {
			_, err := tx.Exec("CREATE TABLE people (id int)")
			return err
		},
		Down: func(tx *sql.Tx) error {
			_, err := tx.Exec("DROP TABLE people")
			return err
		},
	},
	{
		ID: 2,
		// For simple sql migrations, you can use the migrate.Queries
		// helper.
		Up: migrate.Queries([]string{
			"ALTER TABLE people ADD COLUMN first_name text",
		}),
		Down: func(tx *sql.Tx) error {
			// It's not possible to remove a column with
			// sqlite.
			_, err := tx.Exec("SELECT 1 FROM people")
			return err
		},
	},
}

db, _ := sql.Open("sqlite3", ":memory:")
_ = migrate.Exec(db, migrate.Up, migrations...)

Locking

All migrations are run in a transaction, but if you attempt to run a single long running migration concurrently, you could run into a deadlock. For Postgres connections, migrate can use pg_advisory_lock to ensure that only 1 migration is run at a time.

To use this, simply instantiate a Migrator instance using migrate.NewPostgresMigrator:

migrator := NewPostgresMigrator(db)
_ = migrator.Exec(migrate.Up, migrations...)