Skip to content

Commit

Permalink
adding UNION support (#2549)
Browse files Browse the repository at this point in the history
  • Loading branch information
ryross committed Oct 26, 2010
1 parent 129cb31 commit 2b4c657
Showing 1 changed file with 38 additions and 1 deletion.
39 changes: 38 additions & 1 deletion classes/kohana/database/query/builder/select.php
Expand Up @@ -36,6 +36,9 @@ class Kohana_Database_Query_Builder_Select extends Database_Query_Builder_Where
// OFFSET ...
protected $_offset = NULL;

// UNION ...
protected $_union = array();

// The last JOIN statement created
protected $_last_join;

Expand Down Expand Up @@ -298,6 +301,26 @@ public function limit($number)
return $this;
}

/**
* Adds an other UNION clause.
*
* @param mixed $select if string, it must be the name of a table. Else
* must be an instance of Database_Query_Builder_Select
* @param boolean $all decides if it's an UNION or UNION ALL clause
* @return $this
*/
public function union($select, $all = TRUE)
{
if (is_string($select))
{
$select = DB::select()->from($select);
}
if ( ! $select instanceof Database_Query_Builder_Select)
throw new Kohana_Exception('first parameter must be a string or an instance of Database_Query_Builder_Select');
$this->_union []= array('select' => $select, 'all' => $all);
return $this;
}

/**
* Start returning results after "OFFSET ..."
*
Expand Down Expand Up @@ -392,6 +415,18 @@ public function compile(Database $db)
// Add offsets
$query .= ' OFFSET '.$this->_offset;
}

if ( ! empty($this->_union))
{
foreach ($this->_union as $u) {
$query .= ' UNION ';
if ($u['all'] === TRUE)
{
$query .= 'ALL ';
}
$query .= $u['select']->compile($db);
}
}

return $query;
}
Expand All @@ -404,7 +439,8 @@ public function reset()
$this->_where =
$this->_group_by =
$this->_having =
$this->_order_by = array();
$this->_order_by =
$this->_union = array();

$this->_distinct = FALSE;

Expand All @@ -416,3 +452,4 @@ public function reset()
}

} // End Database_Query_Select

0 comments on commit 2b4c657

Please sign in to comment.