github.com/wawandco/oxplugins@v0.7.11/tools/db/reset.go (about)

     1  package db
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  
     8  	pop4 "github.com/gobuffalo/pop"
     9  	pop5 "github.com/gobuffalo/pop/v5"
    10  	"github.com/spf13/pflag"
    11  )
    12  
    13  type ResetCommand struct {
    14  	connections    map[string]URLProvider
    15  	connectionName string
    16  
    17  	flags *pflag.FlagSet
    18  }
    19  
    20  func (d ResetCommand) Name() string {
    21  	return "reset"
    22  }
    23  
    24  func (d ResetCommand) HelpText() string {
    25  	return "resets database specified in GO_ENV or --conn"
    26  }
    27  
    28  func (d ResetCommand) ParentName() string {
    29  	return "db"
    30  }
    31  
    32  func (d *ResetCommand) Run(ctx context.Context, root string, args []string) error {
    33  	conn := d.connections[d.connectionName]
    34  	if conn == nil {
    35  		return ErrConnectionNotFound
    36  	}
    37  
    38  	var resetter Resetter
    39  	if c, ok := conn.(*pop4.Connection); ok {
    40  		resetter = c.Dialect
    41  	}
    42  
    43  	if c, ok := conn.(*pop5.Connection); ok {
    44  		resetter = c.Dialect
    45  	}
    46  
    47  	if resetter == nil {
    48  		return errors.New("provided connection is not a Resetter")
    49  	}
    50  
    51  	err := resetter.DropDB()
    52  	if err != nil {
    53  		fmt.Printf("[warning] could not drop database: %v\n", err)
    54  	}
    55  
    56  	return resetter.CreateDB()
    57  }
    58  
    59  // RunBeforeTests will be invoked to reset the test database before
    60  // tests run.
    61  func (d *ResetCommand) RunBeforeTest(ctx context.Context, root string, args []string) error {
    62  	conn := d.connections["test"]
    63  	if conn == nil {
    64  		return ErrConnectionNotFound
    65  	}
    66  
    67  	var resetter Resetter
    68  	if c, ok := conn.(*pop4.Connection); ok {
    69  		resetter = c.Dialect
    70  	}
    71  
    72  	if c, ok := conn.(*pop5.Connection); ok {
    73  		resetter = c.Dialect
    74  	}
    75  
    76  	if resetter == nil {
    77  		return errors.New("provided connection is not a Resetter")
    78  	}
    79  
    80  	err := resetter.DropDB()
    81  	if err != nil {
    82  		fmt.Printf("[warning] could not drop database: %v\n", err)
    83  	}
    84  
    85  	return resetter.CreateDB()
    86  }
    87  
    88  func (d *ResetCommand) ParseFlags(args []string) {
    89  	d.flags = pflag.NewFlagSet(d.Name(), pflag.ContinueOnError)
    90  	d.flags.StringVarP(&d.connectionName, "conn", "", "development", "the name of the connection to use")
    91  	d.flags.Parse(args) //nolint:errcheck,we don't care hence the flag
    92  }
    93  
    94  func (d *ResetCommand) Flags() *pflag.FlagSet {
    95  	return d.flags
    96  }