Skip to content
Permalink
Browse files

Implementing union

  • Loading branch information...
lorenzo committed Jan 22, 2013
1 parent ec566b3 commit b9873120b32a3ab8db464e194dc02e09c2389dae
@@ -53,7 +53,8 @@ class Query implements Expression, IteratorAggregate {
'having' => null,
'order' => [],
'limit' => null,
'offset' => null
'offset' => null,
'union' => []
];
protected $_distinct = false;
@@ -63,7 +64,7 @@ class Query implements Expression, IteratorAggregate {
'group' => ' GROUP BY %s ',
'having' => ' HAVING %s ',
'limit' => ' LIMIT %s',
'offset' => ' OFFSET %s'
'offset' => ' OFFSET %s',
];
/**
@@ -125,7 +126,7 @@ public function build($builder) {
}
protected function _buildSelect($builder) {
$parts = ['select', 'from', 'join', 'where', 'group', 'having', 'order', 'limit', 'offset'];
$parts = ['select', 'from', 'join', 'where', 'group', 'having', 'order', 'limit', 'offset', 'union'];
foreach ($parts as $part) {
$builder($this->_parts[$part], $part);
}
@@ -219,10 +220,6 @@ public function delete() {
return $this;
}
public function union($query) {
return $this;
}
public function from($tables = [], $overwrite = false) {
if (empty($tables)) {
return $this->_parts['from'];
@@ -371,6 +368,23 @@ public function offset($num) {
return $this;
}
public function union($query, $overwrite = false) {
if ($overwrite) {
$this->_parts['union'] = [];
}
$this->_parts['union'][] = $query;
$this->_dirty = true;
return $this;
}
protected function _buildUnionPart($parts) {
$parts = array_map(function($p) {
$p =(string)$p;
return $p[0] === '(' ? trim($p, '()') : $p;
}, $parts);
return sprintf("\nUNION %s", implode("\nUNION ", $parts));
}
/**
* Returns the type of this query (select, insert, update, delete)
*
@@ -1438,4 +1438,38 @@ public function testSubqueyInJoin() {
$this->assertCount(1, $result);
}
/**
* Tests that it is possible to one or multiple UNION statements in a query
*
* @return void
**/
public function testUnion() {
$this->_insertTwoRecords();
$this->_insertDateRecords();
$union = (new Query($this->connection))->select('*')->from(['a' => 'articles']);
$query = new Query($this->connection);
$result = $query->select('*')
->from(['d' => 'dates'])
->union($union)
->execute();
$this->assertCount(5, $result);
$rows = $result->fetchAll();
$union = (new Query($this->connection))
->select(['id', 'name', 'other' => 'id', 'nameish' => 'name'])
->from(['b' => 'authors'])
->where(['id >' => 1])
->order(['id' => 'desc']);
$result = $query->union($union)->execute();
$this->assertCount(6, $result);
$union = (new Query($this->connection))
->select('*')
->from(['c' => 'articles']);
$result = $query->union($union, true)->execute();
$this->assertCount(5, $result);
$this->assertEquals($rows, $result->fetchAll());
}
}

0 comments on commit b987312

Please sign in to comment.
You can’t perform that action at this time.