Skip to content

Commit

Permalink
Add JSON output support to pg-schema-diff plan.
Browse files Browse the repository at this point in the history
  • Loading branch information
tonycosentini committed Sep 18, 2024
1 parent bc41f09 commit 4b855ac
Showing 1 changed file with 45 additions and 2 deletions.
47 changes: 45 additions & 2 deletions cmd/pg-schema-diff/plan_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package main
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"regexp"
Expand All @@ -29,6 +31,31 @@ const (
lockTimeoutInsertStatementKey = "lock_timeout"
)

type outputFormat string

const (
outputFormatPretty outputFormat = "pretty"
outputFormatJson outputFormat = "json"
)

func (e *outputFormat) String() string {
return string(*e)
}

func (e *outputFormat) Set(v string) error {
switch v {
case "pretty", "json":
*e = outputFormat(v)
return nil
default:
return errors.New(`must be one of "pretty" or "json"`)
}
}

func (e *outputFormat) Type() string {
return "outputFormat"
}

func buildPlanCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "plan",
Expand Down Expand Up @@ -59,8 +86,13 @@ func buildPlanCmd() *cobra.Command {
fmt.Println("Schema matches expected. No plan generated")
return nil
}
fmt.Printf("\n%s\n", header("Generated plan"))
fmt.Println(planToPrettyS(plan))

if planFlags.outputFormat == "" || planFlags.outputFormat == outputFormatPretty {
fmt.Printf("\n%s\n", header("Generated plan"))
fmt.Println(planToPrettyS(plan))
} else if planFlags.outputFormat == outputFormatJson {
fmt.Println(planToJsonS(plan))
}
return nil
}

Expand Down Expand Up @@ -89,6 +121,7 @@ type (
statementTimeoutModifiers []string
lockTimeoutModifiers []string
insertStatements []string
outputFormat outputFormat
}

timeoutModifier struct {
Expand Down Expand Up @@ -139,6 +172,8 @@ func createPlanFlags(cmd *cobra.Command) *planFlags {
),
)

cmd.Flags().Var(&flags.outputFormat, "output-format", "Change the output format for what is printed. Defaults to pretty-printed human-readable output. (options: pretty, json)")

return flags
}

Expand Down Expand Up @@ -448,6 +483,14 @@ func planToPrettyS(plan diff.Plan) string {
return sb.String()
}

func planToJsonS(plan diff.Plan) string {
jsonData, err := json.MarshalIndent(plan, "", " ")
if err != nil {
panic(err)
}
return string(jsonData)
}

func statementToPrettyS(stmt diff.Statement) string {
sb := strings.Builder{}
sb.WriteString(fmt.Sprintf("%s;", stmt.DDL))
Expand Down

0 comments on commit 4b855ac

Please sign in to comment.