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
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,16 +104,16 @@ Create and manage visualizations on saved queries.

| Command | Description |
|---------|-------------|
| `viz create --query-id <id> --name <name> --chart-type <type> --config <json>` | Create a chart from a compact chart config |
| `viz create --query-id <id> --name <name> --chart-type <type> --config <json> [--description]` | Create a chart from a compact chart config |
| `viz create --query-id <id> --name <name> --options <json> [--type chart\|table\|counter\|...]` | Create a visualization from raw Dune options |
| `viz get <visualization-id>` | Get a visualization's details, options, chart type, and chart and image links |
| `viz update <visualization-id> [--name] [--chart-type <type> --config <json>] [--type] [--description] [--options]` | Update an existing visualization |
| `viz update <visualization-id> [--name] [--description] [--counter-label] [--chart-type <type> --config <json>] [--type] [--options]` | Update an existing visualization |
| `viz delete <visualization-id>` | Permanently delete a visualization |
| `viz list --query-id <id> [--limit] [--offset]` | List all visualizations for a query |

Supported types: `chart`, `table`, `counter`, `pivot`, `cohort`, `funnel`, `choropleth`, `sankey`, `sunburst_sequence`, `word_cloud`.

`--chart-type` is one of `column`, `line`, `area`, `scatter`, `pie`, `counter`, or `table`, and `--config` describes the axes and series (run `dune viz create --help` for its format). Column names must match the query's result columns exactly. Dune does not check them, so look at the columns first with `dune execution results`. `--config` and `--options` accept inline JSON, `@path`, or `@-` for standard input.
`--chart-type` is one of `column`, `line`, `area`, `scatter`, `pie`, `counter`, or `table`, and `--config` describes the axes and series (run `dune viz create --help` for its format). Column names must match the query's result columns exactly; when the query has completed results, Dune rejects a config that names other columns. Look at the columns first with `dune execution results`. `--config` and `--options` accept inline JSON, `@path`, or `@-` for standard input.

### `dune dashboard` (alias: `dash`)

Expand All @@ -124,6 +124,8 @@ Create and manage dashboards.
| `dashboard create --name <name> [--visualization-ids 1,2,3] [--text-widgets <json>] [--columns-per-row 1\|2\|3] [--private]` | Create a new dashboard |
| `dashboard get <dashboard-id>` or `dashboard get --owner <handle> --slug <slug>` | Get a dashboard's details and widgets |
| `dashboard update <dashboard-id> [--name] [--slug] [--private] [--tags] [--visualization-widgets <json>] [--text-widgets <json>]` | Update an existing dashboard |
| `dashboard update-widget <dashboard-id> --widget-type visualization\|text\|param --widget-id <id> [--row --col --size-x --size-y] [--text <md>]` | Move or resize one widget, or edit a text widget, keeping the others |
| `dashboard image <dashboard-id> [--file <path>]` | Save a JPEG of the whole dashboard to check its layout |
| `dashboard archive <dashboard-id>` | Archive a dashboard |
| `dashboard search --query <text> [--owned-only] [--limit]` | Find dashboards by name |

Expand Down
2 changes: 2 additions & 0 deletions cmd/dashboard/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ func NewDashboardCmd() *cobra.Command {
cmd.AddCommand(newCreateCmd())
cmd.AddCommand(newGetCmd())
cmd.AddCommand(newUpdateCmd())
cmd.AddCommand(newUpdateWidgetCmd())
cmd.AddCommand(newImageCmd())
cmd.AddCommand(newArchiveCmd())
cmd.AddCommand(newSearchCmd())

Expand Down
137 changes: 137 additions & 0 deletions cmd/dashboard/image.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package dashboard

import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"

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

func newImageCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "image <dashboard_id>",
Short: "Save a JPEG image of a whole dashboard",
Long: `Render a whole dashboard as dune.com shows it and save it as a JPEG file, to
check its layout after 'dune dashboard update' or 'dune dashboard update-widget'.

The image uses each query's latest completed results; it does not run any query.
Rendering takes several seconds.

Dune withholds the image when a chart on the dashboard shows enterprise datasets
that are not available to AI tools, or a query that has never completed; the
command then fails and lists those visualizations.

For a private dashboard, rendering needs a share link: Dune reuses the
dashboard's active share link or creates one, as the Share button on dune.com
does. The command never prints that link.

Examples:
dune dashboard image 12345
dune dashboard image 12345 --file layout.jpg`,
Args: cobra.ExactArgs(1),
RunE: runImage,
}

