Skip to content

Fix count for queries using Subquery or Exists #15

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,5 @@ install:

script:
- pip install -r django/tests/requirements/py3.txt
- python manage.py test
- ./test.sh
10 changes: 10 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testapp.settings")

from django.core.management import execute_from_command_line

execute_from_command_line(sys.argv)
6 changes: 5 additions & 1 deletion sql_server/pyodbc/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from itertools import chain

from django.db.models.aggregates import Avg, Count, StdDev, Variance
from django.db.models.expressions import Exists, OrderBy, Ref, Value
from django.db.models.expressions import Exists, OrderBy, Ref, Subquery, Value
from django.db.models.functions import (
Chr, ConcatPair, Greatest, Least, Length, LPad, Repeat, RPad, StrIndex, Substr, Trim
)
Expand Down Expand Up @@ -374,6 +374,10 @@ def compile(self, node, select_format=False):
node = self._as_microsoft(node)
return super().compile(node, select_format)

def collapse_group_by(self, expressions, having):
expressions = super().collapse_group_by(expressions, having)
return [e for e in expressions if not isinstance(e, Subquery)]

def _as_microsoft(self, node):
as_microsoft = None
if isinstance(node, Avg):
Expand Down
31 changes: 31 additions & 0 deletions testapp/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Generated by Django 2.2.8.dev20191112211527 on 2019-11-15 01:38

from django.db import migrations, models
import django


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255, verbose_name='title')),
],
),
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='testapp.Post')),
('text', models.TextField(verbose_name='text')),
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
],
),
]
Empty file added testapp/migrations/__init__.py
Empty file.
18 changes: 18 additions & 0 deletions testapp/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from django.db import models
from django.utils import timezone


class Post(models.Model):
title = models.CharField('title', max_length=255)

def __str__(self):
return self.title


class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
text = models.TextField('text')
created_at = models.DateTimeField(default=timezone.now)

def __str__(self):
return self.text
7 changes: 7 additions & 0 deletions testapp/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@
'other': dj_database_url.config(env='DATABASE_URL_OTHER', default='sqlite:///db.sqlite'),
}

INSTALLED_APPS = (
'django.contrib.contenttypes',
'django.contrib.staticfiles',
'django.contrib.auth',
'testapp',
)

SECRET_KEY = "django_tests_secret_key"

# Use a fast hasher to speed up tests.
Expand Down
Empty file added testapp/tests/__init__.py
Empty file.
25 changes: 25 additions & 0 deletions testapp/tests/test_expressions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from django.db.models.expressions import Exists, OuterRef, Subquery
from django.test import TestCase

from ..models import Comment, Post


class TestSubquery(TestCase):
def setUp(self):
self.post = Post.objects.create(title="foo")

def test_with_count(self):
newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
Post.objects.annotate(
post_exists=Subquery(newest.values('text')[:1])
).filter(post_exists=True).count()


class TestExists(TestCase):
def setUp(self):
self.post = Post.objects.create(title="foo")

def test_with_count(self):
Post.objects.annotate(
post_exists=Exists(Post.objects.all())
).filter(post_exists=True).count()