Skip to content
This repository was archived by the owner on Dec 10, 2021. It is now read-only.
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
7 changes: 7 additions & 0 deletions packages/superset-ui-chart-controls/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* under the License.
*/
import { t } from '@superset-ui/core';
import { ColumnMeta } from './types';

// eslint-disable-next-line import/prefer-default-export
export const TIME_FILTER_LABELS = {
Expand All @@ -26,3 +27,9 @@ export const TIME_FILTER_LABELS = {
druid_time_origin: t('Origin'),
granularity: t('Time Granularity'),
};

export const TIME_COLUMN_OPTION: ColumnMeta = {
verbose_name: t('Time'),
column_name: '__timestamp',
description: t('A reference to the [Time] configuration, taking granularity into account'),
};
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,7 @@
*/
import { t, validateNonEmpty } from '@superset-ui/core';
import { ExtraControlProps, SharedControlConfig } from '../types';

const timeColumnOption = {
verbose_name: t('Time'),
column_name: '__timestamp',
description: t('A reference to the [Time] configuration, taking granularity into account'),
};
import { TIME_COLUMN_OPTION } from '../constants';

export const dndGroupByControl: SharedControlConfig<'DndColumnSelect'> = {
type: 'DndColumnSelect',
Expand All @@ -36,7 +31,7 @@ export const dndGroupByControl: SharedControlConfig<'DndColumnSelect'> = {
if (state.datasource) {
const options = state.datasource.columns.filter(c => c.groupby);
if (includeTime) {
options.unshift(timeColumnOption);
options.unshift(TIME_COLUMN_OPTION);
}
newState.options = Object.fromEntries(options.map(option => [option.column_name, option]));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import {
} from '@superset-ui/core';

import { mainMetric, formatSelectOptions } from '../utils';
import { TIME_FILTER_LABELS } from '../constants';
import { TIME_FILTER_LABELS, TIME_COLUMN_OPTION } from '../constants';
import {
Metric,
SharedControlConfig,
Expand Down Expand Up @@ -103,12 +103,6 @@ export const D3_TIME_FORMAT_OPTIONS = [

export const D3_TIME_FORMAT_DOCS = t('D3 time format syntax: https://github.com/d3/d3-time-format');

const timeColumnOption = {
verbose_name: t('Time'),
column_name: '__timestamp',
description: t('A reference to the [Time] configuration, taking granularity into account'),
};

type Control = {
savedMetrics?: Metric[] | null;
default?: unknown;
Expand Down Expand Up @@ -137,7 +131,7 @@ const groupByControl: SharedControlConfig<'SelectControl', ColumnMeta> = {
if (state.datasource) {
const options = state.datasource.columns.filter(c => c.groupby);
if (includeTime) {
options.unshift(timeColumnOption);
options.unshift(TIME_COLUMN_OPTION);
}
newState.options = options;
}
Expand Down
14 changes: 4 additions & 10 deletions packages/superset-ui-chart-controls/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
* under the License.
*/
import React, { ReactNode, ReactText, ReactElement } from 'react';
import { QueryFormData, DatasourceType, Metric, JsonValue } from '@superset-ui/core';
import { QueryFormData, DatasourceType, Metric, JsonValue, Column } from '@superset-ui/core';
import sharedControls from './shared-controls';
import sharedControlComponents from './shared-controls/components';

Expand All @@ -38,16 +38,10 @@ export type SharedControlComponents = typeof sharedControlComponents;
/** ----------------------------------------------
* Input data/props while rendering
* ---------------------------------------------*/
export interface ColumnMeta extends AnyDict {
column_name: string;
groupby?: string;
verbose_name?: string;
description?: string;
expression?: string;
is_dttm?: boolean;
export type ColumnMeta = Omit<Column, 'id' | 'type'> & {
id?: number;
type?: string;
filterable?: boolean;
}
} & AnyDict;

export interface DatasourceMeta {
id: number;
Expand Down
83 changes: 45 additions & 38 deletions packages/superset-ui-core/src/query/extractQueryFields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,15 @@ import { t } from '../translation';
import { removeDuplicates } from '../utils';
import { DTTM_ALIAS } from './buildQueryObject';
import getMetricLabel from './getMetricLabel';
import { QueryFields, QueryFieldAliases, FormDataResidual, QueryMode } from './types/QueryFormData';
import {
QueryFields,
QueryFormColumn,
QueryFormMetric,
QueryFormOrderBy,
QueryFieldAliases,
FormDataResidual,
QueryMode,
} from './types/QueryFormData';

/**
* Extra SQL query related fields from chart form data.
Expand All @@ -47,13 +55,12 @@ export default function extractQueryFields(
order_by_cols: 'orderby',
...aliases,
};
const finalQueryFields: QueryFields = {
columns: [],
metrics: [],
orderby: [],
};
const { query_mode: queryMode, include_time: includeTime, ...restFormData } = formData;

let columns: QueryFormColumn[] = [];
let metrics: QueryFormMetric[] = [];
let orderby: QueryFormOrderBy[] = [];

Object.entries(restFormData).forEach(([key, value]) => {
// ignore `null` or `undefined` value
if (value == null) {
Expand All @@ -62,14 +69,6 @@ export default function extractQueryFields(

let normalizedKey: string = queryFieldAliases[key] || key;

// ignore groupby and metrics when in raw records mode
if (
queryMode === QueryMode.raw &&
(normalizedKey === 'groupby' || normalizedKey === 'metrics')
) {
return;
}

// ignore columns when (specifically) in aggregate mode.
// For charts that support both aggregate and raw records mode,
// we store both `groupby` and `columns` in `formData`, so users can
Expand All @@ -78,42 +77,50 @@ export default function extractQueryFields(
return;
}

// for the same reason, ignore groupby and metrics in raw records mode
if (
queryMode === QueryMode.raw &&
(normalizedKey === 'groupby' || normalizedKey === 'metrics')
) {
return;
}

// groupby has been deprecated in QueryObject: https://github.com/apache/superset/pull/9366
// We translate all `groupby` to `columns`.
if (normalizedKey === 'groupby') {
normalizedKey = 'columns';
}

if (normalizedKey === 'metrics') {
finalQueryFields[normalizedKey] = finalQueryFields[normalizedKey].concat(value);
metrics = metrics.concat(value);
} else if (normalizedKey === 'columns') {
// currently the columns field only accept pre-defined columns (string shortcut)
finalQueryFields[normalizedKey] = finalQueryFields[normalizedKey]
.concat(value)
.filter(x => typeof x === 'string' && x);
columns = columns.concat(value);
} else if (normalizedKey === 'orderby') {
finalQueryFields[normalizedKey] = finalQueryFields[normalizedKey].concat(value).map(item => {
// value can be in the format of `['["col1", true]', '["col2", false]'],
// where the option strings come directly from `order_by_choices`.
if (typeof item === 'string') {
try {
return JSON.parse(item);
} catch (error) {
throw new Error(t('Found invalid orderby options'));
}
}
return item;
});
orderby = orderby.concat(value);
}
});

if (includeTime && !finalQueryFields.columns.includes(DTTM_ALIAS)) {
finalQueryFields.columns.unshift(DTTM_ALIAS);
if (includeTime && !columns.includes(DTTM_ALIAS)) {
columns.unshift(DTTM_ALIAS);
}

// remove duplicate columns and metrics
finalQueryFields.columns = removeDuplicates(finalQueryFields.columns);
finalQueryFields.metrics = removeDuplicates(finalQueryFields.metrics, getMetricLabel);

return finalQueryFields;
return {
columns: removeDuplicates(columns.filter(x => typeof x === 'string' && x)),
metrics: queryMode === QueryMode.raw ? undefined : removeDuplicates(metrics, getMetricLabel),
orderby:
orderby.length > 0
? orderby.map(item => {
// value can be in the format of `['["col1", true]', '["col2", false]'],
// where the option strings come directly from `order_by_choices`.
if (typeof item === 'string') {
try {
return JSON.parse(item);
} catch (error) {
throw new Error(t('Found invalid orderby options'));
}
}
return item;
})
: undefined,
};
}
2 changes: 1 addition & 1 deletion packages/superset-ui-core/src/query/getMetricLabel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default function getMetricLabel(metric: QueryFormMetric) {
return metric.label;
}
if (metric.expressionType === 'SIMPLE') {
return `${metric.aggregate}(${metric.column.columnName})`;
return `${metric.aggregate}(${metric.column.columnName || metric.column.column_name})`;
}
return metric.sqlExpression;
}
10 changes: 9 additions & 1 deletion packages/superset-ui-core/src/query/types/Column.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,15 @@ export enum ColumnType {
export interface Column {
id: number;
type: ColumnType;
columnName: string;
column_name: string;
groupby?: boolean;
is_dttm?: boolean;
filterable?: boolean;
verbose_name?: string | null;
description?: string | null;
expression?: string | null;
database_expression?: string | null;
python_date_format?: string | null;
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Consolidate types from Column and ColumnMeta.

}

export default {};
5 changes: 4 additions & 1 deletion packages/superset-ui-core/src/query/types/Metric.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,10 @@ export interface AdhocMetricBase {

export interface AdhocMetricSimple extends AdhocMetricBase {
expressionType: 'SIMPLE';
column: Column;
column: Omit<Column, 'column_name'> & {
column_name?: string;
columnName?: string;
};
aggregate: Aggregate;
}

Expand Down
4 changes: 2 additions & 2 deletions packages/superset-ui-core/src/query/types/QueryFormData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ export enum QueryMode {
*/
export interface QueryFields {
columns: QueryFormColumn[];
metrics: QueryFormMetric[];
orderby: QueryFormOrderBy[];
metrics?: QueryFormMetric[];
orderby?: QueryFormOrderBy[];
}

/**
Expand Down
38 changes: 38 additions & 0 deletions packages/superset-ui-core/test/fixtures.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* 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 { AdhocMetric, ColumnType } from '../src';

export const NUM_METRIC: AdhocMetric = {
expressionType: 'SIMPLE',
label: 'Sum(num)',
column: {
id: 336,
type: ColumnType.BIGINT,
column_name: 'num',
verbose_name: null,
description: null,
expression: '',
filterable: false,
groupby: false,
is_dttm: false,
database_expression: null,
python_date_format: null,
},
aggregate: 'SUM',
};
Loading