github.com/wawandco/oxplugins@v0.7.11/tools/db/db.go (about) 1 // db packs all db operations under this top level command. 2 package db 3 4 import ( 5 "context" 6 "errors" 7 "fmt" 8 9 pop4 "github.com/gobuffalo/pop" 10 pop5 "github.com/gobuffalo/pop/v5" 11 "github.com/wawandco/oxplugins/plugins" 12 ) 13 14 var _ plugins.Command = (*Command)(nil) 15 var _ plugins.HelpTexter = (*Command)(nil) 16 var _ plugins.PluginReceiver = (*Command)(nil) 17 var _ plugins.Subcommander = (*Command)(nil) 18 19 var ErrConnectionNotFound = errors.New("connection not found") 20 21 type Command struct { 22 subcommands []plugins.Command 23 } 24 25 func (c Command) Name() string { 26 return "db" 27 } 28 29 func (c Command) ParentName() string { 30 return "" 31 } 32 33 func (c Command) HelpText() string { 34 return "database operation commands" 35 } 36 37 func (c *Command) Run(ctx context.Context, root string, args []string) error { 38 if len(args) < 2 { 39 fmt.Println("no subcommand specified, please use `db [subcommand]` to run one of the db subcommands.") 40 return nil 41 } 42 43 name := args[1] 44 var subcommand plugins.Command 45 for _, sub := range c.subcommands { 46 if sub.Name() != name { 47 continue 48 } 49 50 subcommand = sub 51 break 52 } 53 54 if subcommand == nil { 55 return fmt.Errorf("subcommand `%v` not found", name) 56 } 57 58 return subcommand.Run(ctx, root, args) 59 } 60 61 func (c *Command) Receive(pls []plugins.Plugin) { 62 for _, plugin := range pls { 63 ptool, ok := plugin.(plugins.Command) 64 if !ok || ptool.ParentName() != c.Name() { 65 continue 66 } 67 68 c.subcommands = append(c.subcommands, ptool) 69 } 70 } 71 72 func (c *Command) Subcommands() []plugins.Command { 73 return c.subcommands 74 } 75 76 func Plugins(conns interface{}) []plugins.Plugin { 77 var result []plugins.Plugin 78 providers := map[string]URLProvider{} 79 switch v := conns.(type) { 80 case map[string]*pop4.Connection: 81 for k, conn := range v { 82 providers[k] = conn 83 } 84 case map[string]*pop5.Connection: 85 for k, conn := range v { 86 providers[k] = conn 87 } 88 default: 89 fmt.Println("DB plugin ONLY receives pop v4 and v5 connections") 90 return result 91 } 92 93 result = append(result, &Command{}) 94 result = append(result, &CreateCommand{connections: providers}) 95 result = append(result, &DropCommand{connections: providers}) 96 result = append(result, &ResetCommand{connections: providers}) 97 98 return result 99 }