Permalink
Browse files

Use column aliases in WHERE, GROUP BY, HAVING and ORDER BY clauses. F…

…ixes #4057
  • Loading branch information...
1 parent 6a0a9bb commit 9ef34f4db2d5e47eb2303735a6eea39e9975b502 @cbandy cbandy committed Jul 4, 2011
Showing with 54 additions and 5 deletions.
  1. +52 −3 classes/kohana/database/query/builder.php
  2. +2 −2 classes/kohana/database/query/builder/select.php
@@ -118,8 +118,16 @@ protected function _compile_conditions(Database $db, array $conditions)
if ($column)
{
- // Apply proper quoting to the column
- $column = $db->quote_column($column);
+ if (is_array($column))
+ {
+ // Use the column alias
+ $column = $db->quote_identifier(end($column));
+ }
+ else
+ {
+ // Apply proper quoting to the column
+ $column = $db->quote_column($column);
+ }
}
// Append the statement to the query
@@ -163,6 +171,36 @@ protected function _compile_set(Database $db, array $values)
return implode(', ', $set);
}
+ /**
+ * Compiles an array of GROUP BY columns into an SQL partial.
+ *
+ * @param object Database instance
+ * @param array columns
+ * @return string
+ */
+ protected function _compile_group_by(Database $db, array $columns)
+ {
+ $group = array();
+
+ foreach ($columns as $column)
+ {
+ if (is_array($column))
+ {
+ // Use the column alias
+ $column = $db->quote_identifier(end($column));
+ }
+ else
+ {
+ // Apply proper quoting to the column
+ $column = $db->quote_column($column);
+ }
+
+ $group[] = $column;
+ }
+
+ return 'GROUP BY '.implode(', ', $group);
+ }
+
/**
* Compiles an array of ORDER BY statements into an SQL partial.
*
@@ -177,13 +215,24 @@ protected function _compile_order_by(Database $db, array $columns)
{
list ($column, $direction) = $group;
+ if (is_array($column))
+ {
+ // Use the column alias
+ $column = $db->quote_identifier(end($column));
+ }
+ else
+ {
+ // Apply proper quoting to the column
+ $column = $db->quote_column($column);
+ }
+
if ($direction)
{
// Make the direction uppercase
$direction = ' '.strtoupper($direction);
}
- $sort[] = $db->quote_column($column).$direction;
+ $sort[] = $column.$direction;
}
return 'ORDER BY '.implode(', ', $sort);
@@ -372,8 +372,8 @@ public function compile(Database $db)
if ( ! empty($this->_group_by))
{
- // Add sorting
- $query .= ' GROUP BY '.implode(', ', array_map($quote_column, $this->_group_by));
+ // Add grouping
+ $query .= ' '.$this->_compile_group_by($db, $this->_group_by);
}
if ( ! empty($this->_having))

0 comments on commit 9ef34f4

Please sign in to comment.