Skip to content

Commit f2d5cdb

Browse files
committed
Update the query correctly
1 parent c9eb696 commit f2d5cdb

1 file changed

Lines changed: 45 additions & 2 deletions

File tree

  • x-pack/platform/plugins/shared/lens/public/app_plugin/shared/edit_on_the_fly

x-pack/platform/plugins/shared/lens/public/app_plugin/shared/edit_on_the_fly/helpers.ts

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,15 @@ import {
1111
formatESQLColumns,
1212
mapVariableToColumn,
1313
} from '@kbn/esql-utils';
14+
import { isEqual, cloneDeep } from 'lodash';
1415
import { type AggregateQuery, buildEsQuery } from '@kbn/es-query';
1516
import type { ESQLControlVariable } from '@kbn/esql-validation-autocomplete';
1617
import type { ESQLRow } from '@kbn/es-types';
17-
import { getLensAttributesFromSuggestion, mapVisToChartType } from '@kbn/visualization-utils';
18+
import {
19+
getLensAttributesFromSuggestion,
20+
mapVisToChartType,
21+
getDatasourceId,
22+
} from '@kbn/visualization-utils';
1823
import type { DataViewSpec } from '@kbn/data-views-plugin/public';
1924
import type { DataView } from '@kbn/data-views-plugin/common';
2025
import type { DatatableColumn } from '@kbn/expressions-plugin/common';
@@ -136,7 +141,9 @@ export const getSuggestions = async (
136141
datasourceMap,
137142
visualizationMap,
138143
preferredChartType,
139-
preferredVisAttributes,
144+
preferredVisAttributes: preferredVisAttributes
145+
? injectESQLQueryIntoLensLayers(preferredVisAttributes, query)
146+
: undefined,
140147
}) ?? [];
141148

142149
// Lens might not return suggestions for some cases, i.e. in case of errors
@@ -162,3 +169,39 @@ export const getSuggestions = async (
162169
}
163170
return undefined;
164171
};
172+
173+
export const injectESQLQueryIntoLensLayers = (
174+
attributes: TypedLensSerializedState['attributes'],
175+
query: AggregateQuery
176+
) => {
177+
const datasourceId = getDatasourceId(attributes.state.datasourceStates);
178+
179+
// if the datasource is formBased, we should not fix the query
180+
if (!datasourceId || datasourceId === 'formBased') {
181+
return attributes;
182+
}
183+
184+
if (!attributes.state.datasourceStates[datasourceId]) {
185+
return attributes;
186+
}
187+
188+
const datasourceState = cloneDeep(attributes.state.datasourceStates[datasourceId]);
189+
190+
if (datasourceState && datasourceState.layers) {
191+
Object.values(datasourceState.layers).forEach((layer) => {
192+
if (!isEqual(layer.query, query)) {
193+
layer.query = query;
194+
}
195+
});
196+
}
197+
return {
198+
...attributes,
199+
state: {
200+
...attributes.state,
201+
datasourceStates: {
202+
...attributes.state.datasourceStates,
203+
[datasourceId]: datasourceState,
204+
},
205+
},
206+
};
207+
};

0 commit comments

Comments
 (0)