Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrapped Unions Fixes #5072

Merged
merged 3 commits into from Mar 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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