From 3575070b9d44472555606a4fbabfb5d011b69c29 Mon Sep 17 00:00:00 2001
From: Guy Marriott <guy@scopey.co.nz>
Date: Fri, 26 Apr 2019 14:13:43 +1200
Subject: [PATCH] FIX Removing selected column detail only if having is empty
 (MySQL "feature")

---
 src/ORM/DataQuery.php           |  3 ++-
 tests/php/ORM/DataQueryTest.php | 14 +++++++++-----
 2 files changed, 11 insertions(+), 6 deletions(-)

diff --git a/src/ORM/DataQuery.php b/src/ORM/DataQuery.php
index e1c8b6f3d..33845cd14 100644
--- a/src/ORM/DataQuery.php
+++ b/src/ORM/DataQuery.php
@@ -464,7 +464,6 @@ class DataQuery
         // Grab a statement selecting "everything" - the engine shouldn't care what's being selected in an "EXISTS"
         // statement anyway
         $statement = $this->getFinalisedQuery();
-        $statement->setSelect('*');
 
         // Clear limit, distinct, and order as it's not relevant for an exists query
         $statement->setDistinct(false);
@@ -472,8 +471,10 @@ class DataQuery
         $statement->setLimit(null);
 
         // We can remove grouping if there's no "having" that might be relying on an aggregate
+        // Additionally, the columns being selected no longer matter
         $having = $statement->getHaving();
         if (empty($having)) {
+            $statement->setSelect('*');
             $statement->setGroupBy(null);
         }
 
diff --git a/tests/php/ORM/DataQueryTest.php b/tests/php/ORM/DataQueryTest.php
index ffadd116a..1b9a3a1a4 100644
--- a/tests/php/ORM/DataQueryTest.php
+++ b/tests/php/ORM/DataQueryTest.php
@@ -6,6 +6,7 @@ use SilverStripe\ORM\DataQuery;
 use SilverStripe\ORM\DataObject;
 use SilverStripe\ORM\DB;
 use SilverStripe\Dev\SapphireTest;
+use SilverStripe\ORM\Tests\DataQueryTest\ObjectE;
 use SilverStripe\Security\Member;
 
 /**
@@ -386,11 +387,7 @@ class DataQueryTest extends SapphireTest
         $query = new DataQuery(DataQueryTest\ObjectC::class);
         $query->sort('"SortOrder"');
         $query->where(
-            [
-            '"DataQueryTest_C"."Title" = ? OR "DataQueryTest_E"."SortOrder" > ?' => [
-                'First', 2
-            ]
-            ]
+            ['"DataQueryTest_C"."Title" = ? OR "DataQueryTest_E"."SortOrder" > ?' => ['First', 2]]
         );
         $result = $query->getFinalisedQuery(['Title']);
         $from = $result->getFrom();
@@ -466,4 +463,11 @@ class DataQueryTest extends SapphireTest
         $this->assertEquals('Second', $titles[1]);
         $this->assertEquals('Last', $titles[2]);
     }
+
+    public function testExistsCreatesFunctionalQueries()
+    {
+        $this->assertTrue(ObjectE::get()->exists());
+        $this->assertFalse(ObjectE::get()->where(['"Title" = ?' => 'Foo'])->exists());
+        $this->assertTrue(ObjectE::get()->dataQuery()->groupby('"SortOrder"')->exists());
+    }
 }