Dirty database version error when using golang-migrate

pkaramol picture pkaramol · Jan 6, 2020 · Viewed 14.7k times · Source

I am a new user of golang-migrate.

I have run some migrations that executed with success.

I am on development mode so I want to fore re-run the migrations so in psql shell and after connecting to my database, I executed drop database schema_migrations

The problem now is that when I run the code that executes the migrations (shown below)


func RunMigrations() {
    m, err := migrate.New(
        "file://db/migrations",
        "postgres://postgres:postgres@localhost:5432/mydatabase?sslmode=disable")
    if err != nil {
        log.Fatal(err)
    }
    if err := m.Up(); err != nil {
        if err.Error() == "no change" {
            log.Println("no change made by migration scripts")
        } else {
            log.Fatal(err)
        }
    }
}

I get this error

Dirty database version 2. Fix and force version.

What is this error about and how can I address this?

Answer

Dmitry Harnitski picture Dmitry Harnitski · Jan 6, 2020

Dirty database version 2 means that you tried to run migration v2 and it failed.

Database can be inconsistent or broken if migration failed.

Rerunning additional migrations on top of broken state is unpredictable and therefore migrations are blocked until you clean up Database.

https://github.com/golang-migrate/migrate/blob/master/FAQ.md#what-does-dirty-database-mean

What does "dirty" database mean?

Before a migration runs, each database sets a dirty flag. Execution stops if a migration fails and the dirty state persists, which prevents attempts to run more migrations on top of a failed migration. You need to manually fix the error and then "force" the expected version.

After you clean up you database you can also open schema_migrations table and change Dirty flag and rollback version number to last migration that was successfully applied.