Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: supported query variable, better default settings #8

Merged
merged 7 commits into from
Jan 8, 2025
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
5 changes: 3 additions & 2 deletions pkg/plugin/datasource.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ func (d *Datasource) QueryData(ctx context.Context, req *backend.QueryDataReques
frame.SetMeta(&data.FrameMeta{Channel: channel.String()})
resp.Frames = append(resp.Frames, frame)
} else {
count := 0
columnTypes, ch, err := d.engine.RunQuery(ctx, q.SQL)
if err != nil {
return nil, err
Expand All @@ -89,7 +90,7 @@ func (d *Datasource) QueryData(ctx context.Context, req *backend.QueryDataReques
return nil, ctx.Err()
case row, ok := <-ch:
if !ok {
logger.Info("Query finished")
logger.Info("Query finished", "count", count)

resp.Frames = append(resp.Frames, frame)
break LOOP
Expand All @@ -99,6 +100,7 @@ func (d *Datasource) QueryData(ctx context.Context, req *backend.QueryDataReques
for i, r := range row {
col := columnTypes[i]
fData[i] = timeplus.ParseValue(col.Name(), col.DatabaseTypeName(), nil, r, false)
count++
}

frame.AppendRow(fData...)
Expand Down Expand Up @@ -206,7 +208,6 @@ func (d *Datasource) CheckHealth(ctx context.Context, req *backend.CheckHealthRe
res.Message = "'Host' cannot be empty"
return res, nil
}

engine := timeplus.NewEngine(logger, config.Host, config.TCPPort, config.HTTPPort, config.Username, config.Secrets.Password)

if err := engine.Ping(ctx); err != nil {
Expand Down
21 changes: 20 additions & 1 deletion pkg/timeplus/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ type TimeplusEngine struct {
}

func NewEngine(logger log.Logger, host string, tcpPort, httpPort int, username, password string) *TimeplusEngine {
if tcpPort == 0 {
tcpPort = 8463
}
if httpPort == 0 {
httpPort = 3218
}
if len(username) == 0 {
username = "default"
}

connection := protonDriver.OpenDB(&protonDriver.Options{
Addr: []string{fmt.Sprintf("%s:%d", host, tcpPort)},
Auth: protonDriver.Auth{
Expand Down Expand Up @@ -150,7 +160,16 @@ func (e *TimeplusEngine) IsStreamingQuery(ctx context.Context, query string) (bo
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 399 {
return false, fmt.Errorf("failed to analyze %d", resp.StatusCode)
var errStr string

body, err := io.ReadAll(resp.Body)
if err != nil {
errStr = err.Error()
} else {
errStr = string(body)
}

return false, fmt.Errorf("failed to analyze code: %d, error: %s", resp.StatusCode, errStr)
}

body, err := io.ReadAll(resp.Body)
Expand Down
133 changes: 114 additions & 19 deletions provisioning/dashboards/carsharing.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,70 @@
"links": [],
"liveNow": false,
"panels": [
{
"datasource": {
"default": true,
"type": "timeplus-proton-datasource",
"uid": "proton-ds"
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "thresholds"
},
"mappings": [],
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
},
{
"color": "red",
"value": 80
}
]
}
},
"overrides": []
},
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 0
},
"id": 5,
"options": {
"colorMode": "value",
"graphMode": "area",
"justifyMode": "auto",
"orientation": "auto",
"percentChangeColorMode": "standard",
"reduceOptions": {
"calcs": ["lastNotNull"],
"fields": "",
"values": false
},
"showPercentChange": false,
"textMode": "auto",
"wideLayout": true
},
"pluginVersion": "11.2.2",
"targets": [
{
"datasource": {
"type": "timeplus-proton-datasource",
"uid": "proton-ds"
},
"refId": "A",
"sql": "select count(*) from table(bookings) where _tp_time < to_datetime($__to/1000) and _tp_time > to_datetime($__from/1000) and cid='$cid'"
}
],
"title": "Total bookings for car $cid between $__from and $__to",
"type": "stat"
},
{
"datasource": {
"type": "timeplus-proton-datasource",
Expand Down Expand Up @@ -57,7 +121,7 @@
"h": 6,
"w": 3,
"x": 0,
"y": 0
"y": 8
},
"id": 1,
"options": {
Expand All @@ -70,16 +134,16 @@
},
"showHeader": true
},
"pluginVersion": "10.2.3",
"pluginVersion": "11.2.2",
"targets": [
{
"addNow": false,
"datasource": {
"type": "timeplus-proton-datasource",
"uid": "proton-ds"
},
"sql": "select now()",
"refId": "A"
"refId": "A",
"sql": "select now()"
}
],
"title": "select now()",
Expand Down Expand Up @@ -112,32 +176,34 @@
"h": 6,
"w": 7,
"x": 3,
"y": 0
"y": 8
},
"id": 2,
"options": {
"colorMode": "value",
"graphMode": "area",
"justifyMode": "auto",
"orientation": "auto",
"percentChangeColorMode": "standard",
"reduceOptions": {
"calcs": ["lastNotNull"],
"fields": "",
"values": false
},
"showPercentChange": false,
"textMode": "auto",
"wideLayout": true
},
"pluginVersion": "10.2.3",
"pluginVersion": "11.2.2",
"targets": [
{
"addNow": false,
"datasource": {
"type": "timeplus-proton-datasource",
"uid": "proton-ds"
},
"sql": "select count() from car_live_data",
"refId": "A"
"refId": "A",
"sql": "select count() from car_live_data"
}
],
"title": "select count() from car_live_data",
Expand Down Expand Up @@ -170,32 +236,34 @@
"h": 6,
"w": 14,
"x": 10,
"y": 0
"y": 8
},
"id": 3,
"options": {
"colorMode": "value",
"graphMode": "area",
"justifyMode": "auto",
"orientation": "auto",
"percentChangeColorMode": "standard",
"reduceOptions": {
"calcs": ["lastNotNull"],
"fields": "",
"values": false
},
"showPercentChange": false,
"textMode": "auto",
"wideLayout": true
},
"pluginVersion": "10.2.3",
"pluginVersion": "11.2.2",
"targets": [
{
"addNow": false,
"datasource": {
"type": "timeplus-proton-datasource",
"uid": "proton-ds"
},
"sql": "select count() from car_live_data where _tp_time>earliest_ts()",
"refId": "A"
"refId": "A",
"sql": "select count() from car_live_data where _tp_time>earliest_ts()"
}
],
"title": "select count() from car_live_data where _tp_time>earliest_ts()",
Expand Down Expand Up @@ -239,7 +307,7 @@
"h": 9,
"w": 24,
"x": 0,
"y": 6
"y": 14
},
"id": 4,
"options": {
Expand Down Expand Up @@ -307,16 +375,16 @@
"zoom": 12
}
},
"pluginVersion": "10.2.3",
"pluginVersion": "11.2.2",
"targets": [
{
"addNow": false,
"datasource": {
"type": "timeplus-proton-datasource",
"uid": "proton-ds"
},
"sql": "select longitude, latitude,speed_kmh,cid from car_live_data where cid like '%1'",
"refId": "A"
"refId": "A",
"sql": "select longitude, latitude,speed_kmh,cid from car_live_data where cid like '%1'"
}
],
"title": "Panel Title",
Expand All @@ -327,16 +395,43 @@
"schemaVersion": 39,
"tags": [],
"templating": {
"list": []
"list": [
{
"current": {
"selected": true,
"text": "c00000",
"value": "c00000"
},
"datasource": {
"type": "timeplus-proton-datasource",
"uid": "proton-ds"
},
"definition": "select cid from table(car_live_data) where _tp_time < to_datetime($__to/1000) and _tp_time > to_datetime($__from/1000)",
"hide": 0,
"includeAll": false,
"label": "Car ID",
"multi": false,
"name": "cid",
"options": [],
"query": {
"query": "select cid from table(car_live_data) where _tp_time < to_datetime($__to/1000) and _tp_time > to_datetime($__from/1000)"
},
"refresh": 2,
"regex": "",
"skipUrlSync": false,
"sort": 0,
"type": "query"
}
]
},
"time": {
"from": "now-6h",
"from": "now-1h",
"to": "now"
},
"timepicker": {},
"timezone": "",
"title": "Carsharing Demo Dashboard",
"uid": "dd9e271d-7225-47d4-9e57-62133db0df62",
"version": 4,
"version": 1,
"weekStart": ""
}
10 changes: 6 additions & 4 deletions src/components/ConfigEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import React, { ChangeEvent } from 'react';
import { InlineField, Input, SecretInput } from '@grafana/ui';
import { DataSourcePluginOptionsEditorProps } from '@grafana/data';
import React, { ChangeEvent } from 'react';
import { TpDataSourceOptions, TpSecureJsonData } from '../types';

import { DataSourcePluginOptionsEditorProps } from '@grafana/data';

interface Props extends DataSourcePluginOptionsEditorProps<TpDataSourceOptions, TpSecureJsonData> {}

export function ConfigEditor(props: Props) {
Expand Down Expand Up @@ -75,8 +76,9 @@ export function ConfigEditor(props: Props) {

return (
<>
<InlineField label="Host" labelWidth={14} interactive tooltip={'Hostname'}>
<InlineField required={true} label="Host" labelWidth={14} interactive tooltip={'Hostname'}>
<Input
required={true}
id="config-editor-host"
onChange={onHostChange}
value={jsonData.host}
Expand Down Expand Up @@ -109,7 +111,7 @@ export function ConfigEditor(props: Props) {
id="config-editor-username"
onChange={onUsernameChange}
value={jsonData.username}
placeholder="Enter the username, e.g. admin"
placeholder="default"
width={40}
/>
</InlineField>
Expand Down
10 changes: 5 additions & 5 deletions src/components/QueryEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import React from 'react';
import { InlineField, Stack, CodeEditor } from '@grafana/ui';
import { QueryEditorProps } from '@grafana/data';
import { DataSource } from '../datasource';
import { CodeEditor, InlineField, Stack } from '@grafana/ui';
import { TpDataSourceOptions, TpQuery } from '../types';

import { DataSource } from '../datasource';
import { QueryEditorProps } from '@grafana/data';
import React from 'react';

type Props = QueryEditorProps<DataSource, TpQuery, TpDataSourceOptions>;

export function QueryEditor({ query, onChange }: Props) {
const onSQLChange = (sql: string) => {
onChange({ ...query, sql: sql });
};


const { sql } = query;

return (
Expand Down
Loading
Loading