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
12 changes: 3 additions & 9 deletions internal/cli/root.go → cli/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,20 @@ import (

"github.com/charmbracelet/fang"
"github.com/duneanalytics/cli/cmd/query"
"github.com/duneanalytics/cli/cmdutil"
"github.com/duneanalytics/duneapi-client-go/config"
"github.com/duneanalytics/duneapi-client-go/dune"
"github.com/spf13/cobra"
)

type clientKey struct{}

var apiKeyFlag string

var rootCmd = &cobra.Command{
Use: "dune",
Short: "Dune CLI — interact with the Dune Analytics API",
Long: "A command-line interface for interacting with the Dune Analytics API.\n" +
"Manage queries, execute them, and retrieve results.",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
var env *config.Env

switch {
Expand All @@ -36,7 +35,7 @@ var rootCmd = &cobra.Command{
}

client := dune.NewDuneClient(env)
cmd.SetContext(context.WithValue(cmd.Context(), clientKey{}, dune.DuneClient(client)))
cmdutil.SetClient(cmd, client)
return nil
},
}
Expand All @@ -46,11 +45,6 @@ func init() {
rootCmd.AddCommand(query.NewQueryCmd())
}

// ClientFromCmd extracts the DuneClient stored in the command's context.
func ClientFromCmd(cmd *cobra.Command) dune.DuneClient {
return cmd.Context().Value(clientKey{}).(dune.DuneClient)
}

// Execute runs the root command via Fang.
func Execute() {
if err := fang.Execute(context.Background(), rootCmd); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package main

import "github.com/duneanalytics/cli/internal/cli"
import "github.com/duneanalytics/cli/cli"

func main() {
cli.Execute()
Expand Down
56 changes: 56 additions & 0 deletions cmd/query/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package query

import (
"fmt"

"github.com/duneanalytics/cli/cmdutil"
"github.com/duneanalytics/cli/output"
"github.com/duneanalytics/duneapi-client-go/models"
"github.com/spf13/cobra"
)

func newCreateCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "create",
Short: "Create a new saved query",
RunE: runCreate,
}

cmd.Flags().String("name", "", "query name (required)")
cmd.Flags().String("sql", "", "query SQL (required)")
cmd.Flags().String("description", "", "query description")
cmd.Flags().Bool("private", false, "make the query private")
_ = cmd.MarkFlagRequired("name")
_ = cmd.MarkFlagRequired("sql")
output.AddFormatFlag(cmd, "text")

return cmd
}

func runCreate(cmd *cobra.Command, _ []string) error {
client := cmdutil.ClientFromCmd(cmd)

name, _ := cmd.Flags().GetString("name")
sql, _ := cmd.Flags().GetString("sql")
description, _ := cmd.Flags().GetString("description")
private, _ := cmd.Flags().GetBool("private")

resp, err := client.CreateQuery(models.CreateQueryRequest{
Name: name,
QuerySQL: sql,
Description: description,
IsPrivate: private,
})
if err != nil {
return err
}

w := cmd.OutOrStdout()
switch output.FormatFromCmd(cmd) {
case output.FormatJSON:
return output.PrintJSON(w, resp)
default:
fmt.Fprintf(w, "Created query %d\n", resp.QueryID)
return nil
}
}
132 changes: 132 additions & 0 deletions cmd/query/create_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package query_test

