Skip to content

Commit

Permalink
[ES|QL] Improved support for Elasticsearch sub-types in AST for both …
Browse files Browse the repository at this point in the history
…validation and autocomplete (#189689)

## Summary

Fixed version of #188600 that
updates the failed tests [caused by clash with the visitor API
tests](#189516).

### 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: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
Co-authored-by: Elastic Machine <elasticmachine@users.noreply.github.com>
  • Loading branch information
3 people authored Aug 1, 2024
1 parent 788e9b3 commit 7dca2aa
Show file tree
Hide file tree
Showing 41 changed files with 31,848 additions and 15,513 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ describe('literal expression', () => {

expect(literal).toMatchObject({
type: 'literal',
literalType: 'number',
literalType: 'integer',
name: '1',
value: 1,
});
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-esql-ast/src/ast_factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ export class AstListener implements ESQLParserListener {
const command = createCommand('limit', ctx);
this.ast.push(command);
if (ctx.getToken(esql_parser.INTEGER_LITERAL, 0)) {
const literal = createLiteral('number', ctx.INTEGER_LITERAL());
const literal = createLiteral('integer', ctx.INTEGER_LITERAL());
if (literal) {
command.args.push(literal);
}
Expand Down
23 changes: 16 additions & 7 deletions packages/kbn-esql-ast/src/ast_helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ import type {
ESQLCommandMode,
ESQLInlineCast,
ESQLUnknownItem,
ESQLNumericLiteralType,
FunctionSubtype,
ESQLNumericLiteral,
} from './types';

export function nonNullable<T>(v: T): v is NonNullable<T> {
Expand Down Expand Up @@ -87,11 +89,14 @@ export function createList(ctx: ParserRuleContext, values: ESQLLiteral[]): ESQLL
};
}

export function createNumericLiteral(ctx: DecimalValueContext | IntegerValueContext): ESQLLiteral {
export function createNumericLiteral(
ctx: DecimalValueContext | IntegerValueContext,
literalType: ESQLNumericLiteralType
): ESQLLiteral {
const text = ctx.getText();
return {
type: 'literal',
literalType: 'number',
literalType,
text,
name: text,
value: Number(text),
Expand All @@ -100,10 +105,13 @@ export function createNumericLiteral(ctx: DecimalValueContext | IntegerValueCont
};
}

export function createFakeMultiplyLiteral(ctx: ArithmeticUnaryContext): ESQLLiteral {
export function createFakeMultiplyLiteral(
ctx: ArithmeticUnaryContext,
literalType: ESQLNumericLiteralType
): ESQLLiteral {
return {
type: 'literal',
literalType: 'number',
literalType,
text: ctx.getText(),
name: ctx.getText(),
value: ctx.PLUS() ? 1 : -1,
Expand Down Expand Up @@ -158,20 +166,21 @@ export function createLiteral(
location: getPosition(node.symbol),
incomplete: isMissingText(text),
};
if (type === 'number') {
if (type === 'decimal' || type === 'integer') {
return {
...partialLiteral,
literalType: type,
value: Number(text),
};
paramType: 'number',
} as ESQLNumericLiteral<'decimal'> | ESQLNumericLiteral<'integer'>;
} else if (type === 'param') {
throw new Error('Should never happen');
}
return {
...partialLiteral,
literalType: type,
value: text,
};
} as ESQLLiteral;
}

export function createTimeUnit(ctx: QualifiedIntegerLiteralContext): ESQLTimeInterval {
Expand Down
19 changes: 14 additions & 5 deletions packages/kbn-esql-ast/src/ast_walker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ import {
createUnknownItem,
} from './ast_helpers';
import { getPosition } from './ast_position_utils';
import type {
import {
ESQLLiteral,
ESQLColumn,
ESQLFunction,
Expand Down Expand Up @@ -289,7 +289,7 @@ function visitOperatorExpression(
const arg = visitOperatorExpression(ctx.operatorExpression());
// this is a number sign thing
const fn = createFunction('*', ctx, undefined, 'binary-expression');
fn.args.push(createFakeMultiplyLiteral(ctx));
fn.args.push(createFakeMultiplyLiteral(ctx, 'integer'));
if (arg) {
fn.args.push(arg);
}
Expand Down Expand Up @@ -328,16 +328,21 @@ function getConstant(ctx: ConstantContext): ESQLAstItem {
// e.g. 1 year, 15 months
return createTimeUnit(ctx);
}

// Decimal type covers multiple ES|QL types: long, double, etc.
if (ctx instanceof DecimalLiteralContext) {
return createNumericLiteral(ctx.decimalValue());
return createNumericLiteral(ctx.decimalValue(), 'decimal');
}

// Integer type encompasses integer
if (ctx instanceof IntegerLiteralContext) {
return createNumericLiteral(ctx.integerValue());
return createNumericLiteral(ctx.integerValue(), 'integer');
}
if (ctx instanceof BooleanLiteralContext) {
return getBooleanValue(ctx);
}
if (ctx instanceof StringLiteralContext) {
// String literal covers multiple ES|QL types: text and keyword types
return createLiteral('string', ctx.string_().QUOTED_STRING());
}
if (
Expand All @@ -346,14 +351,18 @@ function getConstant(ctx: ConstantContext): ESQLAstItem {
ctx instanceof StringArrayLiteralContext
) {
const values: ESQLLiteral[] = [];

for (const numericValue of ctx.getTypedRuleContexts(NumericValueContext)) {
const isDecimal =
numericValue.decimalValue() !== null && numericValue.decimalValue() !== undefined;
const value = numericValue.decimalValue() || numericValue.integerValue();
values.push(createNumericLiteral(value!));
values.push(createNumericLiteral(value!, isDecimal ? 'decimal' : 'integer'));
}
for (const booleanValue of ctx.getTypedRuleContexts(BooleanValueContext)) {
values.push(getBooleanValue(booleanValue)!);
}
for (const string of ctx.getTypedRuleContexts(StringContext)) {
// String literal covers multiple ES|QL types: text and keyword types
const literal = createLiteral('string', string.QUOTED_STRING());
if (literal) {
values.push(literal);
Expand Down
2 changes: 1 addition & 1 deletion packages/kbn-esql-ast/src/builder/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ test('can mint a numeric literal', () => {

expect(node).toMatchObject({
type: 'literal',
literalType: 'number',
literalType: 'integer',
name: '42',
value: 42,
});
Expand Down
16 changes: 10 additions & 6 deletions packages/kbn-esql-ast/src/builder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* Side Public License, v 1.
*/

import { ESQLNumberLiteral } from '../types';
import { ESQLDecimalLiteral, ESQLIntegerLiteral, ESQLNumericLiteralType } from '../types';
import { AstNodeParserFields, AstNodeTemplate } from './types';

export class Builder {
Expand All @@ -25,16 +25,20 @@ export class Builder {
});

/**
* Constructs a number literal node.
* Constructs a integer literal node.
*/
public static readonly numericLiteral = (
template: Omit<AstNodeTemplate<ESQLNumberLiteral>, 'literalType' | 'name'>
): ESQLNumberLiteral => {
const node: ESQLNumberLiteral = {
template: Omit<
AstNodeTemplate<ESQLIntegerLiteral | ESQLDecimalLiteral>,
'literalType' | 'name'
>,
type: ESQLNumericLiteralType = 'integer'
): ESQLIntegerLiteral | ESQLDecimalLiteral => {
const node: ESQLIntegerLiteral | ESQLDecimalLiteral = {
...template,
...Builder.parserFields(template),
type: 'literal',
literalType: 'number',
literalType: type,
name: template.value.toString(),
};

Expand Down
17 changes: 14 additions & 3 deletions packages/kbn-esql-ast/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,19 +179,30 @@ export interface ESQLList extends ESQLAstBaseItem {
values: ESQLLiteral[];
}

export type ESQLNumericLiteralType = 'decimal' | 'integer';

export type ESQLLiteral =
| ESQLNumberLiteral
| ESQLDecimalLiteral
| ESQLIntegerLiteral
| ESQLBooleanLiteral
| ESQLNullLiteral
| ESQLStringLiteral
| ESQLParamLiteral<string>;

// Exporting here to prevent TypeScript error TS4058
// Return type of exported function has or is using name 'ESQLNumericLiteral' from external module
// @internal
export interface ESQLNumberLiteral extends ESQLAstBaseItem {
export interface ESQLNumericLiteral<T extends ESQLNumericLiteralType> extends ESQLAstBaseItem {
type: 'literal';
literalType: 'number';
literalType: T;
value: number;
}
// We cast anything as decimal (e.g. 32.12) as generic decimal numeric type here
// @internal
export type ESQLDecimalLiteral = ESQLNumericLiteral<'decimal'>;

// @internal
export type ESQLIntegerLiteral = ESQLNumericLiteral<'integer'>;

// @internal
export interface ESQLBooleanLiteral extends ESQLAstBaseItem {
Expand Down
11 changes: 8 additions & 3 deletions packages/kbn-esql-ast/src/visitor/contexts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ import type {
ESQLAstNodeWithArgs,
ESQLColumn,
ESQLCommandOption,
ESQLDecimalLiteral,
ESQLFunction,
ESQLInlineCast,
ESQLIntegerLiteral,
ESQLList,
ESQLLiteral,
ESQLNumberLiteral,
ESQLSource,
ESQLTimeInterval,
} from '../types';
Expand Down Expand Up @@ -260,10 +261,14 @@ export class LimitCommandVisitorContext<
/**
* @returns The first numeric literal argument of the command.
*/
public numericLiteral(): ESQLNumberLiteral | undefined {
public numericLiteral(): ESQLIntegerLiteral | ESQLDecimalLiteral | undefined {
const arg = firstItem(this.node.args);

if (arg && arg.type === 'literal' && arg.literalType === 'number') {
if (
arg &&
arg.type === 'literal' &&
(arg.literalType === 'integer' || arg.literalType === 'decimal')
) {
return arg;
}
}
Expand Down
28 changes: 14 additions & 14 deletions packages/kbn-esql-ast/src/walker/walker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ describe('structurally can walk all nodes', () => {
expect(columns).toMatchObject([
{
type: 'literal',
literalType: 'number',
literalType: 'integer',
name: '123',
},
{
Expand Down Expand Up @@ -244,7 +244,7 @@ describe('structurally can walk all nodes', () => {
expect(columns).toMatchObject([
{
type: 'literal',
literalType: 'number',
literalType: 'integer',
name: '1',
},
{
Expand All @@ -264,7 +264,7 @@ describe('structurally can walk all nodes', () => {
},
{
type: 'literal',
literalType: 'number',
literalType: 'decimal',
name: '3.14',
},
]);
Expand All @@ -288,12 +288,12 @@ describe('structurally can walk all nodes', () => {
values: [
{
type: 'literal',
literalType: 'number',
literalType: 'integer',
name: '1',
},
{
type: 'literal',
literalType: 'number',
literalType: 'integer',
name: '2',
},
],
Expand All @@ -318,12 +318,12 @@ describe('structurally can walk all nodes', () => {
values: [
{
type: 'literal',
literalType: 'number',
literalType: 'integer',
name: '1',
},
{
type: 'literal',
literalType: 'number',
literalType: 'integer',
name: '2',
},
],
Expand All @@ -333,7 +333,7 @@ describe('structurally can walk all nodes', () => {
values: [
{
type: 'literal',
literalType: 'number',
literalType: 'decimal',
name: '3.3',
},
],
Expand All @@ -342,17 +342,17 @@ describe('structurally can walk all nodes', () => {
expect(literals).toMatchObject([
{
type: 'literal',
literalType: 'number',
literalType: 'integer',
name: '1',
},
{
type: 'literal',
literalType: 'number',
literalType: 'integer',
name: '2',
},
{
type: 'literal',
literalType: 'number',
literalType: 'decimal',
name: '3.3',
},
]);
Expand Down Expand Up @@ -511,7 +511,7 @@ describe('structurally can walk all nodes', () => {

describe('cast expression', () => {
test('can visit cast expression', () => {
const query = 'FROM index | STATS a = 123::number';
const query = 'FROM index | STATS a = 123::integer';
const { ast } = getAstAndSyntaxErrors(query);

const casts: ESQLInlineCast[] = [];
Expand All @@ -523,10 +523,10 @@ describe('structurally can walk all nodes', () => {
expect(casts).toMatchObject([
{
type: 'inlineCast',
castType: 'number',
castType: 'integer',
value: {
type: 'literal',
literalType: 'number',
literalType: 'integer',
value: 123,
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import { join } from 'path';
import _ from 'lodash';
import type { RecursivePartial } from '@kbn/utility-types';
import { FunctionDefinition } from '../src/definitions/types';
import { esqlToKibanaType } from '../src/shared/esql_to_kibana_type';

const aliasTable: Record<string, string[]> = {
to_version: ['to_ver'],
Expand Down Expand Up @@ -240,10 +239,10 @@ function getFunctionDefinition(ESFunctionDefinition: Record<string, any>): Funct
...signature,
params: signature.params.map((param: any) => ({
...param,
type: esqlToKibanaType(param.type),
type: param.type,
description: undefined,
})),
returnType: esqlToKibanaType(signature.returnType),
returnType: signature.returnType,
variadic: undefined, // we don't support variadic property
minParams: signature.variadic
? signature.params.filter((param: any) => !param.optional).length
Expand Down
Loading

0 comments on commit 7dca2aa

Please sign in to comment.