Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor(cli): get rid of global var (#850)
qsliu9d044b683687
diff --git a/bin/bb/cmd/dump.go b/bin/bb/cmd/dump.goindex 2293905dec..b62e392c94 100644--- a/bin/bb/cmd/dump.go+++ b/bin/bb/cmd/dump.go@@ -14,27 +14,25 @@ import ("github.com/spf13/cobra")-func init() {- dumpCmd.Flags().StringVar(&databaseType, "type", "mysql", "Database type. (mysql or pg).")- dumpCmd.Flags().StringVar(&username, "username", "", "Username to login database. (default mysql:root pg:postgres).")- dumpCmd.Flags().StringVar(&password, "password", "", "Password to login database.")- dumpCmd.Flags().StringVar(&hostname, "hostname", "", "Hostname of database.")- dumpCmd.Flags().StringVar(&port, "port", "", "Port of database. (default mysql:3306 pg:5432).")- dumpCmd.Flags().StringVar(&database, "database", "", "Database to connect and export.")- dumpCmd.Flags().StringVar(&file, "file", "", "File to store the dump. Output to stdout if unspecified")+func newDumpCmd() *cobra.Command {+ var (+ databaseType string+ username string+ password string+ hostname string+ port string+ database string+ file string- // tls flags for SSL connection.- dumpCmd.Flags().StringVar(&sslCA, "ssl-ca", "", "CA file in PEM format.")- dumpCmd.Flags().StringVar(&sslCert, "ssl-cert", "", "X509 cert in PEM format.")- dumpCmd.Flags().StringVar(&sslKey, "ssl-key", "", "X509 key in PEM format.")-- dumpCmd.Flags().BoolVar(&schemaOnly, "schema-only", false, "Schema only dump.")+ // SSL flags.+ sslCA string // server-ca.pem+ sslCert string // client-cert.pem+ sslKey string // client-key.pem- rootCmd.AddCommand(dumpCmd)-}--var (- dumpCmd = &cobra.Command{+ // Dump options.+ schemaOnly bool+ )+ dumpCmd := &cobra.Command{Use: "dump",Short: "Exports the schema of a database instance",RunE: func(cmd *cobra.Command, args []string) error {@@ -55,7 +53,23 @@ var (return dumpDatabase(context.Background(), databaseType, username, password, hostname, port, database, out, tlsCfg, schemaOnly)},}-)+ dumpCmd.Flags().StringVar(&databaseType, "type", "mysql", "Database type. (mysql or pg).")+ dumpCmd.Flags().StringVar(&username, "username", "", "Username to login database. (default mysql:root pg:postgres).")+ dumpCmd.Flags().StringVar(&password, "password", "", "Password to login database.")+ dumpCmd.Flags().StringVar(&hostname, "hostname", "", "Hostname of database.")+ dumpCmd.Flags().StringVar(&port, "port", "", "Port of database. (default mysql:3306 pg:5432).")+ dumpCmd.Flags().StringVar(&database, "database", "", "Database to connect and export.")+ dumpCmd.Flags().StringVar(&file, "file", "", "File to store the dump. Output to stdout if unspecified")++ // tls flags for SSL connection.+ dumpCmd.Flags().StringVar(&sslCA, "ssl-ca", "", "CA file in PEM format.")+ dumpCmd.Flags().StringVar(&sslCert, "ssl-cert", "", "X509 cert in PEM format.")+ dumpCmd.Flags().StringVar(&sslKey, "ssl-key", "", "X509 key in PEM format.")++ 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.@@ -93,7 +107,7 @@ func dumpDatabase(ctx context.Context, databaseType, username, password, hostnamdefer db.Close(ctx)if err := db.Dump(ctx, database, out, schemaOnly); err != nil {- return fmt.Errorf("failed to create dump %s, got error: %w", file, err)+ return fmt.Errorf("failed to create dump, got error: %w", err)}return nil}diff --git a/bin/bb/cmd/restore.go b/bin/bb/cmd/restore.goindex 534d226de1..39daa19783 100644--- a/bin/bb/cmd/restore.go+++ b/bin/bb/cmd/restore.go@@ -11,7 +11,33 @@ import ("github.com/spf13/cobra")-func init() {+func newRestoreCmd() *cobra.Command {+ var (+ databaseType string+ username string+ password string+ hostname string+ port string+ database string+ file string++ // SSL flags.+ sslCA string // server-ca.pem+ sslCert string // client-cert.pem+ sslKey string // client-key.pem+ )+ restoreCmd := &cobra.Command{+ Use: "restore",+ Short: "restores the schema of a database instance",+ RunE: func(cmd *cobra.Command, args []string) error {+ tlsCfg := db.TLSConfig{+ SslCA: sslCA,+ SslCert: sslCert,+ SslKey: sslKey,+ }+ return restoreDatabase(context.Background(), databaseType, username, password, hostname, port, database, file, tlsCfg)+ },+ }restoreCmd.Flags().StringVar(&databaseType, "type", "mysql", "Database type. (mysql, or pg).")restoreCmd.Flags().StringVar(&username, "username", "", "Username to login database. (default mysql:root pg:postgres).")restoreCmd.Flags().StringVar(&password, "password", "", "Password to login database.")@@ -31,24 +57,9 @@ func init() {restoreCmd.Flags().StringVar(&sslCert, "ssl-cert", "", "X509 cert in PEM format.")restoreCmd.Flags().StringVar(&sslKey, "ssl-key", "", "X509 key in PEM format.")- rootCmd.AddCommand(restoreCmd)+ return restoreCmd}-var (- restoreCmd = &cobra.Command{- Use: "restore",- Short: "restores the schema of a database instance",- RunE: func(cmd *cobra.Command, args []string) error {- tlsCfg := db.TLSConfig{- SslCA: sslCA,- SslCert: sslCert,- SslKey: sslKey,- }- return restoreDatabase(context.Background(), databaseType, username, password, hostname, port, database, file, tlsCfg)- },- }-)-// restoreDatabase restores the schema of a database instance.func restoreDatabase(ctx context.Context, databaseType, username, password, hostname, port, database, file string, tlsCfg db.TLSConfig) error {f, err := os.OpenFile(file, os.O_RDONLY, os.ModePerm)diff --git a/bin/bb/cmd/root.go b/bin/bb/cmd/root.goindex f4291fb12a..e8ae8681be 100644--- a/bin/bb/cmd/root.go+++ b/bin/bb/cmd/root.go@@ -8,12 +8,19 @@ import ("go.uber.org/zap")-var rootCmd = &cobra.Command{- Use: "bb",- Short: "A database management tool provided by bytebase.com",- RunE: func(cmd *cobra.Command, args []string) error {- return cmd.Usage()- },+// NewRootCmd creates the root command.+func NewRootCmd() *cobra.Command {+ rootCmd := &cobra.Command{+ Use: "bb",+ Short: "A database management tool provided by bytebase.com",+ RunE: func(cmd *cobra.Command, args []string) error {+ return cmd.Usage()+ },+ }++ rootCmd.AddCommand(newDumpCmd(), newRestoreCmd(), newVersionCmd())++ return rootCmd}// Execute is the execute command for root command.@@ -31,5 +38,5 @@ func Execute() error {}logger = myLogger- return rootCmd.Execute()+ return NewRootCmd().Execute()}diff --git a/bin/bb/cmd/root_test.go b/bin/bb/cmd/root_test.goindex 1a264ab2eb..177c392010 100644--- a/bin/bb/cmd/root_test.go+++ b/bin/bb/cmd/root_test.go@@ -2,6 +2,8 @@ package cmdimport ("bytes"+ "io"+ "os""strings""testing"@@ -36,7 +38,7 @@ type testTable struct {func tableTest(t *testing.T, tables []testTable) {t.Helper()for _, tc := range tables {- actual, err := execute(t, rootCmd, tc.args...)+ actual, err := execute(t, NewRootCmd(), tc.args...)if err != tc.expectedErr {t.Errorf(`"> bb %v"@@ -50,6 +52,16 @@ got unexpected error:got unexpected output:%s`, strings.Join(tc.args, " "), cmp.Diff(actual, tc.expected))++ f, err := os.CreateTemp("", "*")+ if err != nil {+ t.Log(err)+ }+ defer f.Close()+ if _, err := io.WriteString(f, actual); err != nil {+ t.Log(err)+ }+ t.Logf("Actual output written to %s", f.Name())}}}diff --git a/bin/bb/cmd/testdata/mysql_test_schema/2_blog.sql b/bin/bb/cmd/testdata/mysql_test_schema/2_blog.sqlindex b9b6b8ff31..659a380738 100644--- a/bin/bb/cmd/testdata/mysql_test_schema/2_blog.sql+++ b/bin/bb/cmd/testdata/mysql_test_schema/2_blog.sql@@ -53,7 +53,6 @@ ORDER BYLIMIT 10;-- Procedure-DELIMITER //CREATE PROCEDURE bytebase_test_blog.author_post_count (IN author_id INT, OUT post_count INT)BEGINSELECT@@ -62,11 +61,9 @@ BEGINauthor, postWHEREauthor.id = post.author_id AND author.id = author_id;-END //-DELIMITER ;+END;-- Function-DELIMITER //CREATE FUNCTION bytebase_test_blog.author_comment_count (author_id INT)RETURNS INT DETERMINISTICBEGIN@@ -81,11 +78,9 @@ DECLAREauthor.id = comment.author_idAND author.id = author_id;RETURN comment_count;-END //-DELIMITER ;+END;-- Event-DELIMITER //CREATE EVENT bytebase_test_blog.increase_author_coin_daily ON SCHEDULE EVERY 1 DAY DO UPDATE authorSET coin = coin + 1;@@ -100,5 +95,4 @@ BEGINupdated_ts = NOW()WHEREid = OLD.id;-END //-DELIMITER ;+END;diff --git a/bin/bb/cmd/var.go b/bin/bb/cmd/var.goindex a748369d04..df60cde4e4 100644--- a/bin/bb/cmd/var.go+++ b/bin/bb/cmd/var.go@@ -4,21 +4,5 @@ package cmdimport "go.uber.org/zap"var (- databaseType string- username string- password string- hostname string- port string- database string- file string-- // SSL flags.- sslCA string // server-ca.pem- sslCert string // client-cert.pem- sslKey string // client-key.pem-- // Dump options.- schemaOnly bool-logger *zap.Logger)diff --git a/bin/bb/cmd/version.go b/bin/bb/cmd/version.goindex e95349a983..82a82e20d2 100644--- a/bin/bb/cmd/version.go+++ b/bin/bb/cmd/version.go@@ -13,19 +13,18 @@ var gitcommit = "unknown"var buildtime = "unknown"var builduser = "unknown"-func init() {- rootCmd.AddCommand(versionCmd)-}--var versionCmd = &cobra.Command{- Use: "version",- Short: "Print the version of bb",- Run: func(cmd *cobra.Command, args []string) {- out := cmd.OutOrStdout()- fmt.Fprintf(out, "bb version: %s\n", version)- fmt.Fprintf(out, "Golang version: %s\n", goversion)- fmt.Fprintf(out, "Git commit hash: %s\n", gitcommit)- fmt.Fprintf(out, "Built on: %s\n", buildtime)- fmt.Fprintf(out, "Built by: %s\n", builduser)- },+func newVersionCmd() *cobra.Command {+ versionCmd := &cobra.Command{+ Use: "version",+ Short: "Print the version of bb",+ Run: func(cmd *cobra.Command, args []string) {+ out := cmd.OutOrStdout()+ fmt.Fprintf(out, "bb version: %s\n", version)+ fmt.Fprintf(out, "Golang version: %s\n", goversion)+ fmt.Fprintf(out, "Git commit hash: %s\n", gitcommit)+ fmt.Fprintf(out, "Built on: %s\n", buildtime)+ fmt.Fprintf(out, "Built by: %s\n", builduser)+ },+ }+ return versionCmd}diff --git a/resources/mysql/mysql.go b/resources/mysql/mysql.goindex a39b9e0455..6e9679d466 100644--- a/resources/mysql/mysql.go+++ b/resources/mysql/mysql.go@@ -169,16 +169,14 @@ func (i *Instance) Import(path string, stdout, stderr io.Writer) error {return err}- cmd := exec.Command(filepath.Join(i.basedir, "bin", "mysql"),- "--user=root",- "--protocol=TCP",- "--host=localhost",- fmt.Sprintf("--port=%d", i.port),- )- cmd.Stdin = bytes.NewReader(buf.Bytes())- cmd.Stdout = stdout- cmd.Stderr = stderr- return cmd.Run()+ db, err := sql.Open("mysql", fmt.Sprintf("root@tcp(localhost:%d)/?multiStatements=true", i.port))+ if err != nil {+ return err+ }+ defer db.Close()++ _, err = db.Exec(buf.String())+ return err}func cat(path string, out io.Writer) error {