Compare commits

..

3 Commits

Author SHA1 Message Date
yesoreyeram 2f0764d1a0 addded unit tests 2026-01-14 12:42:13 +00:00
yesoreyeram 05ad955c7b added other fields 2026-01-14 11:37:11 +00:00
yesoreyeram 2b82490e88 Revert "convert dataframe response to metricFindValues with properties"
This reverts commit c5bff2df50.
2026-01-13 16:17:02 +00:00
15 changed files with 232 additions and 83 deletions
@@ -13,7 +13,7 @@ import (
// schema is unexported to prevent accidental overwrites // schema is unexported to prevent accidental overwrites
var ( var (
schemaReceiver = resource.NewSimpleSchema("notifications.alerting.grafana.app", "v0alpha1", NewReceiver(), &ReceiverList{}, resource.WithKind("Receiver"), schemaReceiver = resource.NewSimpleSchema("notifications.alerting.grafana.app", "v0alpha1", NewReceiver(), &ReceiverList{}, resource.WithKind("Receiver"),
resource.WithPlural("receivers"), resource.WithScope(resource.NamespacedScope), resource.WithSelectableFields([]resource.SelectableField{resource.SelectableField{ resource.WithPlural("receivers"), resource.WithScope(resource.NamespacedScope), resource.WithSelectableFields([]resource.SelectableField{{
FieldSelector: "spec.title", FieldSelector: "spec.title",
FieldValueFunc: func(o resource.Object) (string, error) { FieldValueFunc: func(o resource.Object) (string, error) {
cast, ok := o.(*Receiver) cast, ok := o.(*Receiver)
@@ -790,8 +790,6 @@ VariableOption: {
text: string | [...string] text: string | [...string]
// Value of the option // Value of the option
value: string | [...string] value: string | [...string]
// Additional properties for multi-props variables
properties?: {[string]: string}
} }
// Query variable specification // Query variable specification
@@ -794,8 +794,6 @@ VariableOption: {
text: string | [...string] text: string | [...string]
// Value of the option // Value of the option
value: string | [...string] value: string | [...string]
// Additional properties for multi-props variables
properties?: {[string]: string}
} }
// Query variable specification // Query variable specification
@@ -301,8 +301,6 @@ var _ resource.ListObject = &DashboardList{}
// Copy methods for all subresource types // Copy methods for all subresource types
// DeepCopy creates a full deep copy of DashboardStatus // DeepCopy creates a full deep copy of DashboardStatus
func (s *DashboardStatus) DeepCopy() *DashboardStatus { func (s *DashboardStatus) DeepCopy() *DashboardStatus {
cpy := &DashboardStatus{} cpy := &DashboardStatus{}
@@ -301,8 +301,6 @@ var _ resource.ListObject = &DashboardList{}
// Copy methods for all subresource types // Copy methods for all subresource types
// DeepCopy creates a full deep copy of DashboardStatus // DeepCopy creates a full deep copy of DashboardStatus
func (s *DashboardStatus) DeepCopy() *DashboardStatus { func (s *DashboardStatus) DeepCopy() *DashboardStatus {
cpy := &DashboardStatus{} cpy := &DashboardStatus{}
@@ -794,8 +794,6 @@ VariableOption: {
text: string | [...string] text: string | [...string]
// Value of the option // Value of the option
value: string | [...string] value: string | [...string]
// Additional properties for multi-props variables
properties?: {[string]: string}
} }
// Query variable specification // Query variable specification
@@ -1411,8 +1411,6 @@ type DashboardVariableOption struct {
Text DashboardStringOrArrayOfString `json:"text"` Text DashboardStringOrArrayOfString `json:"text"`
// Value of the option // Value of the option
Value DashboardStringOrArrayOfString `json:"value"` Value DashboardStringOrArrayOfString `json:"value"`
// Additional properties for multi-props variables
Properties map[string]string `json:"properties,omitempty"`
} }
// NewDashboardVariableOption creates a new DashboardVariableOption object. // NewDashboardVariableOption creates a new DashboardVariableOption object.
@@ -798,8 +798,6 @@ VariableOption: {
text: string | [...string] text: string | [...string]
// Value of the option // Value of the option
value: string | [...string] value: string | [...string]
// Additional properties for multi-props variables
properties?: {[string]: string}
} }
// Query variable specification // Query variable specification
@@ -1414,8 +1414,6 @@ type DashboardVariableOption struct {
Text DashboardStringOrArrayOfString `json:"text"` Text DashboardStringOrArrayOfString `json:"text"`
// Value of the option // Value of the option
Value DashboardStringOrArrayOfString `json:"value"` Value DashboardStringOrArrayOfString `json:"value"`
// Additional properties for multi-props variables
Properties map[string]string `json:"properties,omitempty"`
} }
// NewDashboardVariableOption creates a new DashboardVariableOption object. // NewDashboardVariableOption creates a new DashboardVariableOption object.
File diff suppressed because one or more lines are too long
@@ -18,8 +18,6 @@ import (
v1beta1 "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1" v1beta1 "github.com/grafana/grafana/apps/folder/pkg/apis/folder/v1beta1"
) )
var ()
var appManifestData = app.ManifestData{ var appManifestData = app.ManifestData{
AppName: "folder", AppName: "folder",
Group: "folder.grafana.app", Group: "folder.grafana.app",
@@ -0,0 +1,199 @@
import { Field, FieldType } from '@grafana/data';
import { EditorMode } from '@grafana/plugin-ui';
import { migrateVariableQuery, convertOriginalFieldsToVariableFields } from './SQLVariableSupport';
import { QueryFormat, SQLQuery, SQLQueryMeta } from './types';
const refId = 'SQLVariableQueryEditor-VariableQuery';
const sampleQuery = 'SELECT * FROM users';
describe('migrateVariableQuery', () => {
it('should handle string query', () => {
const result = migrateVariableQuery(sampleQuery);
expect(result).toMatchObject({
refId,
rawSql: sampleQuery,
query: sampleQuery,
editorMode: EditorMode.Code,
format: QueryFormat.Table,
});
});
it('should handle empty string query', () => {
const result = migrateVariableQuery('');
expect(result).toMatchObject({
refId,
rawSql: '',
query: '',
editorMode: EditorMode.Builder,
format: QueryFormat.Table,
});
});
it('should handle SQLQuery object with rawSql', () => {
const rawQuery: SQLQuery = {
refId: 'A',
rawSql: sampleQuery,
format: QueryFormat.Timeseries,
editorMode: EditorMode.Code,
};
const result = migrateVariableQuery(rawQuery);
expect(result).toStrictEqual({ ...rawQuery, query: sampleQuery });
});
it('should preserve all other properties from SQLQuery', () => {
const rawQuery: SQLQuery = {
refId: 'C',
rawSql: sampleQuery,
alias: 'test_alias',
dataset: 'test_dataset',
table: 'test_table',
meta: { textField: 'name', valueField: 'id' },
};
const result = migrateVariableQuery(rawQuery);
expect(result).toStrictEqual({ ...rawQuery, query: sampleQuery });
});
});
const field = (name: string, type: FieldType = FieldType.string, values: unknown[] = [1, 2, 3]): Field => ({
name,
type,
values,
config: {},
});
describe('convertOriginalFieldsToVariableFields', () => {
it('should throw error when no fields provided', () => {
expect(() => convertOriginalFieldsToVariableFields([])).toThrow('at least one field expected for variable');
});
it('should handle fields with __text and __value names', () => {
const fields = [field('__text'), field('__value'), field('other_field')];
expect(convertOriginalFieldsToVariableFields(fields).map((r) => r.name)).toStrictEqual([
'text',
'value',
'__text',
'__value',
'other_field',
]);
});
it('should handle fields with only __text', () => {
const fields = [field('__text'), field('other_field')];
expect(convertOriginalFieldsToVariableFields(fields).map((r) => r.name)).toStrictEqual([
'text',
'value',
'__text',
'other_field',
]);
});
it('should handle fields with only __value', () => {
const fields = [field('__value'), field('other_field')];
expect(convertOriginalFieldsToVariableFields(fields).map((r) => r.name)).toStrictEqual([
'text',
'value',
'__value',
'other_field',
]);
});
it('should use first field when no __text or __value present', () => {
const fields = [field('id'), field('name'), field('category')];
expect(convertOriginalFieldsToVariableFields(fields).map((r) => r.name)).toStrictEqual([
'text',
'value',
'id',
'name',
'category',
]);
});
it('should respect meta.textField and meta.valueField', () => {
const fields = [field('id', FieldType.number, [3, 4]), field('display_name'), field('category')];
const meta: SQLQueryMeta = {
textField: 'display_name',
valueField: 'id',
};
const result = convertOriginalFieldsToVariableFields(fields, meta);
expect(convertOriginalFieldsToVariableFields(fields).map((r) => r.name)).toStrictEqual([
'text',
'value',
'id',
'display_name',
'category',
]);
expect(result[0]).toStrictEqual({ ...fields[1], name: 'text' }); // display_name -> text
expect(result[1]).toStrictEqual({ ...fields[0], name: 'value' }); // id -> value
});
it('should handle meta with non-existent field names', () => {
const fields = [field('id'), field('name')];
const meta: SQLQueryMeta = {
textField: 'non_existent_field',
valueField: 'also_non_existent',
};
const result = convertOriginalFieldsToVariableFields(fields, meta);
expect(result.map((r) => r.name)).toStrictEqual(['text', 'value', 'id', 'name']);
expect(result[0]).toStrictEqual({ ...fields[0], name: 'text' });
expect(result[1]).toStrictEqual({ ...fields[0], name: 'value' });
});
it('should handle partial meta (only textField)', () => {
const fields = [field('id'), field('label'), field('description')];
const meta: SQLQueryMeta = {
textField: 'label',
};
const result = convertOriginalFieldsToVariableFields(fields, meta);
expect(result.map((r) => r.name)).toStrictEqual(['text', 'value', 'id', 'label', 'description']);
expect(result[0]).toStrictEqual({ ...fields[1], name: 'text' }); // label -> text
expect(result[1]).toStrictEqual({ ...fields[0], name: 'value' }); // fallback to text field
});
it('should handle partial meta (only valueField)', () => {
const fields = [field('name'), field('id', FieldType.number), field('type')];
const meta: SQLQueryMeta = {
valueField: 'id',
};
const result = convertOriginalFieldsToVariableFields(fields, meta);
expect(result.map((r) => r.name)).toStrictEqual(['text', 'value', 'name', 'id', 'type']);
expect(result[0]).toStrictEqual({ ...fields[0], name: 'text', type: FieldType.number }); // fallback to value field
expect(result[1]).toStrictEqual({ ...fields[1], name: 'value' }); // id -> value
});
it('should not include duplicate "value" or "text" fields in otherFields', () => {
const fields = [field('value'), field('text'), field('other')];
expect(convertOriginalFieldsToVariableFields(fields).map((r) => r.name)).toStrictEqual(['text', 'value', 'other']);
});
it('should preserve field types and configurations', () => {
const fields = [
{
name: 'id',
type: FieldType.number,
config: { unit: 'short', displayName: 'ID' },
values: [1, 2, 3],
},
{
name: 'name',
type: FieldType.string,
config: { displayName: 'Name' },
values: ['A', 'B', 'C'],
},
];
const meta: SQLQueryMeta = {
textField: 'name',
valueField: 'id',
};
const result = convertOriginalFieldsToVariableFields(fields, meta);
expect(result[0]).toStrictEqual({
name: 'text',
type: FieldType.string,
config: { displayName: 'Name' },
values: ['A', 'B', 'C'],
});
expect(result[1]).toStrictEqual({
name: 'value',
type: FieldType.number,
config: { unit: 'short', displayName: 'ID' },
values: [1, 2, 3],
});
});
});
+20 -39
View File
@@ -9,7 +9,6 @@ import {
QueryEditorProps, QueryEditorProps,
Field, Field,
DataFrame, DataFrame,
MetricFindValue,
} from '@grafana/data'; } from '@grafana/data';
import { t } from '@grafana/i18n'; import { t } from '@grafana/i18n';
import { EditorMode, EditorRows, EditorRow, EditorField } from '@grafana/plugin-ui'; import { EditorMode, EditorRows, EditorRow, EditorField } from '@grafana/plugin-ui';
@@ -36,9 +35,13 @@ export class SQLVariableSupport extends CustomVariableSupport<SqlDatasource, SQL
const updatedQuery = migrateVariableQuery(request.targets[0]); const updatedQuery = migrateVariableQuery(request.targets[0]);
return this.datasource.query({ ...request, targets: [updatedQuery] }).pipe( return this.datasource.query({ ...request, targets: [updatedQuery] }).pipe(
map((d: DataQueryResponse) => { map((d: DataQueryResponse) => {
const frames = d.data || []; return {
const metricFindValues = convertDataFramesToMetricFindValues(frames, updatedQuery.meta); ...d,
return { data: metricFindValues }; data: (d.data || []).map((frame: DataFrame) => ({
...frame,
fields: convertOriginalFieldsToVariableFields(frame.fields, updatedQuery.meta),
})),
};
}) })
); );
} }
@@ -117,7 +120,7 @@ const FieldMapping = (props: SQLVariableQueryEditorProps) => {
); );
}; };
const migrateVariableQuery = (rawQuery: string | SQLQuery): SQLVariableQuery => { export const migrateVariableQuery = (rawQuery: string | SQLQuery): SQLVariableQuery => {
if (typeof rawQuery !== 'string') { if (typeof rawQuery !== 'string') {
return { return {
...rawQuery, ...rawQuery,
@@ -135,40 +138,18 @@ const migrateVariableQuery = (rawQuery: string | SQLQuery): SQLVariableQuery =>
}; };
}; };
const convertDataFramesToMetricFindValues = (frames: DataFrame[], meta?: SQLQueryMeta): MetricFindValue[] => { export const convertOriginalFieldsToVariableFields = (original_fields: Field[], meta?: SQLQueryMeta): Field[] => {
if (!frames.length) { if (original_fields.length < 1) {
throw new Error('no results found'); throw new Error('at least one field expected for variable');
} }
let tf = original_fields.find((f) => f.name === '__text');
const frame = frames[0]; let vf = original_fields.find((f) => f.name === '__value');
if (meta) {
const fields = frame.fields; tf = meta.textField ? original_fields.find((f) => f.name === meta.textField) : undefined;
vf = meta.valueField ? original_fields.find((f) => f.name === meta.valueField) : undefined;
if (fields.length < 1) {
throw new Error('no fields found in the response');
} }
const textField = tf || vf || original_fields[0];
let textField = fields.find((f) => f.name === '__text'); const valueField = vf || tf || original_fields[0];
let valueField = fields.find((f) => f.name === '__value'); const otherFields = original_fields.filter((f: Field) => f.name !== 'value' && f.name !== 'text');
if (meta?.textField) { return [{ ...textField, name: 'text' }, { ...valueField, name: 'value' }, ...otherFields];
textField = fields.find((f) => f.name === meta.textField);
}
if (meta?.valueField) {
valueField = fields.find((f) => f.name === meta.valueField);
}
const resolvedTextField = textField || valueField || fields[0];
const resolvedValueField = valueField || textField || fields[0];
const results: MetricFindValue[] = [];
const rowCount = frame.length;
for (let i = 0; i < rowCount; i++) {
const text = String(resolvedTextField.values[i] ?? '');
const value = String(resolvedValueField.values[i] ?? '');
const properties: Record<string, string> = {};
for (const field of fields) {
properties[field.name] = String(field.values[i] ?? '');
}
results.push({ text, value, properties });
}
return results;
}; };
@@ -284,7 +284,6 @@ function variableValueOptionsToVariableOptions(varState: MultiValueVariable['sta
value: String(o.value), value: String(o.value),
text: o.label, text: o.label,
selected: Array.isArray(varState.value) ? varState.value.includes(o.value) : varState.value === o.value, selected: Array.isArray(varState.value) ? varState.value.includes(o.value) : varState.value === o.value,
...(o.properties && { properties: o.properties }),
})); }));
} }
@@ -80,18 +80,18 @@ const buildLabelPath = (label: string) => {
return label.includes('.') || label.trim().includes(' ') ? `["${label}"]` : `.${label}`; return label.includes('.') || label.trim().includes(' ') ? `["${label}"]` : `.${label}`;
}; };
const isRecord = (value: unknown): value is Record<string, unknown> => {
return typeof value === 'object' && value !== null && !Array.isArray(value);
};
const getVariableValueProperties = (variable: TypedVariableModel): string[] => { const getVariableValueProperties = (variable: TypedVariableModel): string[] => {
function collectFieldPaths(option: Record<string, unknown>, currentPath: string): string[] { if (!('valuesFormat' in variable) || variable.valuesFormat !== 'json') {
return [];
}
function collectFieldPaths(option: Record<string, string>, currentPath: string) {
let paths: string[] = []; let paths: string[] = [];
for (const field in option) { for (const field in option) {
if (option.hasOwnProperty(field)) { if (option.hasOwnProperty(field)) {
const newPath = `${currentPath}.${field}`; const newPath = `${currentPath}.${field}`;
const value = option[field]; const value = option[field];
if (isRecord(value)) { if (typeof value === 'object' && value !== null) {
paths = [...paths, ...collectFieldPaths(value, newPath)]; paths = [...paths, ...collectFieldPaths(value, newPath)];
} }
paths.push(newPath); paths.push(newPath);
@@ -100,23 +100,11 @@ const getVariableValueProperties = (variable: TypedVariableModel): string[] => {
return paths; return paths;
} }
if ('valuesFormat' in variable && variable.valuesFormat === 'json') { try {
try { return collectFieldPaths(JSON.parse(variable.query)[0], variable.name);
return collectFieldPaths(JSON.parse(variable.query)[0], variable.name); } catch {
} catch { return [];
return [];
}
} }
if ('options' in variable && Array.isArray(variable.options) && variable.options.length > 0) {
for (const opt of variable.options) {
if ('properties' in opt && isRecord(opt.properties) && Object.keys(opt.properties).length > 0) {
return collectFieldPaths(opt.properties, variable.name);
}
}
}
return [];
}; };
export const getPanelLinksVariableSuggestions = (): VariableSuggestion[] => [ export const getPanelLinksVariableSuggestions = (): VariableSuggestion[] => [