Code

Ticket #11916: ticket_11916.3.diff

File ticket_11916.3.diff, 2.1 KB (added by paluh, 4 years ago)

patch + unit test

Line 
1Index: django/db/models/sql/compiler.py
2===================================================================
3--- django/db/models/sql/compiler.py    (revision 12835)
4+++ django/db/models/sql/compiler.py    (working copy)
5@@ -484,7 +484,7 @@
6                 elif hasattr(col, 'as_sql'):
7                     result.append(col.as_sql(qn))
8                 else:
9-                    result.append(str(col))
10+                    result.append('(%s)' % str(col))
11         return result, params
12 
13     def fill_related_selections(self, opts=None, root_alias=None, cur_depth=1,
14Index: tests/regressiontests/aggregation_regress/tests.py
15===================================================================
16--- tests/regressiontests/aggregation_regress/tests.py  (revision 12835)
17+++ tests/regressiontests/aggregation_regress/tests.py  (working copy)
18@@ -1,5 +1,7 @@
19+from django.conf import settings
20 from django.test import TestCase
21-from django.db.models import Max
22+from django.db import DEFAULT_DB_ALIAS
23+from django.db.models import Count, Max
24 
25 from regressiontests.aggregation_regress.models import *
26 
27@@ -46,3 +48,26 @@
28         qs1 = books.filter(id__in=qs)
29         qs2 = books.filter(id__in=list(qs))
30         self.assertEqual(list(qs1), list(qs2))
31+
32+    def test_annotate_with_extra(self):
33+        """
34+        Regression test for #11916: Extra params + aggregation creates
35+        incorrect SQL.
36+        """
37+        #oracle doesn't support subqueries in group by clause
38+        if settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE'] == 'django.db.backends.oracle':
39+            return
40+        shortest_book_sql = """
41+        SELECT name
42+        FROM aggregation_regress_book b
43+        WHERE b.publisher_id = aggregation_regress_publisher.id
44+        ORDER BY b.pages
45+        LIMIT 1
46+        """
47+        # tests that this query does not raise a DatabaseError due to the full
48+        # subselect being (erroneously) added to the GROUP BY parameters
49+        qs = Publisher.objects.extra(select={
50+            'name_of_shortest_book': shortest_book_sql,
51+        }).annotate(total_books=Count('book'))
52+        # force execution of the query
53+        list(qs)