Skip to content

Commit

Permalink
Another pass at code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
kenshaw committed Jan 17, 2021
1 parent 1061148 commit 5739801
Show file tree
Hide file tree
Showing 45 changed files with 89 additions and 176 deletions.
22 changes: 3 additions & 19 deletions args.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"os"

"github.com/alecthomas/kingpin"

"github.com/xo/usql/text"
)

Expand All @@ -19,24 +18,21 @@ type CommandOrFile struct {

// Args are the command line arguments.
type Args struct {
DSN string

DSN string
CommandOrFiles []CommandOrFile
Out string
ForcePassword bool
NoPassword bool
NoRC bool
SingleTransaction bool

Variables []string
PVariables []string
Variables []string
PVariables []string
}

func (args *Args) Next() (string, bool, error) {
if len(args.CommandOrFiles) == 0 {
return "", false, io.EOF
}

cmd := args.CommandOrFiles[0]
args.CommandOrFiles = args.CommandOrFiles[1:]
return cmd.Value, cmd.Command, nil
Expand Down Expand Up @@ -85,32 +81,25 @@ func (p pset) IsCumulative() bool {

func NewArgs() *Args {
args := &Args{}

// set usage template
kingpin.UsageTemplate(text.UsageTemplate())

kingpin.Arg("dsn", "database url").StringVar(&args.DSN)

// command / file flags
kingpin.Flag("command", "run only single command (SQL or internal) and exit").Short('c').SetValue(commandOrFile{args, true})
kingpin.Flag("file", "execute commands from file and exit").Short('f').SetValue(commandOrFile{args, false})

// general flags
kingpin.Flag("no-password", "never prompt for password").Short('w').BoolVar(&args.NoPassword)
kingpin.Flag("no-rc", "do not read start up file").Short('X').BoolVar(&args.NoRC)
kingpin.Flag("out", "output file").Short('o').StringVar(&args.Out)
kingpin.Flag("password", "force password prompt (should happen automatically)").Short('W').BoolVar(&args.ForcePassword)
kingpin.Flag("single-transaction", "execute as a single transaction (if non-interactive)").Short('1').BoolVar(&args.SingleTransaction)
kingpin.Flag("set", "set variable NAME to VALUE").Short('v').PlaceHolder(", --variable=NAME=VALUE").StringsVar(&args.Variables)

// pset
kingpin.Flag("pset", `set printing option VAR to ARG (see \pset command)`).Short('P').PlaceHolder("VAR[=ARG]").StringsVar(&args.PVariables)

// pset flags
kingpin.Flag("field-separator", `field separator for unaligned output (default, "|")`).Short('F').SetValue(pset{args, []string{"fieldsep=%q", "fieldsep_zero=off"}})
kingpin.Flag("record-separator", `record separator for unaligned output (default, \n)`).Short('R').SetValue(pset{args, []string{"recordsep=%q", "recordsep_zero=off"}})
kingpin.Flag("table-attr", "set HTML table tag attributes (e.g., width, border)").Short('T').SetValue(pset{args, []string{"tableattr=%q"}})

type psetconfig struct {
long string
short rune
Expand Down Expand Up @@ -138,22 +127,17 @@ func NewArgs() *Args {
return nil
}).Bool()
}

// add --set as a hidden alias for --variable
kingpin.Flag("variable", "set variable NAME to VALUE").Hidden().StringsVar(&args.Variables)

// add --version flag
kingpin.Flag("version", "display version and exit").PreAction(func(*kingpin.ParseContext) error {
fmt.Fprintln(os.Stdout, text.CommandName, text.CommandVersion)
os.Exit(0)
return nil
}).Short('V').Bool()

// hide help flag
kingpin.HelpFlag.Short('h').Hidden()

// parse
kingpin.Parse()

return args
}
12 changes: 5 additions & 7 deletions drivers/drivers.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,15 +124,14 @@ func ForceParams(u *dburl.URL) {

// Open opens a sql.DB connection for the registered driver.
func Open(u *dburl.URL) (*sql.DB, error) {
var err error
d, ok := drivers[u.Driver]
if !ok {
return nil, WrapErr(u.Driver, text.ErrDriverNotAvailable)
}
f := sql.Open
if d.Open != nil {
f, err = d.Open(u)
if err != nil {
var err error
if f, err = d.Open(u); err != nil {
return nil, WrapErr(u.Driver, err)
}
}
Expand Down Expand Up @@ -200,7 +199,7 @@ func User(u *dburl.URL, db DB) (string, error) {
return user, WrapErr(u.Driver, err)
}
var user string
db.QueryRow(`select current_user`).Scan(&user)
_ = db.QueryRow(`select current_user`).Scan(&user)
return user, nil
}

Expand Down Expand Up @@ -250,10 +249,9 @@ func CanChangePassword(u *dburl.URL) error {
// from User.
func ChangePassword(u *dburl.URL, db DB, user, new, old string) (string, error) {
if d, ok := drivers[u.Driver]; ok && d.ChangePassword != nil {
var err error
if user == "" {
user, err = User(u, db)
if err != nil {
var err error
if user, err = User(u, db); err != nil {
return "", err
}
}
Expand Down
21 changes: 8 additions & 13 deletions env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@ func Getenv(keys ...string) string {
// expand expands the tilde (~) in the front of a path to a the supplied
// directory.
func expand(u *user.User, path string) string {
if path == "~" {
switch {
case path == "~":
return u.HomeDir
} else if strings.HasPrefix(path, "~/") {
case strings.HasPrefix(path, "~/"):
return filepath.Join(u.HomeDir, strings.TrimPrefix(path, "~/"))
}
return path
Expand All @@ -53,8 +54,7 @@ func Getvar(s string) (bool, string, error) {
q, n := "", s
if c := rune(s[0]); c == '\'' || c == '"' {
var err error
n, err = unquote(s, c)
if err != nil {
if n, err = unquote(s, c); err != nil {
return false, "", err
}
q = string(c)
Expand All @@ -68,8 +68,7 @@ func Getvar(s string) (bool, string, error) {
// OpenFile opens a file for reading, returning the full, expanded path of the
// file. All callers are responsible for closing the returned file.
func OpenFile(u *user.User, path string, relative bool) (string, *os.File, error) {
var err error
path, err = filepath.EvalSymlinks(expand(u, path))
path, err := filepath.EvalSymlinks(expand(u, path))
switch {
case err != nil && os.IsNotExist(err):
return "", nil, text.ErrNoSuchFileOrDirectory
Expand All @@ -94,16 +93,14 @@ func OpenFile(u *user.User, path string, relative bool) (string, *os.File, error

// EditFile edits a file. If path is empty, then a temporary file will be created.
func EditFile(u *user.User, path, line, s string) ([]rune, error) {
var err error
ed := Getenv(text.CommandUpper()+"_EDITOR", "EDITOR", "VISUAL")
if ed == "" {
return nil, text.ErrNoEditorDefined
}
if path != "" {
path = expand(u, path)
} else {
var f *os.File
f, err = temp.File("", text.CommandLower(), "sql")
f, err := temp.File("", text.CommandLower(), "sql")
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -132,8 +129,7 @@ func EditFile(u *user.User, path, line, s string) ([]rune, error) {
c.Stdout = os.Stdout
c.Stderr = os.Stderr
// run
err = c.Run()
if err != nil {
if err := c.Run(); err != nil {
return nil, err
}
// read
Expand Down Expand Up @@ -355,8 +351,7 @@ func Unquote(u *user.User, s string, exec bool) (string, error) {
return unquote(s, c)
case exec && c == '`':
var err error
s, err = unquote(s, c)
if err != nil {
if s, err = unquote(s, c); err != nil {
return "", err
}
if strings.TrimSpace(s) == "" {
Expand Down
29 changes: 12 additions & 17 deletions handler/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func New(l rline.IO, user *user.User, wd string, nopw bool) *Handler {
return nil, nil
}
// save history
l.Save(string(r))
_ = l.Save(string(r))
return r, nil
}
}
Expand Down Expand Up @@ -142,12 +142,14 @@ func (h *Handler) outputHighlighter(s string) string {
// EOF or when a \ cmd has been encountered
var err error
var cmd, final string
loop:
for {
cmd, _, err = st.Next()
if err != nil && err != io.EOF {
switch {
case err != nil && err != io.EOF:
return s + endl
} else if err == io.EOF {
break
case err == io.EOF:
break loop
}
if st.Ready() || cmd != "" {
final += st.RawString()
Expand Down Expand Up @@ -197,7 +199,6 @@ func (h *Handler) Run() error {
fmt.Fprintln(h.l.Stdout())
}
for {
var err error
var execute bool
// set prompt
if iactive {
Expand Down Expand Up @@ -448,8 +449,7 @@ func (h *Handler) Open(params ...string) error {
switch {
case err == dburl.ErrInvalidDatabaseScheme:
var fi os.FileInfo
fi, err = os.Stat(urlstr)
if err != nil {
if fi, err = os.Stat(urlstr); err != nil {
return err
}
switch {
Expand Down Expand Up @@ -512,11 +512,12 @@ func (h *Handler) forceParams(u *dburl.URL) {
drivers.ForceParams(u)
// see if password entry is present
user, err := env.PassFileEntry(h.user, u)
if err != nil {
switch {
case err != nil:
errout := h.l.Stderr()
fmt.Fprintf(errout, "error: %v", err)
fmt.Fprintln(errout)
} else if user != nil {
case user != nil:
u.User = user
}
// copy back to u
Expand All @@ -527,7 +528,6 @@ func (h *Handler) forceParams(u *dburl.URL) {
// Password collects a password from input, and returns a modified DSN
// including the collected password.
func (h *Handler) Password(dsn string) (string, error) {
var err error
if dsn == "" {
return "", text.ErrMissingDSN
}
Expand Down Expand Up @@ -720,7 +720,7 @@ func (h *Handler) execSet(w io.Writer, prefix, qstr string, _ bool, namePrefix s
if err = env.ValidIdentifier(n); err != nil {
return fmt.Errorf(text.CouldNotSetVariable, n)
}
env.Set(n, row[i])
_ = env.Set(n, row[i])
}
return nil
}
Expand Down Expand Up @@ -750,7 +750,6 @@ func (h *Handler) execExec(w io.Writer, prefix, qstr string, qtyp bool, _ string

// query executes a query against the database.
func (h *Handler) query(w io.Writer, _, qstr string) error {
var err error
// run query
q, err := h.DB().Query(qstr)
if err != nil {
Expand All @@ -763,7 +762,6 @@ func (h *Handler) query(w io.Writer, _, qstr string) error {

// execRows executes all the columns in the row.
func (h *Handler) execRows(w io.Writer, q *sql.Rows) error {
var err error
// get columns
cols, err := drivers.Columns(h.u, q)
if err != nil {
Expand Down Expand Up @@ -801,8 +799,7 @@ func (h *Handler) scan(q *sql.Rows, clen int, tfmt string) ([]string, error) {
return nil, err
}
// get conversion funcs
cb, cm, cs, cd := drivers.ConvertBytes(h.u), drivers.ConvertMap(h.u),
drivers.ConvertSlice(h.u), drivers.ConvertDefault(h.u)
cb, cm, cs, cd := drivers.ConvertBytes(h.u), drivers.ConvertMap(h.u), drivers.ConvertSlice(h.u), drivers.ConvertDefault(h.u)
row := make([]string, clen)
for n, z := range r {
j := z.(*interface{})
Expand Down Expand Up @@ -848,7 +845,6 @@ func (h *Handler) scan(q *sql.Rows, clen int, tfmt string) ([]string, error) {

// exec does a database exec.
func (h *Handler) exec(w io.Writer, typ, qstr string) error {
var err error
res, err := h.DB().Exec(qstr)
if err != nil {
return err
Expand Down Expand Up @@ -920,7 +916,6 @@ func (h *Handler) Rollback() error {

// Include includes the specified path.
func (h *Handler) Include(path string, relative bool) error {
var err error
if relative && !filepath.IsAbs(path) {
path = filepath.Join(h.wd, path)
}
Expand Down
3 changes: 1 addition & 2 deletions internal/adodb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions internal/athena.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions internal/avatica.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions internal/bigquery.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions internal/cassandra.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions internal/clickhouse.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions internal/cosmos.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions internal/couchbase.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions internal/firebird.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 5739801

Please sign in to comment.