github.com/duskeagle/pop@v4.10.1-0.20190417200916-92f2b794aab5+incompatible/soda/cmd/reset.go (about)

     1  package cmd
     2  
     3  import (
     4  	"os"
     5  
     6  	"github.com/gobuffalo/pop"
     7  	"github.com/pkg/errors"
     8  	"github.com/spf13/cobra"
     9  )
    10  
    11  var resetOptions = struct {
    12  	all   bool
    13  	input string
    14  }{}
    15  
    16  var resetCmd = &cobra.Command{
    17  	Use:   "reset",
    18  	Short: "Drop, then recreate databases",
    19  	RunE: func(cmd *cobra.Command, args []string) error {
    20  		var schema *os.File
    21  		useMigrations := false
    22  
    23  		if _, err := os.Stat(resetOptions.input); err == nil {
    24  			schema, err = os.Open(resetOptions.input)
    25  			if err != nil {
    26  				return err
    27  			}
    28  			defer schema.Close()
    29  		} else {
    30  			// Fallback to migrations
    31  			useMigrations = true
    32  		}
    33  
    34  		if all {
    35  			for _, conn := range pop.Connections {
    36  				if err := doReset(conn, schema, useMigrations); err != nil {
    37  					return err
    38  				}
    39  			}
    40  		} else {
    41  			c := getConn()
    42  			if err := doReset(c, schema, useMigrations); err != nil {
    43  				return err
    44  			}
    45  		}
    46  
    47  		return nil
    48  	},
    49  }
    50  
    51  func init() {
    52  	resetCmd.Flags().BoolVarP(&resetOptions.all, "all", "a", false, "Drops and recreate all of the databases in the database.yml")
    53  	resetCmd.Flags().StringVarP(&resetOptions.input, "input", "i", "schema.sql", "The path to the schema file you want to load")
    54  	RootCmd.AddCommand(resetCmd)
    55  }
    56  
    57  func doReset(c *pop.Connection, f *os.File, useMigrations bool) error {
    58  	if err := pop.DropDB(c); err != nil {
    59  		return err
    60  	}
    61  	if err := pop.CreateDB(c); err != nil {
    62  		return err
    63  	}
    64  	mig, err := pop.NewFileMigrator(migrationPath, getConn())
    65  	if err != nil {
    66  		return errors.WithStack(err)
    67  	}
    68  	if useMigrations {
    69  		// Apply the migrations directly
    70  		return mig.Up()
    71  	}
    72  	// Otherwise, use schema instead
    73  	if err := c.Dialect.LoadSchema(f); err != nil {
    74  		return err
    75  	}
    76  	// Then load migrations entries, without applying them
    77  	return mig.UpLogOnly()
    78  }