cmd.Flags().String("file", "", "where to save the JPEG (default dashboard-<id>.jpg)")
output.AddFormatFlag(cmd, "text")

return cmd
}

type dashboardImage struct {
DashboardID int `json:"dashboardId"`
DashboardURL string `json:"dashboardUrl"`
DashboardImageURL string `json:"dashboardImageUrl"`
WithheldVisualizationIDs []int `json:"withheldVisualizationIds"`
}

func runImage(cmd *cobra.Command, args []string) error {
dashboardID, err := strconv.Atoi(args[0])
if err != nil {
return fmt.Errorf("invalid dashboard ID %q: must be an integer", args[0])
}
path, _ := cmd.Flags().GetString("file")
if path == "" {
path = fmt.Sprintf("dashboard-%d.jpg", dashboardID)
}

var res dashboardImage
raw, images, err := cmdutil.CallToolWithImages(cmd, "getDashboardImage", map[string]any{"dashboardId": dashboardID}, &res)
if err != nil {
return err
}
if len(res.WithheldVisualizationIDs) > 0 {
ids := make([]string, len(res.WithheldVisualizationIDs))
for i, id := range res.WithheldVisualizationIDs {
ids[i] = strconv.Itoa(id)
}
return fmt.Errorf("the image is withheld because visualizations %s show enterprise datasets "+
"that are not available to AI tools, or a query that has never completed", strings.Join(ids, ", "))
}

var jpeg []byte
switch {
case len(images) > 0:
jpeg = images[0]
case res.DashboardImageURL != "":
// The tool leaves out images larger than it returns inline.
if jpeg, err = download(cmd, res.DashboardImageURL); err != nil {
return err
}
default:
return fmt.Errorf("getDashboardImage returned no image for dashboard %d", dashboardID)
}
if err := os.WriteFile(path, jpeg, 0o644); err != nil {
return err
}

w := cmd.OutOrStdout()
if output.FormatFromCmd(cmd) == output.FormatJSON {
// The image URL of a private dashboard carries its share key, so it is left out.
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
return err
}
delete(out, "dashboardImageUrl")
delete(out, "imageIncluded")
out["file"] = path
return output.PrintJSON(w, out)
}
fmt.Fprintf(w, "Saved an image of dashboard %d to %s\n", dashboardID, path)
fmt.Fprintf(w, "Dashboard: %s\n", res.DashboardURL)
return nil
}

func download(cmd *cobra.Command, imageURL string) ([]byte, error) {
req, err := http.NewRequestWithContext(cmd.Context(), http.MethodGet, imageURL, nil)
if err != nil {
return nil, errors.New("getDashboardImage returned an invalid image URL")
}
resp, err := http.DefaultClient.Do(req)
Comment thread
rahuldotiyer marked this conversation as resolved.
Resolved
if err != nil {
// Drop the URL from the error: it may carry the dashboard's share key.
var urlErr *url.Error
if errors.As(err, &urlErr) {
err = urlErr.Err
}
return nil, fmt.Errorf("downloading the dashboard image: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("downloading the dashboard image failed: %s", resp.Status)
}
// A 200 with an HTML error or login page must not be saved as the image.
if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "image/") {
return nil, fmt.Errorf("downloading the dashboard image failed: got %q instead of an image", ct)
}
return io.ReadAll(resp.Body)
Comment thread
rahuldotiyer marked this conversation as resolved.
Resolved
}
109 changes: 109 additions & 0 deletions cmd/dashboard/update_widget.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package dashboard

