Skip to content

fix: Handle aggregate expressions in chart sorting#1389

Draft
sentry[bot] wants to merge 1 commit into
mainfrom
seer/fix/handle-agg-sort-expressions
Draft

fix: Handle aggregate expressions in chart sorting#1389
sentry[bot] wants to merge 1 commit into
mainfrom
seer/fix/handle-agg-sort-expressions

Conversation

@sentry

@sentry sentry Bot commented May 27, 2026

Copy link
Copy Markdown

This PR addresses the ProgrammingError: (psycopg2.errors.UndefinedColumn) column "SUM(silt_achieved)" does not exist that occurred when attempting to sort charts by aggregate expressions (e.g., SUM(silt_achieved)).

Root Cause:
The apply_chart_sorting() function in ddpui/core/charts/charts_service.py was incorrectly treating aggregate expressions provided in the sort configuration as raw column names. When SQLAlchemy processed these, it would quote them as literal identifiers (e.g., "SUM(silt_achieved)"), which do not exist as actual columns in the database, leading to the UndefinedColumn error.

Solution:

  1. Enhanced Parsing: The apply_chart_sorting() function now includes logic to detect and parse aggregate-expression-style sort column strings (e.g., SUM(column_name)) using a regular expression.
  2. Metric Matching: After parsing, it first attempts to match the extracted aggregation and column name against the payload.metrics to find a corresponding metric. If a match is found, the metric's alias is used for sorting.
  3. SQLAlchemy Expression Generation: If no direct metric match is found, the function now dynamically constructs the appropriate SQLAlchemy func expression (e.g., func.sum(column('column_name'))) for the ORDER BY clause. These expressions are directly appended to query_builder.order_by_clauses, bypassing the order_cols_by method's default behavior of quoting string column names.

This ensures that aggregate expressions in sort configurations are correctly translated into valid SQL, resolving the UndefinedColumn error.

Fixes DALGO-BACKEND-29P

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants