Improve order by type handling

This commit is contained in:
Konsta Vesterinen
2014-10-21 14:24:17 +03:00
parent 26db4e94b4
commit 3a92a609ea
3 changed files with 20 additions and 0 deletions

View File

@@ -8,6 +8,8 @@ Here you can see the full list of changes between each SQLAlchemy-Utils release.
^^^^^^^^^^^^^^^^^^^
- Fixed MapperEntity handling in get_mapper and get_tables utility functions
- Fixed make_order_by_deterministic handling for queries without order by (no just silently ignores those rather than throws exception)
- Made make_order_by_deterministic if given query uses strings as order by args
0.27.1 (2014-10-20)

View File

@@ -1,3 +1,4 @@
import six
import sqlalchemy as sa
from sqlalchemy.sql.expression import desc, asc
@@ -169,6 +170,9 @@ def make_order_by_deterministic(query):
.. versionadded: 0.27.1
"""
if not query._order_by:
return query
order_by = query._order_by[0]
if isinstance(order_by, sa.Column):
order_by_func = sa.asc
@@ -179,6 +183,10 @@ def make_order_by_deterministic(query):
else:
order_by_func = sa.asc
column = order_by.get_children()[0]
elif isinstance(order_by, six.string_types):
raise TypeError(
'Order by str is not supported. Use SA Column objects instead.'
)
else:
raise TypeError('Only simple columns in query order by are supported.')

View File

@@ -49,3 +49,13 @@ class TestMakeOrderByDeterministic(TestCase):
)
query = make_order_by_deterministic(query)
assert_contains('ORDER BY "user".name ASC, "user".id ASC', query)
def test_string_order_by(self):
query = self.session.query(self.User).order_by('name')
with raises(TypeError):
query = make_order_by_deterministic(query)
def test_query_without_order_by(self):
query = self.session.query(self.User)
query = make_order_by_deterministic(query)
assert 'ORDER BY' not in str(query)