diff --git a/x-pack/plugins/observability_solution/observability_ai_assistant_app/server/functions/query/correct_common_esql_mistakes.test.ts b/x-pack/plugins/observability_solution/observability_ai_assistant_app/server/functions/query/correct_common_esql_mistakes.test.ts index 9ff8a479535b7..ace8f801c2274 100644 --- a/x-pack/plugins/observability_solution/observability_ai_assistant_app/server/functions/query/correct_common_esql_mistakes.test.ts +++ b/x-pack/plugins/observability_solution/observability_ai_assistant_app/server/functions/query/correct_common_esql_mistakes.test.ts @@ -35,10 +35,13 @@ describe('correctCommonEsqlMistakes', () => { | STATS avg_duration = AVG(transaction.duration.us), total_successes = SUM(success), total_requests = COUNT(*) BY service.name` ); }); - it("replaces ` or ' escaping in FROM statements with double quotes", () => { expectQuery(`FROM "logs-*" | LIMIT 10`, 'FROM "logs-*"\n| LIMIT 10'); expectQuery(`FROM 'logs-*' | LIMIT 10`, 'FROM "logs-*"\n| LIMIT 10'); + expectQuery( + `FROM 'logs-2024-07-01','logs-2024-07-02' | LIMIT 10`, + 'FROM "logs-2024-07-01","logs-2024-07-02"\n| LIMIT 10' + ); expectQuery(`FROM logs-* | LIMIT 10`, 'FROM logs-*\n| LIMIT 10'); }); diff --git a/x-pack/plugins/observability_solution/observability_ai_assistant_app/server/functions/query/correct_common_esql_mistakes.ts b/x-pack/plugins/observability_solution/observability_ai_assistant_app/server/functions/query/correct_common_esql_mistakes.ts index ea61e47c5cfe7..b22960fccd351 100644 --- a/x-pack/plugins/observability_solution/observability_ai_assistant_app/server/functions/query/correct_common_esql_mistakes.ts +++ b/x-pack/plugins/observability_solution/observability_ai_assistant_app/server/functions/query/correct_common_esql_mistakes.ts @@ -4,6 +4,7 @@ * 2.0; you may not use this file except in compliance with the Elastic License * 2.0. */ +import { getIndexPatternFromESQLQuery } from '@kbn/esql-utils'; const STRING_DELIMITER_TOKENS = ['`', "'", '"']; const ESCAPE_TOKEN = '\\\\'; @@ -234,14 +235,14 @@ export function correctCommonEsqlMistakes(query: string): { const formattedCommands: string[] = commands.map(({ name, command }, index) => { let formattedCommand = command; - switch (name) { - case 'FROM': - formattedCommand = formattedCommand - .replaceAll(/FROM '(.*)'/g, 'FROM "$1"') - .replaceAll(/FROM `(.*)`/g, 'FROM "$1"'); + case 'FROM': { + // gets the index pattern from the FROM command using AST parsing + const indexPattern = getIndexPatternFromESQLQuery(formattedCommand); + const indexPatternWithFixedQuotes = replaceSingleQuotesWithDoubleQuotes(indexPattern); + formattedCommand = formattedCommand.replace(indexPattern, indexPatternWithFixedQuotes); break; - + } case 'WHERE': formattedCommand = replaceSingleQuotesWithDoubleQuotes(formattedCommand); formattedCommand = ensureEqualityOperators(formattedCommand);