Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support sql direct query visualizations #1524

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions common/query_manager/query_parser/sql_query_parser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import { getGroupBy } from './sql_query_parser';

describe('sql parser', () => {
it('parses a single field', async () => {
const results = getGroupBy('select count(*), field from index group by field');
expect(results).toMatchInlineSnapshot(`
Object {
"aggregations": Array [
Object {
"function": Object {
"name": "count",
"percentile_agg_function": "",
"value_expression": "*",
},
"function_alias": "",
},
],
"groupby": Object {
"group_fields": Array [
Object {
"name": "field",
},
],
"span": null,
},
}
`);
});

it('removes backticks', async () => {
const results = getGroupBy('select count(*), `field` from index group by `field`');
expect(results).toMatchInlineSnapshot(`
Object {
"aggregations": Array [
Object {
"function": Object {
"name": "count",
"percentile_agg_function": "",
"value_expression": "*",
},
"function_alias": "",
},
],
"groupby": Object {
"group_fields": Array [
Object {
"name": "field",
},
],
"span": null,
},
}
`);
});

it('parses multiple fields', async () => {
const results = getGroupBy(
'select a, count(*) as b, avg(c) as d from index where 1 = 1 group by span(a, 1d) as e, f, g limit 10'
);
expect(results).toMatchInlineSnapshot(`
Object {
"aggregations": Array [
Object {
"function": Object {
"name": "count",
"percentile_agg_function": "",
"value_expression": "*",
},
"function_alias": "b",
},
Object {
"function": Object {
"name": "avg",
"percentile_agg_function": "",
"value_expression": "c",
},
"function_alias": "d",
},
],
"groupby": Object {
"group_fields": Array [
Object {
"name": "f",
},
Object {
"name": "g",
},
],
"span": Object {
"customLabel": "e",
"span_expression": Object {
"field": "a",
"literal_value": "1",
"time_unit": "d",
"type": "",
},
},
},
}
`);
});
});
67 changes: 67 additions & 0 deletions common/query_manager/query_parser/sql_query_parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

import { statsChunk } from '../ast/types/stats';

/**
* This is a temporary solution before introducing SQL antlrs.
* @param query - sql query
*/
export const getGroupBy = (query: string): Pick<statsChunk, 'aggregations' | 'groupby'> => {
let match;
const regex = /(?:SELECT\s+)?(?:(\w+)\(([^\)]+)\))(?:\s+AS\s+(\S+))?\s*(?:,|\bFROM\b|$)|(?:GROUP\s+BY\s+)(?:SPAN\(([^,]+?)(?:\s*,\s*)(\d+)(\w+)\)(?:\s+AS\s+(\S+))?)?((?:(?:\s*,\s*)?(?:[^\s,]+))+)/gi;
const chunk: Pick<statsChunk, 'aggregations' | 'groupby'> = {
aggregations: [],
groupby: { group_fields: [], span: null },
};

while ((match = regex.exec(query)) !== null) {
for (let i = 0; i < match.length; i++) {
if (match[i] === undefined) match[i] = '';
}

const [
_,
aggFunc,
aggExpr,
aggAlias,
spanField,
spanAmount,
spanUnit,
spanAlias,
groupByFields,
] = match;
if (aggFunc) {
chunk.aggregations.push({
function_alias: aggAlias,
function: {
name: aggFunc,
value_expression: aggExpr,
percentile_agg_function: '',
},
});
}
if (spanField && spanAmount && spanUnit) {
chunk.groupby.span = {
customLabel: spanAlias,
span_expression: {
field: spanField,
type: '',
literal_value: spanAmount,
time_unit: spanUnit,
},
};
}
if (groupByFields) {
chunk.groupby.group_fields.push(
...groupByFields
.split(',')
.map((field) => ({ name: field.replace(/^\s*`?|`?\s*$/g, '') }))
.filter((field) => field.name)
);
}
}
return chunk;
};
40 changes: 20 additions & 20 deletions public/components/event_analytics/explorer/explorer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
PPL_NEWLINE_REGEX,
} from '../../../../common/constants/shared';
import { QueryManager } from '../../../../common/query_manager';
import { getGroupBy } from '../../../../common/query_manager/query_parser/sql_query_parser';
import {
IExplorerProps,
IField,
Expand Down Expand Up @@ -128,7 +129,6 @@
import { TimechartHeader } from './timechart_header';
import { ExplorerVisualizations } from './visualizations';
import { CountDistribution } from './visualizations/count_distribution';
import { DirectQueryVisualization } from './visualizations/direct_query_vis';

export const Explorer = ({
pplService,
Expand Down Expand Up @@ -204,7 +204,7 @@
return explorerSearchMeta.datasources?.[0]?.type
? dataSourcePluggables[explorerSearchMeta?.datasources[0]?.type]
: dataSourcePluggables.DEFAULT_INDEX_PATTERNS;
}, [explorerSearchMeta.datasources]);

Check warning on line 207 in public/components/event_analytics/explorer/explorer.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useMemo has a missing dependency: 'dataSourcePluggables'. Either include it or remove the dependency array
const { ui } =
currentPluggable?.getComponentSetForVariation(
'languages',
Expand Down Expand Up @@ -288,10 +288,10 @@
setRefresh({});
});
}
}, []);

Check warning on line 291 in public/components/event_analytics/explorer/explorer.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'http'. Either include it or remove the dependency array

