Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

feat: bb stub for interacting with Bytebase API (#11652)

Tianzhou (天舟)f899aaf68c04
diff --git a/backend/bin/bb/README.md b/backend/bin/bb/README.md
index 7ad34f0be7..f9add012af 100644
--- a/backend/bin/bb/README.md
+++ b/backend/bin/bb/README.md
@@ -1,10 +1,14 @@
-# bb - the Bytebase CLI
+# bb
-## Supported database engines
+The CLI interacting with https://api.bytebase.com
-- MySQL
-- PostgreSQL
+## Usage
-## Supported command
+```shell
+bb version
+```
-- bb dump - similar to mysqldump (MySQL), pg_dump (PostgreSQL)
+```shell
+# List all projects
+bb projects list --url=https://bytebase.example.com --token=xxxx
+```
diff --git a/backend/bin/bb/cmd/dump.go b/backend/bin/bb/cmd/dump.go
deleted file mode 100644
index 2f80216e72..0000000000
--- a/backend/bin/bb/cmd/dump.go
+++ /dev/null
@@ -1,62 +0,0 @@
-// Package cmd is the command surface of Bytebase bb tool provided by bytebase.com.
-package cmd
-
-import (
- "context"
- "io"
- "os"
-
- "github.com/pkg/errors"
- "github.com/spf13/cobra"
- "github.com/xo/dburl"
-)
-
-func newDumpCmd() *cobra.Command {
- var (
- dsn string
- file string
-
- // Dump options.
- schemaOnly bool
- )
- dumpCmd := &cobra.Command{
- Use: "dump",
- Short: "Exports schema and data of a database.",
- RunE: func(cmd *cobra.Command, _ []string) error {
- u, err := dburl.Parse(dsn)
- if err != nil {
- return errors.Wrap(err, "failed to parse dsn, got error")
- }
- out := cmd.OutOrStdout()
- if file != "" {
- f, err := os.Create(file)
- if err != nil {
- return errors.Wrapf(err, "failed to create dump file %s", file)
- }
- defer f.Close()
- out = f
- }
- return dumpDatabase(context.Background(), u, out, schemaOnly)
- },
- }
-
- dumpCmd.Flags().StringVar(&dsn, "dsn", "", dsnUsage)
- dumpCmd.Flags().StringVar(&file, "file", "", "File to store the dump. Output to stdout if unspecified")
- dumpCmd.Flags().BoolVar(&schemaOnly, "schema-only", false, "Schema only dump.")
- return dumpCmd
-}
-
-// dumpDatabase exports the schema of a database instance.
-// When file isn't specified, the schema will be exported to stdout.
-func dumpDatabase(ctx context.Context, u *dburl.URL, out io.Writer, schemaOnly bool) error {
- db, err := open(ctx, u)
- if err != nil {
- return err
- }
- defer db.Close(ctx)
-
- if _, err := db.Dump(ctx, out, schemaOnly); err != nil {
- return errors.Wrap(err, "failed to create dump")
- }
- return nil
-}
diff --git a/backend/bin/bb/cmd/migrate.go b/backend/bin/bb/cmd/migrate.go
deleted file mode 100644
index 77605cb2a1..0000000000
--- a/backend/bin/bb/cmd/migrate.go
+++ /dev/null
@@ -1,79 +0,0 @@
-package cmd
-
-import (
- "bytes"
- "context"
- "io"
- "os"
- "strings"
-
- "github.com/pkg/errors"
- "github.com/spf13/cobra"
- "github.com/xo/dburl"
-
- "github.com/bytebase/bytebase/backend/plugin/db"
-)
-
-func newMigrateCmd() *cobra.Command {
- var (
- dsn string
- fileList []string
- commandList []string
- description string
- issueID string
- )
- migrateCmd := &cobra.Command{
- Use: "migrate",
- Short: "Migrate the database schema.",
- RunE: func(_ *cobra.Command, _ []string) error {
- u, err := dburl.Parse(dsn)
- if err != nil {
- return errors.Wrap(err, "failed to parse dsn")
- }
-
- var sqlReaders []io.Reader
-
- // TODO(qsliu): support file and command combined as the passed order.
- for _, file := range fileList {
- f, err := os.Open(file)
- if err != nil {
- return err
- }
- //nolint:revive
- // f.Close() is intended to be deferred to the end of the function.
- defer f.Close()
- sqlReaders = append(sqlReaders, f)
- }
-
- for _, command := range commandList {
- sqlReaders = append(sqlReaders, strings.NewReader(command))
- }
-
- sqlReader := io.MultiReader(sqlReaders...)
- return migrateDatabase(context.Background(), u, sqlReader)
- }}
-
- migrateCmd.Flags().StringVar(&dsn, "dsn", "", dsnUsage)
- migrateCmd.Flags().StringSliceVarP(&fileList, "file", "f", []string{}, "SQL file to execute.")
- migrateCmd.Flags().StringSliceVarP(&commandList, "command", "c", []string{}, "SQL command to execute.")
- migrateCmd.Flags().StringVar(&description, "description", "", "Description of migration.")
- migrateCmd.Flags().StringVar(&issueID, "issue-id", "", "Issue ID of migration.")
- return migrateCmd
-}
-
-func migrateDatabase(ctx context.Context, u *dburl.URL, sqlReader io.Reader) error {
- driver, err := open(ctx, u)
- if err != nil {
- return err
- }
- defer driver.Close(ctx)
-
- var buf bytes.Buffer
- if _, err := io.Copy(&buf, sqlReader); err != nil {
- return errors.Wrap(err, "failed to read sql file")
- }
- if _, err := driver.Execute(ctx, buf.String(), db.ExecuteOptions{}); err != nil {
- return errors.Wrap(err, "failed to migrate database")
- }
- return nil
-}
diff --git a/backend/bin/bb/cmd/projects/list.go b/backend/bin/bb/cmd/projects/list.go
new file mode 100644
index 0000000000..5948afbb59
--- /dev/null
+++ b/backend/bin/bb/cmd/projects/list.go
@@ -0,0 +1,24 @@
+package projects
+
+import (
+ "fmt"
+
+ "github.com/spf13/cobra"
+
+ "github.com/bytebase/bytebase/backend/bin/bb/util"
+)
+
+// ListCmd encapsulates the command for listing backups for a branch.
+func listCmd(s *util.Setting) *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "list",
+ Short: "List all projects",
+ Aliases: []string{"ls"},
+ RunE: func(_ *cobra.Command, _ []string) error {
+ fmt.Printf("All projects: token: %s url: %s\n", s.Config.Token, s.Config.URL)
+ return nil
+ },
+ }
+
+ return cmd
+}
diff --git a/backend/bin/bb/cmd/projects/projects.go b/backend/bin/bb/cmd/projects/projects.go
new file mode 100644
index 0000000000..8d1f2f901a
--- /dev/null
+++ b/backend/bin/bb/cmd/projects/projects.go
@@ -0,0 +1,17 @@
+package projects
+
+import (
+ "github.com/spf13/cobra"
+
+ "github.com/bytebase/bytebase/backend/bin/bb/util"
+)
+
+func Cmd(s *util.Setting) *cobra.Command {
+ cmd := &cobra.Command{
+ Use: "projects <command>",
+ Short: "List projects",
+ }
+
+ cmd.AddCommand(listCmd(s))
+ return cmd
+}
diff --git a/backend/bin/bb/cmd/restore.go b/backend/bin/bb/cmd/restore.go
deleted file mode 100644
index c3564f7d22..0000000000
--- a/backend/bin/bb/cmd/restore.go
+++ /dev/null
@@ -1,56 +0,0 @@
-// Package cmd is the command surface of Bytebase bb tool provided by bytebase.com.
-package cmd
-
-import (
- "context"
- "os"
-
- "github.com/pkg/errors"
- "github.com/spf13/cobra"
- "github.com/xo/dburl"
-)
-
-func newRestoreCmd() *cobra.Command {
- var (
- dsn string
- file string
- )
- restoreCmd := &cobra.Command{
- Use: "restore",
- Short: "Restores schema and data of a database.",
- RunE: func(_ *cobra.Command, _ []string) error {
- u, err := dburl.Parse(dsn)
- if err != nil {
- return errors.Wrap(err, "failed to parse dsn")
- }
- return restoreDatabase(context.Background(), u, file)
- },
- }
- restoreCmd.Flags().StringVar(&dsn, "dsn", "", dsnUsage)
- restoreCmd.Flags().StringVar(&file, "file", "", "File to store the dump.")
- if err := restoreCmd.MarkFlagRequired("file"); err != nil {
- panic(err)
- }
-
- return restoreCmd
-}
-
-// restoreDatabase restores the schema of a database instance.
-func restoreDatabase(ctx context.Context, u *dburl.URL, file string) error {
- f, err := os.Open(file)
- if err != nil {
- return errors.Wrapf(err, "failed to open file %q", file)
- }
- defer f.Close()
-
- db, err := open(ctx, u)
- if err != nil {
- return err
- }
- defer db.Close(ctx)
-
- if err := db.Restore(ctx, f); err != nil {
- return errors.Wrapf(err, "failed to restore from backup file %q", file)
- }
- return nil
-}
diff --git a/backend/bin/bb/cmd/root.go b/backend/bin/bb/cmd/root.go
index e2ed623aa4..7f83adcadc 100644
--- a/backend/bin/bb/cmd/root.go
+++ b/backend/bin/bb/cmd/root.go
@@ -2,25 +2,51 @@
package cmd
import (
+ "context"
+
"github.com/spf13/cobra"
+
+ "github.com/bytebase/bytebase/backend/bin/bb/config"
+
+ "github.com/bytebase/bytebase/backend/bin/bb/cmd/projects"
+ "github.com/bytebase/bytebase/backend/bin/bb/cmd/version"
+ "github.com/bytebase/bytebase/backend/bin/bb/util"
)
-// NewRootCmd creates the root command.
-func NewRootCmd() *cobra.Command {
+func runCmd(ctx context.Context) error {
rootCmd := &cobra.Command{
Use: "bb",
- Short: "A database management tool provided by bytebase.com",
+ Short: "CLI for Bytebase",
+ Long: "bb is the CLI interacting with https://api.bytebase.com.",
RunE: func(cmd *cobra.Command, _ []string) error {
return cmd.Usage()
},
}
- rootCmd.AddCommand(newDumpCmd(), newRestoreCmd(), newVersionCmd(), newMigrateCmd())
+ cfg, err := config.New()
+ if err != nil {
+ return err
+ }
+
+ rootCmd.PersistentFlags().StringVar(&cfg.URL,
+ "url", "", "The URL for the Bytebase instance.")
+ rootCmd.PersistentFlags().StringVar(&cfg.Token,
+ "token", "", "The API token to interact with the Bytebase API.")
- return rootCmd
+ s := &util.Setting{
+ Config: cfg,
+ }
+
+ rootCmd.AddCommand(version.Cmd(), projects.Cmd(s))
+
+ return rootCmd.ExecuteContext(ctx)
}
// Execute is the execute command for root command.
-func Execute() (err error) {
- return NewRootCmd().Execute()
+func Execute(ctx context.Context) int {
+ err := runCmd(ctx)
+ if err == nil {
+ return 0
+ }
+ return 1
}
diff --git a/backend/bin/bb/cmd/utils.go b/backend/bin/bb/cmd/utils.go
deleted file mode 100644
index 3b0411aa02..0000000000
--- a/backend/bin/bb/cmd/utils.go
+++ /dev/null
@@ -1,76 +0,0 @@
-package cmd
-
-import (
- "context"
- "os"
-
- "github.com/pkg/errors"
- "github.com/xo/dburl"
-
- "github.com/bytebase/bytebase/backend/plugin/db"
- "github.com/bytebase/bytebase/backend/resources/mysqlutil"
- "github.com/bytebase/bytebase/backend/resources/postgres"
-
- storepb "github.com/bytebase/bytebase/proto/generated-go/store"
- // install mysql driver.
- _ "github.com/bytebase/bytebase/backend/plugin/db/mysql"
- // register pg driver.
- _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
- // install pg driver.
-)
-
-func getDatabase(u *dburl.URL) string {
- if u.Path == "" {
- return ""
- }
- return u.Path[1:]
-}
-
-func open(ctx context.Context, u *dburl.URL) (db.Driver, error) {
- var dbType storepb.Engine
- var dbBinDir string
- resourceDir := os.TempDir()
- switch u.Driver {
- case "mysql":
- dbType = storepb.Engine_MYSQL
- dir, err := mysqlutil.Install(resourceDir)
- if err != nil {
- return nil, errors.Wrapf(err, "cannot install mysqlutil in directory %q", resourceDir)
- }
- dbBinDir = dir
- case "postgres":
- dbType = storepb.Engine_POSTGRES
- dir, err := postgres.Install(resourceDir)
- if err != nil {
- return nil, errors.Wrapf(err, "cannot install postgres in directory %q", resourceDir)
- }
- dbBinDir = dir
- default:
- return nil, errors.Errorf("database type %q not supported; supported types: mysql, pg", u.Driver)
- }
- passwd, _ := u.User.Password()
- driver, err := db.Open(
- ctx,
- dbType,
- db.DriverConfig{
- DbBinDir: dbBinDir,
- },
- db.ConnectionConfig{
- Host: u.Hostname(),
- Port: u.Port(),
- Username: u.User.Username(),
- Password: passwd,
- Database: getDatabase(u),
- TLSConfig: db.TLSConfig{
- SslCA: u.Query().Get("ssl-ca"),
- SslCert: u.Query().Get("ssl-cert"),
- SslKey: u.Query().Get("ssl-key"),
- },
- },
- )
- if err != nil {
- return nil, errors.Wrap(err, "failed to open database")
- }
-
- return driver, nil
-}
diff --git a/backend/bin/bb/cmd/var.go b/backend/bin/bb/cmd/var.go
deleted file mode 100644
index 8df2ceda69..0000000000
--- a/backend/bin/bb/cmd/var.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// Package cmd is the command surface of Bytebase bb tool provided by bytebase.com.
-package cmd
-
-const dsnUsage = `Database connection string.
-
-DSN format:
- DRIVER://USERNAME[:PASSWORD]@HOST[:PORT]/[DATABASE][?PARAM=VALUE&...&PARAM=VALUE]
-
-Drivers:
- mysql
- postgres or postgresql
-
-Examples:
- mysql://root@localhost:3306/
- mysql://user:pass@localhost:3306/dbname
- postgres://$(whoami)@localhost:5432/postgres
- postgresql://$(whoami)@localhost:5432/postgres
- postgresql://user:pass@localhost:5432/dbname?ssl-key=a&ssl-ca=b&ssl-cert=c
-`
diff --git a/backend/bin/bb/cmd/version.go b/backend/bin/bb/cmd/version/version.go
similarity index 53%
rename from backend/bin/bb/cmd/version.go
rename to backend/bin/bb/cmd/version/version.go
index e25416ea21..58aaad6a31 100644
--- a/backend/bin/bb/cmd/version.go
+++ b/backend/bin/bb/cmd/version/version.go
@@ -1,4 +1,4 @@
-package cmd
+package version
import (
"fmt"
@@ -13,16 +13,12 @@ var gitcommit = "unknown"
var buildtime = "unknown"
var builduser = "unknown"
-func newVersionCmd() *cobra.Command {
+func Cmd() *cobra.Command {
versionCmd := &cobra.Command{
Use: "version",
- Short: "Print the version of bb",
+ Short: "Show bb version",
Run: func(_ *cobra.Command, _ []string) {
- fmt.Printf("bb version: %s\n", version)
- fmt.Printf("Golang version: %s\n", goversion)
- fmt.Printf("Git commit hash: %s\n", gitcommit)
- fmt.Printf("Built on: %s\n", buildtime)
- fmt.Printf("Built by: %s\n", builduser)
+ fmt.Printf("bb version %s (Golang version: %s build on: %s by: %s commit: %s)\n", version, goversion, buildtime, builduser, gitcommit)
},
}
return versionCmd
diff --git a/backend/bin/bb/config/config.go b/backend/bin/bb/config/config.go
new file mode 100644
index 0000000000..dc3252dcf4
--- /dev/null
+++ b/backend/bin/bb/config/config.go
@@ -0,0 +1,13 @@
+package config
+
+type Config struct {
+ URL string
+ Token string
+}
+
+func New() (*Config, error) {
+ return &Config{
+ URL: "",
+ Token: "",
+ }, nil
+}
diff --git a/backend/bin/bb/main.go b/backend/bin/bb/main.go
index 7d8445274f..3fa77445e4 100644
--- a/backend/bin/bb/main.go
+++ b/backend/bin/bb/main.go
@@ -2,18 +2,20 @@
package main
import (
+ "context"
"os"
+ "os/signal"
"github.com/bytebase/bytebase/backend/bin/bb/cmd"
-
- // Register mysql driver.
- _ "github.com/bytebase/bytebase/backend/plugin/db/mysql"
- // Register postgres driver.
- _ "github.com/bytebase/bytebase/backend/plugin/db/pg"
)
func main() {
- if err := cmd.Execute(); err != nil {
- os.Exit(1)
- }
+ os.Exit(realMain())
+}
+
+func realMain() int {
+ ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
+ defer cancel()
+
+ return cmd.Execute(ctx)
}
diff --git a/backend/bin/bb/util/setting.go b/backend/bin/bb/util/setting.go
new file mode 100644
index 0000000000..070f372636
--- /dev/null
+++ b/backend/bin/bb/util/setting.go
@@ -0,0 +1,10 @@
+package util
+
+import (
+ "github.com/bytebase/bytebase/backend/bin/bb/config"
+)
+
+// Setting is passed to each command. This eases swapping implementation.
+type Setting struct {
+ Config *config.Config
+}
diff --git a/go.mod b/go.mod
index 64d0af4814..57cc6926fa 100644
--- a/go.mod
+++ b/go.mod
@@ -74,7 +74,6 @@ require (
github.com/tmc/grpc-websocket-proxy v0.0.0-20220101234140-673ab2c3ae75
github.com/vjeantet/ldapserver v1.0.1
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8
- github.com/xo/dburl v0.22.0
github.com/xuri/excelize/v2 v2.8.1
go.mongodb.org/mongo-driver v1.14.0
go.uber.org/multierr v1.11.0
diff --git a/go.sum b/go.sum
index eca234993a..2d5423e1cf 100644
--- a/go.sum
+++ b/go.sum
@@ -1133,8 +1133,6 @@ github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQ
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo=
github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
-github.com/xo/dburl v0.22.0 h1:sO5WLm2ywMzyiLxEcLBlw5AyKvdR5hirq9U7s3fCoeM=
-github.com/xo/dburl v0.22.0/go.mod h1:B7/G9FGungw6ighV8xJNwWYQPMfn3gsi2sn5SE8Bzco=
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c h1:3lbZUMbMiGUW/LMkfsEABsc5zNT9+b1CvsJx47JzJ8g=
github.com/xtgo/uuid v0.0.0-20140804021211-a0b114877d4c/go.mod h1:UrdRz5enIKZ63MEE3IF9l2/ebyx59GyGgPi+tICQdmM=