import (
"bytes"
"context"
"encoding/json"
"errors"
"testing"

"github.com/duneanalytics/cli/cmd/query"
"github.com/duneanalytics/cli/cmdutil"
"github.com/duneanalytics/duneapi-client-go/dune"
"github.com/duneanalytics/duneapi-client-go/models"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// mockClient embeds the interface so unimplemented methods panic.
type mockClient struct {
dune.DuneClient
createQueryFn func(models.CreateQueryRequest) (*models.CreateQueryResponse, error)
}

func (m *mockClient) CreateQuery(req models.CreateQueryRequest) (*models.CreateQueryResponse, error) {
return m.createQueryFn(req)
}

// newTestRoot builds a root → query → create command tree with the mock injected.
func newTestRoot(mock dune.DuneClient) (*cobra.Command, *bytes.Buffer) {
root := &cobra.Command{
Use: "dune",
PersistentPreRun: func(cmd *cobra.Command, _ []string) {
cmdutil.SetClient(cmd, mock)
},
}
root.SetContext(context.Background())

root.AddCommand(query.NewQueryCmd())

var buf bytes.Buffer
root.SetOut(&buf)

return root, &buf
}

func TestCreateSuccess(t *testing.T) {
mock := &mockClient{
createQueryFn: func(req models.CreateQueryRequest) (*models.CreateQueryResponse, error) {
assert.Equal(t, "Test", req.Name)
assert.Equal(t, "SELECT 1", req.QuerySQL)
return &models.CreateQueryResponse{QueryID: 4125432}, nil
},
}

root, buf := newTestRoot(mock)
root.SetArgs([]string{"query", "create", "--name", "Test", "--sql", "SELECT 1"})
require.NoError(t, root.Execute())
assert.Equal(t, "Created query 4125432\n", buf.String())
}

func TestCreateJSONOutput(t *testing.T) {
mock := &mockClient{
createQueryFn: func(_ models.CreateQueryRequest) (*models.CreateQueryResponse, error) {
return &models.CreateQueryResponse{QueryID: 4125432}, nil
},
}

root, buf := newTestRoot(mock)
root.SetArgs([]string{"query", "create", "--name", "Test", "--sql", "SELECT 1", "-o", "json"})
require.NoError(t, root.Execute())

var got map[string]int
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
assert.Equal(t, 4125432, got["query_id"])
}

func TestCreatePrivateFlag(t *testing.T) {
mock := &mockClient{
createQueryFn: func(req models.CreateQueryRequest) (*models.CreateQueryResponse, error) {
assert.True(t, req.IsPrivate)
return &models.CreateQueryResponse{QueryID: 1}, nil
},
}

root, _ := newTestRoot(mock)
root.SetArgs([]string{"query", "create", "--name", "T", "--sql", "S", "--private"})
require.NoError(t, root.Execute())
}

func TestCreateDescriptionFlag(t *testing.T) {
mock := &mockClient{
createQueryFn: func(req models.CreateQueryRequest) (*models.CreateQueryResponse, error) {
assert.Equal(t, "my desc", req.Description)
return &models.CreateQueryResponse{QueryID: 1}, nil
},
}

root, _ := newTestRoot(mock)
root.SetArgs([]string{"query", "create", "--name", "T", "--sql", "S", "--description", "my desc"})
require.NoError(t, root.Execute())
}

func TestCreateMissingName(t *testing.T) {
root, _ := newTestRoot(&mockClient{})
root.SetArgs([]string{"query", "create", "--sql", "SELECT 1"})
err := root.Execute()
require.Error(t, err)
assert.Contains(t, err.Error(), `required flag(s) "name" not set`)
}

func TestCreateMissingSQL(t *testing.T) {
root, _ := newTestRoot(&mockClient{})
root.SetArgs([]string{"query", "create", "--name", "Test"})
err := root.Execute()
require.Error(t, err)
assert.Contains(t, err.Error(), `required flag(s) "sql" not set`)
}

func TestCreateAPIError(t *testing.T) {
mock := &mockClient{
createQueryFn: func(_ models.CreateQueryRequest) (*models.CreateQueryResponse, error) {
return nil, errors.New("api: unauthorized")
},
}

root, _ := newTestRoot(mock)
root.SetArgs([]string{"query", "create", "--name", "T", "--sql", "S"})
err := root.Execute()
require.Error(t, err)
assert.Contains(t, err.Error(), "api: unauthorized")
}
4 changes: 3 additions & 1 deletion cmd/query/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import "github.com/spf13/cobra"

// NewQueryCmd returns the `query` parent command.
func NewQueryCmd() *cobra.Command {
return &cobra.Command{
cmd := &cobra.Command{
Use: "query",
Short: "Manage Dune queries",
}
cmd.AddCommand(newCreateCmd())
return cmd
}
24 changes: 24 additions & 0 deletions cmdutil/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package cmdutil

import (
"context"

"github.com/duneanalytics/duneapi-client-go/dune"
"github.com/spf13/cobra"
)

type clientKey struct{}

// SetClient stores a DuneClient in the command's context.
func SetClient(cmd *cobra.Command, client dune.DuneClient) {
ctx := cmd.Context()
if ctx == nil {
ctx = context.Background()
}
cmd.SetContext(context.WithValue(ctx, clientKey{}, client))
}

// ClientFromCmd extracts the DuneClient stored in the command's context.
func ClientFromCmd(cmd *cobra.Command) dune.DuneClient {
return cmd.Context().Value(clientKey{}).(dune.DuneClient)
}
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ require (
github.com/charmbracelet/fang v0.4.4
github.com/duneanalytics/duneapi-client-go v0.4.0
github.com/spf13/cobra v1.10.2
github.com/stretchr/testify v1.11.1
)

require (
Expand All @@ -20,6 +21,7 @@ require (
github.com/clipperhouse/displaywidth v0.4.1 // indirect
github.com/clipperhouse/stringish v0.1.1 // indirect
github.com/clipperhouse/uax29/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
github.com/mattn/go-runewidth v0.0.19 // indirect
Expand All @@ -28,10 +30,12 @@ require (
github.com/muesli/mango-cobra v1.2.0 // indirect
github.com/muesli/mango-pflag v0.1.0 // indirect
github.com/muesli/roff v0.1.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/spf13/pflag v1.0.9 // indirect
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
golang.org/x/sync v0.17.0 // indirect
golang.org/x/sys v0.37.0 // indirect
golang.org/x/text v0.24.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
5 changes: 3 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
Expand All @@ -69,6 +69,7 @@ golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Loading