Skip to content

Commit

Permalink
kwil-cli: small formatting changes
Browse files Browse the repository at this point in the history
  • Loading branch information
brennanjl committed Jan 22, 2025
1 parent 736a749 commit 2de910f
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 28 deletions.
17 changes: 15 additions & 2 deletions cmd/kwil-cli/cmds/call-action.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,25 @@ func (r *respCall) MarshalJSON() ([]byte, error) {
return bts, nil
}

func getStringRows(v [][]any) [][]string {
var rows [][]string
for _, r := range v {
var row []string
for _, c := range r {
row = append(row, fmt.Sprintf("%v", c))
}
rows = append(rows, row)
}

return rows
}

func (r *respCall) MarshalText() (text []byte, err error) {
if !r.PrintLogs {
return recordsToTable(r.Data.QueryResult.ExportToStringMap(), r.tableConf), nil
return recordsToTable(r.Data.QueryResult.ColumnNames, getStringRows(r.Data.QueryResult.Values), r.tableConf), nil
}

bts := recordsToTable(r.Data.QueryResult.ExportToStringMap(), r.tableConf)
bts := recordsToTable(r.Data.QueryResult.ColumnNames, getStringRows(r.Data.QueryResult.Values), r.tableConf)

if len(r.Data.Logs) > 0 {
bts = append(bts, []byte("\n\nLogs:")...)
Expand Down
2 changes: 1 addition & 1 deletion cmd/kwil-cli/cmds/exec-sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func execSQLCmd() *cobra.Command {
},
}

cmd.Flags().StringVarP(&sqlStmt, "statement", "s", "", "the SQL statement to execute")
cmd.Flags().StringVarP(&sqlStmt, "stmt", "s", "", "the SQL statement to execute")
cmd.Flags().StringVarP(&sqlFilepath, "file", "f", "", "the file containing the SQL statement(s) to execute")
cmd.Flags().StringArrayVarP(&params, "param", "p", nil, `the parameters to pass to the SQL statement. format: "key:type=value"`)
common.BindTxFlags(cmd)
Expand Down
23 changes: 18 additions & 5 deletions cmd/kwil-cli/cmds/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,27 @@ kwil-cli query "SELECT * FROM my_table WHERE id = $id" --param id:int=1`
func queryCmd() *cobra.Command {
var namedParams []string
var gwAuth, rpcAuth bool
var stmt string

cmd := &cobra.Command{
Use: "query",
Short: "Execute a SELECT statement against the database",
Long: queryLong,
Example: queryExample,
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return display.PrintErr(cmd, fmt.Errorf("SELECT statement must be the only argument"))
var sqlStmt string
switch {
case stmt != "" && len(args) == 0:
sqlStmt = stmt
case stmt == "" && len(args) == 1:
sqlStmt = args[0]
case stmt != "" && len(args) == 1:
return display.PrintErr(cmd, fmt.Errorf("cannot provide both a --stmt flag and an argument"))
case stmt == "" && len(args) == 0:
return display.PrintErr(cmd, fmt.Errorf("no SQL statement provided"))
default:
return display.PrintErr(cmd, fmt.Errorf("unexpected error"))
}

tblConf, err := getTableConfig(cmd)
Expand All @@ -69,13 +81,13 @@ func queryCmd() *cobra.Command {
return display.PrintErr(cmd, err)
}

_, err = parse.Parse(args[0])
_, err = parse.Parse(sqlStmt)
if err != nil {
return display.PrintErr(cmd, fmt.Errorf("failed to parse SQL statement: %s", err))
}

return client.DialClient(cmd.Context(), cmd, dialFlags, func(ctx context.Context, cl clientType.Client, conf *config.KwilCliConfig) error {
res, err := cl.Query(ctx, args[0], params)
res, err := cl.Query(ctx, sqlStmt, params)
if err != nil {
return display.PrintErr(cmd, err)
}
Expand All @@ -85,6 +97,7 @@ func queryCmd() *cobra.Command {
},
}

cmd.Flags().StringVarP(&stmt, "stmt", "s", "", "the SELECT statement to execute")
cmd.Flags().StringArrayVarP(&namedParams, "param", "p", nil, `named parameters that will be used in the query. format: "key:type=value"`)
cmd.Flags().BoolVar(&rpcAuth, "rpc-auth", false, "signals that the call is being made to a kwil node and should be authenticated with the private key")
cmd.Flags().BoolVar(&gwAuth, "gateway-auth", false, "signals that the call is being made to a gateway and should be authenticated with the private key")
Expand All @@ -106,5 +119,5 @@ func (r *respRelations) MarshalJSON() ([]byte, error) {
}

func (r *respRelations) MarshalText() ([]byte, error) {
return recordsToTable(r.Data.ExportToStringMap(), r.conf), nil
return recordsToTable(r.Data.ColumnNames, getStringRows(r.Data.Values), r.conf), nil
}
27 changes: 9 additions & 18 deletions cmd/kwil-cli/cmds/tableprint.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cmds

import (
"bytes"
"sort"

"github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -56,39 +55,31 @@ func (t *tableConfig) apply(table *tablewriter.Table) {

// recordsToTable converts records to a formatted table structure
// that can be printed
func recordsToTable(data []map[string]string, c *tableConfig) []byte {
func recordsToTable(columns []string, rows [][]string, c *tableConfig) []byte {
if c == nil {
c = &tableConfig{}
}
if len(data) == 0 {
if len(rows) == 0 {
return []byte("No data to display.")
}

// collect headers
headers := make([]string, 0, len(data[0]))
for k := range data[0] {
headers = append(headers, k)
}

// keep the headers in a sorted order
sort.Strings(headers)

var buf bytes.Buffer
table := tablewriter.NewWriter(&buf)
table.SetHeader(headers)
table.SetHeader(columns)
table.SetAutoFormatHeaders(false)
table.SetBorders(
tablewriter.Border{Left: true, Top: false, Right: true, Bottom: false})
c.apply(table)

for _, row := range data {
rs := make([]string, 0, len(headers))
for _, h := range headers {
v := row[h]
if c.maxRowWidth > 0 && len(v) > c.maxRowWidth {
v = v[:c.maxRowWidth] + "..."
for _, row := range rows {
rs := make([]string, 0, len(columns))
for _, col := range row {
if c.maxRowWidth > 0 && len(col) > c.maxRowWidth {
col = col[:c.maxRowWidth] + "..."
}
rs = append(rs, v)
rs = append(rs, col)
}
table.Append(rs)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/kwil-cli/cmds/utils/generate_key.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func generateKeyCmd() *cobra.Command {
pubKeyBts := pubKey.Bytes()

pubKeyHex := hex.EncodeToString(pubKeyBts)
address, err := auth.EthSecp256k1Authenticator{}.Identifier(crypto.EthereumAddressFromPubKey(pubKey.(*crypto.Secp256k1PublicKey)))
address, err := auth.EthSecp256k1Authenticator{}.Identifier(auth.GetUserSigner(pk).CompactID())
if err != nil {
return display.PrintErr(cmd, err)
}
Expand Down
2 changes: 1 addition & 1 deletion test/setup/jsonrpc_cli_driver.go
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ func stringifyCLIArg(a any) string {
}

func (j *jsonRPCCLIDriver) ExecuteSQL(ctx context.Context, sql string, params map[string]any, opts ...client.TxOpt) (types.Hash, error) {
args := append([]string{"exec-sql"}, "--statement", sql)
args := append([]string{"exec-sql"}, "--stmt", sql)
for k, v := range params {
encoded, err := types.EncodeValue(v)
if err != nil {
Expand Down

0 comments on commit 2de910f

Please sign in to comment.