Adding 'Fixing errors in SQL migrations' sub-section.
This commit is contained in:
29
README.md
29
README.md
@@ -129,6 +129,35 @@ Applying all down migrations
|
||||
|
||||
Another variant of this is the **drop** command, which will remove all tables from the database including the **schema_migrations** table - but the database itself will remain, [along with anything else that has been created](https://github.com/golang-migrate/migrate/issues/193) like sequences and enums. Because if this, using **drop** can leave your database in a messy and unknown state, and it's generally better to stick with the **down** command if you want to roll back everything.
|
||||
|
||||
### Fixing errors in SQL migrations
|
||||
|
||||
When you run a migration that contains an error, all SQL statements up to the erroneous one will be applied and then the **migrate** tool will exit with a message describing the error. Similar to this :
|
||||
|
||||
```bash
|
||||
$ migrate -path=./migrations -database=$EXAMPLE_DSN up
|
||||
1/u create_foo_table (39.38729ms)
|
||||
2/u create_bar_table (78.29829ms)
|
||||
error: migration failed: syntax error at end of input in line 0: CREATE TABLE (details: pq syntax error at end of input)
|
||||
```
|
||||
|
||||
If the migration file which failed contained multiple SQL statements, then it's possible that the migration file was **partially** applied before the error was encountered. In turn, this means that the database is in an unknown state as far as the **migrate** tool is concerned.
|
||||
|
||||
Accordingly, the **version** field in the **schema_migrations** field will contain the number for the failed migration and the **dirty** field will be set to **true**. At this point, if you run another migration (**even a "down" migration**) you will get an error message similar to this:
|
||||
|
||||
```bash
|
||||
Dirty database version {X}. Fix and force version.
|
||||
```
|
||||
|
||||
What you need to do is investigate the original error and figure out if the migration file which failed was partially applied. If it was, then you need to manually roll-back the partially applied migration.
|
||||
|
||||
Once that's done, then you must also 'force' the version number in the schema_migrations table to the correct value. For example, to force the database version number to 1 you should use the force command like so :
|
||||
|
||||
```bash
|
||||
$ migrate -path=./migrations -database=$EXAMPLE_DSN force 1
|
||||
```
|
||||
|
||||
Once you force the version, the database is considered 'clean' and you should be able to run migrations again without any problem.
|
||||
|
||||
## Additional Information
|
||||
|
||||
### How different Go Types are encoded
|
||||
|
||||
Reference in New Issue
Block a user