Skip to content

Commit

Permalink
Refactor command flags and improve logging
Browse files Browse the repository at this point in the history
  • Loading branch information
chand1012 committed Feb 24, 2024
1 parent c9ab892 commit c85b317
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 50 deletions.
49 changes: 31 additions & 18 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,30 +46,38 @@ func Execute() {
}

func init() {
rootCmd.Flags().StringVarP(&inputFilePath, "read", "r", "", "input file path")
rootCmd.Flags().StringVarP(&tableName, "table", "t", "", "table name")
rootCmd.Flags().StringVarP(&outputFormat, "format", "f", "", "output format. csv, json, jsonl")
rootCmd.Flags().StringVarP(&outputFilePath, "output", "o", "", "output file path")
rootCmd.Flags().BoolVarP(&columnNames, "columns", "c", false, "print the columns names and exit")
rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "print verbose output. Prints full stack trace for debugging.")
rootCmd.Flags().BoolVarP(&quiet, "quiet", "q", false, "execute the query and exit without printing anything")
rootCmd.Flags().StringVarP(&inputFilePath, "read", "r", "", "Input file path.")
rootCmd.Flags().StringVarP(&tableName, "table", "t", constants.TableName, "Table name for non-SQL input.")
rootCmd.Flags().StringVarP(&outputFormat, "format", "f", "", "Output format. Must be one of csv, json, jsonl, or sqlite")
rootCmd.Flags().StringVarP(&outputFilePath, "output", "o", "", "Output file path. Required for sqlite output.")
rootCmd.Flags().BoolVarP(&columnNames, "columns", "c", false, "Print the columns names and exit.")
rootCmd.Flags().BoolVarP(&verbose, "verbose", "v", false, "Print verbose output. Prints full stack trace for debugging.")
rootCmd.Flags().BoolVarP(&quiet, "quiet", "q", false, "Execute the query and exit without printing anything. For use in scripts where input file is an existing SQLite database.")
}

func run(cmd *cobra.Command, args []string) {
var err error
var d *sql.DB
// var filePath string
var content string
// always has one argument, which is a sql query
query := args[0]
var query string
// tread the input as bytes
// no matter where it came from
// or what it is
var input []byte

if len(args) > 0 {
query = args[0]
} else {
query = "SELECT * FROM " + tableName + ";"
}

log.Debugf("Query: %s", query)

// if the input file path is not empty
// load the bytes from the file
if inputFilePath != "" {
log.Debugf("Input file path: %s", inputFilePath)
d, _, err = db.LoadFile(inputFilePath)
if err != nil {
file, err := os.ReadFile(inputFilePath)
Expand All @@ -79,21 +87,15 @@ func run(cmd *cobra.Command, args []string) {
input = file
}
} else {
log.Debug("Reading from stdin")
// check stdin
input, err = utils.ReadStdin()
if err != nil {
logger.HandlePanic(log, err, verbose)
}
}

if tableName == "" {
// if an error occurs it stays empty
tableName, err = utils.GetTableName(query)
if err != nil {
log.Warn(err.Error())
tableName = constants.TableName
}
}
log.Debugf("Read %d bytes from input", len(input))

// if the database hasn't been loaded
if d == nil {
Expand All @@ -104,7 +106,10 @@ func run(cmd *cobra.Command, args []string) {
logger.HandlePanic(log, errors.New("input is empty"), verbose)
}

switch file_types.Resolve(input) {
fType := file_types.Resolve(input)
log.Debugf("Resolved file type: %s", fType.String())

switch fType {
case file_types.SQLite:
d, _, err = db.LoadStdin(input)
case file_types.JSONL:
Expand All @@ -124,6 +129,7 @@ func run(cmd *cobra.Command, args []string) {
defer d.Close()

if columnNames {
log.Debug("Printing column names and exiting")
columns, err := db.GetColumnNames(d, tableName)
if err != nil {
logger.HandlePanic(log, err, verbose)
Expand All @@ -132,16 +138,20 @@ func run(cmd *cobra.Command, args []string) {
os.Exit(0)
}

log.Debug("Executing query")
// run the query
rows, err := d.Query(query)
if err != nil {
logger.HandlePanic(log, err, verbose)
}

// if quiet is true, exit without printing anything
if quiet {
os.Exit(0)
}

log.Debugf("Outputting rows to format %s", outputFormat)

switch outputFormat {
case "json":
content, err = db.RowsToJSON(rows)
Expand All @@ -167,6 +177,7 @@ func run(cmd *cobra.Command, args []string) {
}

if outputFilePath != "" {
log.Debugf("Writing to file: %s", outputFilePath)
err = os.WriteFile(outputFilePath, []byte(content), 0644)
if err != nil {
logger.HandlePanic(log, err, verbose)
Expand All @@ -181,6 +192,7 @@ func prerun(cmd *cobra.Command, args []string) {
if verbose {
log = logger.VerboseLogger
}
log.Debug("Resolving output format")
if outputFilePath != "" && outputFormat == "" {
outputFormat = file_types.ResolveByPath(outputFilePath).String()
} else if outputFormat == "" {
Expand All @@ -190,4 +202,5 @@ func prerun(cmd *cobra.Command, args []string) {
if outputFormat != "json" && outputFormat != "jsonl" && outputFormat != "csv" && outputFormat != "sqlite" {
logger.HandlePanic(log, errors.New("unsupported output format"), verbose)
}
log.Debugf("Output format: %s", outputFormat)
}
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ go 1.22.0
require (
github.com/charmbracelet/log v0.3.1
github.com/glebarez/go-sqlite v1.22.0
github.com/krasun/gosqlparser v1.0.5
github.com/spf13/cobra v1.8.0
)

Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU=
github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/krasun/gosqlparser v1.0.5 h1:sHaexkxGb9NrAcjZ3mUs6u33iJ9qhR2fH7XrpZekMt8=
github.com/krasun/gosqlparser v1.0.5/go.mod h1:aXCTW1xnPl4qAaNROeqESauGJ8sqhoB4OFEIOVIDYI4=
github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
Expand Down
29 changes: 0 additions & 29 deletions pkg/utils/sql.go

This file was deleted.

0 comments on commit c85b317

Please sign in to comment.