Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ Manage and execute Dune queries.
| `query archive <query-id>` | Archive a saved query |
| `query run <query-id> [--param key=value] [--performance small\|medium\|large] [--limit] [--timeout] [--no-wait]` | Execute a saved query and display results |
| `query run-sql --sql <sql> [--param key=value] [--performance small\|medium\|large] [--limit] [--timeout] [--no-wait]` | Execute raw SQL directly |
| `query results <query-id> [--limit] [--offset]` | Show a saved query's latest stored result without running it |
| `query alert <query-id> --cron <expr> --performance small\|medium\|large --email <addr>... \| --slack-webhook <url> \| --discord-webhook <url> \| --webhook <url>` | Schedule a query and get notified each time a run returns rows |

### `dune matview` (alias: `mv`)
Expand Down
2 changes: 2 additions & 0 deletions cmd/query/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ func NewQueryCmd() *cobra.Command {
" archive - Hide a query from the library (still retrievable by ID)\n" +
" run - Execute a saved query by ID and display results\n" +
" run-sql - Execute raw DuneSQL inline without saving a query\n" +
" results - Show a saved query's latest stored result without running it\n" +
" alert - Schedule a query and get notified when a run returns rows",
}
cmd.AddCommand(newCreateCmd())
Expand All @@ -27,6 +28,7 @@ func NewQueryCmd() *cobra.Command {
cmd.AddCommand(newArchiveCmd())
cmd.AddCommand(newRunCmd())
cmd.AddCommand(newRunSQLCmd())
cmd.AddCommand(newResultsCmd())
cmd.AddCommand(newAlertCmd())
return cmd
}
6 changes: 6 additions & 0 deletions cmd/query/result_preview.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,12 @@ func printExecutionResult(w io.Writer, r executionResult) {
fmt.Fprintf(w, "State: %s\n", r.State)
return
}
// Withheld rows come back as a notice without data; a table would read as
// an empty result.
if r.Data == nil && r.Notice != "" {
fmt.Fprintln(w, r.Notice)
return
}
var columns []string
total := 0
credits := ""
Expand Down
92 changes: 92 additions & 0 deletions cmd/query/results.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package query

import (
"fmt"
"strconv"

"github.com/duneanalytics/cli/cmdutil"
"github.com/duneanalytics/cli/output"
"github.com/spf13/cobra"
)

func newResultsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "results <query-id>",
Short: "Show a saved query's latest stored result without running it",
Long: `Show the rows of the latest completed run of a saved query's current SQL,
whoever started it (you, a schedule, or the API), and when that run happened.

This starts no execution and uses no execution credits, but the result can be
old: check "Executed at". When no run is stored for the current SQL, or the
stored result has expired, the command says so; run the query with
'dune query run <query-id>' to get a fresh result.

For a query with parameters, the stored run may have used other values than the
defaults. They are shown when they are the defaults or you started the run.

Dune withholds rows from enterprise datasets that are not available to AI tools;
Comment thread
rahuldotiyer marked this conversation as resolved.
Resolved
the command then prints the reason and a dune.com link instead.

Examples:
dune query results 12345
dune query results 12345 --limit 1000 --offset 1000 -o json`,
Args: cobra.ExactArgs(1),
RunE: runResults,
}
cmd.Flags().Int("limit", 0, "maximum rows to return, up to 32000 (default 100)")
cmd.Flags().Int("offset", 0, "rows to skip, for the next page")
output.AddFormatFlag(cmd, "text")
return cmd
}

// latestResult is what the Dune MCP's getLatestQueryResult tool returns.
type latestResult struct {
executionResult
QueryURL string `json:"queryUrl"`
ExecutedAt string `json:"executedAt"`
Parameters []struct {
Key string `json:"key"`
Value any `json:"value"`
} `json:"parameters"`
}

