From 6b4889f7b43378881a5d131141e55b6a2b290bd5 Mon Sep 17 00:00:00 2001 From: naisila Date: Thu, 11 Jul 2024 14:12:16 +0200 Subject: [PATCH] Ruleutils_17 Add support for MERGE ... WHEN NOT MATCHED BY SOURCE Relevant PG commit: 0294df2f1f842dfb0eed79007b21016f486a3c6c https://github.com/postgres/postgres/commit/0294df2f1f842dfb0eed79007b21016f486a3c6c --- .../distributed/deparser/ruleutils_17.c | 41 ++++++++++++++++++- 1 file changed, 39 insertions(+), 2 deletions(-) diff --git a/src/backend/distributed/deparser/ruleutils_17.c b/src/backend/distributed/deparser/ruleutils_17.c index 08a863fe3..ea3ebcee0 100644 --- a/src/backend/distributed/deparser/ruleutils_17.c +++ b/src/backend/distributed/deparser/ruleutils_17.c @@ -3752,6 +3752,7 @@ get_merge_query_def(Query *query, deparse_context *context, StringInfo buf = context->buf; RangeTblEntry *rte; ListCell *lc; + bool haveNotMatchedBySource; /* Insert the WITH clause if given */ get_with_clause(query, context); @@ -3801,7 +3802,26 @@ get_merge_query_def(Query *query, deparse_context *context, get_from_clause(query, " USING ", context); appendContextKeyword(context, " ON ", -PRETTYINDENT_STD, PRETTYINDENT_STD, 2); - get_rule_expr(query->jointree->quals, context, false); + get_rule_expr(query->mergeJoinCondition, context, false); + + /* + * Test for any NOT MATCHED BY SOURCE actions. If there are none, then + * any NOT MATCHED BY TARGET actions are output as "WHEN NOT MATCHED", per + * SQL standard. Otherwise, we have a non-SQL-standard query, so output + * "BY SOURCE" / "BY TARGET" qualifiers for all NOT MATCHED actions, to be + * more explicit. + */ + haveNotMatchedBySource = false; + foreach(lc, query->mergeActionList) + { + MergeAction *action = lfirst_node(MergeAction, lc); + + if (action->matchKind == MERGE_WHEN_NOT_MATCHED_BY_SOURCE) + { + haveNotMatchedBySource = true; + break; + } + } /* Print each merge action */ foreach(lc, query->mergeActionList) @@ -3810,7 +3830,24 @@ get_merge_query_def(Query *query, deparse_context *context, appendContextKeyword(context, " WHEN ", -PRETTYINDENT_STD, PRETTYINDENT_STD, 2); - appendStringInfo(buf, "%sMATCHED", action->matched ? "" : "NOT "); + switch (action->matchKind) + { + case MERGE_WHEN_MATCHED: + appendStringInfo(buf, "MATCHED"); + break; + case MERGE_WHEN_NOT_MATCHED_BY_SOURCE: + appendStringInfo(buf, "NOT MATCHED BY SOURCE"); + break; + case MERGE_WHEN_NOT_MATCHED_BY_TARGET: + if (haveNotMatchedBySource) + appendStringInfo(buf, "NOT MATCHED BY TARGET"); + else + appendStringInfo(buf, "NOT MATCHED"); + break; + default: + elog(ERROR, "unrecognized matchKind: %d", + (int) action->matchKind); + } if (action->qual) {