"=?utf-8?B?5pu+5ruh?=" <zeng...@halodbtech.com> writes: > We can comment out the assertion that raises the exception, because I looked > up the code and found that the assertion doesn't seem to make a lot > of sense here.
I looked at the git history and found that I added this assertion in 07b4c48b6. Your example shows that indeed it's a thinko, but I'm not convinced that simply removing it is the best answer. The real point here is that we'd want to parenthesize if a "leaf" subquery contains set operations, to ensure that the setop nesting is represented correctly. Normally, a "leaf" query would not contain any set operations, but that can happen if the leaf query also contains WITH/ORDER BY/FOR UPDATE/LIMIT, because that stops transformSetOperationTree from merging it into the upper SetOperationStmt tree. So the assertion should have been less "can't have setOperations here" and more "can't have setOperations here unless there's also one of sortClause etc". But on reflection I don't see why it needs to be an assert at all. Let's just make nonempty setOperations another reason to force need_paren on, as attached. regards, tom lane
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c index a39068d1bf..2194ab3dfa 100644 --- a/src/backend/utils/adt/ruleutils.c +++ b/src/backend/utils/adt/ruleutils.c @@ -6353,13 +6353,19 @@ get_setop_query(Node *setOp, Query *query, deparse_context *context) Query *subquery = rte->subquery; Assert(subquery != NULL); - Assert(subquery->setOperations == NULL); - /* Need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y */ + + /* + * We need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y. + * Also add parens if the leaf query contains its own set operations. + * (That shouldn't happen unless one of the other clauses is also + * present, see transformSetOperationTree; but let's be safe.) + */ need_paren = (subquery->cteList || subquery->sortClause || subquery->rowMarks || subquery->limitOffset || - subquery->limitCount); + subquery->limitCount || + subquery->setOperations); if (need_paren) appendStringInfoChar(buf, '('); get_query_def(subquery, buf, context->namespaces,