From f6fd726cdb91a0b1c5eb132936a1099ec1ce87fc Mon Sep 17 00:00:00 2001 From: Patrick Hayes Date: Tue, 22 Oct 2019 09:47:52 -0700 Subject: [PATCH] Add public accessor to for `is_single_entity` to Query class Fixes: #4934 This is useful when writing middleware between your application and sqlalchemy, to inspect what type of results we will be seeing. As an example, ``` def issue_query_and_wrap_results(query, Wrapper): results = query.all() for result in results: if q.is_single_entity: return Wrapper(result) else: return tuple(Wrapper(r) for r in result) ``` Without this accessor, you need to inspect the return results or private members of the query and try to guess the intent --- lib/sqlalchemy/orm/loading.py | 6 +----- lib/sqlalchemy/orm/query.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/lib/sqlalchemy/orm/loading.py b/lib/sqlalchemy/orm/loading.py index 8de7d5a8b8..25ba8a3986 100644 --- a/lib/sqlalchemy/orm/loading.py +++ b/lib/sqlalchemy/orm/loading.py @@ -42,11 +42,7 @@ def instances(query, cursor, context): filtered = query._has_mapper_entities - single_entity = ( - not query._only_return_tuples - and len(query._entities) == 1 - and query._entities[0].supports_single_entity - ) + single_entity = query.is_single_entity if filtered: if single_entity: diff --git a/lib/sqlalchemy/orm/query.py b/lib/sqlalchemy/orm/query.py index 92f9ee9525..ad5ed412bc 100644 --- a/lib/sqlalchemy/orm/query.py +++ b/lib/sqlalchemy/orm/query.py @@ -648,6 +648,18 @@ class Query(Generative): """ self._only_return_tuples = value + @property + def is_single_entity(self): + """Returns True if this query returns a single entity for each instance in its + result list, and False if this query returns a tuple of entities for each result. + + """ + return ( + not self._only_return_tuples + and len(self._entities) == 1 + and self._entities[0].supports_single_entity + ) + @_generative def enable_eagerloads(self, value): """Control whether or not eager joins and subqueries are -- 2.47.3