diff --git a/janitor/db.go b/janitor/db.go new file mode 100644 index 0000000..d20519c --- /dev/null +++ b/janitor/db.go @@ -0,0 +1,67 @@ +package janitor + +import ( + "fmt" + "runtime" + + "github.com/urfave/cli/v2" + "go.uber.org/zap" + + "github.com/ngerakines/tavern/config" +) + +var CopyDatabaseCommand = cli.Command{ + Name: "database:copy", + Usage: "Creates a copy of the database.", + Flags: []cli.Flag{ + &config.DatabaseFlag, + &config.EnvironmentFlag, + &cli.StringFlag{ + Name: "source", + Usage: "The name of the database being copied.", + Required: true, + }, + &cli.StringFlag{ + Name: "destination", + Usage: "The name of the new database.", + Required: true, + }, + &cli.BoolFlag{ + Name: "delete", + Usage: "Delete the destination first.", + Value: false, + }, + }, + Action: databaseCopyCommandAction, +} + +func databaseCopyCommandAction(cliCtx *cli.Context) error { + logger, err := config.Logger(cliCtx) + if err != nil { + return err + } + + logger.Info("Starting", + zap.String("command", cliCtx.Command.Name), + zap.String("GOOS", runtime.GOOS), + zap.String("env", cliCtx.String("environment"))) + + db, dbClose, err := config.DB(cliCtx, logger) + if err != nil { + return err + } + defer dbClose() + + source := cliCtx.String("source") + destination := cliCtx.String("destination") + + if cliCtx.Bool("delete") { + _, err = db.Exec(fmt.Sprintf(`DROP DATABASE %s`, destination)) + if err != nil { + return err + } + } + + _, err = db.Exec(fmt.Sprintf(`CREATE DATABASE %s WITH TEMPLATE %s`, destination, source)) + return err +} diff --git a/janitor/command.go b/janitor/skeleton.go similarity index 100% rename from janitor/command.go rename to janitor/skeleton.go diff --git a/main.go b/main.go index 3824ce0..814acf8 100644 --- a/main.go +++ b/main.go @@ -56,6 +56,7 @@ func main() { &json.DebugJSONLDCommand, &publisher.Command, &janitor.SkeletonCommand, + &janitor.CopyDatabaseCommand, } sort.Sort(cli.FlagsByName(app.Flags))