Skip to content

Commit

Permalink
[ES|QL] Fix new variables being suggested in incorrect places (elasti…
Browse files Browse the repository at this point in the history
…c#192405)

## Summary

Fixes elastic#191876 and another bug
where var0 was being suggested within the case expression if it was not
previously prefixed with `var0 =`.

1. No more suggestions for new variable assignment if cursor is within a
function

Before

https://github.com/user-attachments/assets/01327c3e-f339-44f5-bb69-922318d2ded6

After

https://github.com/user-attachments/assets/3eb490d4-46c3-4839-a1d9-06b61a030e97

2. No more suggestions within `case()`

Before

https://github.com/user-attachments/assets/36707c65-e2c8-458a-97c2-4b287cada3f8

After

https://github.com/user-attachments/assets/bee088cd-2140-4e9e-bf09-22bd278a242d

### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)

### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces—unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes—Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |

### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

---------

Co-authored-by: Elastic Machine <[email protected]>
(cherry picked from commit ef5aee1)
  • Loading branch information
qn895 committed Sep 19, 2024
1 parent 886fb40 commit 7dd5984
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ describe('autocomplete.suggest', () => {
test('case', async () => {
const { assertSuggestions } = await setup();
const comparisonOperators = ['==', '!=', '>', '<', '>=', '<=']
.map((op) => `${op} `)
.map((op) => `${op}`)
.concat(',');

// case( / ) suggest any field/eval function in this position as first argument
Expand Down Expand Up @@ -626,7 +626,6 @@ describe('autocomplete.suggest', () => {
// Notice no extra space after field name
...getFieldNamesByType('any').map((field) => `${field}`),
...getFunctionSignaturesByReturnType('eval', 'any', { scalar: true }, undefined, []),
'var0 = ',
]);

// case( field > 0, >) suggests fields like normal
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ import {
} from '../definitions/types';
import { metadataOption } from '../definitions/options';
import { comparisonFunctions } from '../definitions/builtin';
import { countBracketsUnclosed } from '../shared/helpers';

type GetFieldsByTypeFn = (
type: string | string[],
Expand Down Expand Up @@ -554,8 +555,11 @@ async function getExpressionSuggestionsByType(
const fieldsMap: Map<string, ESQLRealField> = await (argDef ? getFieldsMap() : new Map());
const anyVariables = collectVariables(commands, fieldsMap, innerText);

const previousWord = findPreviousWord(innerText);
// enrich with assignment has some special rules who are handled somewhere else
const canHaveAssignments = ['eval', 'stats', 'row'].includes(command.name);
const canHaveAssignments =
['eval', 'stats', 'row'].includes(command.name) &&
!comparisonFunctions.map((fn) => fn.name).includes(previousWord);

const references = { fields: fieldsMap, variables: anyVariables };

Expand Down Expand Up @@ -1422,10 +1426,9 @@ async function getFunctionArgsSuggestions(
suggestions.push(
...comparisonFunctions.map<SuggestionRawDefinition>(({ name, description }) => ({
label: name,
text: name + ' ',
text: name,
kind: 'Function' as ItemKind,
detail: description,
command: TRIGGER_SUGGESTION_COMMAND,
}))
);
}
Expand Down Expand Up @@ -1786,10 +1789,13 @@ async function getOptionArgsSuggestions(
openSuggestions: true,
}))
);
// Checks if cursor is still within function ()
// by checking if the marker editor/cursor is within an unclosed parenthesis
const canHaveAssignment = countBracketsUnclosed('(', innerText) === 0;

if (option.name === 'by') {
// Add quick snippet for for stats ... by bucket(<>)
if (command.name === 'stats') {
if (command.name === 'stats' && canHaveAssignment) {
suggestions.push({
label: i18n.translate(
'kbn-esql-validation-autocomplete.esql.autocomplete.addDateHistogram',
Expand Down Expand Up @@ -1820,12 +1826,13 @@ async function getOptionArgsSuggestions(
{
functions: true,
fields: false,
}
},
{ ignoreFn: canHaveAssignment ? [] : ['bucket', 'case'] }
))
);
}

if (command.name === 'stats' && isNewExpression) {
if (command.name === 'stats' && isNewExpression && canHaveAssignment) {
suggestions.push(buildNewVarDefinition(findNewVariable(anyVariables)));
}
}
Expand Down

0 comments on commit 7dd5984

Please sign in to comment.