From 45695b6b5cc358f12811fcadbdfe3c0b1a7e6b15 Mon Sep 17 00:00:00 2001 From: mark_story Date: Tue, 9 Jan 2018 17:01:00 -0500 Subject: [PATCH] Fix missing field identifier quoting for COUNT(DISTINCT in SQLServer. Refs #11186 --- lib/Cake/Model/Datasource/Database/Sqlserver.php | 4 ++++ .../Test/Case/Model/Datasource/Database/SqlserverTest.php | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/lib/Cake/Model/Datasource/Database/Sqlserver.php b/lib/Cake/Model/Datasource/Database/Sqlserver.php index 2e9c78fd7..c25934409 100644 --- a/lib/Cake/Model/Datasource/Database/Sqlserver.php +++ b/lib/Cake/Model/Datasource/Database/Sqlserver.php @@ -302,6 +302,10 @@ class Sqlserver extends DboSource { $prepend = 'DISTINCT '; $fields[$i] = trim(str_replace('DISTINCT', '', $fields[$i])); } + if (strpos($fields[$i], 'COUNT(DISTINCT') !== false) { + $prepend = 'COUNT(DISTINCT '; + $fields[$i] = trim(str_replace('COUNT(DISTINCT', '', $this->_quoteFields($fields[$i]))); + } if (!preg_match('/\s+AS\s+/i', $fields[$i])) { if (substr($fields[$i], -1) === '*') { diff --git a/lib/Cake/Test/Case/Model/Datasource/Database/SqlserverTest.php b/lib/Cake/Test/Case/Model/Datasource/Database/SqlserverTest.php index 4013d215d..622992ab1 100644 --- a/lib/Cake/Test/Case/Model/Datasource/Database/SqlserverTest.php +++ b/lib/Cake/Test/Case/Model/Datasource/Database/SqlserverTest.php @@ -383,6 +383,10 @@ class SqlserverTest extends CakeTestCase { $result = $this->db->fields($this->model, null, 'DISTINCT Car.country_code'); $expected = array('DISTINCT [Car].[country_code] AS [Car__country_code]'); $this->assertEquals($expected, $result); + + $result = $this->db->fields($this->model, null, 'COUNT(DISTINCT Car.country_code)'); + $expected = array('COUNT(DISTINCT [Car].[country_code]) AS [Car__country_code]'); + $this->assertEquals($expected, $result); } /**