# HG changeset patch # User Peter Sanchez # Date 1645288358 21600 # Sat Feb 19 10:32:38 2022 -0600 # Node ID c6b69ef9bdd6e43c4ee35ceebb2d73ec879d1816 # Parent 7d8a4c32f53ea12170c61cd8ccc405f21eb2356f Adding Command helper to easily add cli migrations to existing projects diff --git a/command.go b/command.go new file mode 100644 --- /dev/null +++ b/command.go @@ -0,0 +1,60 @@ +package migrate + +import ( + "context" + "database/sql" + "flag" + "fmt" + "os" +) + +// Command will run a very simple command line processor using +// `os.Args[2:]`. bindType should be set to one of the constants exported +// in this module. +// +// flag options are: +// -fake - this will "fake" migrations and just add entries to the migration table. +// -verbose - this will enable verbose output. +// +// positional arguments are +// up | down - Migrate up (forward) or down (rollback). If not given "up" is assumed. +// - If given, migrations will stop after this migration is processed. +func Command(db *sql.DB, migrations []Migration, bindType int) error { + var ( + verbose, fakeIt bool + direction, stopID string + ) + + mf := flag.NewFlagSet("migrate", flag.ContinueOnError) + mf.BoolVar(&verbose, "verbose", false, "verbose output") + mf.BoolVar(&fakeIt, "fake", false, "fake migrations") + mf.Usage = func() { + msg := fmt.Sprintf( + "usage: %s %s [options...] [up | down] [migration ID]\n", + os.Args[0], os.Args[1], + ) + fmt.Fprintf(flag.CommandLine.Output(), msg) + mf.PrintDefaults() + } + + mf.Parse(os.Args[2:]) + args := mf.Args() + + if len(args) > 0 { + direction = args[0] + if direction != "up" && direction != "down" { + return fmt.Errorf("Unknown migration direction: %s", direction) + } + } + + if len(args) > 1 { + stopID = args[1] + } + + ctx := context.Background() + engine := NewEngine(db, migrations, bindType, verbose) + if direction == "down" { + return engine.Rollback(ctx, stopID) + } + return engine.Migrate(ctx, stopID, fakeIt) +}