migrate: github.com/golang-migrate/migrate Index | Examples | Files | Directories

package migrate

import "github.com/golang-migrate/migrate"

Package migrate reads migrations from sources and runs them against databases. Sources are defined by the `source.Driver` and databases by the `database.Driver` interface. The driver interfaces are kept "dump", all migration logic is kept in this package.

Index

Examples

Package Files

log.go migrate.go migration.go util.go

Variables

var (
    ErrNoChange       = errors.New("no change")
    ErrNilVersion     = errors.New("no migration")
    ErrInvalidVersion = errors.New("version must be >= -1")
    ErrLocked         = errors.New("database locked")
    ErrLockTimeout    = errors.New("timeout: can't acquire database lock")
)
var DefaultBufferSize = uint(100000)

DefaultBufferSize sets the in memory buffer size (in Bytes) for every pre-read migration (see DefaultPrefetchMigrations).

var DefaultLockTimeout = 15 * time.Second

DefaultLockTimeout sets the max time a database driver has to acquire a lock.

var DefaultPrefetchMigrations = uint(10)

DefaultPrefetchMigrations sets the number of migrations to pre-read from the source. This is helpful if the source is remote, but has little effect for a local source (i.e. file system). Please note that this setting has a major impact on the memory usage, since each pre-read migration is buffered in memory. See DefaultBufferSize.

func FilterCustomQuery Uses

func FilterCustomQuery(u *nurl.URL) *nurl.URL

FilterCustomQuery filters all query values starting with `x-`

type ErrDirty Uses

type ErrDirty struct {
    Version int
}

func (ErrDirty) Error Uses

func (e ErrDirty) Error() string

type ErrShortLimit Uses

type ErrShortLimit struct {
    Short uint
}

ErrShortLimit is an error returned when not enough migrations can be returned by a source for a given limit.

func (ErrShortLimit) Error Uses

func (e ErrShortLimit) Error() string

Error implements the error interface.

type Logger Uses

type Logger interface {

    // Printf is like fmt.Printf
    Printf(format string, v ...interface{})

    // Verbose should return true when verbose logging output is wanted
    Verbose() bool
}

Logger is an interface so you can pass in your own logging implementation.

type Migrate Uses

type Migrate struct {

    // Log accepts a Logger interface
    Log Logger

    // GracefulStop accepts `true` and will stop executing migrations
    // as soon as possible at a safe break point, so that the database
    // is not corrupted.
    GracefulStop chan bool

    // PrefetchMigrations defaults to DefaultPrefetchMigrations,
    // but can be set per Migrate instance.
    PrefetchMigrations uint

    // LockTimeout defaults to DefaultLockTimeout,
    // but can be set per Migrate instance.
    LockTimeout time.Duration
    // contains filtered or unexported fields
}

func New Uses

func New(sourceUrl, databaseUrl string) (*Migrate, error)

New returns a new Migrate instance from a source URL and a database URL. The URL scheme is defined by each driver.

Code:

// Read migrations from /home/mattes/migrations and connect to a local postgres database.
m, err := New("file:///home/mattes/migrations", "postgres://mattes:secret@localhost:5432/database?sslmode=disable")
if err != nil {
    log.Fatal(err)
}

// Migrate all the way up ...
if err := m.Up(); err != nil {
    log.Fatal(err)
}

func NewWithDatabaseInstance Uses

func NewWithDatabaseInstance(sourceUrl string, databaseName string, databaseInstance database.Driver) (*Migrate, error)

NewWithDatabaseInstance returns a new Migrate instance from a source URL and an existing database instance. The source URL scheme is defined by each driver. Use any string that can serve as an identifier during logging as databaseName. You are responsible for closing the underlying database client if necessary.

Code:

// Create and use an existing database instance.
db, err := sql.Open("postgres", "postgres://mattes:secret@localhost:5432/database?sslmode=disable")
if err != nil {
    log.Fatal(err)
}
defer db.Close()

// Create driver instance from db.
// Check each driver if it supports the WithInstance function.
// `import "github.com/golang-migrate/migrate/v4/database/postgres"`
instance, err := dStub.WithInstance(db, &dStub.Config{})
if err != nil {
    log.Fatal(err)
}

