Skip to content

Commit

Permalink
[ES|QL] Add improved support for Elasticsearch sub-types in AST for b…
Browse files Browse the repository at this point in the history
…oth validation and autocomplete (elastic#188600)

## Summary

This PR addresses elastic#174710 and
leverages sub-types in AST for both validation and autocomplete. Changes
include:
- Expanded the automatically generated function signatures to not longer
cast to `string` or `number`. Instead, it expands out to `keyword`,
`text`, `double`, `long`, `float`, etc.
- Expanded math function signatures to reflect the true return types
(e.g double + interger => double)
- Expanded function signatures for `bucket`
- Expanded builtin functions to better support types
-  Literal support: 
- Added a `decimal` literal context → Which will be accepted by function
signatures for 'double', 'long', 'float', etc.
- Added and `integer` literal type → Which will be accepted by function
signatures for 'interger'
- Updated tests

After:
<img width="1181" alt="Screenshot 2024-07-24 at 13 06 23"
src="https://github.com/user-attachments/assets/42f32f3b-2e6e-4dff-8b20-dd60f8c45750">
<img width="1726" alt="Screenshot 2024-07-24 at 13 06 47"
src="https://github.com/user-attachments/assets/3c6f1eac-600e-4b2c-9e57-f71f79ad9ce9">
<img width="1726" alt="Screenshot 2024-07-24 at 13 07 09"
src="https://github.com/user-attachments/assets/e8b5817e-d4de-446b-8b41-c6c7b8612420">

### 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
- [x] [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&mdash;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&mdash;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 Jul 31, 2024
1 parent 0be8295 commit d9282a6
Show file tree
Hide file tree
Showing 37 changed files with 31,828 additions and 15,502 deletions.
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
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
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 d9282a6

Please sign in to comment.