john-bodley commented on a change in pull request #9065: [sqla] Fixing ORDER BY 
logic
URL: 
https://github.com/apache/incubator-superset/pull/9065#discussion_r373742361
 
 

 ##########
 File path: superset/connectors/sqla/models.py
 ##########
 @@ -841,13 +841,27 @@ def get_sqla_query(  # sqla
         if not orderby and not columns:
             orderby = [(main_metric_expr, not order_desc)]
 
+        # To ensure correct handling of the ORDER BY labeling we need to 
reference the
+        # metric instance if defined in the SELECT clause.
+        metrics_exprs_by_name = {str(m): m for m in metrics_exprs}
+
         for col, ascending in orderby:
             direction = asc if ascending else desc
-            if utils.is_adhoc_metric(col):
-                col = self.adhoc_metric_to_sqla(col, cols)
-            elif col in cols:
-                col = cols[col].get_sqla_col()
-            qry = qry.order_by(direction(col))
+            sqla_col = None
+
+            if isinstance(col, Column):
+                sqla_col = col
+            else:
+                if utils.is_adhoc_metric(col):
+                    sqla_col = self.adhoc_metric_to_sqla(col, cols)
+                elif col in cols:
+                    sqla_col = cols[col].get_sqla_col()
+
+                if sqla_col is not None and str(sqla_col) in 
metrics_exprs_by_name:
 
 Review comment:
   Matching of the string representation of a SQLAlchemy column seems kludgy 
though I'm not certain of a better approach. I initially was going to create an 
`OrderedDict` of `metrics` to `metric_expr` however the `metric` can be a 
`dict` which isn't hashable.  

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to