Skip to content

Commit

Permalink
feat(connection): add logic to validate and parse postgres and mysql …
Browse files Browse the repository at this point in the history
…connections
  • Loading branch information
danvergara committed Apr 22, 2021
1 parent 45636c7 commit c8b2bd5
Showing 1 changed file with 54 additions and 2 deletions.
56 changes: 54 additions & 2 deletions pkg/connection/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,25 @@ import (
"errors"
"fmt"
"net/url"
"os"
"os/user"
"strings"

"github.com/danvergara/dblab/pkg/command"
)

var (
// ErrCantDetectUSer is the error used to notify that a default username is not found
// in the system to be used as database username.
ErrCantDetectUSer = errors.New("could not detect default username")
// ErrInvalidUPostgresRLFormat is the error used to notify that the postgres given url is not valid.
ErrInvalidUPostgresRLFormat = errors.New("Invalid URL. Valid format: postgres://user:password@host:port/db?sslmode=mode")
ErrInvalidUPostgresRLFormat = errors.New("invalid URL - Valid format: postgres://user:password@host:port/db?sslmode=mode")
// ErrInvalidUMySQLRLFormat is the error used to notify that the given mysql url is not valid.
ErrInvalidUMySQLRLFormat = errors.New("Invalid URL. Valid format: mysql://user:password@tcp(host:port)/db")
ErrInvalidUMySQLRLFormat = errors.New("invalid URL - valid format: mysql://user:password@tcp(host:port)/db")
// ErrInvalidURLFormat is used to notify the url is invalid.
ErrInvalidURLFormat = errors.New("invalid url")
// ErrInvalidDriver is used to notify that the provided driver is not supported.
ErrInvalidDriver = errors.New("invalid driver")
)

// BuildConnectionFromOpts return the connection uri string given the options passed by the uses.
Expand All @@ -31,6 +38,51 @@ func BuildConnectionFromOpts(opts command.Options) (string, error) {
}
}

if opts.User == "" {
u, err := currentUser()
if err == nil {
opts.User = u
}
}

switch opts.Driver {
case "postgres":
query := url.Values{}
if opts.SSL != "" {
query.Add("sslmode", opts.SSL)
} else {
if opts.Host == "localhost" || opts.Host == "127.0.0.1" {
query.Add("sslmode", "disable")
}
}

connDB := url.URL{
Scheme: opts.Driver,
Host: fmt.Sprintf("%v:%v", opts.Host, opts.Port),
User: url.UserPassword(opts.User, opts.Pass),
Path: fmt.Sprintf("/%s", opts.DBName),
RawQuery: query.Encode(),
}

return connDB.String(), nil
case "mysql":
return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", opts.User, opts.Pass, opts.Host, opts.Port, opts.DBName), nil
default:
return "", fmt.Errorf("%s: %w", opts.URL, ErrInvalidDriver)
}
}

func currentUser() (string, error) {
u, err := user.Current()
if err == nil {
return u.Username, nil
}

name := os.Getenv("USER")
if name != "" {
return name, nil
}

return "", nil
}

Expand Down

0 comments on commit c8b2bd5

Please sign in to comment.