Skip to content

Commit 630520c

Browse files
committed
Avoid assertion failure if a setop leaf query contains setops.
Ordinarily transformSetOperationTree will collect all UNION/ INTERSECT/EXCEPT steps into the setOperations tree of the topmost Query, so that leaf queries do not contain any setOperations. However, it cannot thus flatten a subquery that also contains WITH, ORDER BY, FOR UPDATE, or LIMIT. I (tgl) forgot that in commit 07b4c48 and wrote an assertion in rule deparsing that a leaf's setOperations would always be empty. If it were nonempty then we would want to parenthesize the subquery to ensure that the output represents the setop nesting correctly (e.g. UNION below INTERSECT had better get parenthesized). So rather than just removing the faulty Assert, let's change it into an additional case to check to decide whether to add parens. We don't expect that the additional case will ever fire, but it's cheap insurance. Man Zeng and Tom Lane Discussion: https://postgr.es/m/tencent_7ABF9B1F23B0C77606FC5FE3@qq.com
1 parent 6b66dba commit 630520c

File tree

1 file changed

+9
-3
lines changed

1 file changed

+9
-3
lines changed

src/backend/utils/adt/ruleutils.c

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5724,13 +5724,19 @@ get_setop_query(Node *setOp, Query *query, deparse_context *context,
57245724
Query *subquery = rte->subquery;
57255725

57265726
Assert(subquery != NULL);
5727-
Assert(subquery->setOperations == NULL);
5728-
/* Need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y */
5727+
5728+
/*
5729+
* We need parens if WITH, ORDER BY, FOR UPDATE, or LIMIT; see gram.y.
5730+
* Also add parens if the leaf query contains its own set operations.
5731+
* (That shouldn't happen unless one of the other clauses is also
5732+
* present, see transformSetOperationTree; but let's be safe.)
5733+
*/
57295734
need_paren = (subquery->cteList ||
57305735
subquery->sortClause ||
57315736
subquery->rowMarks ||
57325737
subquery->limitOffset ||
5733-
subquery->limitCount);
5738+
subquery->limitCount ||
5739+
subquery->setOperations);
57345740
if (need_paren)
57355741
appendStringInfoChar(buf, '(');
57365742
get_query_def(subquery, buf, context->namespaces, resultDesc,

0 commit comments

Comments
 (0)