* @return string
*/
public static function appendAnyValueToSelect($selectClauses, $groupBy) {
- $mysqlVersion = CRM_Core_DAO::singleValueQuery('SELECT VERSION()');
- $sqlMode = explode(',', CRM_Core_DAO::singleValueQuery('SELECT @@sql_mode'));
-
- // Disable only_full_group_by mode for lower sql versions.
- if (version_compare($mysqlVersion, '5.7', '<') || (!empty($sqlMode) && !in_array('ONLY_FULL_GROUP_BY', $sqlMode))) {
- $key = array_search('ONLY_FULL_GROUP_BY', $sqlMode);
- unset($sqlMode[$key]);
- CRM_Core_DAO::executeQuery("SET SESSION sql_mode = '" . implode(',', $sqlMode) . "'");
- }
- else {
+ if (!CRM_Utils_SQL::disableFullGroupByMode()) {
$groupBy = array_map('trim', (array) $groupBy);
$aggregateFunctions = '/(ROUND|AVG|COUNT|GROUP_CONCAT|SUM|MAX|MIN)\(/i';
foreach ($selectClauses as $key => &$val) {
return "SELECT " . implode(', ', $selectClauses) . " ";
}
+ /**
+ * For some special cases, where if non-aggregate ORDER BY columns are not present in GROUP BY
+ * on full_group_by mode, then append the those missing columns to GROUP BY clause
+ * keyword to select fields not present in groupBy
+ *
+ * @param string $groupBy - GROUP BY clause where missing ORDER BY columns will be appended
+ * @param array $orderBys - ORDER BY sub-clauses
+ *
+ */
+ public static function getGroupByFromOrderBy(&$groupBy, $orderBys) {
+ if (!CRM_Utils_SQL::disableFullGroupByMode()) {
+ foreach ($orderBys as $orderBy) {
+ $orderBy = str_replace(array(' DESC', ' ASC'), '', $orderBy); // remove sort syntax from ORDER BY clauses if present
+ // if ORDER BY column is not present in GROUP BY then append it to end
+ if (!strstr($groupBy, $orderBy)) {
+ $groupBy .= ", {$orderBy}";
+ }
+ }
+ }
+ }
+
/**
* Include Select columns in groupBy clause.
*
else {
$this->_where = "WHERE " . implode(' AND ', $clauses);
}
-
- // if ( $this->_aclWhere ) {
- // $this->_where .= " AND {$this->_aclWhere} ";
- // }
}
public function groupBy() {
$this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, $groupBy);
}
+ public function orderBy() {
+ parent::orderBy();
+ CRM_Contact_BAO_Query::getGroupByFromOrderBy($this->_groupBy, $this->_orderByArray);
+ }
+
public function postProcess() {
$this->beginPostProcess();
return version_compare(CRM_Core_DAO::singleValueQuery('SELECT VERSION()'), '5.7', '>=');
}
+ /**
+ * Disable ONLY_FULL_GROUP_BY for MySQL versions lower then 5.7
+ *
+ * @return bool
+ */
+ public static function disableFullGroupByMode() {
+ $sqlModes = self::getSqlModes();
+
+ // Disable only_full_group_by mode for lower sql versions.
+ if (!self::supportsFullGroupBy() || (!empty($sqlModes) && !in_array('ONLY_FULL_GROUP_BY', $sqlModes))) {
+ if ($key = array_search('ONLY_FULL_GROUP_BY', $sqlModes)) {
+ unset($sqlModes[$key]);
+ CRM_Core_DAO::executeQuery("SET SESSION sql_mode = '" . implode(',', $sqlModes) . "'");
+ }
+ return TRUE;
+ }
+
+ return FALSE;
+ }
+
}