Skip to content

Commit 9b26693

Browse files
authored
SQL utils: Fix error source when unmarhsaling invalid query object (#1222)
1 parent 8da6c1b commit 9b26693

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

data/sqlutil/query.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ func GetQuery(query backend.DataQuery) (*Query, error) {
7171
model := &Query{}
7272

7373
if err := json.Unmarshal(query.JSON, &model); err != nil {
74-
return nil, fmt.Errorf("%w: %v", ErrorJSON, err)
74+
return nil, backend.DownstreamError(fmt.Errorf("%w: %v", ErrorJSON, err))
7575
}
7676

7777
// Copy directly from the well typed query

data/sqlutil/query_test.go

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ import (
1212
"github.com/grafana/grafana-plugin-sdk-go/data/sqlutil"
1313
)
1414

15-
func TestQuery(t *testing.T) {
16-
t.Run("GetQuery", func(t *testing.T) {
15+
func TestGetQuery(t *testing.T) {
16+
t.Run("returns correct query", func(t *testing.T) {
1717
timeRange := backend.TimeRange{From: time.Now().Add(-time.Hour), To: time.Now()}
1818
dataQuery := backend.DataQuery{
1919
RefID: "foo",
@@ -45,4 +45,23 @@ func TestQuery(t *testing.T) {
4545
assert.Equal(t, parsedQuery.Table, "y")
4646
assert.Equal(t, parsedQuery.Column, "z")
4747
})
48+
49+
t.Run("returns error if invalid query", func(t *testing.T) {
50+
timeRange := backend.TimeRange{From: time.Now().Add(-time.Hour), To: time.Now()}
51+
dataQuery := backend.DataQuery{
52+
RefID: "foo",
53+
MaxDataPoints: 10,
54+
Interval: time.Second,
55+
TimeRange: timeRange,
56+
// invalid JSON, rawSql should be a string
57+
JSON: json.RawMessage(`{
58+
"rawSql": 1,
59+
}`),
60+
}
61+
62+
_, err := sqlutil.GetQuery(dataQuery)
63+
assert.Error(t, err)
64+
assert.ErrorContains(t, err, "error unmarshaling query JSON to the Query Model")
65+
assert.True(t, backend.IsDownstreamError(err))
66+
})
4867
}

0 commit comments

Comments
 (0)