|
1 | 1 | from itertools import chain |
2 | 2 |
|
3 | 3 | from django.db.models.aggregates import Avg, Count, StdDev, Variance |
4 | | -from django.db.models.expressions import OrderBy, Ref, Value |
| 4 | +from django.db.models.expressions import Exists, OrderBy, Ref, Value |
5 | 5 | from django.db.models.functions import ConcatPair, Greatest, Least, Length, Substr |
6 | 6 | from django.db.models.sql import compiler |
7 | 7 | from django.db.transaction import TransactionManagementError |
@@ -39,6 +39,14 @@ def _as_sql_least(self, compiler, connection): |
39 | 39 | def _as_sql_length(self, compiler, connection): |
40 | 40 | return self.as_sql(compiler, connection, function='LEN') |
41 | 41 |
|
| 42 | +def _as_sql_exists(self, compiler, connection, template=None, **extra_context): |
| 43 | + # MS SQL doesn't allow EXISTS() in the SELECT list, so wrap it with a |
| 44 | + # CASE WHEN expression. Change the template since the When expression |
| 45 | + # requires a left hand side (column) to compare against. |
| 46 | + sql, params = self.as_sql(compiler, connection, template, **extra_context) |
| 47 | + sql = 'CASE WHEN {} THEN 1 ELSE 0 END'.format(sql) |
| 48 | + return sql, params |
| 49 | + |
42 | 50 | def _as_sql_order_by(self, compiler, connection): |
43 | 51 | template = None |
44 | 52 | if self.nulls_last: |
@@ -243,6 +251,8 @@ def _as_microsoft(self, node): |
243 | 251 | as_microsoft = _as_sql_least |
244 | 252 | elif isinstance(node, Length): |
245 | 253 | as_microsoft = _as_sql_length |
| 254 | + elif isinstance(node, Exists): |
| 255 | + as_microsoft = _as_sql_exists |
246 | 256 | elif isinstance(node, OrderBy): |
247 | 257 | as_microsoft = _as_sql_order_by |
248 | 258 | elif isinstance(node, StdDev): |
|
0 commit comments