// apply migration
package main

import (
	"code.justin.tv/d8a/iceman/lib/dbconf"
	"code.justin.tv/d8a/iceman/lib/migrations"
	"code.justin.tv/d8a/iceman/lib/queries"
	"github.com/spf13/cobra"
)

var upCmd = &cobra.Command{
	Use:   "up",
	Short: "apply all unapplied migrations",
	Long:  "This will apply all migrations in your local directory that have not yet been applied.",
	RunE: func(cmd *cobra.Command, args []string) error {
		conf, err := dbconf.NewDBConf(path, env, schema, "migrations")
		if err != nil {
			return err
		}

		db, err := dbconf.OpenDBFromDBConf(conf)
		if err != nil {
			return err
		}
		defer queries.TryClose(db)

		names, err := migrations.RunMigrations(db, conf.DriverQueries, &migrations.DirectoryMigrationSource{MigrationsDirectory: conf.Dir}, true)
		for _, name := range names {
			green.Printf("Successfully applied: %v\n", name)
		}

		if err != nil {
			return err
		}
		return nil
	},
}

func init() {
	RootCmd.AddCommand(upCmd)
}
