From adde83a51a7dc4ff34158621202145fb189cd1dc Mon Sep 17 00:00:00 2001 From: Robin x <83790096+0xRobin@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:10:10 +0000 Subject: [PATCH] List columns in dataset search text output and add --compact JSON dataset search and search-by-contract fetched column schemas but their text output dropped them, so agents had to use -o json to write SQL. Text output now lists each table's columns under COLUMNS: the Dune MCP's top-3 columns, or the API schema with --include-schema. Every command with -o now also takes --compact, which prints JSON on one line. Indented JSON was about 60% larger than the same data compact. Amp-Thread-ID: https://ampcode.com/threads/T-01a1f9a9-af80-7151-a7e6-0056ca994479 Co-authored-by: Amp --- README.md | 3 ++ cmd/contract/submissions.go | 2 +- cmd/contract/submit.go | 2 +- cmd/dashboard/archive.go | 2 +- cmd/dashboard/create.go | 2 +- cmd/dashboard/get.go | 2 +- cmd/dashboard/search.go | 2 +- cmd/dashboard/update.go | 2 +- cmd/dataset/blockchains.go | 2 +- cmd/dataset/columns.go | 45 ++++++++++++++++++++++++++ cmd/dataset/search.go | 10 ++++-- cmd/dataset/search_by_contract.go | 6 +++- cmd/dataset/search_by_contract_test.go | 18 +++++++++++ cmd/dataset/search_test.go | 33 +++++++++++++++---- cmd/dataset/size.go | 2 +- cmd/docs/search.go | 2 +- cmd/execution/results.go | 2 +- cmd/folder/delete.go | 2 +- cmd/folder/folder.go | 2 +- cmd/folder/get.go | 2 +- cmd/folder/list.go | 2 +- cmd/folder/move_content.go | 2 +- cmd/matview/create.go | 2 +- cmd/matview/delete.go | 2 +- cmd/matview/get.go | 2 +- cmd/matview/list.go | 2 +- cmd/matview/refresh.go | 2 +- cmd/matview/update.go | 2 +- cmd/query/archive.go | 2 +- cmd/query/create.go | 2 +- cmd/query/create_and_run.go | 2 +- cmd/query/get.go | 4 +-- cmd/query/helpers.go | 2 +- cmd/query/search.go | 2 +- cmd/query/update.go | 2 +- cmd/schedule/delete.go | 2 +- cmd/schedule/list.go | 2 +- cmd/schedule/set.go | 2 +- cmd/usage/usage.go | 2 +- cmd/visualization/chart.go | 2 +- cmd/visualization/create.go | 2 +- cmd/visualization/delete.go | 2 +- cmd/visualization/get.go | 2 +- cmd/visualization/list.go | 2 +- cmd/visualization/update.go | 2 +- cmd/whoami/whoami.go | 2 +- output/output.go | 37 +++++++++++++++------ output/output_test.go | 32 ++++++++++++++++-- output/results.go | 2 +- 49 files changed, 204 insertions(+), 64 deletions(-) create mode 100644 cmd/dataset/columns.go diff --git a/README.md b/README.md index 4ddfa3c..31c05c8 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,9 @@ dune usage [--start-date YYYY-MM-DD] [--end-date YYYY-MM-DD] ## Output Format All commands (except `auth`) support `-o, --output ` with `text` (default) or `json`. +Add `--compact` to print the JSON on one line without indentation, which cuts its size by about a third for agents and scripts. + +`dataset search` and `dataset search-by-contract` list each result's columns under `COLUMNS` in text output: the top 3 hits of `dataset search` always, and every result with `--include-schema`. ## How the CLI talks to Dune diff --git a/cmd/contract/submissions.go b/cmd/contract/submissions.go index 1fba9ff..42bdabd 100644 --- a/cmd/contract/submissions.go +++ b/cmd/contract/submissions.go @@ -59,7 +59,7 @@ func runSubmissions(cmd *cobra.Command, _ []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintJSON(w, res) + return output.PrintJSON(cmd, res) } if len(res.Submissions) == 0 { fmt.Fprintln(w, "No submissions found.") diff --git a/cmd/contract/submit.go b/cmd/contract/submit.go index 692558f..cc66b68 100644 --- a/cmd/contract/submit.go +++ b/cmd/contract/submit.go @@ -95,7 +95,7 @@ func runSubmit(cmd *cobra.Command, _ []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - if err := output.PrintJSON(w, res); err != nil { + if err := output.PrintJSON(cmd, res); err != nil { return err } } else { diff --git a/cmd/dashboard/archive.go b/cmd/dashboard/archive.go index 6b21a74..010e99b 100644 --- a/cmd/dashboard/archive.go +++ b/cmd/dashboard/archive.go @@ -46,7 +46,7 @@ func runArchive(cmd *cobra.Command, args []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Archived dashboard %d\n", dashboardID) return nil diff --git a/cmd/dashboard/create.go b/cmd/dashboard/create.go index 785ad68..7dc9dcd 100644 --- a/cmd/dashboard/create.go +++ b/cmd/dashboard/create.go @@ -92,7 +92,7 @@ func runCreate(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Created dashboard %d\n%s\n", resp.DashboardID, resp.DashboardURL) return nil diff --git a/cmd/dashboard/get.go b/cmd/dashboard/get.go index e6d2fd0..95357ce 100644 --- a/cmd/dashboard/get.go +++ b/cmd/dashboard/get.go @@ -73,7 +73,7 @@ func runGet(cmd *cobra.Command, args []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: tags := "" if len(resp.Tags) > 0 { diff --git a/cmd/dashboard/search.go b/cmd/dashboard/search.go index be72396..1d98464 100644 --- a/cmd/dashboard/search.go +++ b/cmd/dashboard/search.go @@ -51,7 +51,7 @@ func runSearch(cmd *cobra.Command, _ []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintRawJSON(w, raw) + return output.PrintRawJSON(cmd, raw) } if len(res.Results) == 0 { fmt.Fprintln(w, "No dashboards found.") diff --git a/cmd/dashboard/update.go b/cmd/dashboard/update.go index b9d75db..42a2e86 100644 --- a/cmd/dashboard/update.go +++ b/cmd/dashboard/update.go @@ -134,7 +134,7 @@ func runUpdate(cmd *cobra.Command, args []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Updated dashboard %d\n", resp.DashboardID) return nil diff --git a/cmd/dataset/blockchains.go b/cmd/dataset/blockchains.go index 682286a..ddaa4a3 100644 --- a/cmd/dataset/blockchains.go +++ b/cmd/dataset/blockchains.go @@ -52,7 +52,7 @@ func runBlockchains(cmd *cobra.Command, _ []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintRawJSON(w, raw) + return output.PrintRawJSON(cmd, raw) } rows := make([][]string, len(res.Results)) for i, r := range res.Results { diff --git a/cmd/dataset/columns.go b/cmd/dataset/columns.go new file mode 100644 index 0000000..da53fa4 --- /dev/null +++ b/cmd/dataset/columns.go @@ -0,0 +1,45 @@ +package dataset + +import ( + "encoding/json" + "fmt" + "io" + "strings" +) + +// tableColumns returns a table's columns as "name type" strings. It reads the +// Dune MCP's columns list ([{"name","type",...}]) and falls back to the API's +// --include-schema field ({"fields":[{"name","type",...}]}). +func tableColumns(columns, schema json.RawMessage) []string { + type column struct{ Name, Type string } + var cols []column + if len(columns) > 0 { + _ = json.Unmarshal(columns, &cols) + } + if len(cols) == 0 && len(schema) > 0 { + var s struct{ Fields []column } + _ = json.Unmarshal(schema, &s) + cols = s.Fields + } + out := make([]string, len(cols)) + for i, c := range cols { + out[i] = c.Name + " " + c.Type + } + return out +} + +// printColumns lists the columns of each table that has them, one table per +// line, so text output carries what an agent needs to write SQL. +func printColumns(w io.Writer, names []string, columns [][]string) { + header := false + for i, cols := range columns { + if len(cols) == 0 { + continue + } + if !header { + fmt.Fprintln(w, "\nCOLUMNS") + header = true + } + fmt.Fprintf(w, "%s: %s\n", names[i], strings.Join(cols, ", ")) + } +} diff --git a/cmd/dataset/search.go b/cmd/dataset/search.go index 922119b..4864c41 100644 --- a/cmd/dataset/search.go +++ b/cmd/dataset/search.go @@ -24,8 +24,8 @@ func newSearchCmd() *cobra.Command { " - community: user-contributed tables and uploads\n\n" + "Filter by category, blockchain, schema, dataset type, or ownership scope. Each\n" + "result lists the columns the table is partitioned by: filter on them in SQL (e.g.\n" + - "WHERE block_month >= DATE '2026-01-01') to cut query cost. With -o json the top 3 hits also carry\n" + - "their columns and types; --include-schema adds the schema of every result.\n\n" + + "WHERE block_month >= DATE '2026-01-01') to cut query cost. The top 3 hits also list\n" + + "their columns and types; --include-schema lists them for every result.\n\n" + "For contract-specific lookup, use 'dune dataset search-by-contract' instead.\n\n" + "Examples:\n" + " dune dataset search --query \"uniswap swaps\"\n" + @@ -119,11 +119,14 @@ func runSearch(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: columns := []string{"FULL_NAME", "CATEGORY", "DATASET_TYPE", "PARTITIONED_BY", "BLOCKCHAINS"} rows := make([][]string, len(resp.Results)) + names := make([]string, len(resp.Results)) + cols := make([][]string, len(resp.Results)) for i, r := range resp.Results { + names[i], cols[i] = r.FullName, tableColumns(r.Columns, r.Schema) dt := "" if r.DatasetType != nil { dt = *r.DatasetType @@ -137,6 +140,7 @@ func runSearch(cmd *cobra.Command, _ []string) error { } } output.PrintTable(w, columns, rows) + printColumns(w, names, cols) fmt.Fprintf(w, "\n%d of %d results\n", len(resp.Results), resp.Total) return nil } diff --git a/cmd/dataset/search_by_contract.go b/cmd/dataset/search_by_contract.go index e30ffb4..5cfbad8 100644 --- a/cmd/dataset/search_by_contract.go +++ b/cmd/dataset/search_by_contract.go @@ -93,11 +93,14 @@ func runSearchByContract(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: columns := []string{"FULL_NAME", "CATEGORY", "DATASET_TYPE", "BLOCKCHAINS"} rows := make([][]string, len(resp.Results)) + names := make([]string, len(resp.Results)) + cols := make([][]string, len(resp.Results)) for i, r := range resp.Results { + names[i], cols[i] = r.FullName, tableColumns(nil, r.Schema) dt := "" if r.DatasetType != nil { dt = *r.DatasetType @@ -110,6 +113,7 @@ func runSearchByContract(cmd *cobra.Command, _ []string) error { } } output.PrintTable(w, columns, rows) + printColumns(w, names, cols) fmt.Fprintf(w, "\n%d of %d results\n", len(resp.Results), resp.Total) return nil } diff --git a/cmd/dataset/search_by_contract_test.go b/cmd/dataset/search_by_contract_test.go index 3b74b71..5c81ef8 100644 --- a/cmd/dataset/search_by_contract_test.go +++ b/cmd/dataset/search_by_contract_test.go @@ -65,6 +65,24 @@ func TestSearchByContractSuccess(t *testing.T) { assert.Contains(t, out, "2 of 2 results") } +func TestSearchByContractTextListsSchema(t *testing.T) { + mock := &mockClient{ + searchByContractAddressFn: func(req models.SearchDatasetsByContractAddressRequest) (*models.SearchDatasetsResponse, error) { + return &models.SearchDatasetsResponse{Total: 2, Results: []models.SearchDatasetResult{ + {FullName: "pool.evt_Swap", Category: "decoded", + Schema: []byte(`{"fields":[{"name":"amount0","type":"int256"},{"name":"evt_block_time","type":"timestamp"}]}`)}, + {FullName: "pool.call_swap", Category: "decoded"}, + }}, nil + }, + } + root, buf := newTestRoot(mock) + root.SetArgs([]string{"dataset", "search-by-contract", "--contract-address", "0xabc", "--include-schema"}) + require.NoError(t, root.Execute()) + assert.Contains(t, buf.String(), + "\nCOLUMNS\npool.evt_Swap: amount0 int256, evt_block_time timestamp\n\n2 of 2 results\n") + assert.NotContains(t, buf.String(), "pool.call_swap:") +} + func TestSearchByContractJSON(t *testing.T) { mock := &mockClient{ searchByContractAddressFn: func(req models.SearchDatasetsByContractAddressRequest) (*models.SearchDatasetsResponse, error) { diff --git a/cmd/dataset/search_test.go b/cmd/dataset/search_test.go index fe74ecf..385571f 100644 --- a/cmd/dataset/search_test.go +++ b/cmd/dataset/search_test.go @@ -67,13 +67,18 @@ func runSearch(t *testing.T, fake *dunemcptest.Fake, args ...string) (models.Sea next := int32(2) mock := &mockClient{searchDatasetsFn: func(req models.SearchDatasetsRequest) (*models.SearchDatasetsResponse, error) { got = req + trades := models.SearchDatasetResult{FullName: "dex.trades", Category: "spell", DatasetType: strPtr("spell"), + Blockchains: []string{"ethereum", "arbitrum"}} + private := models.SearchDatasetResult{FullName: "my.private_table", Category: "community", + Visibility: strPtr("private")} + if req.IncludeSchema != nil && *req.IncludeSchema { + trades.Schema = []byte(`{"fields":[{"name":"rest_only","type":"bigint","nullable":true}]}`) + private.Schema = []byte(`{"fields":[{"name":"id","type":"bigint","nullable":false},` + + `{"name":"amount","type":"decimal(38,0)","nullable":true}]}`) + } return &models.SearchDatasetsResponse{ - Total: 144, - Results: []models.SearchDatasetResult{ - {FullName: "dex.trades", Category: "spell", DatasetType: strPtr("spell"), - Blockchains: []string{"ethereum", "arbitrum"}}, - {FullName: "my.private_table", Category: "community", Visibility: strPtr("private")}, - }, + Total: 144, + Results: []models.SearchDatasetResult{trades, private}, Pagination: models.SearchDatasetsPagination{Limit: 2, NextOffset: &next, HasMore: true}, }, nil }} @@ -110,6 +115,22 @@ func TestSearchSendsEveryFlagToTheAPI(t *testing.T) { assert.Contains(t, out, "2 of 144 results") } +// Text output must carry columns: agents read it to write SQL. The MCP's +// columns win over the API schema; --include-schema fills in the other hits. +func TestSearchTextListsColumns(t *testing.T) { + fake := &dunemcptest.Fake{Results: map[string]string{"searchTables": searchTablesResult}} + _, out, _, err := runSearch(t, fake, "--query", "dex") + require.NoError(t, err) + assert.Contains(t, out, "\nCOLUMNS\ndex.trades: blockchain varchar\n") + assert.NotContains(t, out, "my.private_table:") + + _, out, _, err = runSearch(t, fake, "--query", "dex", "--include-schema") + require.NoError(t, err) + assert.Contains(t, out, "\nCOLUMNS\ndex.trades: blockchain varchar\n"+ + "my.private_table: id bigint, amount decimal(38,0)\n\n2 of 144 results\n") + assert.NotContains(t, out, "rest_only") +} + func TestSearchJSONIsTheAPIShapePlusColumns(t *testing.T) { fake := &dunemcptest.Fake{Results: map[string]string{"searchTables": searchTablesResult}} _, out, _, err := runSearch(t, fake, "--query", "dex", "-o", "json") diff --git a/cmd/dataset/size.go b/cmd/dataset/size.go index f5d015b..6033094 100644 --- a/cmd/dataset/size.go +++ b/cmd/dataset/size.go @@ -45,7 +45,7 @@ func runSize(cmd *cobra.Command, args []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintRawJSON(w, raw) + return output.PrintRawJSON(cmd, raw) } if res.TotalSizeBytes != nil { fmt.Fprintf(w, "%s: %s\n", res.TableName, output.FormatBytes(*res.TotalSizeBytes)) diff --git a/cmd/docs/search.go b/cmd/docs/search.go index eefa443..ec47568 100644 --- a/cmd/docs/search.go +++ b/cmd/docs/search.go @@ -105,7 +105,7 @@ func runSearch(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, searchResponse{ + return output.PrintJSON(cmd, searchResponse{ Query: query, Results: results, }) diff --git a/cmd/execution/results.go b/cmd/execution/results.go index 2201f5d..8b73a2d 100644 --- a/cmd/execution/results.go +++ b/cmd/execution/results.go @@ -131,7 +131,7 @@ func handleResultsResponse(cmd *cobra.Command, executionID string, resp *models. w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Execution ID: %s\n", executionID) fmt.Fprintf(w, "State: %s\n", resp.State) diff --git a/cmd/folder/delete.go b/cmd/folder/delete.go index 03cba02..456ed66 100644 --- a/cmd/folder/delete.go +++ b/cmd/folder/delete.go @@ -41,7 +41,7 @@ func runDelete(cmd *cobra.Command, posArgs []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintJSON(w, res) + return output.PrintJSON(cmd, res) } fmt.Fprintf(w, "Deleted folder %s: %d folders deleted, %d queries and %d dashboards archived\n", res.Path, res.DeletedFolderCount, res.ArchivedQueryCount, res.ArchivedDashboardCount) diff --git a/cmd/folder/folder.go b/cmd/folder/folder.go index 600c0aa..dd2729c 100644 --- a/cmd/folder/folder.go +++ b/cmd/folder/folder.go @@ -44,7 +44,7 @@ func NewFolderCmd() *cobra.Command { func printFolder(cmd *cobra.Command, f *models.Folder, verb string) error { w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintJSON(w, f) + return output.PrintJSON(cmd, f) } fmt.Fprintf(w, "%s folder %s (%s)\n", verb, f.Path, f.FolderID) return nil diff --git a/cmd/folder/get.go b/cmd/folder/get.go index a89cf11..e82ac6f 100644 --- a/cmd/folder/get.go +++ b/cmd/folder/get.go @@ -36,7 +36,7 @@ func runGet(cmd *cobra.Command, posArgs []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintJSON(w, res) + return output.PrintJSON(cmd, res) } f := res.Folder diff --git a/cmd/folder/list.go b/cmd/folder/list.go index 6602265..7844ade 100644 --- a/cmd/folder/list.go +++ b/cmd/folder/list.go @@ -52,7 +52,7 @@ func runList(cmd *cobra.Command, _ []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintJSON(w, res) + return output.PrintJSON(cmd, res) } if len(res.Folders) == 0 { fmt.Fprintln(w, "No folders found.") diff --git a/cmd/folder/move_content.go b/cmd/folder/move_content.go index e8fc68a..bcc442c 100644 --- a/cmd/folder/move_content.go +++ b/cmd/folder/move_content.go @@ -51,7 +51,7 @@ func runMoveContent(cmd *cobra.Command, _ []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintJSON(w, res) + return output.PrintJSON(cmd, res) } where := "out of folders" if res.TargetFolder != nil { diff --git a/cmd/matview/create.go b/cmd/matview/create.go index 6f8bf4e..f77e37a 100644 --- a/cmd/matview/create.go +++ b/cmd/matview/create.go @@ -88,7 +88,7 @@ func runCreate(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Created materialized view %s\n", resp.SQLID) fmt.Fprintf(w, "Execution ID: %s\n", resp.ExecutionID) diff --git a/cmd/matview/delete.go b/cmd/matview/delete.go index a7ef782..5c9f24d 100644 --- a/cmd/matview/delete.go +++ b/cmd/matview/delete.go @@ -39,7 +39,7 @@ func runDelete(cmd *cobra.Command, args []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Deleted materialized view %s\n", args[0]) return nil diff --git a/cmd/matview/get.go b/cmd/matview/get.go index 7517b2b..8047025 100644 --- a/cmd/matview/get.go +++ b/cmd/matview/get.go @@ -56,7 +56,7 @@ func runGet(cmd *cobra.Command, args []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Name: %s\n", resp.SQLID) fmt.Fprintf(w, "Query ID: %d\n", resp.QueryID) diff --git a/cmd/matview/list.go b/cmd/matview/list.go index 37a5c15..a89fafc 100644 --- a/cmd/matview/list.go +++ b/cmd/matview/list.go @@ -62,7 +62,7 @@ func runList(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, result) + return output.PrintJSON(cmd, result) default: if len(result.MaterializedViews) == 0 { fmt.Fprintln(w, "No materialized views found.") diff --git a/cmd/matview/refresh.go b/cmd/matview/refresh.go index 55d27c6..f31b347 100644 --- a/cmd/matview/refresh.go +++ b/cmd/matview/refresh.go @@ -47,7 +47,7 @@ func runRefresh(cmd *cobra.Command, args []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Refreshing materialized view %s\n", resp.SQLID) fmt.Fprintf(w, "Execution ID: %s\n", resp.ExecutionID) diff --git a/cmd/matview/update.go b/cmd/matview/update.go index 0f34eca..fccc665 100644 --- a/cmd/matview/update.go +++ b/cmd/matview/update.go @@ -120,7 +120,7 @@ func runUpdate(cmd *cobra.Command, args []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Updated materialized view %s\n", resp.SQLID) fmt.Fprintf(w, "Execution ID: %s\n", resp.ExecutionID) diff --git a/cmd/query/archive.go b/cmd/query/archive.go index 7c4c5e2..67e27d9 100644 --- a/cmd/query/archive.go +++ b/cmd/query/archive.go @@ -40,7 +40,7 @@ func runArchive(cmd *cobra.Command, args []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Archived query %d\n", resp.QueryID) return nil diff --git a/cmd/query/create.go b/cmd/query/create.go index 122f644..227e7fd 100644 --- a/cmd/query/create.go +++ b/cmd/query/create.go @@ -98,7 +98,7 @@ func runCreate(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Created query %d\n", resp.QueryID) return nil diff --git a/cmd/query/create_and_run.go b/cmd/query/create_and_run.go index e42cd42..c35218a 100644 --- a/cmd/query/create_and_run.go +++ b/cmd/query/create_and_run.go @@ -114,7 +114,7 @@ func runCreateAndRun(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - if err := output.PrintRawJSON(w, raw); err != nil { + if err := output.PrintRawJSON(cmd, raw); err != nil { return err } return errors.Join(errs...) diff --git a/cmd/query/get.go b/cmd/query/get.go index 081f5bb..dcc0009 100644 --- a/cmd/query/get.go +++ b/cmd/query/get.go @@ -56,9 +56,9 @@ func runGet(cmd *cobra.Command, args []string) error { case output.FormatJSON: if !latestKnown { // Leave the keys out, so an unknown latest execution does not read as "never run" (null). - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) } - return output.PrintJSON(w, struct { + return output.PrintJSON(cmd, struct { *models.GetQueryResponse LatestExecutionID *string `json:"latest_execution_id"` LatestExecutionState *string `json:"latest_execution_state"` diff --git a/cmd/query/helpers.go b/cmd/query/helpers.go index 73dd0d6..ce19a5c 100644 --- a/cmd/query/helpers.go +++ b/cmd/query/helpers.go @@ -61,7 +61,7 @@ func displayExecuteResponse(cmd *cobra.Command, resp *models.ExecuteResponse) er w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Execution ID: %s\n", resp.ExecutionID) fmt.Fprintf(w, "State: %s\n", resp.State) diff --git a/cmd/query/search.go b/cmd/query/search.go index b6da8cb..b96f0a6 100644 --- a/cmd/query/search.go +++ b/cmd/query/search.go @@ -50,7 +50,7 @@ func runSearch(cmd *cobra.Command, _ []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintRawJSON(w, raw) + return output.PrintRawJSON(cmd, raw) } if len(res.Results) == 0 { fmt.Fprintln(w, "No queries found.") diff --git a/cmd/query/update.go b/cmd/query/update.go index 490a7a4..d56ba92 100644 --- a/cmd/query/update.go +++ b/cmd/query/update.go @@ -161,7 +161,7 @@ func runUpdate(cmd *cobra.Command, posArgs []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Updated query %d\n", resp.QueryID) return nil diff --git a/cmd/schedule/delete.go b/cmd/schedule/delete.go index bbf3b0b..4184d5d 100644 --- a/cmd/schedule/delete.go +++ b/cmd/schedule/delete.go @@ -44,7 +44,7 @@ func runDelete(cmd *cobra.Command, _ []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintJSON(w, res) + return output.PrintJSON(cmd, res) } if res.Deleted { fmt.Fprintln(w, "Deleted the schedule") diff --git a/cmd/schedule/list.go b/cmd/schedule/list.go index 8df5814..3d80364 100644 --- a/cmd/schedule/list.go +++ b/cmd/schedule/list.go @@ -42,7 +42,7 @@ func runList(cmd *cobra.Command, _ []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintJSON(w, res) + return output.PrintJSON(cmd, res) } rows := make([][]string, len(res.Schedules)) for i, s := range res.Schedules { diff --git a/cmd/schedule/set.go b/cmd/schedule/set.go index 4b2e38e..16a0441 100644 --- a/cmd/schedule/set.go +++ b/cmd/schedule/set.go @@ -77,7 +77,7 @@ func runSet(cmd *cobra.Command, _ []string) error { } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintJSON(w, res) + return output.PrintJSON(cmd, res) } verb := "Replaced" if res.Created { diff --git a/cmd/usage/usage.go b/cmd/usage/usage.go index e5fe27f..e08dcee 100644 --- a/cmd/usage/usage.go +++ b/cmd/usage/usage.go @@ -65,7 +65,7 @@ func runUsage(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Private Queries: %d\n", resp.PrivateQueries) fmt.Fprintf(w, "Private Dashboards: %d\n", resp.PrivateDashboards) diff --git a/cmd/visualization/chart.go b/cmd/visualization/chart.go index dd9ca7c..f4ec599 100644 --- a/cmd/visualization/chart.go +++ b/cmd/visualization/chart.go @@ -87,7 +87,7 @@ func runChartTool(cmd *cobra.Command, tool string, args map[string]any, verb str } w := cmd.OutOrStdout() if output.FormatFromCmd(cmd) == output.FormatJSON { - return output.PrintRawJSON(w, raw) + return output.PrintRawJSON(cmd, raw) } fmt.Fprintf(w, "%s visualization %d on query %d\n", verb, res.VisualizationID, res.QueryID) fmt.Fprintf(w, "Chart: %s\n", res.InteractiveChartURL) diff --git a/cmd/visualization/create.go b/cmd/visualization/create.go index eef6fc4..81403e7 100644 --- a/cmd/visualization/create.go +++ b/cmd/visualization/create.go @@ -163,7 +163,7 @@ func runCreate(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, map[string]any{ + return output.PrintJSON(cmd, map[string]any{ "id": resp.ID, "url": url, }) diff --git a/cmd/visualization/delete.go b/cmd/visualization/delete.go index 8b5db23..bb705ae 100644 --- a/cmd/visualization/delete.go +++ b/cmd/visualization/delete.go @@ -43,7 +43,7 @@ func runDelete(cmd *cobra.Command, args []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, map[string]any{"ok": true}) + return output.PrintJSON(cmd, map[string]any{"ok": true}) default: fmt.Fprintf(w, "Deleted visualization %d\n", vizID) return nil diff --git a/cmd/visualization/get.go b/cmd/visualization/get.go index 38a354e..08a4006 100644 --- a/cmd/visualization/get.go +++ b/cmd/visualization/get.go @@ -61,7 +61,7 @@ func runGet(cmd *cobra.Command, args []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, struct { + return output.PrintJSON(cmd, struct { *models.GetVisualizationResponse ChartType *string `json:"chart_type"` IsPrivate *bool `json:"is_private"` diff --git a/cmd/visualization/list.go b/cmd/visualization/list.go index 138ff0d..d3f408d 100644 --- a/cmd/visualization/list.go +++ b/cmd/visualization/list.go @@ -48,7 +48,7 @@ func runList(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: rows := make([][]string, len(resp.Results)) for i, v := range resp.Results { diff --git a/cmd/visualization/update.go b/cmd/visualization/update.go index f3d4afa..16a20d7 100644 --- a/cmd/visualization/update.go +++ b/cmd/visualization/update.go @@ -115,7 +115,7 @@ func runUpdate(cmd *cobra.Command, args []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Updated visualization %d\n", resp.ID) return nil diff --git a/cmd/whoami/whoami.go b/cmd/whoami/whoami.go index 1d8a1e5..e356b12 100644 --- a/cmd/whoami/whoami.go +++ b/cmd/whoami/whoami.go @@ -37,7 +37,7 @@ func runWhoAmI(cmd *cobra.Command, _ []string) error { w := cmd.OutOrStdout() switch output.FormatFromCmd(cmd) { case output.FormatJSON: - return output.PrintJSON(w, resp) + return output.PrintJSON(cmd, resp) default: fmt.Fprintf(w, "Handle: %s\n", resp.Handle) fmt.Fprintf(w, "Customer ID: %s\n", resp.CustomerID) diff --git a/output/output.go b/output/output.go index cff4f27..49f591c 100644 --- a/output/output.go +++ b/output/output.go @@ -15,9 +15,12 @@ const ( FormatJSON = "json" ) -// AddFormatFlag registers the -o/--output flag on cmd with the given default. +// AddFormatFlag registers the -o/--output and --compact flags on cmd, with the +// given default format. func AddFormatFlag(cmd *cobra.Command, defaultFormat string) { cmd.Flags().StringP("output", "o", defaultFormat, `output format: "text" or "json"`) + cmd.Flags().Bool("compact", false, + "with -o json, print the JSON on one line without indentation (fewer tokens for agents and scripts)") } // FormatFromCmd reads the output flag value from cmd. @@ -26,24 +29,40 @@ func FormatFromCmd(cmd *cobra.Command) string { return f } -// PrintJSON encodes v as indented JSON and writes it to w. -func PrintJSON(w io.Writer, v any) error { - enc := json.NewEncoder(w) - enc.SetIndent("", " ") +// jsonIndent is the indentation PrintJSON and PrintRawJSON use: none with +// --compact, two spaces otherwise. +func jsonIndent(cmd *cobra.Command) string { + if compact, _ := cmd.Flags().GetBool("compact"); compact { + return "" + } + return " " +} + +// PrintJSON encodes v as JSON, indented unless --compact is set, and writes it +// to cmd's output. +func PrintJSON(cmd *cobra.Command, v any) error { + enc := json.NewEncoder(cmd.OutOrStdout()) + enc.SetIndent("", jsonIndent(cmd)) // Keep URLs and SQL readable: write & < > as they are, not as \u0026 \u003c \u003e. enc.SetEscapeHTML(false) return enc.Encode(v) } // PrintRawJSON writes JSON that is already encoded, such as a Dune MCP tool -// result, indented the same way as PrintJSON. -func PrintRawJSON(w io.Writer, raw json.RawMessage) error { +// result, formatted the same way as PrintJSON. +func PrintRawJSON(cmd *cobra.Command, raw json.RawMessage) error { var buf bytes.Buffer - if err := json.Indent(&buf, raw, "", " "); err != nil { + var err error + if indent := jsonIndent(cmd); indent == "" { + err = json.Compact(&buf, raw) + } else { + err = json.Indent(&buf, raw, "", indent) + } + if err != nil { return err } buf.WriteByte('\n') - _, err := buf.WriteTo(w) + _, err = buf.WriteTo(cmd.OutOrStdout()) return err } diff --git a/output/output_test.go b/output/output_test.go index 5d7f2f8..b632bd8 100644 --- a/output/output_test.go +++ b/output/output_test.go @@ -9,19 +9,45 @@ import ( "github.com/stretchr/testify/require" ) +// jsonCmd returns a command with the format flags, writing to buf. +func jsonCmd(buf *bytes.Buffer, args ...string) *cobra.Command { + cmd := &cobra.Command{} + AddFormatFlag(cmd, "json") + cmd.SetOut(buf) + _ = cmd.ParseFlags(args) + return cmd +} + func TestPrintJSON(t *testing.T) { var buf bytes.Buffer - err := PrintJSON(&buf, map[string]int{"query_id": 42}) + err := PrintJSON(jsonCmd(&buf), map[string]int{"query_id": 42}) require.NoError(t, err) - assert.JSONEq(t, `{"query_id": 42}`, buf.String()) + assert.Equal(t, "{\n \"query_id\": 42\n}\n", buf.String()) // URLs and SQL stay readable instead of turning & < > into \u0026 \u003c \u003e. buf.Reset() - require.NoError(t, PrintJSON(&buf, map[string]string{"url": "https://x/?a=1&b=2", "sql": "SELECT 1 WHERE 1 < 2"})) + v := map[string]string{"url": "https://x/?a=1&b=2", "sql": "SELECT 1 WHERE 1 < 2"} + require.NoError(t, PrintJSON(jsonCmd(&buf), v)) assert.Contains(t, buf.String(), `"https://x/?a=1&b=2"`) assert.Contains(t, buf.String(), `"SELECT 1 WHERE 1 < 2"`) } +func TestCompactJSONIsOneLine(t *testing.T) { + var buf bytes.Buffer + v := map[string]any{"rows": []map[string]any{{"a": 1}, {"a": 2}}, "url": "https://x/?a=1&b=2"} + require.NoError(t, PrintJSON(jsonCmd(&buf, "--compact"), v)) + assert.Equal(t, `{"rows":[{"a":1},{"a":2}],"url":"https://x/?a=1&b=2"}`+"\n", buf.String()) + + buf.Reset() + raw := []byte("{\n \"total\": 1,\n \"results\": [ {\"x\": \"a b\"} ]\n}") + require.NoError(t, PrintRawJSON(jsonCmd(&buf, "--compact"), raw)) + assert.Equal(t, `{"total":1,"results":[{"x":"a b"}]}`+"\n", buf.String()) + + buf.Reset() + require.NoError(t, PrintRawJSON(jsonCmd(&buf), []byte(`{"total":1}`))) + assert.Equal(t, "{\n \"total\": 1\n}\n", buf.String()) +} + func TestPrintTable(t *testing.T) { var buf bytes.Buffer PrintTable(&buf, []string{"ID", "NAME"}, [][]string{ diff --git a/output/results.go b/output/results.go index 5d01a00..7e7a7af 100644 --- a/output/results.go +++ b/output/results.go @@ -12,7 +12,7 @@ func DisplayResults(cmd *cobra.Command, resp *models.ResultsResponse) error { w := cmd.OutOrStdout() if FormatFromCmd(cmd) == FormatJSON { - return PrintJSON(w, resp) + return PrintJSON(cmd, resp) } limit, _ := cmd.Flags().GetInt("limit")