Skip to content

Commit 5ace488

Browse files
Merge pull request #4 from KowalskiPiotr98/initial-migrations-handling
Fix initial migration handling
2 parents f24f96b + 7f9b507 commit 5ace488

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ You can execute migrations by calling the `Migrate` method in the `migrations` p
2121

2222
There are a couple of important things to remember:
2323
1. You should store your migrations in a file with `.sql` extension. These files should be contained in a folder called `sql`. The files should have names consisting of a single number, starting at 0 and going **SEQUENTIALLY** up (as in `0.sql`, `1.sql`, `2.sql`...). If you need to remove a migration after a next number has been used, leave the file empty instead of removing it.
24-
2. Your database model must, from the very beginning, include a migrations table (it **MUST** be created in your `0.sql` migration file). By default, it should contain a single integer column called `id` as a primary key. Note that this behaviour can be modified or adjusted to a different DBMS by overwriting the `MigrationCreator` and `LatestMigrationSelectorSql` variables of the `migrations` package.
24+
2. Your database model must, from the very beginning, include a migrations table (it **MUST** be created in your `0.sql` migration file). By default, it should contain a single integer column called `id` as a primary key. Note that this behaviour can be modified or adjusted to a different DBMS by overwriting the `MigrationCreator`, `IsInitialMigrationError` and `LatestMigrationSelectorSql` variables of the `migrations` package.
2525
3. The interface for providing database migrations files must be implemented, as there's no default implementation. You can, however, use the `embed.FS` struct, as it fulfills the conditions of this interface. See below for more details.
2626

2727
#### Usage of `embed.FS` as migration provider

migrations/runner.go

+8-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package migrations
33
import (
44
"fmt"
55
database "github.com/KowalskiPiotr98/gotabase"
6+
"strings"
67
)
78

89
var (
@@ -15,12 +16,18 @@ var (
1516
currentMigration)
1617
}
1718
LatestMigrationSelectorSql = "select id from migrations order by id desc limit 1"
19+
IsInitialMigrationError = func(err error) bool {
20+
return strings.HasPrefix(err.Error(), "pq: relation") && strings.HasSuffix(err.Error(), "does not exist")
21+
}
1822
)
1923

2024
func Migrate(connector database.Connector, fileProvider MigrationFileProvider) error {
2125
latestApplied, err := getLatestAppliedMigration(connector)
2226
if err != nil {
23-
return err
27+
if !IsInitialMigrationError(err) {
28+
return err
29+
}
30+
latestApplied = -1
2431
}
2532

2633
latestAvailable, err := getLatestAvailableMigration(fileProvider)

0 commit comments

Comments
 (0)