# -*- coding: utf-8 -*-
from django.db.models import Count
from django.db.models.expressions import RawSQL
from django.test import TestCase

from .models import Author


class Bisect29416TestCase(TestCase):

    def test_bisect_29416(self):
        nb_books = RawSQL((
            "SELECT COUNT(*) FROM annotations_book "
            "WHERE annotations_book.author_id=annotations_author.id"
        ), [])
        query = str(
            Author.objects.all().values('id')
            .annotate(
                nb_books=nb_books,
                nb_friends=Count('friends'),
            )
            .order_by()
            .query
        )
        self.assertEqual(query, (
            "SELECT `annotations_author`.`id`, ("
            "SELECT COUNT(*) FROM annotations_book "
            "WHERE annotations_book.author_id=annotations_author.id"
            ") AS `nb_books`, "
            "COUNT(`annotations_author_friends`.`to_author_id`) AS `nb_friends` "
            "FROM `annotations_author` "
            "LEFT OUTER JOIN `annotations_author_friends` ON ("
            "`annotations_author`.`id` = `annotations_author_friends`.`from_author_id`) "
            "GROUP BY `annotations_author`.`id` ORDER BY NULL"
        ))