import (
"errors"
"fmt"
"strconv"

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

// positionArgs maps the position flags to the fields of the tool's position.
var positionArgs = map[string]string{"row": "row", "col": "col", "size-x": "sizeX", "size-y": "sizeY"}

func newUpdateWidgetCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "update-widget <dashboard_id>",
Short: "Move or resize one widget, or edit a text widget's markdown",
Long: `Change one widget on a dashboard. Every other widget keeps its content and
position, so unlike 'dune dashboard update' there is no need to send them all.

Get the widget's ID and type from 'dune dashboard get <id> -o json':
visualization an entry in visualization_widgets (numeric widget_id)
text an entry in text_widgets (numeric widget_id)
param an entry in param_widgets (UUID widget_id)

Give a new position (all of --row, --col, --size-x and --size-y), new --text
for a text widget, or both. The grid has 6 columns; one row is 32 px and charts
are 8 rows high by default.

To add or remove widgets, use 'dune dashboard update'. To change a chart's
title, description, or counter label, use 'dune viz update'.

Examples:
dune dashboard update-widget 12345 --widget-type visualization --widget-id 678 \
--row 0 --col 0 --size-x 6 --size-y 8
dune dashboard update-widget 12345 --widget-type text --widget-id 679 --text @intro.md`,
Args: cobra.ExactArgs(1),
RunE: runUpdateWidget,
}

cmd.Flags().String("widget-type", "", "visualization, text, or param (required)")
cmd.Flags().String("widget-id", "", "the widget_id from 'dune dashboard get' (required)")
cmd.Flags().Int("row", 0, "top edge, in grid rows from the top (0 is the top)")
cmd.Flags().Int("col", 0, "left edge, in grid columns from the left (0 to 5)")
cmd.Flags().Int("size-x", 0, "width in grid columns (1 to 6)")
cmd.Flags().Int("size-y", 0, "height in grid rows")
cmd.Flags().String("text", "", "new markdown for a text widget: inline, @path, or @-")
_ = cmd.MarkFlagRequired("widget-type")
_ = cmd.MarkFlagRequired("widget-id")
cmd.MarkFlagsRequiredTogether("row", "col", "size-x", "size-y")
output.AddFormatFlag(cmd, "text")

return cmd
}

func runUpdateWidget(cmd *cobra.Command, args []string) error {
dashboardID, err := strconv.Atoi(args[0])
if err != nil {
return fmt.Errorf("invalid dashboard ID %q: must be an integer", args[0])
}
widgetType, _ := cmd.Flags().GetString("widget-type")
idFlag, _ := cmd.Flags().GetString("widget-id")

var widgetID any = idFlag
switch widgetType {
case "visualization", "text":
if widgetID, err = strconv.Atoi(idFlag); err != nil {
return fmt.Errorf("invalid --widget-id %q: %s widgets have integer IDs", idFlag, widgetType)
}
case "param":
default:
return fmt.Errorf("invalid --widget-type %q: must be visualization, text, or param", widgetType)
}

toolArgs := map[string]any{"dashboardId": dashboardID, "widgetType": widgetType, "widgetId": widgetID}
if cmd.Flags().Changed("row") {
position := map[string]any{}
for flag, field := range positionArgs {
position[field], _ = cmd.Flags().GetInt(flag)
}
toolArgs["position"] = position
}
if cmd.Flags().Changed("text") {
text, err := cmdutil.FileFlag(cmd, "text")
if err != nil {
return err
}
toolArgs["text"] = string(text)
}
if toolArgs["position"] == nil && toolArgs["text"] == nil {
return errors.New("provide a new position (--row, --col, --size-x and --size-y), --text, or both")
}

var res struct {
DashboardURL string `json:"dashboardUrl"`
}
raw, err := cmdutil.CallTool(cmd, "updateDashboardWidget", toolArgs, &res)
if err != nil {
return err
}
w := cmd.OutOrStdout()
if output.FormatFromCmd(cmd) == output.FormatJSON {
return output.PrintRawJSON(w, raw)
}
fmt.Fprintf(w, "Updated %s widget %s on dashboard %d\n%s\n", widgetType, idFlag, dashboardID, res.DashboardURL)
return nil
}
Loading
Loading