github.com/wawandco/ox@v0.13.6-0.20230809142027-913b3d837f2a/plugins/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 "os" 9 10 "github.com/gobuffalo/pop/v6" 11 "github.com/wawandco/ox/internal/info" 12 "github.com/wawandco/ox/internal/log" 13 "github.com/wawandco/ox/plugins/core" 14 ) 15 16 var _ core.Command = (*Command)(nil) 17 var _ core.HelpTexter = (*Command)(nil) 18 var _ core.PluginReceiver = (*Command)(nil) 19 var _ core.Subcommander = (*Command)(nil) 20 21 var ErrConnectionNotFound = errors.New("connection not found") 22 23 type Command struct { 24 subcommands []core.Command 25 } 26 27 func (c Command) Name() string { 28 return "database" 29 } 30 31 func (c Command) Alias() string { 32 return "db" 33 } 34 35 func (c Command) ParentName() string { 36 return "" 37 } 38 39 func (c Command) HelpText() string { 40 return "database operation commands" 41 } 42 43 func (c *Command) Run(ctx context.Context, root string, args []string) error { 44 if len(args) < 2 { 45 log.Error("no subcommand specified, please use `db [subcommand]` to run one of the db subcommands.") 46 return nil 47 } 48 49 if len(pop.Connections) == 0 { 50 err := pop.LoadConfigFile() 51 if err != nil { 52 log.Errorf("error on db.Run: %v", err.Error()) 53 } 54 } 55 56 name := args[1] 57 var subcommand core.Command 58 for _, sub := range c.subcommands { 59 if sub.Name() != name { 60 continue 61 } 62 63 subcommand = sub 64 break 65 } 66 67 if subcommand == nil { 68 return fmt.Errorf("subcommand `%v` not found", name) 69 } 70 71 return subcommand.Run(ctx, root, args) 72 } 73 74 func (c *Command) Receive(pls []core.Plugin) { 75 for _, plugin := range pls { 76 ptool, ok := plugin.(core.Command) 77 if !ok || ptool.ParentName() != c.Name() { 78 continue 79 } 80 81 c.subcommands = append(c.subcommands, ptool) 82 } 83 } 84 85 func (c *Command) Subcommands() []core.Command { 86 return c.subcommands 87 } 88 89 func (c *Command) FindRoot() string { 90 root := info.RootFolder() 91 if root != "" { 92 return root 93 } 94 95 root, err := os.Getwd() 96 if err != nil { 97 return "" 98 } 99 100 return root 101 } 102 103 func Plugins() []core.Plugin { 104 var result []core.Plugin 105 106 result = append(result, &Command{}) 107 result = append(result, &CreateCommand{}) 108 result = append(result, &DropCommand{}) 109 result = append(result, &ResetCommand{}) 110 111 return result 112 }