diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c index 361bf09d24..bc1fbe97a6 100644 --- a/src/backend/utils/adt/ruleutils.c +++ b/src/backend/utils/adt/ruleutils.c @@ -6201,13 +6201,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, resultDesc,