Skip to content
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
15 changes: 15 additions & 0 deletions superset/models/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2800,6 +2800,21 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
col = self.convert_tbl_column_to_sqla_col(
columns_by_name[col], template_processor=template_processor
)
elif isinstance(col, str) and columns:
# Check if this is a label reference to an adhoc column
adhoc_col = next(
(
c
for c in columns
if utils.is_adhoc_column(c) and c.get("label") == col
),
None,
)
if adhoc_col:
col = self.adhoc_column_to_sqla(
col=adhoc_col,
template_processor=template_processor,
)

Comment thread
wuqicyber marked this conversation as resolved.
if isinstance(col, ColumnElement):
orderby_exprs.append(col)
Expand Down
40 changes: 40 additions & 0 deletions tests/unit_tests/models/helpers_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1703,3 +1703,43 @@ def test_adhoc_column_with_spaces_in_full_query(database: Database) -> None:
# Verify SELECT and FROM clauses are present
assert "SELECT" in sql
assert "FROM" in sql


def test_orderby_adhoc_column(database: Database) -> None:
"""
Test that orderby works with adhoc column labels.

When orderby contains a string that matches the label of an adhoc column
in the columns list, it should correctly convert to a SQLAlchemy column
instead of raising QueryObjectValidationError.
"""
from superset.connectors.sqla.models import SqlaTable, TableColumn

table = SqlaTable(
database=database,
schema=None,
table_name="t",
columns=[
TableColumn(column_name="a"),
TableColumn(column_name="b"),
],
)

# Should not raise QueryObjectValidationError
result = table.get_sqla_query(
columns=[
{"expressionType": "SQL", "label": "custom_col", "sqlExpression": "a + 1"},
"b",
],
orderby=[("custom_col", False)], # Order by adhoc column label
metrics=[],
extras={},
filter=[],
granularity=None,
is_timeseries=False,
)
assert result is not None

# Verify the SQL contains the expression from the adhoc column
sql = str(result.sqla_query)
assert "ORDER BY" in sql.upper()
Loading