]> git.ipfire.org Git - thirdparty/sqlalchemy/sqlalchemy.git/commitdiff
Add public accessor to for `is_single_entity` to Query class
authorPatrick Hayes <pfhayes@gmail.com>
Tue, 22 Oct 2019 16:47:52 +0000 (09:47 -0700)
committerPatrick Hayes <pfhayes@gmail.com>
Tue, 22 Oct 2019 16:59:34 +0000 (09:59 -0700)
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
lib/sqlalchemy/orm/query.py

index 8de7d5a8b8824c80c2ad44943ca4c7d2eb4011e8..25ba8a3986a635bcab9e742e5c0393c026359a61 100644 (file)
@@ -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:
index 92f9ee9525820b854c1d947fa85fe2e6adc5e4f2..ad5ed412bc8e2b4426c0ef0fd503d3912dbc45f0 100644 (file)
@@ -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