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

refactor: get Axis from a helper function #21449

Merged
merged 3 commits into from
Sep 16, 2022
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,26 @@
* under the License.
*/
import {
DTTM_ALIAS,
ensureIsArray,
getColumnLabel,
getMetricLabel,
PostProcessingPivot,
} from '@superset-ui/core';
import { PostProcessingFactory } from './types';
import { getAxis } from './utils';

export const pivotOperator: PostProcessingFactory<PostProcessingPivot> = (
formData,
queryObject,
) => {
const metricLabels = ensureIsArray(queryObject.metrics).map(getMetricLabel);
const { x_axis: xAxis } = formData;
const xAxis = getAxis(formData);

if ((xAxis || queryObject.is_timeseries) && metricLabels.length) {
const index = [getColumnLabel(xAxis || DTTM_ALIAS)];
if (xAxis && metricLabels.length) {
return {
operation: 'pivot',
options: {
index,
index: [xAxis],
columns: ensureIsArray(queryObject.columns).map(getColumnLabel),
// Create 'dummy' mean aggregates to assign cell values in pivot table
// use the 'mean' aggregates to avoid drop NaN. PR: https://github.com/apache-superset/superset-ui/pull/1231
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,17 @@
* specific language governing permissions and limitationsxw
* under the License.
*/
import {
DTTM_ALIAS,
getColumnLabel,
PostProcessingProphet,
} from '@superset-ui/core';
import { PostProcessingProphet } from '@superset-ui/core';
import { PostProcessingFactory } from './types';
import { getAxis } from './utils';

/* eslint-disable @typescript-eslint/no-unused-vars */
export const prophetOperator: PostProcessingFactory<PostProcessingProphet> = (
formData,
queryObject,
) => {
const index = getColumnLabel(formData.x_axis || DTTM_ALIAS);
if (formData.forecastEnabled) {
const xAxis = getAxis(formData);
if (formData.forecastEnabled && xAxis) {
return {
operation: 'prophet',
options: {
Expand All @@ -39,7 +36,7 @@ export const prophetOperator: PostProcessingFactory<PostProcessingProphet> = (
yearly_seasonality: formData.forecastSeasonalityYearly,
weekly_seasonality: formData.forecastSeasonalityWeekly,
daily_seasonality: formData.forecastSeasonalityDaily,
index,
index: xAxis,
},
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,33 +18,32 @@
* under the License.
*/
import {
DTTM_ALIAS,
ensureIsArray,
getColumnLabel,
NumpyFunction,
PostProcessingPivot,
} from '@superset-ui/core';
import { getMetricOffsetsMap, isTimeComparison } from './utils';
import { getMetricOffsetsMap, isTimeComparison, getAxis } from './utils';
import { PostProcessingFactory } from './types';

export const timeComparePivotOperator: PostProcessingFactory<PostProcessingPivot> =
(formData, queryObject) => {
const metricOffsetMap = getMetricOffsetsMap(formData, queryObject);
const xAxis = getAxis(formData);

if (isTimeComparison(formData, queryObject)) {
if (isTimeComparison(formData, queryObject) && xAxis) {
const aggregates = Object.fromEntries(
[...metricOffsetMap.values(), ...metricOffsetMap.keys()].map(metric => [
metric,
// use the 'mean' aggregates to avoid drop NaN
{ operator: 'mean' as NumpyFunction },
]),
);
const index = [getColumnLabel(formData.x_axis || DTTM_ALIAS)];

return {
operation: 'pivot',
options: {
index,
index: [xAxis],
columns: ensureIsArray(queryObject.columns).map(getColumnLabel),
drop_missing_columns: !formData?.show_empty_columns,
aggregates,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import {
DTTM_ALIAS,
getColumnLabel,
isDefined,
QueryFormData,
} from '@superset-ui/core';

export const getAxis = (formData: QueryFormData): string | undefined => {
// The formData should be "raw form_data" -- the snake_case version of formData rather than camelCase.
if (!(formData.granularity_sqla || formData.x_axis)) {
return undefined;
}

return isDefined(formData.x_axis)
? getColumnLabel(formData.x_axis)
: DTTM_ALIAS;
};
Comment on lines +26 to +35
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To future proof this to n dimensions, I think it might make sense to call this helper getBaseAxes that returns an array (that way we also wouldn't need to wrap the return value in an array when passing it to the index prop). Also, I believe the return type should be based on QueryFormColumn, as it may also be an AdhocColumn. So maybe the sig should be

export const getBaseAxes = (formData: QueryFormData): QueryFormColumn[] | undefined => {...}

Also, shouldn't we assume that the return value should always be defined, i.e. we always fall back to DTTM_ALIAS (at least for now) unless formData.x_axis is defined?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function returns a label of a column(the label of the columns, or alias clause for the SQL), so the return value might be a string rather than a structure data(QueryFormColumn).

another issue is that whether the return value is a string or a string array. both work for me, but the string array return value might not directly apply to the post processing function. I promise that if we will support the multiple axes, I am going to refactor this.

The undefined value represents a form_data that cannot apply a query with an axis. For example, if a form_data had granularity_sqla neither nor axis, this function would return an undefined value, then the caller should easily skip some logic.

Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,4 @@ export { getMetricOffsetsMap } from './getMetricOffsetsMap';
export { isTimeComparison } from './isTimeComparison';
export { isDerivedSeries } from './isDerivedSeries';
export { TIME_COMPARISON_SEPARATOR } from './constants';
export { getAxis } from './getAxis';
Original file line number Diff line number Diff line change
Expand Up @@ -56,21 +56,20 @@ const queryObject: QueryObject = {

test('skip pivot', () => {
expect(pivotOperator(formData, queryObject)).toEqual(undefined);
expect(
pivotOperator(formData, { ...queryObject, is_timeseries: false }),
).toEqual(undefined);
expect(
pivotOperator(formData, {
...queryObject,
is_timeseries: true,
metrics: [],
}),
).toEqual(undefined);
});

test('pivot by __timestamp without groupby', () => {
expect(
pivotOperator(formData, { ...queryObject, is_timeseries: true }),
pivotOperator(
{ ...formData, granularity_sqla: 'time_column' },
queryObject,
),
).toEqual({
operation: 'pivot',
options: {
Expand All @@ -87,11 +86,13 @@ test('pivot by __timestamp without groupby', () => {

test('pivot by __timestamp with groupby', () => {
expect(
pivotOperator(formData, {
...queryObject,
columns: ['foo', 'bar'],
is_timeseries: true,
}),
pivotOperator(
{ ...formData, granularity_sqla: 'time_column' },
{
...queryObject,
columns: ['foo', 'bar'],
},
),
).toEqual({
operation: 'pivot',
options: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ test('should do prophetOperator with default index', () => {
prophetOperator(
{
...formData,
granularity_sqla: 'time_column',
forecastEnabled: true,
forecastPeriods: '3',
forecastInterval: '5',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ test('should pivot on any type of timeCompare', () => {
...formData,
comparison_type: cType,
time_compare: ['1 year ago', '1 year later'],
granularity_sqla: 'time_column',
},
{
...queryObject,
is_timeseries: true,
},
),
).toEqual({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export function normalizeTimeColumn(
formData: QueryFormData,
queryObject: QueryObject,
): QueryObject {
// The formData should be "raw form_data" -- the snake_case version of formData rather than camelCase.
if (!(isFeatureEnabled(FeatureFlag.GENERIC_CHART_AXES) && formData.x_axis)) {
return queryObject;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,18 +20,17 @@
import {
AnnotationLayer,
CategoricalColorNamespace,
DTTM_ALIAS,
GenericDataType,
getColumnLabel,
getNumberFormatter,
isEventAnnotationLayer,
isFormulaAnnotationLayer,
isIntervalAnnotationLayer,
isTimeseriesAnnotationLayer,
TimeseriesChartDataResponseResult,
t,
DTTM_ALIAS,
} from '@superset-ui/core';
import { isDerivedSeries } from '@superset-ui/chart-controls';
import { getAxis, isDerivedSeries } from '@superset-ui/chart-controls';
import { EChartsCoreOption, SeriesOption } from 'echarts';
import { ZRLineType } from 'echarts/types/src/util/types';
import {
Expand Down Expand Up @@ -149,8 +148,9 @@ export default function transformProps(

const colorScale = CategoricalColorNamespace.getScale(colorScheme as string);
const rebasedData = rebaseForecastDatum(data, verboseMap);
// todo: if the both granularity_sqla and x_axis are `null`, should throw an error
const xAxisCol =
verboseMap[xAxisOrig] || getColumnLabel(xAxisOrig || DTTM_ALIAS);
verboseMap[xAxisOrig] || getAxis(chartProps.rawFormData) || DTTM_ALIAS;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we make getAxis always return a non-undefined value, then we won't need to have the || DTTM_ALIAS here, right? It feels slightly redundant, as it feels like the getAxis helper should always return a value (or raise if it can't).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the DTTM_ALIAS is a redundant case. I consider that if a chart can't have an axis here, the chart should throw an error, but there wasn't an appropriate approach to throw an error in the Chart and TS throw a type error, so I added a redundant condition here. I think we need to catch this error in the separated PR.

const isHorizontal = orientation === OrientationType.horizontal;
const { totalStackedValues, thresholdValues } = extractDataTotalValues(
rebasedData,
Expand Down