Skip to content

Commit

Permalink
Fix missing () in unioned queries.
Browse files Browse the repository at this point in the history
The original SELECT also needs () for unions to work. While having the
parentheses added in very disparate parts of the code is a bit awkward
I really didn't want to restructure the entire QueryCompiler for this
scenario.
  • Loading branch information
markstory committed Feb 26, 2015
1 parent 8490c9d commit f94b743
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/Database/QueryCompiler.php
Expand Up @@ -135,6 +135,9 @@ protected function _buildSelectPart($parts, $query, $generator)
{
$driver = $query->connection()->driver();
$select = 'SELECT %s%s%s';
if ($query->clause('union')) {
$select = '(SELECT %s%s%s';
}
$distinct = $query->clause('distinct');
$modifiers = $query->clause('modifier') ?: null;

Expand Down Expand Up @@ -253,10 +256,10 @@ protected function _buildUnionPart($parts, $query, $generator)
$parts = array_map(function ($p) use ($generator) {
$p['query'] = $p['query']->sql($generator);
$p['query'] = $p['query'][0] === '(' ? trim($p['query'], '()') : $p['query'];
$prefix = $p['all'] ? 'ALL' : '';
return sprintf('%s (%s)', $prefix, $p['query']);
$prefix = $p['all'] ? 'ALL ' : '';
return sprintf('%s(%s)', $prefix, $p['query']);
}, $parts);
return sprintf("\nUNION %s", implode("\nUNION ", $parts));
return sprintf(")\nUNION %s", implode("\nUNION ", $parts));
}

/**
Expand Down
19 changes: 19 additions & 0 deletions src/Database/SqliteCompiler.php
Expand Up @@ -24,6 +24,25 @@
*/
class SqliteCompiler extends QueryCompiler
{
/**
* Helper function used to build the string representation of a SELECT clause,
* it constructs the field list taking care of aliasing and
* converting expression objects to string. This function also constructs the
* DISTINCT clause for the query.
*
* @param array $parts list of fields to be transformed to string
* @param \Cake\Database\Query $query The query that is being compiled
* @param \Cake\Database\ValueBinder $generator the placeholder generator to be used in expressions
* @return string
*/
protected function _buildSelectPart($parts, $query, $generator)
{
$clause = parent::_buildSelectPart($parts, $query, $generator);
if ($clause[0] === '(') {
return substr($clause, 1);
}
return $clause;
}

/**
* Builds the SQL string for all the UNION clauses in this query, when dealing
Expand Down

0 comments on commit f94b743

Please sign in to comment.