add tests for this unusual order_by bug

Issue #1218 resolved
Mike Bayer repo owner created an issue

this fix is being committed soon:

Index: lib/sqlalchemy/orm/query.py
===================================================================
--- lib/sqlalchemy/orm/query.py (revision 5244)
+++ lib/sqlalchemy/orm/query.py (working copy)
@@ -195,12 +195,12 @@
         if as_filter and self._filter_aliases:
             adapters.append(self._filter_aliases.replace)

+        if self._from_obj_alias:
+            adapters.append(self._from_obj_alias.replace)
+
         if self._polymorphic_adapters:
             adapters.append(self.__adapt_polymorphic_element)

-        if self._from_obj_alias:
-            adapters.append(self._from_obj_alias.replace)
-
         if not adapters:
             return clause

@@ -1701,9 +1701,9 @@
         if context.order_by is False and self.mapper.order_by:
             context.order_by = self.mapper.order_by

-        if context.order_by and adapter:
-            context.order_by = adapter.adapt_list(util.to_list(context.order_by))
-
+            if adapter:
+                context.order_by = adapter.adapt_list(util.to_list(context.order_by))
+                    
         for value in self.mapper._iterate_polymorphic_properties(self._with_polymorphic):
             if query._only_load_props and value.key not in query._only_load_props:
                 continue

need to understand exactly how the order of adapters in query._adapt_clause is significant here, and also add tests which ensure that the order by is properly rendered for queries with multiple versions of the same entity:

ualias = aliased(User)
sess.query(User, ualias).filter(User.id > ualias.id).order_by(User.id, ualias.id)

Comments (2)

  1. Mike Bayer reporter

    the from_obj adapters have to be first since query.select_from() names a selectable that is the ultimate "thing we are selecting" from, superceding a polymorphic selectable. test coverage is in test/orm/inheritance/polymorphic.py

    test coverage for the order_by fix is in 9b89103394fb90f92763f66de7624ff8bbbe0a58. the aliasing of the mapper order_by is already tested in test/orm/query.py SelectFromTest.test_join_mapper_order_by.

  2. Log in to comment