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 5 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
9 changes: 8 additions & 1 deletion 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,6 +208,11 @@ func (d *Datasource) CheckHealth(ctx context.Context, req *backend.CheckHealthRe
res.Message = "'Host' cannot be empty"
return res, nil
}
if len(config.Username) == 0 {
res.Status = backend.HealthStatusError
res.Message = "'Username' cannot be empty"
return res, nil
}

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

Expand Down
17 changes: 16 additions & 1 deletion pkg/timeplus/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ 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
}
connection := protonDriver.OpenDB(&protonDriver.Options{
Addr: []string{fmt.Sprintf("%s:%d", host, tcpPort)},
Auth: protonDriver.Auth{
Expand Down Expand Up @@ -150,7 +156,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
11 changes: 7 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 @@ -104,8 +106,9 @@ export function ConfigEditor(props: Props) {
width={40}
/>
</InlineField>
<InlineField label="Username" labelWidth={14} interactive tooltip={'Username'}>
<InlineField required={true} label="Username" labelWidth={14} interactive tooltip={'Username'}>
<Input
required={true}
id="config-editor-username"
onChange={onUsernameChange}
value={jsonData.username}
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
36 changes: 36 additions & 0 deletions src/components/VariableQueryEditor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { CodeEditor, Field } from '@grafana/ui';
import React, { useState } from 'react';

import { VariableQueryProps } from '../types';

export const VariableQueryEditor = ({ onChange, query }: VariableQueryProps) => {
const [state, setState] = useState(query);

const saveQuery = () => {
onChange(state, `${state.query}`);
};

const onSQLChange = (sql: string) => {
setState({
query: sql,
});
};

return (
<Field
label=""
description="Make sure your query returns either 1 or 2 columns. If your query returns 1 column only, it will be used as the value and label. If it returns 2 columns, the first column will be used as the value while the second column will be used as the label."
>
<CodeEditor
onChange={onSQLChange}
onBlur={saveQuery}
width={600}
height={100}
language="sql"
showLineNumbers={true}
showMiniMap={false}
value={state.query}
/>
</Field>
);
};
49 changes: 45 additions & 4 deletions src/datasource.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,59 @@
import { DataSourceInstanceSettings, ScopedVars } from '@grafana/data';
import { DataQueryRequest, DataSourceInstanceSettings, MetricFindValue, ScopedVars } from '@grafana/data';
import { DataSourceWithBackend, getTemplateSrv } from '@grafana/runtime';

import { TpQuery, TpDataSourceOptions } from './types';
import { TpDataSourceOptions, TpQuery, TpVariableQuery } from './types';

export class DataSource extends DataSourceWithBackend<TpQuery, TpDataSourceOptions> {
constructor(instanceSettings: DataSourceInstanceSettings<TpDataSourceOptions>) {
super(instanceSettings);
}


metricFindQuery(query: TpVariableQuery, options?: any) {
let metrics: MetricFindValue[] = []
if (!query || !options.variable.datasource) {
return Promise.resolve(metrics);
}

const prom = new Promise<MetricFindValue[]>((resolve) => {
const req = {
targets: [{ datasource: options.variable.datasource,
sql: query.query,
refId: String(Math.random()) }],
range: options ? options.range : (getTemplateSrv() as any).timeRange,
} as DataQueryRequest<TpQuery> ;

this.query(req).subscribe((res) => {
const result = res.data[0] || { fields: [] }


if (result.fields.length === 2) {
for (let i = 0; i < result.fields[0].values.length; i++) {
metrics.push({
text: result.fields[1].values[i],
value: result.fields[0].values[i]
})
}
} else if (result.fields.length === 1) {
metrics = result.fields[0].values.map((v: string) => {
return {
text: v,
value: v
}});
}

resolve(metrics);
});
})

return prom
}

applyTemplateVariables(query: TpQuery, scopedVars: ScopedVars) {
const srv = getTemplateSrv()
const sql = srv.replace(query.sql, scopedVars)
return {
...query,
sql: getTemplateSrv().replace(query.sql, scopedVars),
sql: sql,
};
}

Expand Down
11 changes: 7 additions & 4 deletions src/module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import { DataSourcePlugin } from '@grafana/data';
import { DataSource } from './datasource';
import { TpDataSourceOptions, TpQuery } from './types';

import { ConfigEditor } from './components/ConfigEditor';
import { DataSource } from './datasource';
import { DataSourcePlugin } from '@grafana/data';
import { QueryEditor } from './components/QueryEditor';
import { TpQuery, TpDataSourceOptions } from './types';
import { VariableQueryEditor } from './components/VariableQueryEditor';

export const plugin = new DataSourcePlugin<DataSource, TpQuery, TpDataSourceOptions>(DataSource)
.setConfigEditor(ConfigEditor)
.setQueryEditor(QueryEditor);
.setQueryEditor(QueryEditor)
.setVariableQueryEditor(VariableQueryEditor)

Check warning on line 12 in src/module.ts

View workflow job for this annotation

GitHub Actions / Build, lint and unit tests

'setVariableQueryEditor' is deprecated. -- prefer using {@link StandardVariableSupport} or {@link CustomVariableSupport} or {@link DataSourceVariableSupport} in data source instead
11 changes: 10 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { DataSourceJsonData } from '@grafana/data';
import { DataQuery } from '@grafana/schema';
import { DataSourceJsonData } from '@grafana/data';

export interface TpQuery extends DataQuery {
sql: string;
Expand All @@ -21,3 +21,12 @@ export interface TpDataSourceOptions extends DataSourceJsonData {
export interface TpSecureJsonData {
password?: string;
}

export interface TpVariableQuery {
query: string;
}

export interface VariableQueryProps {
query: TpVariableQuery;
onChange: (query: TpVariableQuery, definition: string) => void;
}
Loading