Skip to content

Commit

Permalink
Wrapped Unions Fixes (#5072)
Browse files Browse the repository at this point in the history
  • Loading branch information
OlivierCavadenti committed Mar 19, 2022
1 parent 9d62cbf commit c3e41e3
Show file tree
Hide file tree
Showing 3 changed files with 368 additions and 32 deletions.
42 changes: 30 additions & 12 deletions lib/query/querycompiler.js
Expand Up @@ -125,16 +125,27 @@ class QueryCompiler {
let sql = this.with();

let unionStatement = '';
// Compute all statements to main query
const statements = components.map((component) => {

const firstStatements = [];
const endStatements = [];

components.forEach((component) => {
const statement = this[component](this);
// We store the 'union' statement to append it at the end.
// We still need to call the component sequentially because of
// order of bindings.
if (component === 'union') {
unionStatement = statement;
} else {
return statement;
switch (component) {
case 'union':
unionStatement = statement;
break;
case 'columns':
case 'join':
case 'where':
firstStatements.push(statement);
break;
default:
endStatements.push(statement);
break;
}
});

Expand All @@ -144,15 +155,22 @@ class QueryCompiler {
const wrapMainQuery =
this.grouped.union &&
this.grouped.union.map((u) => u.wrap).some((u) => u);
const allStatements =
(wrapMainQuery ? '(' : '') +
compact(statements).join(' ') +
(wrapMainQuery ? ')' : '');

if (this.onlyUnions()) {
sql += unionStatement + ' ' + allStatements;
const statements = compact(firstStatements.concat(endStatements)).join(
' '
);
sql += unionStatement + (statements ? ' ' + statements : '');
} else {
sql += allStatements + (unionStatement ? ' ' + unionStatement : '');
const allStatements =
(wrapMainQuery ? '(' : '') +
compact(firstStatements).join(' ') +
(wrapMainQuery ? ')' : '');
const endStat = compact(endStatements).join(' ');
sql +=
allStatements +
(unionStatement ? ' ' + unionStatement : '') +
(endStat ? ' ' + endStat : endStat);
}
return sql;
}
Expand Down

0 comments on commit c3e41e3

Please sign in to comment.