https://github.com/remind101/migrate
Simple migrations for database/sql
https://github.com/remind101/migrate
Last synced: 5 months ago
JSON representation
Simple migrations for database/sql
- Host: GitHub
- URL: https://github.com/remind101/migrate
- Owner: remind101
- License: bsd-2-clause
- Created: 2016-04-15T05:36:11.000Z (over 10 years ago)
- Default Branch: master
- Last Pushed: 2017-07-29T03:19:35.000Z (about 9 years ago)
- Last Synced: 2025-04-29T22:36:32.139Z (over 1 year ago)
- Language: Go
- Homepage: https://godoc.org/github.com/remind101/migrate
- Size: 12.7 KB
- Stars: 40
- Watchers: 57
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Migrate
[](https://travis-ci.org/remind101/migrate)
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
```go
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](http://www.postgresql.org/docs/9.1/static/explicit-locking.html) to ensure that only 1 migration is run at a time.
To use this, simply instantiate a `Migrator` instance using `migrate.NewPostgresMigrator`:
```go
migrator := NewPostgresMigrator(db)
_ = migrator.Exec(migrate.Up, migrations...)
```