diff --git a/superset/models/helpers.py b/superset/models/helpers.py index 6c5937e64410..1b49e50aa300 100644 --- a/superset/models/helpers.py +++ b/superset/models/helpers.py @@ -158,7 +158,6 @@ ) from superset.sql.metric_normalization import normalize_custom_metric from superset.sql.parse import ( - has_aggregate, is_constant_expression, sanitize_clause, SQLScript, @@ -7410,36 +7409,6 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma inner_to_dttm or to_dttm, ) - # Gate on `groupby_all_columns` rather than the raw dimensions: it is the - # real GROUP BY signal and also captures the timeseries time bucket. A - # non-aggregate Custom SQL metric under a GROUP BY is invalid SQL, so - # raise a clear error instead of a raw database one (#38913). Templated - # expressions may render to an aggregate at runtime, so leave them alone. - if groupby_all_columns: - for metric in metrics: - if ( - utils.is_adhoc_metric(metric) - and metric.get("expressionType") - == utils.AdhocMetricExpressionType.SQL - ): - expression = metric.get("sqlExpression") - if ( - isinstance(expression, str) - and "{{" not in expression - and "{%" not in expression - and not has_aggregate(expression, self.database.backend) - ): - raise QueryObjectValidationError( - _( - 'The Custom SQL metric "%(metric)s" is not an ' - "aggregate and can't be combined with a GROUP BY. " - "Wrap it in an aggregate function, e.g. " - "%(example)s.", - metric=utils.get_metric_name(metric), - example="MAX(%s)" % expression, - ) - ) - # Always remove duplicates by column name, as sometimes `metrics_exprs` # can have the same name as a groupby column (e.g. when users use # raw columns as custom SQL adhoc metric). diff --git a/superset/translations/messages.pot b/superset/translations/messages.pot index 020b07463cb4..7da07ad6103f 100644 --- a/superset/translations/messages.pot +++ b/superset/translations/messages.pot @@ -14842,10 +14842,6 @@ msgstr "" msgid "The CTAS (create table as select) doesn't have a SELECT statement at the end. Please make sure your query has a SELECT as its last statement. Then, try running your query again." msgstr "" -#, python-format -msgid "The Custom SQL metric \"%(metric)s\" is not an aggregate and can't be combined with a GROUP BY. Wrap it in an aggregate function, e.g. %(example)s." -msgstr "" - msgid "The ENABLE_EXTENSIONS feature flag must be on when the server starts. Enable it in the server configuration and restart." msgstr "" diff --git a/tests/unit_tests/models/helpers_test.py b/tests/unit_tests/models/helpers_test.py index 9010b5da9a80..d3c2c202610e 100644 --- a/tests/unit_tests/models/helpers_test.py +++ b/tests/unit_tests/models/helpers_test.py @@ -2767,51 +2767,11 @@ def test_adhoc_metric_to_sqla_invalid_sql_expression_raises_validation_error( table.adhoc_metric_to_sqla(metric, {}) -def test_get_sqla_query_raises_for_nonaggregate_custom_sql_metric_with_columns( - database: Database, -) -> None: - """ - A grouped query (e.g. a Deck.gl Screen Grid's spatial ``columns``) with a - non-aggregate Custom SQL metric must raise a clear validation error - instead of letting an invalid ``GROUP BY`` reach the database (#38913). - """ - from superset.connectors.sqla.models import SqlaTable, TableColumn - from superset.exceptions import QueryObjectValidationError - - table = SqlaTable( - database=database, - schema=None, - table_name="t", - columns=[ - TableColumn(column_name="lon"), - TableColumn(column_name="lat"), - TableColumn(column_name="confirmed"), - TableColumn(column_name="predicted"), - ], - ) - metric: AdhocMetric = { - "expressionType": "SQL", - "sqlExpression": "GREATEST(confirmed, predicted)", - "label": "weight", - } - - with pytest.raises(QueryObjectValidationError, match="not an aggregate"): - table.get_sqla_query( - columns=["lon", "lat"], - metrics=[metric], - extras={}, - filter=[], - granularity=None, - is_timeseries=False, - ) - - def test_get_sqla_query_allows_aggregate_wrapped_custom_sql_metric_with_columns( database: Database, ) -> None: """ - Wrapping the Custom SQL metric in an aggregate (the fix's guidance) must - let the grouped query build normally. + An aggregate Custom SQL metric builds a grouped query. """ from superset.connectors.sqla.models import SqlaTable, TableColumn @@ -2843,13 +2803,21 @@ def test_get_sqla_query_allows_aggregate_wrapped_custom_sql_metric_with_columns( assert result is not None -def test_get_sqla_query_allows_nonaggregate_custom_sql_metric_without_dimensions( +@pytest.mark.parametrize( + "expression", + [ + "'WIP'", + "NULL", + "(this_week - last_week) / last_week", + ], +) +def test_get_sqla_query_allows_nonaggregate_custom_sql_metric_with_groupby( database: Database, + expression: str, ) -> None: """ - A dimensionless query (e.g. Big Number) built from a non-aggregate Custom - SQL metric alone is valid SQL and must not be blocked: there is no - ``GROUP BY`` for the expression to conflict with. + A constant, or an expression over grouped columns only, is valid SQL under a + GROUP BY, so building the query must not reject it (#46641). """ from superset.connectors.sqla.models import SqlaTable, TableColumn @@ -2858,17 +2826,19 @@ def test_get_sqla_query_allows_nonaggregate_custom_sql_metric_without_dimensions schema=None, table_name="t", columns=[ - TableColumn(column_name="confirmed"), - TableColumn(column_name="predicted"), + TableColumn(column_name="franchise"), + TableColumn(column_name="this_week"), + TableColumn(column_name="last_week"), ], ) metric: AdhocMetric = { "expressionType": "SQL", - "sqlExpression": "GREATEST(confirmed, predicted)", - "label": "weight", + "sqlExpression": expression, + "label": "m", } result = table.get_sqla_query( + columns=["franchise", "this_week", "last_week"], metrics=[metric], extras={}, filter=[], @@ -2878,26 +2848,21 @@ def test_get_sqla_query_allows_nonaggregate_custom_sql_metric_without_dimensions assert result is not None -def test_get_sqla_query_raises_for_nonaggregate_custom_sql_metric_with_groupby( +def test_get_sqla_query_allows_nonaggregate_custom_sql_metric_without_dimensions( database: Database, ) -> None: """ - A ``groupby``-driven grouped query (e.g. a Deck.gl Screen Grid, which sends - its spatial dimensions via ``query_obj["groupby"]`` -- see - ``BaseDeckGLViz.query_obj`` in ``superset/viz.py``) with a non-aggregate - Custom SQL metric must raise the same clear validation error as the - ``columns``-driven case (#38913). + A dimensionless query (e.g. Big Number) built from a non-aggregate Custom + SQL metric alone is valid SQL and must not be blocked: there is no + ``GROUP BY`` for the expression to conflict with. """ from superset.connectors.sqla.models import SqlaTable, TableColumn - from superset.exceptions import QueryObjectValidationError table = SqlaTable( database=database, schema=None, table_name="t", columns=[ - TableColumn(column_name="longitude"), - TableColumn(column_name="latitude"), TableColumn(column_name="confirmed"), TableColumn(column_name="predicted"), ], @@ -2908,54 +2873,14 @@ def test_get_sqla_query_raises_for_nonaggregate_custom_sql_metric_with_groupby( "label": "weight", } - with pytest.raises(QueryObjectValidationError, match="not an aggregate"): - table.get_sqla_query( - groupby=["longitude", "latitude"], - metrics=[metric], - extras={}, - filter=[], - granularity=None, - is_timeseries=False, - ) - - -def test_get_sqla_query_raises_for_nonaggregate_custom_sql_metric_with_timeseries( - database: Database, -) -> None: - """ - A timeseries query's time bucket (from ``granularity``/``is_timeseries``) - also produces a ``GROUP BY``, even with no ``columns``/``groupby`` - dimensions. A non-aggregate Custom SQL metric must be rejected here too - (#38913). - """ - from superset.connectors.sqla.models import SqlaTable, TableColumn - from superset.exceptions import QueryObjectValidationError - - table = SqlaTable( - database=database, - schema=None, - table_name="t", - columns=[ - TableColumn(column_name="ts", type="TIMESTAMP", is_dttm=True), - TableColumn(column_name="confirmed"), - TableColumn(column_name="predicted"), - ], + result = table.get_sqla_query( + metrics=[metric], + extras={}, + filter=[], + granularity=None, + is_timeseries=False, ) - metric: AdhocMetric = { - "expressionType": "SQL", - "sqlExpression": "GREATEST(confirmed, predicted)", - "label": "weight", - } - - with pytest.raises(QueryObjectValidationError, match="not an aggregate"): - table.get_sqla_query( - columns=[], - metrics=[metric], - extras={"time_grain_sqla": "P1D"}, - filter=[], - granularity="ts", - is_timeseries=True, - ) + assert result is not None def test_get_sqla_query_allows_jinja_templated_custom_sql_metric_with_columns(