Skip to content

Commit

Permalink
feat(mysql): Add list DBs functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
ondrejsika committed Aug 3, 2021
1 parent 4d680f0 commit 7b9229d
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 0 deletions.
1 change: 1 addition & 0 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
_ "github.com/sikalabs/slut/cmd/mysql"
_ "github.com/sikalabs/slut/cmd/mysql/create"
_ "github.com/sikalabs/slut/cmd/mysql/drop"
_ "github.com/sikalabs/slut/cmd/mysql/list"
_ "github.com/sikalabs/slut/cmd/postgres"
_ "github.com/sikalabs/slut/cmd/postgres/create"
_ "github.com/sikalabs/slut/cmd/postgres/drop"
Expand Down
36 changes: 36 additions & 0 deletions cmd/mysql/list/list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package drop

import (
mysqlcmd "github.com/sikalabs/slut/cmd/mysql"
rootcmd "github.com/sikalabs/slut/cmd/root"
"github.com/sikalabs/slut/utils/mysql"

"github.com/spf13/cobra"
)

var MysqlListCmd = &cobra.Command{
Use: "list",
Short: "list Mysql databases",
Args: cobra.NoArgs,
Run: func(c *cobra.Command, args []string) {
if rootcmd.RootCmdFlagJson {
mysql.ListJSON(
mysqlcmd.MysqlCmdFlagHost,
mysqlcmd.MysqlCmdFlagPort,
mysqlcmd.MysqlCmdFlagUser,
mysqlcmd.MysqlCmdFlagPassword,
)
} else {
mysql.ListText(
mysqlcmd.MysqlCmdFlagHost,
mysqlcmd.MysqlCmdFlagPort,
mysqlcmd.MysqlCmdFlagUser,
mysqlcmd.MysqlCmdFlagPassword,
)
}
},
}

func init() {
mysqlcmd.MysqlCmd.AddCommand(MysqlListCmd)
}
76 changes: 76 additions & 0 deletions utils/mysql/list.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package mysql

import (
"database/sql"
"encoding/json"
"fmt"
"strconv"
)

func List(
host string,
port int,
user string,
password string,
) ([]string, error) {
db, err := sql.Open(
"mysql",
user+":"+password+"@tcp("+host+":"+strconv.Itoa(port)+")/")
if err != nil {
panic(err)
}
if err != nil {
return nil, err
}
defer db.Close()

rows, err := db.Query("SHOW DATABASES;")
if err != nil {
return nil, err
}
defer rows.Close()

var dbNames []string
var dbName string

for rows.Next() {
err := rows.Scan(&dbName)
if err != nil {
return nil, err
}
dbNames = append(dbNames, dbName)
}
return dbNames, err
}

func ListText(
host string,
port int,
user string,
password string,
) {
dbNames, err := List(host, port, user, password)
if err != nil {
panic(err)
}
for _, dbName := range dbNames {
fmt.Println(dbName)
}
}

func ListJSON(
host string,
port int,
user string,
password string,
) {
dbNames, err := List(host, port, user, password)
if err != nil {
panic(err)
}
outJson, err := json.Marshal(dbNames)
if err != nil {
panic(err)
}
fmt.Println(string(outJson))
}

0 comments on commit 7b9229d

Please sign in to comment.