github.com/mahkhaled/pop@v4.13.1+incompatible/soda/cmd/reset.go (about)

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