Skip to content

Commit

Permalink
feat(migrate.go): initMigrateMariadb added
Browse files Browse the repository at this point in the history
  • Loading branch information
Adam Bezecny committed Oct 30, 2023
1 parent bc1fb27 commit 0eefa96
Showing 1 changed file with 43 additions and 1 deletion.
44 changes: 43 additions & 1 deletion test/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import (
_ "github.com/golang-migrate/migrate/v4/database/postgres"
"github.com/golang-migrate/migrate/v4/source/iofs"
"github.com/rs/zerolog/log"
"strings"
)

func InitMigratePostgresql(conn string, migrations embed.FS, migrationTable *string) {
// InitMigratePostgres is used to apply db migration scripts from embedded file system to given postgres database
func InitMigratePostgres(conn string, migrations embed.FS, migrationTable *string) {
source, err := iofs.New(migrations, "migrations")
if err != nil {
log.Fatal().Err(err).Msg("cannot open migrations")
Expand Down Expand Up @@ -41,3 +43,43 @@ func InitMigratePostgresql(conn string, migrations embed.FS, migrationTable *str
log.Fatal().Err(err).Msg("cannot migrate")
}
}

// InitMigrateMariadb is used to apply db migration scripts from embedded file system to given mariadb database
func InitMigrateMariadb(conn string, migrations embed.FS, migrationTable *string) {
source, err := iofs.New(migrations, "migrations")
if err != nil {
log.Fatal().Err(err).Msg("cannot open migrations")
}

var uri string
if migrationTable != nil {
// see https://github.com/golang-migrate/migrate/blob/master/database/mysql/README.md
uri = fmt.Sprintf("mysql://%s?x-migrations-table=%s", conn, *migrationTable)
} else {
uri = fmt.Sprintf("mysql://%s", conn)
}

// mysql://user:test@tcp(localhost:55250)/hrnogomet?parseTime=true
// ->
// mysql://user:test@tcp(localhost:55250)/hrnogomet
// we are using ?parseTime=true in conn string so that mysql parses timestamps during sqlx scans
// but somehow this does not go well with migrate so let's remove it at this particular place
uri = strings.Replace(uri, "?parseTime=true", "", 1)

m, err := migrate.NewWithSourceInstance("iofs", source, uri)
if err != nil {
log.Fatal().Err(err).Msg("cannot open source migrations")
}

defer func(m *migrate.Migrate) {
err, _ := m.Close()
if err != nil {
log.Fatal().Err(err).Msg("cannot close migration")
}
}(m)

err = m.Up()
if err != nil && !errors.Is(err, migrate.ErrNoChange) {
log.Fatal().Err(err).Msg("cannot migrate")
}
}

0 comments on commit 0eefa96

Please sign in to comment.