-
Notifications
You must be signed in to change notification settings - Fork 51
/
schema.go
88 lines (77 loc) · 2.54 KB
/
schema.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package branch
import (
"bufio"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/pkg/browser"
"github.com/planetscale/cli/internal/cmdutil"
"github.com/planetscale/cli/internal/printer"
"github.com/planetscale/planetscale-go/planetscale"
"github.com/spf13/cobra"
)
// SchemaCmd is the command for showing the schema of a branch.
func SchemaCmd(ch *cmdutil.Helper) *cobra.Command {
var flags struct {
web bool
keyspace string
}
cmd := &cobra.Command{
Use: "schema <database> <branch>",
Short: "Show the schema of a branch",
Args: cmdutil.RequiredArgs("database", "branch"),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
database, branch := args[0], args[1]
if flags.web {
ch.Printer.Println("🌐 Redirecting you to your branch schema in your web browser.")
return browser.OpenURL(fmt.Sprintf("%s/%s/%s/%s/schema", cmdutil.ApplicationURL, ch.Config.Organization, database, branch))
}
client, err := ch.Client()
if err != nil {
return err
}
schemas, err := client.DatabaseBranches.Schema(ctx, &planetscale.BranchSchemaRequest{
Organization: ch.Config.Organization,
Database: database,
Branch: branch,
Keyspace: flags.keyspace,
})
if err != nil {
switch cmdutil.ErrCode(err) {
case planetscale.ErrNotFound:
return fmt.Errorf("branch %s does not exist in database %s (organization: %s)",
printer.BoldBlue(branch), printer.BoldBlue(database), printer.BoldBlue(ch.Config.Organization))
default:
return cmdutil.HandleError(err)
}
}
if ch.Printer.Format() != printer.Human {
return ch.Printer.PrintResource(schemas)
}
// human readable output
for _, df := range schemas {
ch.Printer.Println("--", printer.BoldBlue(df.Name), "--")
scanner := bufio.NewScanner(strings.NewReader(strings.TrimSpace(df.Raw)))
for scanner.Scan() {
txt := scanner.Text()
if strings.HasPrefix(txt, "+") {
ch.Printer.Println(color.New(color.FgGreen).Add(color.Bold).Sprint(txt))
} else if strings.HasPrefix(txt, "-") {
ch.Printer.Println(color.New(color.FgRed).Add(color.Bold).Sprint(txt))
} else {
ch.Printer.Println(txt)
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("reading schema raw: %s", err)
}
}
return nil
},
}
cmd.PersistentFlags().BoolVar(&flags.web, "web", false, "Open in your web browser")
cmd.Flags().StringVar(&flags.keyspace, "keyspace", "", "The keyspace in the branch")
cmd.Flags().MarkHidden("keyspace")
return cmd
}