Skip to content

Commit 546bdff

Browse files
[8.19] [ES|QL] Fixes the columns selection in Lens when there are ES|QL variables (#221083) (#221150)
# Backport This will backport the following commits from `main` to `8.19`: - [[ES|QL] Fixes the columns selection in Lens when there are ES|QL variables (#221083)](#221083) <!--- Backport version: 9.6.6 --> ### Questions ? Please refer to the [Backport tool documentation](https://github.com/sorenlouv/backport) <!--BACKPORT [{"author":{"name":"Stratoula Kalafateli","email":"[email protected]"},"sourceCommit":{"committedDate":"2025-05-21T16:11:37Z","message":"[ES|QL] Fixes the columns selection in Lens when there are ES|QL variables (#221083)\n\n## Summary\n\nIt fixes the problem described in the PR. Specifically when you have a\nvariable in your esql query and you try to select extra columns. Because\nwe were not passing the esql Variables, the query failed and the columns\narray was empty.\n\nThis PR is passing the dashboard variables in the component, and now the\nquery runs successfully\n\n<img width=\"616\" alt=\"image\"\nsrc=\"https://github.com/user-attachments/assets/cd009af9-9465-48cd-bb3b-918c3a872cff\"\n/>\n \n\n### Checklist\n- [ ] [Unit or functional\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\nwere updated or added to match the most common scenarios","sha":"6fa3152f2773890e4bf721b9149b875ece83f45c","branchLabelMapping":{"^v9.1.0$":"main","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["Team:Visualizations","release_note:skip","Feature:Lens","Feature:ES|QL","backport:version","v9.1.0","v8.19.0","v8.18.2"],"title":"[ES|QL] Fixes the columns selection in Lens when there are ES|QL variables","number":221083,"url":"https://github.com/elastic/kibana/pull/221083","mergeCommit":{"message":"[ES|QL] Fixes the columns selection in Lens when there are ES|QL variables (#221083)\n\n## Summary\n\nIt fixes the problem described in the PR. Specifically when you have a\nvariable in your esql query and you try to select extra columns. Because\nwe were not passing the esql Variables, the query failed and the columns\narray was empty.\n\nThis PR is passing the dashboard variables in the component, and now the\nquery runs successfully\n\n<img width=\"616\" alt=\"image\"\nsrc=\"https://github.com/user-attachments/assets/cd009af9-9465-48cd-bb3b-918c3a872cff\"\n/>\n \n\n### Checklist\n- [ ] [Unit or functional\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\nwere updated or added to match the most common scenarios","sha":"6fa3152f2773890e4bf721b9149b875ece83f45c"}},"sourceBranch":"main","suggestedTargetBranches":["8.19","8.18"],"targetPullRequestStates":[{"branch":"main","label":"v9.1.0","branchLabelMappingKey":"^v9.1.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/221083","number":221083,"mergeCommit":{"message":"[ES|QL] Fixes the columns selection in Lens when there are ES|QL variables (#221083)\n\n## Summary\n\nIt fixes the problem described in the PR. Specifically when you have a\nvariable in your esql query and you try to select extra columns. Because\nwe were not passing the esql Variables, the query failed and the columns\narray was empty.\n\nThis PR is passing the dashboard variables in the component, and now the\nquery runs successfully\n\n<img width=\"616\" alt=\"image\"\nsrc=\"https://github.com/user-attachments/assets/cd009af9-9465-48cd-bb3b-918c3a872cff\"\n/>\n \n\n### Checklist\n- [ ] [Unit or functional\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\nwere updated or added to match the most common scenarios","sha":"6fa3152f2773890e4bf721b9149b875ece83f45c"}},{"branch":"8.19","label":"v8.19.0","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"},{"branch":"8.18","label":"v8.18.2","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"}]}] BACKPORT--> Co-authored-by: Stratoula Kalafateli <[email protected]>
1 parent c633030 commit 546bdff

File tree

4 files changed

+97
-1
lines changed

4 files changed

+97
-1
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the Elastic License
4+
* 2.0; you may not use this file except in compliance with the Elastic License
5+
* 2.0.
6+
*/
7+
import React from 'react';
8+
import { render, screen, waitFor } from '@testing-library/react';
9+
import { TextBasedDimensionEditor, TextBasedDimensionEditorProps } from './dimension_editor';
10+
11+
// Mock fetchFieldsFromESQL
12+
jest.mock('@kbn/esql-editor', () => ({
13+
fetchFieldsFromESQL: jest.fn(),
14+
}));
15+
16+
const { fetchFieldsFromESQL } = jest.requireMock('@kbn/esql-editor');
17+
18+
describe('TextBasedDimensionEditor', () => {
19+
const defaultProps = {
20+
isFullscreen: false,
21+
columnId: 'dim1',
22+
layerId: 'layer1',
23+
state: {
24+
layers: {
25+
layer1: {
26+
query: { esql: 'FROM my_data' },
27+
columns: [],
28+
indexPatternRefs: [],
29+
},
30+
},
31+
indexPatternRefs: [],
32+
},
33+
setState: jest.fn(),
34+
indexPatterns: {},
35+
dateRange: { fromDate: '2023-01-01', toDate: '2023-01-31' },
36+
expressions: {},
37+
esqlVariables: [
38+
{
39+
key: 'agent_keyword',
40+
value: 'Mozilla/5.0 (X11; Linux x86_64; rv:6.0a1) Gecko/20110421 Firefox/6.0a1',
41+
type: 'values',
42+
},
43+
],
44+
isMetricDimension: false,
45+
filterOperations: jest.fn(() => true),
46+
core: { docLinks: {} },
47+
groupId: 'rows',
48+
} as unknown as TextBasedDimensionEditorProps;
49+
50+
beforeEach(() => {
51+
jest.clearAllMocks();
52+
53+
fetchFieldsFromESQL.mockResolvedValue({
54+
columns: [
55+
{ id: 'field1', name: 'Field One', meta: { type: 'string' } },
56+
{ id: 'field2', name: 'Field Two', meta: { type: 'number' } },
57+
],
58+
});
59+
});
60+
61+
it('renders correctly and fetches columns on mount', async () => {
62+
render(<TextBasedDimensionEditor {...defaultProps} />);
63+
64+
// Check if fetchFieldsFromESQL was called
65+
await waitFor(() => {
66+
expect(fetchFieldsFromESQL).toHaveBeenCalledTimes(1);
67+
expect(fetchFieldsFromESQL).toHaveBeenCalledWith(
68+
{ esql: 'FROM my_data | limit 0' },
69+
{},
70+
{ from: defaultProps.dateRange.fromDate, to: defaultProps.dateRange.toDate },
71+
undefined,
72+
undefined, // No index patterns
73+
defaultProps.esqlVariables
74+
);
75+
});
76+
77+
expect(screen.getByTestId('text-based-dimension-field')).toBeInTheDocument();
78+
});
79+
});

x-pack/platform/plugins/shared/lens/public/datasources/form_based/esql_layer/components/dimension_editor.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ export function TextBasedDimensionEditor(props: TextBasedDimensionEditorProps) {
3939
indexPatterns,
4040
dateRange,
4141
expressions,
42+
esqlVariables,
4243
} = props;
4344

4445
useEffect(() => {
@@ -52,7 +53,8 @@ export function TextBasedDimensionEditor(props: TextBasedDimensionEditorProps) {
5253
undefined,
5354
Object.values(indexPatterns).length
5455
? Object.values(indexPatterns)[0].timeFieldName
55-
: undefined
56+
: undefined,
57+
esqlVariables
5658
);
5759
if (table) {
5860
const hasNumberTypeColumns = table.columns?.some(isNumeric);
@@ -84,6 +86,7 @@ export function TextBasedDimensionEditor(props: TextBasedDimensionEditorProps) {
8486
indexPatterns,
8587
props,
8688
props.expressions,
89+
esqlVariables,
8790
query,
8891
]);
8992

@@ -122,6 +125,7 @@ export function TextBasedDimensionEditor(props: TextBasedDimensionEditorProps) {
122125
className="lnsIndexPatternDimensionEditor--padded"
123126
>
124127
<FieldSelect
128+
data-test-subj="text-based-dimension-field"
125129
existingFields={allColumns ?? []}
126130
selectedField={selectedField}
127131
onChoose={(choice) => {

x-pack/platform/plugins/shared/lens/public/editor_frame_service/editor_frame/config_panel/layer_panel.tsx

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,13 @@ import {
1616
EuiIconTip,
1717
useEuiTheme,
1818
} from '@elastic/eui';
19+
import { BehaviorSubject } from 'rxjs';
1920
import { i18n } from '@kbn/i18n';
2021
import { css } from '@emotion/react';
2122
import { euiThemeVars } from '@kbn/ui-theme';
2223
import { DragDropIdentifier, ReorderProvider, DropType } from '@kbn/dom-drag-drop';
2324
import { DimensionButton } from '@kbn/visualization-ui-components';
25+
import { useStateFromPublishingSubject } from '@kbn/presentation-publishing';
2426
import { isOfAggregateQueryType } from '@kbn/es-query';
2527
import { LayerActions } from './layer_actions';
2628
import { isOperation, LayerAction, VisualizationDimensionGroupConfig } from '../../../types';
@@ -40,6 +42,7 @@ import { getSharedActions } from './layer_actions/layer_actions';
4042
import { FlyoutContainer } from '../../../shared_components/flyout_container';
4143
import { FakeDimensionButton } from './buttons/fake_dimension_button';
4244
import { getLongMessage } from '../../../user_messages_utils';
45+
import { isApiESQLVariablesCompatible } from '../../../react_embeddable/types';
4346
import { ESQLEditor } from './esql_editor';
4447

4548
export function LayerPanel(props: LayerPanelProps) {
@@ -78,6 +81,13 @@ export function LayerPanel(props: LayerPanelProps) {
7881
...editorProps
7982
} = props;
8083

84+
const { parentApi } = editorProps;
85+
const esqlVariables = useStateFromPublishingSubject(
86+
isApiESQLVariablesCompatible(parentApi)
87+
? parentApi?.esqlVariables$
88+
: new BehaviorSubject(undefined)
89+
);
90+
8191
const isInlineEditing = Boolean(props?.setIsInlineFlyoutVisible);
8292

8393
const isSaveable = useLensSelector((state) => state.lens.isSaveable);
@@ -814,6 +824,7 @@ export function LayerPanel(props: LayerPanelProps) {
814824
layerType: activeVisualization.getLayerType(layerId, visualizationState),
815825
indexPatterns: dataViews.indexPatterns,
816826
activeData: layerVisualizationConfigProps.activeData,
827+
esqlVariables,
817828
dataSectionExtra: !isFullscreen &&
818829
openDimension.isComplete &&
819830
activeVisualization.DimensionEditorDataExtraComponent && (

x-pack/platform/plugins/shared/lens/public/types.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import type { IconType } from '@elastic/eui/src/components/icon/icon';
99
import type { CoreStart, SavedObjectReference, ResolvedSimpleSavedObject } from '@kbn/core/public';
1010
import type { ColorMapping, PaletteOutput } from '@kbn/coloring';
1111
import type { TopNavMenuData } from '@kbn/navigation-plugin/public';
12+
import type { ESQLControlVariable } from '@kbn/esql-types';
1213
import type { MutableRefObject, ReactElement } from 'react';
1314
import type { Query, AggregateQuery, Filter, TimeRange } from '@kbn/es-query';
1415
import type {
@@ -673,6 +674,7 @@ export type DatasourceDimensionEditorProps<T = unknown> = DatasourceDimensionPro
673674
| 'docLinks'
674675
>;
675676
dateRange: DateRange;
677+
esqlVariables?: ESQLControlVariable[] | undefined;
676678
dimensionGroups: VisualizationDimensionGroupConfig[];
677679
toggleFullscreen: () => void;
678680
isFullscreen: boolean;

0 commit comments

Comments
 (0)