func runResults(cmd *cobra.Command, args []string) error {
queryID, err := strconv.Atoi(args[0])
if err != nil || queryID <= 0 {
return fmt.Errorf("invalid query ID %q: must be a positive integer", args[0])
}
toolArgs := cmdutil.ToolArgs(cmd, map[string]string{"limit": "limit", "offset": "offset"})
toolArgs["query_id"] = queryID

var res latestResult
raw, err := cmdutil.CallTool(cmd, "getLatestQueryResult", toolArgs, &res)
if err != nil {
return err
}
w := cmd.OutOrStdout()
if output.FormatFromCmd(cmd) == output.FormatJSON {
Comment thread
rahuldotiyer marked this conversation as resolved.
Resolved
// A failed stored run still fails the command, so scripts see it.
if err := output.PrintRawJSON(w, raw); err != nil {
return err
}
return res.Err()
}
if err := res.Err(); err != nil {
return err
}
// No stored run: the tool returns only the query and a notice.
if res.State == "" {
fmt.Fprintf(w, "%s\n%s\n", res.Notice, res.QueryURL)
return nil
}
fmt.Fprintf(w, "Query: %s\n", res.QueryURL)
if res.ExecutedAt != "" {
fmt.Fprintf(w, "Executed at: %s\n", res.ExecutedAt)
}
for _, p := range res.Parameters {
fmt.Fprintf(w, "Parameter: %s = %v\n", p.Key, p.Value)
}
fmt.Fprintln(w)
printExecutionResult(w, res.executionResult)
Comment thread
rahuldotiyer marked this conversation as resolved.
Resolved
return nil
}
67 changes: 67 additions & 0 deletions cmd/query/results_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package query_test

import (
"testing"

"github.com/duneanalytics/cli/dunemcp/dunemcptest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func runResults(fake *dunemcptest.Fake, args ...string) (string, error) {
root, buf := newMCPRoot(fake)
root.SetArgs(append([]string{"query", "results"}, args...))
err := root.Execute()
return buf.String(), err
}

func TestResultsShowsStoredRunWithItsAge(t *testing.T) {
fake := &dunemcptest.Fake{Results: map[string]string{"getLatestQueryResult": `{"queryId":42,
"queryUrl":"https://dune.com/queries/42","executedAt":"2026-11-29T08:00:00Z",
"parameters":[{"key":"chain","value":"base"}],"executionId":"01E","state":"COMPLETED",
"resultMetadata":{"columns":[{"name":"n"}],"totalRowCount":3},"data":{"rows":[{"n":7}]}}`}}
out, err := runResults(fake, "42", "--limit", "1")
require.NoError(t, err)
// Only the flags the user set are sent, so the server's defaults apply to the rest.
assert.JSONEq(t, `{"query_id":42,"limit":1}`, fake.Last().Args)
assert.Contains(t, out, "Executed at: 2026-11-29T08:00:00Z")
assert.Contains(t, out, "Parameter: chain = base")
assert.Contains(t, out, "1 of 3 rows")
}

func TestResultsWithoutStoredRunPrintsTheNotice(t *testing.T) {
fake := &dunemcptest.Fake{Results: map[string]string{"getLatestQueryResult": `{"queryId":42,
"queryUrl":"https://dune.com/queries/42","notice":"This query has no stored result for its current SQL."}`}}
out, err := runResults(fake, "42")
require.NoError(t, err)
assert.Equal(t, "This query has no stored result for its current SQL.\nhttps://dune.com/queries/42\n", out)
}

func TestResultsWithheldRowsShowTheNotice(t *testing.T) {
fake := &dunemcptest.Fake{Results: map[string]string{"getLatestQueryResult": `{"queryId":42,
"queryUrl":"https://dune.com/queries/42","executedAt":"2026-11-29T08:00:00Z","executionId":"01E",
"state":"COMPLETED","notice":"Rows withheld: licensed dataset. See https://dune.com/queries/42"}`}}
out, err := runResults(fake, "42")
require.NoError(t, err)
assert.Contains(t, out, "Rows withheld: licensed dataset")
assert.NotContains(t, out, "0 of 0 rows")
}

func TestResultsFailedRunIsAnError(t *testing.T) {
fake := &dunemcptest.Fake{Results: map[string]string{"getLatestQueryResult": `{"queryId":42,
"executionId":"01E","state":"FAILED","errorMessage":"line 1: syntax error"}`}}
_, err := runResults(fake, "42")
assert.EqualError(t, err, "execution 01E failed: line 1: syntax error")

// -o json prints the result and still fails, so scripts see the failure.
out, err := runResults(fake, "42", "-o", "json")
assert.EqualError(t, err, "execution 01E failed: line 1: syntax error")
assert.Contains(t, out, `"state": "FAILED"`)
}

func TestResultsRejectsBadQueryID(t *testing.T) {
fake := &dunemcptest.Fake{}
_, err := runResults(fake, "abc")
require.Error(t, err)
assert.Empty(t, fake.Calls)
}
Loading