// Read migrations from /home/mattes/migrations and connect to a local postgres database.
m, err := NewWithDatabaseInstance("file:///home/mattes/migrations", "postgres", instance)
if err != nil {
    log.Fatal(err)
}

// Migrate all the way up ...
if err := m.Up(); err != nil {
    log.Fatal(err)
}

func NewWithInstance Uses

func NewWithInstance(sourceName string, sourceInstance source.Driver, databaseName string, databaseInstance database.Driver) (*Migrate, error)

NewWithInstance returns a new Migrate instance from an existing source and database instance. Use any string that can serve as an identifier during logging as sourceName and databaseName. You are responsible for closing down the underlying source and database client if necessary.

Code:

// See NewWithDatabaseInstance and NewWithSourceInstance for an example.

func NewWithSourceInstance Uses

func NewWithSourceInstance(sourceName string, sourceInstance source.Driver, databaseUrl string) (*Migrate, error)

NewWithSourceInstance returns a new Migrate instance from an existing source instance and a database URL. The database URL scheme is defined by each driver. Use any string that can serve as an identifier during logging as sourceName. You are responsible for closing the underlying source client if necessary.

Code:

di := &DummyInstance{"think any client required for a source here"}

// Create driver instance from DummyInstance di.
// Check each driver if it support the WithInstance function.
// `import "github.com/golang-migrate/migrate/v4/source/stub"`
instance, err := sStub.WithInstance(di, &sStub.Config{})
if err != nil {
    log.Fatal(err)
}

// Read migrations from Stub and connect to a local postgres database.
m, err := NewWithSourceInstance("stub", instance, "postgres://mattes:secret@localhost:5432/database?sslmode=disable")
if err != nil {
    log.Fatal(err)
}

// Migrate all the way up ...
if err := m.Up(); err != nil {
    log.Fatal(err)
}

func (*Migrate) Close Uses

func (m *Migrate) Close() (source error, database error)

Close closes the source and the database.

func (*Migrate) Down Uses

func (m *Migrate) Down() error

Down looks at the currently active migration version and will migrate all the way down (applying all down migrations).

func (*Migrate) Drop Uses

func (m *Migrate) Drop() error

Drop deletes everything in the database.

func (*Migrate) Force Uses

func (m *Migrate) Force(version int) error

Force sets a migration version. It does not check any currently active version in database. It resets the dirty state to false.

func (*Migrate) Migrate Uses

func (m *Migrate) Migrate(version uint) error

Migrate looks at the currently active migration version, then migrates either up or down to the specified version.

func (*Migrate) Run Uses

func (m *Migrate) Run(migration ...*Migration) error

Run runs any migration provided by you against the database. It does not check any currently active version in database. Usually you don't need this function at all. Use Migrate, Steps, Up or Down instead.

func (*Migrate) Steps Uses

func (m *Migrate) Steps(n int) error

Steps looks at the currently active migration version. It will migrate up if n > 0, and down if n < 0.

func (*Migrate) Up Uses

func (m *Migrate) Up() error

Up looks at the currently active migration version and will migrate all the way up (applying all up migrations).

func (*Migrate) Version Uses

func (m *Migrate) Version() (version uint, dirty bool, err error)

Version returns the currently active migration version. If no migration has been applied, yet, it will return ErrNilVersion.

type Migration Uses

type Migration struct {
    // Identifier can be any string to help identifying
    // the migration in the source.
    Identifier string

    // Version is the version of this migration.
    Version uint

    // TargetVersion is the migration version after this migration
    // has been applied to the database.
    // Can be -1, implying that this is a NilVersion.
    TargetVersion int

    // Body holds an io.ReadCloser to the source.
    Body io.ReadCloser

    // BufferedBody holds an buffered io.Reader to the underlying Body.
    BufferedBody io.Reader

    // BufferSize defaults to DefaultBufferSize
    BufferSize uint

    // Scheduled is the time when the migration was scheduled/ queued.
    Scheduled time.Time

    // StartedBuffering is the time when buffering of the migration source started.
    StartedBuffering time.Time

    // FinishedBuffering is the time when buffering of the migration source finished.
    FinishedBuffering time.Time

    // FinishedReading is the time when the migration source is fully read.
    FinishedReading time.Time

    // BytesRead holds the number of Bytes read from the migration source.
    BytesRead int64
    // contains filtered or unexported fields
}