const getErrorHandler = (title: string) => {
return (error: any) => {

Check warning on line 294 in public/components/event_analytics/explorer/explorer.tsx

View workflow job for this annotation

GitHub Actions / Lint

Unexpected any. Specify a different type
if (coreRefs.summarizeEnabled) return;
const formattedError = formatError(error.name, error.message, error.body.message);
notifications.toasts.addError(formattedError, {
Expand Down Expand Up @@ -406,7 +406,7 @@
callbackInApp(() => prepareAvailability());
}
}
}, [appBasedRef.current]);

Check warning on line 409 in public/components/event_analytics/explorer/explorer.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has missing dependencies: 'callback', 'callbackInApp', and 'prepareAvailability'. Either include them or remove the dependency array. Mutable values like 'appBasedRef.current' aren't valid dependencies because mutating them doesn't re-render the component

useEffect(() => {
if (
Expand All @@ -415,14 +415,14 @@
) {
setSelectedContentTab(TAB_CHART_ID);
}
}, []);

Check warning on line 418 in public/components/event_analytics/explorer/explorer.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'routerContext'. Either include it or remove the dependency array

useEffect(() => {
if (savedObjectId && !isObjectIdUpdatedFromSave.current) {
updateTabData(savedObjectId);
isObjectIdUpdatedFromSave.current = false;
}
}, [savedObjectId]);

Check warning on line 425 in public/components/event_analytics/explorer/explorer.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useEffect has a missing dependency: 'updateTabData'. Either include it or remove the dependency array

const handleTimePickerChange = async (timeRange: string[]) => {
if (appLogEvents) {
Expand Down Expand Up @@ -496,7 +496,7 @@
return hits;
}
return 0;
}, [countDistribution?.data]);

Check warning on line 499 in public/components/event_analytics/explorer/explorer.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useMemo has missing dependencies: 'isLiveTailOn' and 'liveHits'. Either include them or remove the dependency array

const mainContent = useMemo(() => {
return (
Expand Down Expand Up @@ -627,7 +627,7 @@
)}
</div>
);
}, [

Check warning on line 630 in public/components/event_analytics/explorer/explorer.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useMemo has missing dependencies: 'appLogEvents', 'dispatch', 'endTime', 'getCountVisualizations', 'getErrorHandler', 'getPatterns', 'handleTimeRangePickerRefresh', 'http', 'isDefaultDataSourceType', 'liveTimestamp', 'pplService', 'requestParams', 'startTime', 'tabId', 'timeIntervalOptions', and 'totalHits'. Either include them or remove the dependency array. Mutable values like 'isLiveTailOnRef.current' aren't valid dependencies because mutating them doesn't re-render the component
isPanelTextFieldInvalid,
explorerData,
explorerFields,
Expand All @@ -642,7 +642,11 @@
const visualizationSettings = !isEmpty(userVizConfigs[curVisId])
? { ...userVizConfigs[curVisId] }
: {
dataConfig: getDefaultVisConfig(queryManager.queryParser().parse(tempQuery).getStats()),
dataConfig: getDefaultVisConfig(
explorerSearchMeta.lang === QUERY_LANGUAGE.SQL
? getGroupBy(tempQuery)
: queryManager.queryParser().parse(tempQuery).getStats()
),
};

const visualizations: IVisualizationContainerProps = useMemo(() => {
Expand All @@ -658,7 +662,7 @@
appData: { fromApp: appLogEvents },
explorer: { explorerData, explorerFields, query, http, pplService },
});
}, [curVisId, explorerVisualizations, explorerFields, query, userVizConfigs]);

Check warning on line 665 in public/components/event_analytics/explorer/explorer.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useMemo has missing dependencies: 'appLogEvents', 'explorerData', 'http', 'pplService', and 'visualizationSettings'. Either include them or remove the dependency array

const callbackForConfig = (childFunc: () => void) => {
if (childFunc && triggerAvailability) {
Expand All @@ -667,8 +671,8 @@
}
};

const explorerVis = useMemo(() => {
return isDefaultDataSourceType || appLogEvents ? (
const explorerVis = useMemo(
() => (
<ExplorerVisualizations
query={query}
curVisId={curVisId}
Expand All @@ -680,23 +684,19 @@
handleOverrideTimestamp={handleOverrideTimestamp}
callback={callbackForConfig}
queryManager={queryManager}
shouldShowConfigurationUI={isDefaultDataSourceType}
/>
) : (
<DirectQueryVisualization
currentDataSource={
explorerSearchMeta.datasources ? explorerSearchMeta.datasources?.[0]?.label : ''
}
/>
);
}, [
query,
curVisId,
explorerFields,
explorerVisualizations,
explorerData,
visualizations,
explorerSearchMeta.datasources,
]);
),
[

Check warning on line 690 in public/components/event_analytics/explorer/explorer.tsx

View workflow job for this annotation

GitHub Actions / Lint

React Hook useMemo has missing dependencies: 'callbackForConfig', 'handleOverrideTimestamp', 'isDefaultDataSourceType', and 'queryManager'. Either include them or remove the dependency array
query,
curVisId,
explorerFields,
explorerVisualizations,
explorerData,
visualizations,
explorerSearchMeta.datasources,
]
);

const contentTabs = [
{
Expand Down

This file was deleted.

Loading
Loading