From 3a92a609eaac26e60fb3e23e2eafcd0cdfdd0c8b Mon Sep 17 00:00:00 2001 From: Konsta Vesterinen Date: Tue, 21 Oct 2014 14:24:17 +0300 Subject: [PATCH] Improve order by type handling --- CHANGES.rst | 2 ++ sqlalchemy_utils/functions/sort_query.py | 8 ++++++++ tests/functions/test_make_order_by_deterministic.py | 10 ++++++++++ 3 files changed, 20 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 9277c5a..2a23e48 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -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) diff --git a/sqlalchemy_utils/functions/sort_query.py b/sqlalchemy_utils/functions/sort_query.py index ded72a1..3ea12e4 100644 --- a/sqlalchemy_utils/functions/sort_query.py +++ b/sqlalchemy_utils/functions/sort_query.py @@ -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.') diff --git a/tests/functions/test_make_order_by_deterministic.py b/tests/functions/test_make_order_by_deterministic.py index f17e679..5aa6ba3 100644 --- a/tests/functions/test_make_order_by_deterministic.py +++ b/tests/functions/test_make_order_by_deterministic.py @@ -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)