From 5c68eb31ba9109c33d3decbb65f2b05b2fb00a51 Mon Sep 17 00:00:00 2001
From: Jared Hancock <jared@osticket.com>
Date: Fri, 28 Aug 2015 10:02:34 -0500
Subject: [PATCH] orm: Allow specification of GROUP BY clause, speed-up client
 stats

This patch changes the automatic GROUP BY clause for annotations in the ORM
including aggregate queries (like COUNT), by allowing the query to specify
"distinct" fields. If distinct fields are specified, then no other fields
are automatically added to the GROUP BY clause of the compiled query.

This will likely only be supported by MySQL, as other engines and the ANSI
standard require all non-aggregate fields in the SELECT clause to be present
in the GROUP BY clause.
---
 include/class.client.php | 3 ++-
 include/class.orm.php    | 4 ++--
 2 files changed, 4 insertions(+), 3 deletions(-)

diff --git a/include/class.client.php b/include/class.client.php
index 31e185c8b..50fda6cef 100644
--- a/include/class.client.php
+++ b/include/class.client.php
@@ -303,7 +303,8 @@ class  EndUser extends BaseAuthenticatedUser {
     private function getStats() {
         $basic = Ticket::objects()
             ->annotate(array('count' => SqlAggregate::COUNT('ticket_id')))
-            ->values('status__state', 'topic_id');
+            ->values('status__state', 'topic_id')
+            ->distinct('status_id', 'topic_id');
 
         // Share tickets among the organization for owners only
         $mine = clone $basic;
diff --git a/include/class.orm.php b/include/class.orm.php
index 72495a85a..cac0eb39e 100644
--- a/include/class.orm.php
+++ b/include/class.orm.php
@@ -2523,7 +2523,7 @@ class MySqlCompiler extends SqlCompiler {
                 }
                 // If there are annotations, add in these fields to the
                 // GROUP BY clause
-                if ($queryset->annotations)
+                if ($queryset->annotations && !$queryset->distinct)
                     $group_by[] = $unaliased;
             }
         }
@@ -2557,7 +2557,7 @@ class MySqlCompiler extends SqlCompiler {
                 }
             }
             // If no group by has been set yet, use the root model pk
-            if (!$group_by && !$queryset->aggregated) {
+            if (!$group_by && !$queryset->aggregated && !$queryset->distinct) {
                 foreach ($model::getMeta('pk') as $pk)
                     $group_by[] = $rootAlias .'.'. $pk;
             }
-- 
GitLab