Migration holds information about a migration. It is initially created from data coming from the source and then used when run against the database.

func NewMigration Uses

func NewMigration(body io.ReadCloser, identifier string,
    version uint, targetVersion int) (*Migration, error)

NewMigration returns a new Migration and sets the body, identifier, version and targetVersion. Body can be nil, which turns this migration into a "NilMigration". If no identifier is provided, it will default to "<empty>". targetVersion can be -1, implying it is a NilVersion.

What is a NilMigration? Usually each migration version coming from source is expected to have an Up and Down migration. This is not a hard requirement though, leading to a situation where only the Up or Down migration is present. So let's say the user wants to migrate up to a version that doesn't have the actual Up migration, in that case we still want to apply the version, but with an empty body. We are calling that a NilMigration, a migration with an empty body.

What is a NilVersion? NilVersion is a const(-1). When running down migrations and we are at the last down migration, there is no next down migration, the targetVersion should be nil. Nil in this case is represented by -1 (because type int).

Code:

// Create a dummy migration body, this is coming from the source usually.
body := ioutil.NopCloser(strings.NewReader("dumy migration that creates users table"))

// Create a new Migration that represents version 1486686016.
// Once this migration has been applied to the database, the new
// migration version will be 1486689359.
migr, err := NewMigration(body, "create_users_table", 1486686016, 1486689359)
if err != nil {
    log.Fatal(err)
}

fmt.Print(migr.LogString())

Output:

1486686016/u create_users_table

Code:

// Create a new Migration that represents a NilMigration.
// Once this migration has been applied to the database, the new
// migration version will be 1486689359.
migr, err := NewMigration(nil, "", 1486686016, 1486689359)
if err != nil {
    log.Fatal(err)
}

fmt.Print(migr.LogString())

Output:

1486686016/u <empty>

Code:

// Create a dummy migration body, this is coming from the source usually.
body := ioutil.NopCloser(strings.NewReader("dumy migration that deletes users table"))

// Create a new Migration that represents version 1486686016.
// This is the last available down migration, so the migration version
// will be -1, meaning NilVersion once this migration ran.
migr, err := NewMigration(body, "drop_users_table", 1486686016, -1)
if err != nil {
    log.Fatal(err)
}

fmt.Print(migr.LogString())

Output:

1486686016/d drop_users_table

func (*Migration) Buffer Uses

func (m *Migration) Buffer() error

Buffer buffers Body up to BufferSize. Calling this function blocks. Call with goroutine.

func (*Migration) LogString Uses

func (m *Migration) LogString() string

LogString returns a string describing this migration to humans.

func (*Migration) String Uses

func (m *Migration) String() string

String implements string.Stringer and is used in tests.

type MultiError Uses

type MultiError struct {
    Errs []error
}

MultiError holds multiple errors.

func NewMultiError Uses

func NewMultiError(errs ...error) MultiError

NewMultiError returns an error type holding multiple errors.

func (MultiError) Error Uses

func (m MultiError) Error() string

Error implements error. Mulitple errors are concatenated with 'and's.

Directories

PathSynopsis
cli
databasePackage database provides the Database interface.
database/cassandra
database/clickhouse
database/cockroachdb
database/mongodb
database/mysql
database/postgres
database/ql
database/redshift
database/spanner
database/sqlite3
database/stub
database/testingPackage testing has the database tests.
dktesting
sourcePackage source provides the Source interface.
source/aws_s3
source/file
source/github
source/go_bindata
source/godoc_vfsPackage vfs contains a driver that reads migrations from a virtual file system.
source/google_cloud_storage
source/stub
source/testingPackage testing has the source tests.
testingPackage testing is used in driver tests.

Package migrate imports 11 packages (graph) and is imported by 35 packages. Updated 2019-02-19. Refresh now. Tools for package owners.