Skip to content
Snippets Groups Projects
cmdMigrate.gotmpl 1.94 KiB
Newer Older
// Code generated by go-swagger/go-orusapi; DO NOT EDIT.
{{ if .Copyright -}}// {{ comment .Copyright -}}{{ end }}

Christophe de Vienne's avatar
Christophe de Vienne committed
{{- $noDB := not (not (index .Info.Extensions "x-go-orusapi-no-db") ) }}
package cmd

Christophe de Vienne's avatar
Christophe de Vienne committed
{{- if $noDB }}
// "info.x-go-orusapi-no-db" is 'true', no 'migrate' command
{{- else }}

import (
	"github.com/golang-migrate/migrate/v4"
	"github.com/rs/zerolog"
Florent Aide's avatar
Florent Aide committed
	orusapi "orus.io/orus-io/go-orusapi"
	"orus.io/orus-io/go-orusapi/database"

	"{{ joinFilePath .TargetImportPath "migration" }}"
)

// NewMigrateCmd instanciates a MigrateCmd
func NewMigrateCmd(dbOptions *database.Options, loggingOptions *orusapi.LoggingOptions) *MigrateCmd {
	return &MigrateCmd{
		db: dbOptions,
		log: loggingOptions,
	}
}

// MigrateCmd is the "migrate" command
type MigrateCmd struct{
	log *orusapi.LoggingOptions
	db *database.Options
}

// Execute does the actual migration
func (cmd *MigrateCmd) Execute([]string) error {
	cmd.log.SetMinLoggingLevel(zerolog.InfoLevel)
	log := cmd.log.Logger()
	m, err := database.NewMigrate(cmd.db.DSN, migration.Source)
	if err != nil {
		return fmt.Errorf("failed to init migration engine: %s", err)
	}
	defer func() {
		if sourceErr, databaseErr := m.Close(); sourceErr != nil || databaseErr != nil {
			if sourceErr != nil {
				log.Err(err).Msg("error closing Migrate source")
			}
			if databaseErr != nil {
				log.Err(err).Msg("error closing Migrate database")
			}
		}
	}()

	if err := m.Up(); err != nil {
		if err == migrate.ErrNoChange {
			log.Info().Msg("The database is already up-to-date")
		} else {
			return fmt.Errorf("failed to run migration: %s", err)
		}
	} else {
		log.Info().Msg("database successfully upgraded")
	}

	return nil
}

var Migrate = NewMigrateCmd(DatabaseOptions, LoggingOptions)

func init() {
	var migrateCmd = NewMigrateCmd(DatabaseOptions, LoggingOptions)

	_, err := parser.AddCommand("migrate", "Init/migrate the database schema", "", migrateCmd)
	if err != nil {
		Logger.Fatal().Msg(err.Error())
	}
}
Christophe de Vienne's avatar
Christophe de Vienne committed
{{- end }}