Adding Command helper to easily add cli migrations to existing projects
1 files changed, 60 insertions(+), 0 deletions(-)

A => command.go
A => command.go +60 -0
@@ 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.
+//   <migration id> - 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)
+}