/** * Returns the ORDER BY clauses ready for inserting into a query. * * @param SQLSelect $query The expression object to build from * @param array $parameters Out parameter for the resulting query parameters * @return string Completed order by part of statement */ public function buildOrderByFragment(SQLSelect $query, array &$parameters) { $orderBy = $query->getOrderBy(); if (empty($orderBy)) { return ''; } // Build orders, each with direction considered $statements = array(); foreach ($orderBy as $clause => $dir) { $statements[] = trim("{$clause} {$dir}"); } $nl = $this->getSeparator(); return "{$nl}ORDER BY " . implode(', ', $statements); }
/** * Ensure that if a query has an order by clause, those columns are present in the select. * * @param SQLSelect $query * @param array $originalSelect * @return null */ protected function ensureSelectContainsOrderbyColumns($query, $originalSelect = array()) { if ($orderby = $query->getOrderBy()) { $newOrderby = array(); $i = 0; foreach ($orderby as $k => $dir) { $newOrderby[$k] = $dir; // don't touch functions in the ORDER BY or public function calls // selected as fields if (strpos($k, '(') !== false) { continue; } $col = str_replace('"', '', trim($k)); $parts = explode('.', $col); // Pull through SortColumn references from the originalSelect variables if (preg_match('/_SortColumn/', $col)) { if (isset($originalSelect[$col])) { $query->selectField($originalSelect[$col], $col); } continue; } if (count($parts) == 1) { // Get expression for sort value $qualCol = "\"{$parts[0]}\""; $table = DataObject::getSchema()->tableForField($this->dataClass(), $parts[0]); if ($table) { $qualCol = "\"{$table}\".{$qualCol}"; } // remove original sort unset($newOrderby[$k]); // add new columns sort $newOrderby[$qualCol] = $dir; // To-do: Remove this if block once SQLSelect::$select has been refactored to store getSelect() // format internally; then this check can be part of selectField() $selects = $query->getSelect(); if (!isset($selects[$col]) && !in_array($qualCol, $selects)) { $query->selectField($qualCol); } } else { $qualCol = '"' . implode('"."', $parts) . '"'; if (!in_array($qualCol, $query->getSelect())) { unset($newOrderby[$k]); $newOrderby["\"_SortColumn{$i}\""] = $dir; $query->selectField($qualCol, "_SortColumn{$i}"); $i++; } } } $query->setOrderBy($newOrderby); } }