pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Allow ON CONFLICT DO UPDATE to return EXCLUDED values
17+ messages / 7 participants
[nested] [flat]

* Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2025-06-24 18:49  Dean Rasheed <dean.a.rasheed@gmail.com>
  0 siblings, 1 reply; 17+ messages in thread

From: Dean Rasheed @ 2025-06-24 18:49 UTC (permalink / raw)
  To: pgsql-hackers

The attached patch allows EXCLUDED values to appear in the RETURNING
list of INSERT ... ON CONFLICT DO UPDATE. For example:

CREATE TABLE t (a int PRIMARY KEY, b text);
INSERT INTO t VALUES (1, 'old value');

INSERT INTO t VALUES (1, 'excluded value')
  ON CONFLICT (a) DO UPDATE SET b = 'new value'
  RETURNING a, old.b, new.b, excluded.b;

 a |     b     |     b     |       b
---+-----------+-----------+----------------
 1 | old value | new value | excluded value
(1 row)

If there is no conflict, then OLD and EXCLUDED values are NULL.


For the most part, this is just an extension of the code to support
returning OLD and NEW. Originally, I had intended to not use
varreturningtype, since EXCLUDED is a different RTE than the result
relation, so the executor just uses the Var's varno (set to INNER_VAR
in setrefs.c). However, the rewriter code needed to support updatable
views and virtual generated columns turns out to be simpler if these
Vars have a separate varreturningtype.

I still have a lot more testing to do, and docs to update, but so far
the results look promising. I'll add this to the next CF.

Regards,
Dean

Attachments:

v1-0001-Allow-EXCLUDED-in-RETURNING-list-of-INSERT-ON-CON.patch (text/x-patch, 61.4K) download From fe79b310c287bf4bc6b37e25d53053b342d05767 Mon Sep 17 00:00:00 2001 From: Dean Rasheed <dean.a.rasheed@gmail.com> Date: Mon, 23 Jun 2025 17:20:02 +0100 Subject: [PATCH v1] Allow EXCLUDED in RETURNING list of INSERT ON CONFLICT DO UPDATE. TODO: * More testing * Docs --- src/backend/executor/execExpr.c | 44 +++++++++-- src/backend/executor/execExprInterp.c | 21 ++++- src/backend/executor/execPartition.c | 14 ++++ src/backend/executor/nodeModifyTable.c | 51 +++++++++--- src/backend/optimizer/path/allpaths.c | 3 +- src/backend/optimizer/plan/setrefs.c | 77 ++++++++++++------- src/backend/optimizer/prep/prepjointree.c | 13 ++-- src/backend/optimizer/prep/preptlist.c | 9 ++- src/backend/optimizer/util/clauses.c | 2 +- src/backend/optimizer/util/var.c | 11 ++- src/backend/parser/analyze.c | 17 +++- src/backend/parser/parse_expr.c | 2 +- src/backend/parser/parse_relation.c | 4 +- src/backend/rewrite/rewriteHandler.c | 42 ++++++---- src/backend/rewrite/rewriteManip.c | 65 +++++++++------- src/include/executor/execExpr.h | 7 +- src/include/nodes/execnodes.h | 2 + src/include/nodes/primnodes.h | 26 +++++-- src/include/parser/parse_node.h | 7 +- src/include/rewrite/rewriteManip.h | 4 +- src/test/regress/expected/arrays.out | 26 +++++-- src/test/regress/expected/inherit.out | 9 ++- src/test/regress/expected/insert_conflict.out | 26 ++++--- src/test/regress/expected/updatable_views.out | 16 +++- src/test/regress/sql/arrays.sql | 9 ++- src/test/regress/sql/inherit.sql | 3 +- src/test/regress/sql/insert_conflict.sql | 8 +- src/test/regress/sql/updatable_views.sql | 6 +- src/tools/pgindent/typedefs.list | 1 + 29 files changed, 366 insertions(+), 159 deletions(-) diff --git a/src/backend/executor/execExpr.c b/src/backend/executor/execExpr.c index f1569879b52..d13c82bdd30 100644 --- a/src/backend/executor/execExpr.c +++ b/src/backend/executor/execExpr.c @@ -455,6 +455,7 @@ ExecBuildProjectionInfo(List *targetList, /* * Get the tuple from the relation being scanned, or the * old/new tuple slot, if old/new values were requested. + * Should not see EXCLUDED here (should be INNER_VAR). */ switch (variable->varreturningtype) { @@ -469,6 +470,10 @@ ExecBuildProjectionInfo(List *targetList, scratch.opcode = EEOP_ASSIGN_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -972,6 +977,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_SYSVAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -1007,6 +1016,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -2638,10 +2651,23 @@ ExecInitExprRec(Expr *node, ExprState *state, ReturningExpr *rexpr = (ReturningExpr *) node; int retstep; - /* Skip expression evaluation if OLD/NEW row doesn't exist */ + /* + * Skip expression evaluation if OLD/NEW/EXCLUDED row doesn't + * exist. + */ scratch.opcode = EEOP_RETURNINGEXPR; - scratch.d.returningexpr.nullflag = rexpr->retold ? - EEO_FLAG_OLD_IS_NULL : EEO_FLAG_NEW_IS_NULL; + switch (rexpr->retkind) + { + case RETURNING_OLD_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_OLD_IS_NULL; + break; + case RETURNING_NEW_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_NEW_IS_NULL; + break; + case RETURNING_EXCLUDED_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_INNER_IS_NULL; + break; + } scratch.d.returningexpr.jumpdone = -1; /* set below */ ExprEvalPushStep(state, &scratch); retstep = state->steps_len - 1; @@ -2649,14 +2675,15 @@ ExecInitExprRec(Expr *node, ExprState *state, /* Steps to evaluate expression to return */ ExecInitExprRec(rexpr->retexpr, state, resv, resnull); - /* Jump target used if OLD/NEW row doesn't exist */ + /* Jump target used if OLD/NEW/EXCLUDED row doesn't exist */ state->steps[retstep].d.returningexpr.jumpdone = state->steps_len; /* Update ExprState flags */ - if (rexpr->retold) + if (rexpr->retkind == RETURNING_OLD_EXPR) state->flags |= EEO_FLAG_HAS_OLD; - else + else if (rexpr->retkind == RETURNING_NEW_EXPR) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ break; } @@ -3013,6 +3040,10 @@ expr_setup_walker(Node *node, ExprSetupInfo *info) case VAR_RETURNING_NEW: info->last_new = Max(info->last_new, attnum); break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -3178,6 +3209,7 @@ ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable, ExprState *state) state->flags |= EEO_FLAG_HAS_OLD; else if (variable->varreturningtype == VAR_RETURNING_NEW) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ /* * If the input tuple came from a subquery, it might contain "resjunk" diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c index 8a72b5e70a4..2e8ecd8b30a 100644 --- a/src/backend/executor/execExprInterp.c +++ b/src/backend/executor/execExprInterp.c @@ -5340,7 +5340,21 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) switch (variable->varno) { case INNER_VAR: - /* get the tuple from the inner node */ + + /* + * Get the tuple from the inner node. + * + * In a RETURNING expression, this is used for EXCLUDED values in + * an INSERT ... ON CONFLICT DO UPDATE. If the non-conflicting + * branch is taken, the EXCLUDED row is NULL, and we return NULL + * rather than an all-NULL record. + */ + if (state->flags & EEO_FLAG_INNER_IS_NULL) + { + *op->resvalue = (Datum) 0; + *op->resnull = true; + return; + } slot = econtext->ecxt_innertuple; break; @@ -5385,6 +5399,11 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) } slot = econtext->ecxt_newtuple; break; + + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } diff --git a/src/backend/executor/execPartition.c b/src/backend/executor/execPartition.c index 514eae1037d..6adc07cbed3 100644 --- a/src/backend/executor/execPartition.c +++ b/src/backend/executor/execPartition.c @@ -642,12 +642,26 @@ ExecInitPartitionInfo(ModifyTableState *mtstate, EState *estate, /* * Convert Vars in it to contain this partition's attribute numbers. + * If we're doing an INSERT ... ON CONFLICT DO UPDATE, the RETURNING + * list might contain references to the EXCLUDED pseudo-relation + * (INNER_VAR), so we must map their attribute numbers too. */ if (part_attmap == NULL) part_attmap = build_attrmap_by_name(RelationGetDescr(partrel), RelationGetDescr(firstResultRel), false); + + if (node->onConflictAction == ONCONFLICT_UPDATE) + { + returningList = (List *) + map_variable_attnos((Node *) returningList, + INNER_VAR, 0, + part_attmap, + RelationGetForm(partrel)->reltype, + &found_whole_row); + /* We ignore the value of found_whole_row. */ + } returningList = (List *) map_variable_attnos((Node *) returningList, firstVarno, 0, diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c index 54da8e7995b..1e09ceb00da 100644 --- a/src/backend/executor/nodeModifyTable.c +++ b/src/backend/executor/nodeModifyTable.c @@ -277,6 +277,7 @@ ExecCheckPlanOutput(Relation resultRel, List *targetList) * oldSlot: slot holding old tuple deleted or updated * newSlot: slot holding new tuple inserted or updated * planSlot: slot holding tuple returned by top subplan node + * exclSlot: slot holding EXCLUDED tuple (for INSERT ... ON CONFLICT ...) * * Note: If oldSlot and newSlot are NULL, the FDW should have already provided * econtext's scan tuple and its old & new tuples are not needed (FDW direct- @@ -290,8 +291,11 @@ ExecProcessReturning(ModifyTableContext *context, CmdType cmdType, TupleTableSlot *oldSlot, TupleTableSlot *newSlot, - TupleTableSlot *planSlot) + TupleTableSlot *planSlot, + TupleTableSlot *exclSlot) { + ModifyTableState *mtstate = context->mtstate; + ModifyTable *node = (ModifyTable *) mtstate->ps.plan; EState *estate = context->estate; ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning; ExprContext *econtext = projectReturning->pi_exprContext; @@ -332,10 +336,18 @@ ExecProcessReturning(ModifyTableContext *context, else econtext->ecxt_newtuple = NULL; /* No references to NEW columns */ + /* Make EXCLUDED tuple available to ExecProject, if required */ + if (exclSlot) + econtext->ecxt_innertuple = exclSlot; + else if (cmdType == CMD_INSERT && node->onConflictAction == ONCONFLICT_UPDATE) + econtext->ecxt_innertuple = ExecGetAllNullSlot(estate, resultRelInfo); + else + econtext->ecxt_innertuple = NULL; + /* - * Tell ExecProject whether or not the OLD/NEW rows actually exist. This - * information is required to evaluate ReturningExpr nodes and also in - * ExecEvalSysVar() and ExecEvalWholeRowVar(). + * Tell ExecProject whether or not the OLD/NEW/EXCLUDED rows actually + * exist. This information is required to evaluate ReturningExpr nodes + * and also in ExecEvalSysVar() and ExecEvalWholeRowVar(). */ if (oldSlot == NULL) projectReturning->pi_state.flags |= EEO_FLAG_OLD_IS_NULL; @@ -347,6 +359,11 @@ ExecProcessReturning(ModifyTableContext *context, else projectReturning->pi_state.flags &= ~EEO_FLAG_NEW_IS_NULL; + if (exclSlot == NULL) + projectReturning->pi_state.flags |= EEO_FLAG_INNER_IS_NULL; + else + projectReturning->pi_state.flags &= ~EEO_FLAG_INNER_IS_NULL; + /* Compute the RETURNING expressions */ return ExecProject(projectReturning); } @@ -1330,7 +1347,7 @@ ExecInsert(ModifyTableContext *context, } result = ExecProcessReturning(context, resultRelInfo, CMD_INSERT, - oldSlot, slot, planSlot); + oldSlot, slot, planSlot, NULL); /* * For a cross-partition UPDATE, release the old tuple, first making @@ -1890,7 +1907,7 @@ ldelete: } rslot = ExecProcessReturning(context, resultRelInfo, CMD_DELETE, - slot, NULL, context->planSlot); + slot, NULL, context->planSlot, NULL); /* * Before releasing the target tuple again, make sure rslot has a @@ -2449,6 +2466,8 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, * planSlot is the output of the ModifyTable's subplan; we use it * to access values from other input tables (for RETURNING), * row-ID junk columns, etc. + * exclSlot contains the EXCLUDED tuple if this is the auxiliary + * UPDATE of an INSERT ... ON CONFLICT DO UPDATE. * * Returns RETURNING result if any, otherwise NULL. On exit, if tupleid * had identified the tuple to update, it will identify the tuple @@ -2458,7 +2477,7 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, static TupleTableSlot * ExecUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *oldSlot, - TupleTableSlot *slot, bool canSetTag) + TupleTableSlot *slot, TupleTableSlot *exclSlot, bool canSetTag) { EState *estate = context->estate; Relation resultRelationDesc = resultRelInfo->ri_RelationDesc; @@ -2691,7 +2710,8 @@ redo_act: /* Process RETURNING if present */ if (resultRelInfo->ri_projectReturning) return ExecProcessReturning(context, resultRelInfo, CMD_UPDATE, - oldSlot, slot, context->planSlot); + oldSlot, slot, context->planSlot, + exclSlot); return NULL; } @@ -2913,6 +2933,7 @@ ExecOnConflictUpdate(ModifyTableContext *context, *returning = ExecUpdate(context, resultRelInfo, conflictTid, NULL, existing, resultRelInfo->ri_onConflict->oc_ProjSlot, + excludedSlot, canSetTag); /* @@ -3537,7 +3558,8 @@ lmerge_matched: CMD_UPDATE, resultRelInfo->ri_oldTupleSlot, newslot, - context->planSlot); + context->planSlot, + NULL); break; case CMD_DELETE: @@ -3546,7 +3568,8 @@ lmerge_matched: CMD_DELETE, resultRelInfo->ri_oldTupleSlot, NULL, - context->planSlot); + context->planSlot, + NULL); break; case CMD_NOTHING: @@ -4310,12 +4333,16 @@ ExecModifyTable(PlanState *pstate) * provide it here. The individual old and new slots are not * needed, since direct-modify is disabled if the RETURNING list * refers to OLD/NEW values. + * + * Currently, foreign tables do not support UNIQUE constraints, + * and therefore they do not support INSERT ... ON CONFLICT, and + * so the EXCLUDED slot is also not needed. */ Assert((resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD) == 0 && (resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_NEW) == 0); slot = ExecProcessReturning(&context, resultRelInfo, operation, - NULL, NULL, context.planSlot); + NULL, NULL, context.planSlot, NULL); return slot; } @@ -4505,7 +4532,7 @@ ExecModifyTable(PlanState *pstate) /* Now apply the update. */ slot = ExecUpdate(&context, resultRelInfo, tupleid, oldtuple, - oldSlot, slot, node->canSetTag); + oldSlot, slot, NULL, node->canSetTag); if (tuplock) UnlockTuple(resultRelInfo->ri_RelationDesc, tupleid, InplaceUpdateTupleLock); diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index 6cc6966b060..017a685959b 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -4013,8 +4013,7 @@ subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual) * each component query gets its own copy of the qual. */ qual = ReplaceVarsFromTargetList(qual, rti, 0, rte, - subquery->targetList, - subquery->resultRelation, + subquery->targetList, 0, REPLACEVARS_REPORT_ERROR, 0, &subquery->hasSubLinks); diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c index 846e44186c3..6d45e6e0c40 100644 --- a/src/backend/optimizer/plan/setrefs.c +++ b/src/backend/optimizer/plan/setrefs.c @@ -206,6 +206,8 @@ static List *set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset); static List *set_windowagg_runcondition_references(PlannerInfo *root, List *runcondition, @@ -1061,10 +1063,14 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) { ModifyTable *splan = (ModifyTable *) plan; Plan *subplan = outerPlan(splan); + indexed_tlist *excl_itlist = NULL; Assert(splan->plan.targetlist == NIL); Assert(splan->plan.qual == NIL); + if (splan->onConflictSet) + excl_itlist = build_tlist_index(splan->exclRelTlist); + splan->withCheckOptionLists = fix_scan_list(root, splan->withCheckOptionLists, rtoffset, 1); @@ -1090,6 +1096,8 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) rlist, subplan, resultrel, + splan->exclRelRTI, + excl_itlist, rtoffset); newRL = lappend(newRL, rlist); } @@ -1117,23 +1125,19 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) */ if (splan->onConflictSet) { - indexed_tlist *itlist; - - itlist = build_tlist_index(splan->exclRelTlist); - splan->onConflictSet = fix_join_expr(root, splan->onConflictSet, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); splan->onConflictWhere = (Node *) fix_join_expr(root, (List *) splan->onConflictWhere, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); - pfree(itlist); + pfree(excl_itlist); splan->exclRelTlist = fix_scan_list(root, splan->exclRelTlist, rtoffset, 1); @@ -2798,12 +2802,12 @@ build_tlist_index(List *tlist) * build_tlist_index_other_vars --- build a restricted tlist index * * This is like build_tlist_index, but we only index tlist entries that - * are Vars belonging to some rel other than the one specified. We will set + * are Vars belonging to some rel other than the ones specified. We will set * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars * (so nothing other than Vars and PlaceHolderVars can be matched). */ static indexed_tlist * -build_tlist_index_other_vars(List *tlist, int ignore_rel) +build_tlist_index_other_vars(List *tlist, int ignore_rel1, int ignore_rel2) { indexed_tlist *itlist; tlist_vinfo *vinfo; @@ -2828,7 +2832,7 @@ build_tlist_index_other_vars(List *tlist, int ignore_rel) { Var *var = (Var *) tle->expr; - if (var->varno != ignore_rel) + if (var->varno != ignore_rel1 && var->varno != ignore_rel2) { vinfo->varno = var->varno; vinfo->varattno = var->varattno; @@ -3067,10 +3071,14 @@ search_indexed_tlist_for_sortgroupref(Expr *node, * acceptable_rel should be zero so that any failure to match a Var will be * reported as an error. * 2) RETURNING clauses, which may contain both Vars of the target relation - * and Vars of other relations. In this case we want to replace the - * other-relation Vars by OUTER_VAR references, while leaving target Vars - * alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the - * target relation should be passed. + * and Vars of other relations, including the EXCLUDED pseudo-relation in + * an INSERT ... ON CONFLICT DO UPDATE command. In this case, we want to + * replace references to EXCLUDED with INNER_VAR references, and + * other-relation Vars with OUTER_VAR references, while leaving target Vars + * alone. Thus inner_itlist is to be EXCLUDED elements, if this is an + * INSERT with an ON CONFLICT DO UPDATE clause, outer_itlist is any other + * non-target relation elements, and acceptable_rel = the ID of the target + * relation. * 3) ON CONFLICT UPDATE SET/WHERE clauses. Here references to EXCLUDED are * to be replaced with INNER_VAR references, while leaving target Vars (the * to-be-updated relation) alone. Correspondingly inner_itlist is to be @@ -3131,15 +3139,16 @@ fix_join_expr_mutator(Node *node, fix_join_expr_context *context) /* * Verify that Vars with non-default varreturningtype only appear in - * the RETURNING list, and refer to the target relation. + * the RETURNING list, and that OLD/NEW Vars refer to the target + * relation. */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { - if (context->inner_itlist != NULL || - context->outer_itlist == NULL || + if (context->outer_itlist == NULL || context->acceptable_rel == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); - if (var->varno != context->acceptable_rel) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list"); + if (var->varreturningtype != VAR_RETURNING_EXCLUDED && + var->varno != context->acceptable_rel) elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new", var->varno, context->acceptable_rel); } @@ -3369,11 +3378,14 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * * If the query involves more than just the result table, we have to * adjust any Vars that refer to other tables to reference junk tlist - * entries in the top subplan's targetlist. Vars referencing the result - * table should be left alone, however (the executor will evaluate them - * using the actual heap tuple, after firing triggers if any). In the - * adjusted RETURNING list, result-table Vars will have their original - * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR. + * entries in the top subplan's targetlist. Vars referencing the EXCLUDED + * pseudo-relation of an INSERT ... ON CONFLICT DO UPDATE command should be + * adjusted to reference INNER_VAR, and Vars referencing the result table + * should be left alone (the executor will evaluate them using the actual heap + * tuple, after firing triggers if any). In the adjusted RETURNING list, + * result-table Vars will have their original varno (plus rtoffset), but Vars + * for the EXCLUDED pseudo-relation and other rels will have varno INNER_VAR + * and OUTER_VAR espectively. * * We also must perform opcode lookup and add regclass OIDs to * root->glob->relationOids. @@ -3382,6 +3394,8 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * 'topplan': the top subplan node that will be just below the ModifyTable * node (note it's not yet passed through set_plan_refs) * 'resultRelation': RT index of the associated result relation + * 'exclRelRTI': RT index of EXCLUDED pseudo-relation + * 'excl_itlist': EXCLUDED pseudo-relation elements (or NULL) * 'rtoffset': how much to increment varnos by * * Note: the given 'root' is for the parent query level, not the 'topplan'. @@ -3396,6 +3410,8 @@ set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset) { indexed_tlist *itlist; @@ -3403,9 +3419,11 @@ set_returning_clause_references(PlannerInfo *root, /* * We can perform the desired Var fixup by abusing the fix_join_expr * machinery that formerly handled inner indexscan fixup. We search the - * top plan's targetlist for Vars of non-result relations, and use - * fix_join_expr to convert RETURNING Vars into references to those tlist - * entries, while leaving result-rel Vars as-is. + * top plan's targetlist for Vars of non-result relations (other than + * EXCLUDED), and use fix_join_expr to convert RETURNING Vars into + * references to those tlist entries, and convert RETURNING EXCLUDED Vars + * into references to excl_itlist entries, while leaving result-rel Vars + * as-is. * * PlaceHolderVars will also be sought in the targetlist, but no * more-complex expressions will be. Note that it is not possible for a @@ -3414,12 +3432,13 @@ set_returning_clause_references(PlannerInfo *root, * prepared to pick apart the PlaceHolderVar and evaluate its contained * expression instead. */ - itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation); + itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation, + exclRelRTI); rlist = fix_join_expr(root, rlist, itlist, - NULL, + excl_itlist, resultRelation, rtoffset, NRM_EQUAL, diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index 87dc6f56b57..02c9dfe2585 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -71,8 +71,7 @@ typedef struct pullup_replace_vars_context PlannerInfo *root; List *targetlist; /* tlist of subquery being pulled up */ RangeTblEntry *target_rte; /* RTE of subquery */ - int result_relation; /* the index of the result relation in the - * rewritten query */ + int new_target_varno; /* see ReplaceVarFromTargetList() */ Relids relids; /* relids within subquery, as numbered after * pullup (set only if target_rte->lateral) */ nullingrel_info *nullinfo; /* per-RTE nullingrel info (set only if @@ -1038,7 +1037,7 @@ expand_virtual_generated_columns(PlannerInfo *root) rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = parse->resultRelation; + rvcontext.new_target_varno = rt_index; /* won't need these values */ rvcontext.relids = NULL; rvcontext.nullinfo = NULL; @@ -1436,7 +1435,7 @@ pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte, rvcontext.root = root; rvcontext.targetlist = subquery->targetList; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; if (rte->lateral) { rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree, @@ -1987,7 +1986,7 @@ pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte) rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; rvcontext.relids = NULL; /* can't be any lateral references here */ rvcontext.nullinfo = NULL; rvcontext.outer_hasSubLinks = &parse->hasSubLinks; @@ -2147,7 +2146,7 @@ pull_up_constant_function(PlannerInfo *root, Node *jtnode, NULL, /* resname */ false)); /* resjunk */ rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; /* * Since this function was reduced to a Const, it doesn't contain any @@ -2681,7 +2680,7 @@ pullup_replace_vars_callback(Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, REPLACEVARS_REPORT_ERROR, 0); diff --git a/src/backend/optimizer/prep/preptlist.c b/src/backend/optimizer/prep/preptlist.c index ffc9d6c3f30..098d8f8498a 100644 --- a/src/backend/optimizer/prep/preptlist.c +++ b/src/backend/optimizer/prep/preptlist.c @@ -291,7 +291,10 @@ preprocess_targetlist(PlannerInfo *root) * used in RETURNING that belong to other relations. We need to do this * to make these Vars available for the RETURNING calculation. Vars that * belong to the result rel don't need to be added, because they will be - * made to refer to the actual heap tuple. + * made to refer to the actual heap tuple. Vars that refer to the + * EXCLUDED pseudo-relation of an INSERT ... ON CONFLICT DO UPDATE command + * are also not needed, because they are handled specially in the + * executor. */ if (parse->returningList && list_length(parse->rtable) > 1) { @@ -308,7 +311,9 @@ preprocess_targetlist(PlannerInfo *root) TargetEntry *tle; if (IsA(var, Var) && - var->varno == result_relation) + (var->varno == result_relation || + (parse->onConflict && + var->varno == parse->onConflict->exclRelIndex))) continue; /* don't need it */ if (tlist_member((Expr *) var, tlist)) diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 26a3e050086..dc50f0a5c84 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -3407,7 +3407,7 @@ eval_const_expressions_mutator(Node *node, fselect->resulttypmod, fselect->resultcollid, ((Var *) arg)->varlevelsup); - /* New Var has same OLD/NEW returning as old one */ + /* New Var has same returningtype as old one */ newvar->varreturningtype = ((Var *) arg)->varreturningtype; /* New Var is nullable by same rels as the old one */ newvar->varnullingrels = ((Var *) arg)->varnullingrels; diff --git a/src/backend/optimizer/util/var.c b/src/backend/optimizer/util/var.c index 8065237a189..c2642c88e92 100644 --- a/src/backend/optimizer/util/var.c +++ b/src/backend/optimizer/util/var.c @@ -501,8 +501,8 @@ contain_vars_of_level_walker(Node *node, int *sublevels_up) * * Returns true if any found. * - * Any ReturningExprs are also detected --- if an OLD/NEW Var was rewritten, - * we still regard this as a clause that returns OLD/NEW values. + * Any ReturningExprs are also checked --- if an OLD/NEW Var was rewritten, we + * still regard this as a clause that returns OLD/NEW values. * * Does not examine subqueries, therefore must only be used after reduction * of sublinks to subplans! @@ -521,13 +521,16 @@ contain_vars_returning_old_or_new_walker(Node *node, void *context) if (IsA(node, Var)) { if (((Var *) node)->varlevelsup == 0 && - ((Var *) node)->varreturningtype != VAR_RETURNING_DEFAULT) + (((Var *) node)->varreturningtype == VAR_RETURNING_OLD || + ((Var *) node)->varreturningtype == VAR_RETURNING_NEW)) return true; /* abort the tree traversal and return true */ return false; } if (IsA(node, ReturningExpr)) { - if (((ReturningExpr *) node)->retlevelsup == 0) + if (((ReturningExpr *) node)->retlevelsup == 0 && + (((ReturningExpr *) node)->retkind == RETURNING_OLD_EXPR || + ((ReturningExpr *) node)->retkind == RETURNING_NEW_EXPR)) return true; /* abort the tree traversal and return true */ return false; } diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index 34f7c17f576..bf7ee465a14 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -1234,12 +1234,21 @@ transformOnConflictClause(ParseState *pstate, EXPR_KIND_WHERE, "WHERE"); /* - * Remove the EXCLUDED pseudo relation from the query namespace, since - * it's not supposed to be available in RETURNING. (Maybe someday we - * could allow that, and drop this step.) + * Leave the EXCLUDED pseudo relation in the query namespace so that + * it is available in RETURNING expressions, but change it to be a + * table-only item so that its columns are only accessible using + * qualified names. This ensures that columns from the target + * relation can be accessed using unqualified names without ambiguity. + * + * Also, set its returning_type so that any RETURNING list Vars + * referencing it are marked correctly. */ Assert((ParseNamespaceItem *) llast(pstate->p_namespace) == exclNSItem); - pstate->p_namespace = list_delete_last(pstate->p_namespace); + exclNSItem->p_cols_visible = false; + + exclNSItem->p_returning_type = VAR_RETURNING_EXCLUDED; + for (int i = 0; i < list_length(exclNSItem->p_names->colnames); i++) + exclNSItem->p_nscolumns[i].p_varreturningtype = VAR_RETURNING_EXCLUDED; } /* Finally, build ON CONFLICT DO [NOTHING | UPDATE] expression */ diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c index d66276801c6..e551c0bd7a1 100644 --- a/src/backend/parser/parse_expr.c +++ b/src/backend/parser/parse_expr.c @@ -2653,7 +2653,7 @@ transformWholeRowRef(ParseState *pstate, ParseNamespaceItem *nsitem, result = makeWholeRowVar(nsitem->p_rte, nsitem->p_rtindex, sublevels_up, true); - /* mark Var for RETURNING OLD/NEW, as necessary */ + /* mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ result->varreturningtype = nsitem->p_returning_type; /* location is not filled in by makeWholeRowVar */ diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c index 04ecf64b1fc..1651c52eb87 100644 --- a/src/backend/parser/parse_relation.c +++ b/src/backend/parser/parse_relation.c @@ -258,7 +258,7 @@ scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location) /* If not inside LATERAL, ignore lateral-only items */ if (nsitem->p_lateral_only && !pstate->p_lateral_active) continue; - /* Ignore OLD/NEW namespace items that can appear in RETURNING */ + /* Ignore OLD/NEW/EXCLUDED namespace items in RETURNING */ if (nsitem->p_returning_type != VAR_RETURNING_DEFAULT) continue; @@ -775,7 +775,7 @@ scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem, } var->location = location; - /* Mark Var for RETURNING OLD/NEW, as necessary */ + /* Mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ var->varreturningtype = nsitem->p_returning_type; /* Mark Var if it's nulled by any outer joins */ diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c index 2ef0e7fbf3a..98a02167f23 100644 --- a/src/backend/rewrite/rewriteHandler.c +++ b/src/backend/rewrite/rewriteHandler.c @@ -97,7 +97,7 @@ static List *matchLocks(CmdType event, Relation relation, static Query *fireRIRrules(Query *parsetree, List *activeRIRs); static Bitmapset *adjust_view_column_set(Bitmapset *cols, List *targetlist); static Node *expand_generated_columns_internal(Node *node, Relation rel, int rt_index, - RangeTblEntry *rte, int result_relation); + RangeTblEntry *rte); /* @@ -643,7 +643,7 @@ rewriteRuleAction(Query *parsetree, 0, rt_fetch(new_varno, sub_action->rtable), parsetree->targetList, - sub_action->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -2345,7 +2345,7 @@ CopyAndAddInvertedQual(Query *parsetree, rt_fetch(rt_index, parsetree->rtable), parsetree->targetList, - parsetree->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -3704,12 +3704,12 @@ rewriteTargetView(Query *parsetree, Relation view) BuildOnConflictExcludedTargetlist(base_rel, new_exclRelIndex); /* - * Update all Vars in the ON CONFLICT clause that refer to the old - * EXCLUDED pseudo-relation. We want to use the column mappings - * defined in the view targetlist, but we need the outputs to refer to - * the new EXCLUDED pseudo-relation rather than the new target RTE. - * Also notice that "EXCLUDED.*" will be expanded using the view's - * rowtype, which seems correct. + * Update all Vars in the ON CONFLICT clause and RETURNING list that + * refer to the old EXCLUDED pseudo-relation. We want to use the + * column mappings defined in the view targetlist, but we need the + * outputs to refer to the new EXCLUDED pseudo-relation rather than + * the new target RTE. Also notice that "EXCLUDED.*" will be expanded + * using the view's rowtype, which seems correct. */ tmp_tlist = copyObject(view_targetlist); @@ -3722,7 +3722,18 @@ rewriteTargetView(Query *parsetree, Relation view) 0, view_rte, tmp_tlist, - new_rt_index, + 0, + REPLACEVARS_REPORT_ERROR, + 0, + &parsetree->hasSubLinks); + + parsetree->returningList = (List *) + ReplaceVarsFromTargetList((Node *) parsetree->returningList, + old_exclRelIndex, + 0, + view_rte, + tmp_tlist, + new_exclRelIndex, REPLACEVARS_REPORT_ERROR, 0, &parsetree->hasSubLinks); @@ -4420,13 +4431,11 @@ RewriteQuery(Query *parsetree, List *rewrite_events, int orig_rt_length) * virtual generated column expressions from rel, if there are any. * * The caller must also provide rte, the RTE describing the target relation, - * in order to handle any whole-row Vars referencing the target, and - * result_relation, the index of the result relation, if this is part of an - * INSERT/UPDATE/DELETE/MERGE query. + * in order to handle any whole-row Vars referencing the target. */ static Node * expand_generated_columns_internal(Node *node, Relation rel, int rt_index, - RangeTblEntry *rte, int result_relation) + RangeTblEntry *rte) { TupleDesc tupdesc; @@ -4454,8 +4463,7 @@ expand_generated_columns_internal(Node *node, Relation rel, int rt_index, Assert(list_length(tlist) > 0); - node = ReplaceVarsFromTargetList(node, rt_index, 0, rte, tlist, - result_relation, + node = ReplaceVarsFromTargetList(node, rt_index, 0, rte, tlist, 0, REPLACEVARS_CHANGE_VARNO, rt_index, NULL); } @@ -4484,7 +4492,7 @@ expand_generated_columns_in_expr(Node *node, Relation rel, int rt_index) rte->rtekind = RTE_RELATION; rte->relid = RelationGetRelid(rel); - node = expand_generated_columns_internal(node, rel, rt_index, rte, 0); + node = expand_generated_columns_internal(node, rel, rt_index, rte); } return node; diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index cd786aa4112..b7bce45fd01 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -921,7 +921,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, /* * SetVarReturningType - adjust Var nodes for a specified varreturningtype. * - * Find all Var nodes referring to the specified result relation in the given + * Find all Var nodes referring to the specified relation in the given * expression and set their varreturningtype to the specified value. * * NOTE: although this has the form of a walker, we cheat and modify the @@ -931,7 +931,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, typedef struct { - int result_relation; + int target_varno; int sublevels_up; VarReturningType returning_type; } SetVarReturningType_context; @@ -945,7 +945,7 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) { Var *var = (Var *) node; - if (var->varno == context->result_relation && + if (var->varno == context->target_varno && var->varlevelsup == context->sublevels_up) var->varreturningtype = context->returning_type; @@ -967,12 +967,12 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) } static void -SetVarReturningType(Node *node, int result_relation, int sublevels_up, +SetVarReturningType(Node *node, int target_varno, int sublevels_up, VarReturningType returning_type) { SetVarReturningType_context context; - context.result_relation = result_relation; + context.target_varno = target_varno; context.sublevels_up = sublevels_up; context.returning_type = returning_type; @@ -1744,14 +1744,25 @@ map_variable_attnos(Node *node, * relation. This is needed to handle whole-row Vars referencing the target. * We expand such Vars into RowExpr constructs. * - * In addition, for INSERT/UPDATE/DELETE/MERGE queries, the caller must - * provide result_relation, the index of the result relation in the rewritten - * query. This is needed to handle OLD/NEW RETURNING list Vars referencing - * target_varno. When such Vars are expanded, their varreturningtype is - * copied onto any replacement Vars referencing result_relation. In addition, - * if the replacement expression from the targetlist is not simply a Var - * referencing result_relation, it is wrapped in a ReturningExpr node (causing - * the executor to return NULL if the OLD/NEW row doesn't exist). + * In addition, the caller should provide new_target_varno, which is needed to + * handle OLD/NEW/EXCLUDED RETURNING list Vars referencing target_varno. When + * such Vars are expanded, their varreturningtype is copied onto any + * replacement Vars that reference new_target_varno. In addition, if the + * replacement expression from the targetlist is not simply a Var referencing + * new_target_varno, it is wrapped in a ReturningExpr node (causing the + * executor to return NULL if the OLD/NEW/EXCLUDED row doesn't exist). The + * caller should set new_target_varno as follows: + * + * If the input node contains Vars from the RETURNING list of a query, and + * target_varno is the resultRelation of that query, then new_target_varno + * should be the (possibly new) resultRelation of the rewritten query. + * + * If the input node contains Vars from the RETURNING list of an INSERT ... + * ON CONFLICT DO UPDATE query, and target_varno is the index of the + * EXCLUDED pseudo-relation, then new_target_varno should be the (possibly + * new) index of the EXCLUDED pseudo-relation in the rewritten query. + * + * Otherwise, new_target_varno is not used. * * Note that ReplaceVarFromTargetList always generates the replacement * expression with varlevelsup = 0. The caller is responsible for adjusting @@ -1765,7 +1776,7 @@ typedef struct { RangeTblEntry *target_rte; List *targetlist; - int result_relation; + int new_target_varno; ReplaceVarsNoMatchOption nomatch_option; int nomatch_varno; } ReplaceVarsFromTargetList_context; @@ -1780,7 +1791,7 @@ ReplaceVarsFromTargetList_callback(Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, rcon->nomatch_option, rcon->nomatch_varno); @@ -1795,7 +1806,7 @@ Node * ReplaceVarFromTargetList(Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno) { @@ -1844,7 +1855,7 @@ ReplaceVarFromTargetList(Var *var, field = ReplaceVarFromTargetList((Var *) field, target_rte, targetlist, - result_relation, + new_target_varno, nomatch_option, nomatch_varno); rowexpr->args = lappend(rowexpr->args, field); @@ -1856,7 +1867,7 @@ ReplaceVarFromTargetList(Var *var, ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = (Expr *) rowexpr; return (Node *) rexpr; @@ -1925,28 +1936,28 @@ ReplaceVarFromTargetList(Var *var, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("NEW variables in ON UPDATE rules cannot reference columns that are part of a multiple assignment in the subject UPDATE command"))); - /* Handle any OLD/NEW RETURNING list Vars */ + /* Handle any OLD/NEW/EXCLUDED RETURNING list Vars */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { /* * Copy varreturningtype onto any Vars in the tlist item that - * refer to result_relation (which had better be non-zero). + * refer to new_target_varno (which had better be non-zero). */ - if (result_relation == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); + if (new_target_varno == 0) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list"); - SetVarReturningType((Node *) newnode, result_relation, + SetVarReturningType((Node *) newnode, new_target_varno, 0, var->varreturningtype); /* Wrap it in a ReturningExpr, if needed, per comments above */ if (!IsA(newnode, Var) || - ((Var *) newnode)->varno != result_relation || + ((Var *) newnode)->varno != new_target_varno || ((Var *) newnode)->varlevelsup != 0) { ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = newnode; newnode = (Expr *) rexpr; @@ -1962,7 +1973,7 @@ ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks) @@ -1971,7 +1982,7 @@ ReplaceVarsFromTargetList(Node *node, context.target_rte = target_rte; context.targetlist = targetlist; - context.result_relation = result_relation; + context.new_target_varno = new_target_varno; context.nomatch_option = nomatch_option; context.nomatch_varno = nomatch_varno; diff --git a/src/include/executor/execExpr.h b/src/include/executor/execExpr.h index 75366203706..1ce4d98afce 100644 --- a/src/include/executor/execExpr.h +++ b/src/include/executor/execExpr.h @@ -26,9 +26,9 @@ struct JsonConstructorExprState; /* Bits in ExprState->flags (see also execnodes.h for public flag bits): */ /* expression's interpreter has been initialized */ -#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 5) +#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 6) /* jump-threading is in use */ -#define EEO_FLAG_DIRECT_THREADED (1 << 6) +#define EEO_FLAG_DIRECT_THREADED (1 << 7) /* Typical API for out-of-line evaluation subroutines */ typedef void (*ExecEvalSubroutine) (ExprState *state, @@ -338,7 +338,8 @@ typedef struct ExprEvalStep /* but it's just the normal (negative) attr number for SYSVAR */ int attnum; Oid vartype; /* type OID of variable */ - VarReturningType varreturningtype; /* return old/new/default */ + /* if not default, return old/new/excluded value */ + VarReturningType varreturningtype; } var; /* for EEOP_WHOLEROW */ diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index 2492282213f..cac584a88d4 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -82,6 +82,8 @@ typedef Datum (*ExprStateEvalFunc) (struct ExprState *expression, #define EEO_FLAG_OLD_IS_NULL (1 << 3) /* NEW table row is NULL in RETURNING list */ #define EEO_FLAG_NEW_IS_NULL (1 << 4) +/* INNER (EXCLUDED) table row is NULL in RETURNING list */ +#define EEO_FLAG_INNER_IS_NULL (1 << 5) typedef struct ExprState { diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h index 01510b01b64..0fc24910c6d 100644 --- a/src/include/nodes/primnodes.h +++ b/src/include/nodes/primnodes.h @@ -227,7 +227,9 @@ typedef struct Expr * varreturningtype is used for Vars that refer to the target relation in the * RETURNING list of data-modifying queries. The default behavior is to * return old values for DELETE and new values for INSERT and UPDATE, but it - * is also possible to explicitly request old or new values. + * is also possible to explicitly request old or new values. For INSERT ... + * ON CONFLICT DO UPDATE, varreturningtype is also used for Vars in the + * RETURNING list that refer to the EXCLUDED pseudo-relation. * * In the parser, varnosyn and varattnosyn are either identical to * varno/varattno, or they specify the column's position in an aliased JOIN @@ -256,6 +258,7 @@ typedef enum VarReturningType VAR_RETURNING_DEFAULT, /* return OLD for DELETE, else return NEW */ VAR_RETURNING_OLD, /* return OLD for DELETE/UPDATE, else NULL */ VAR_RETURNING_NEW, /* return NEW for INSERT/UPDATE, else NULL */ + VAR_RETURNING_EXCLUDED, /* return EXCLUDED on conflict, else NULL */ } VarReturningType; typedef struct Var @@ -2138,14 +2141,15 @@ typedef struct InferenceElem } InferenceElem; /* - * ReturningExpr - return OLD/NEW.(expression) in RETURNING list + * ReturningExpr - return OLD/NEW/EXCLUDED.(expression) in RETURNING list * * This is used when updating an auto-updatable view and returning a view * column that is not simply a Var referring to the base relation. In such - * cases, OLD/NEW.viewcol can expand to an arbitrary expression, but the - * result is required to be NULL if the OLD/NEW row doesn't exist. To handle - * this, the rewriter wraps the expanded expression in a ReturningExpr, which - * is equivalent to "CASE WHEN (OLD/NEW row exists) THEN (expr) ELSE NULL". + * cases, OLD/NEW/EXCLUDED.viewcol can expand to an arbitrary expression, but + * the result is required to be NULL if the OLD/NEW/EXCLUDED row doesn't + * exist. To handle this, the rewriter wraps the expanded expression in a + * ReturningExpr, which is equivalent to "CASE WHEN (OLD/NEW/EXCLUDED row + * exists) THEN (expr) ELSE NULL". * * A similar situation can arise when rewriting the RETURNING clause of a * rule, which may also contain arbitrary expressions. @@ -2153,11 +2157,19 @@ typedef struct InferenceElem * ReturningExpr nodes never appear in a parsed Query --- they are only ever * inserted by the rewriter and the planner. */ +typedef enum ReturningExprKind +{ + /* values here match non-default VarReturningType values */ + RETURNING_OLD_EXPR = VAR_RETURNING_OLD, + RETURNING_NEW_EXPR = VAR_RETURNING_NEW, + RETURNING_EXCLUDED_EXPR = VAR_RETURNING_EXCLUDED, +} ReturningExprKind; + typedef struct ReturningExpr { Expr xpr; int retlevelsup; /* > 0 if it belongs to outer query */ - bool retold; /* true for OLD, false for NEW */ + ReturningExprKind retkind; /* return OLD/NEW/EXCLUDED expression */ Expr *retexpr; /* expression to be returned */ } ReturningExpr; diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h index f7d07c84542..1f0c21543b2 100644 --- a/src/include/parser/parse_node.h +++ b/src/include/parser/parse_node.h @@ -280,7 +280,8 @@ struct ParseState * forbid LATERAL references to an UPDATE/DELETE target table. * * While processing the RETURNING clause, special namespace items are added to - * refer to the OLD and NEW state of the result relation. These namespace + * refer to the OLD and NEW state of the result relation, and the EXCLUDED + * pseudo-relation for an INSERT ... ON CONFLICT DO UPDATE. These namespace * items have p_returning_type set appropriately, for use when creating Vars. * For convenience, this information is duplicated on each namespace column. * @@ -301,7 +302,7 @@ struct ParseNamespaceItem bool p_cols_visible; /* Column names visible as unqualified refs? */ bool p_lateral_only; /* Is only visible to LATERAL expressions? */ bool p_lateral_ok; /* If so, does join type allow use? */ - VarReturningType p_returning_type; /* Is OLD/NEW for use in RETURNING? */ + VarReturningType p_returning_type; /* for RETURNING OLD/NEW/EXCLUDED */ }; /* @@ -332,7 +333,7 @@ struct ParseNamespaceColumn Oid p_vartype; /* pg_type OID */ int32 p_vartypmod; /* type modifier value */ Oid p_varcollid; /* OID of collation, or InvalidOid */ - VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW */ + VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW/EXCLUDED */ Index p_varnosyn; /* rangetable index of syntactic referent */ AttrNumber p_varattnosyn; /* attribute number of syntactic referent */ bool p_dontexpand; /* not included in star expansion */ diff --git a/src/include/rewrite/rewriteManip.h b/src/include/rewrite/rewriteManip.h index 7c018f2a4e3..81a1493ad31 100644 --- a/src/include/rewrite/rewriteManip.h +++ b/src/include/rewrite/rewriteManip.h @@ -107,14 +107,14 @@ extern Node *map_variable_attnos(Node *node, extern Node *ReplaceVarFromTargetList(Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno); extern Node *ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks); diff --git a/src/test/regress/expected/arrays.out b/src/test/regress/expected/arrays.out index b815473f414..5a5a06e6a06 100644 --- a/src/test/regress/expected/arrays.out +++ b/src/test/regress/expected/arrays.out @@ -1398,20 +1398,30 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+--------- - 1 | {3,2,5} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+---------+------------- + 1 | {3,2,5} | {3,4,5} (1 row) insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+------------ - 1 | {6,7,NULL} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+------------+------------- + 1 | {6,7,NULL} | {6,7} +(1 row) + +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+----------------+------------- + 1 | {NULL,10,NULL} | [2:2]={10} (1 row) -- note: if above selects don't produce the expected tuple order, diff --git a/src/test/regress/expected/inherit.out b/src/test/regress/expected/inherit.out index f9b0c415cfd..c17b79a00a6 100644 --- a/src/test/regress/expected/inherit.out +++ b/src/test/regress/expected/inherit.out @@ -2123,7 +2123,14 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; + old | new | excluded +--------+---------+---------- + (3,3-) | (3,3-+) | (3,) + (7,7-) | (7,7-+) | (7,) +(2 rows) + select * from inhpar order by f1; -- tuple order might be unstable here f1 | f2 ----+----- diff --git a/src/test/regress/expected/insert_conflict.out b/src/test/regress/expected/insert_conflict.out index fdd0f6c8f25..3a2c63f4479 100644 --- a/src/test/regress/expected/insert_conflict.out +++ b/src/test/regress/expected/insert_conflict.out @@ -249,13 +249,13 @@ insert into insertconflicttest values (2, 'Orange') on conflict (key, key, key) insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -ERROR: invalid reference to FROM-clause entry for table "excluded" -LINE 1: ...y) do update set fruit = excluded.fruit RETURNING excluded.f... - ^ -DETAIL: There is an entry for table "excluded", but it cannot be referenced from this part of the query. + fruit +------- + Apple +(1 row) + -- Only suggest <table>.* column when inference element misspelled: insert into insertconflicttest values (1, 'Apple') on conflict (keyy) do update set fruit = excluded.fruit; ERROR: column "keyy" does not exist @@ -628,11 +628,17 @@ insert into excluded AS target values(1, '2') on conflict (key) do update set da 1 | 2 (1 row) --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; - key | data ------+------ - 1 | 3 +ERROR: table reference "excluded" is ambiguous +LINE 1: ...n conflict (key) do update set data = 3 RETURNING excluded.*... + ^ +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; + key | data | key | data +-----+------+-----+------ + 1 | 3 | 1 | 2 (1 row) -- clean up diff --git a/src/test/regress/expected/updatable_views.out b/src/test/regress/expected/updatable_views.out index 095df0a670c..0c08cf120c6 100644 --- a/src/test/regress/expected/updatable_views.out +++ b/src/test/regress/expected/updatable_views.out @@ -3653,7 +3653,13 @@ insert into uv_iocu_tab values ('xyxyxy', 0); create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- @@ -3661,7 +3667,13 @@ select * from uv_iocu_tab; (1 row) insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- diff --git a/src/test/regress/sql/arrays.sql b/src/test/regress/sql/arrays.sql index 47d62c1d38d..47a5d7c9d72 100644 --- a/src/test/regress/sql/arrays.sql +++ b/src/test/regress/sql/arrays.sql @@ -426,12 +426,17 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; -- note: if above selects don't produce the expected tuple order, -- then you didn't get an indexscan plan, and something is busted. diff --git a/src/test/regress/sql/inherit.sql b/src/test/regress/sql/inherit.sql index 699e8ac09c8..da1d418abfc 100644 --- a/src/test/regress/sql/inherit.sql +++ b/src/test/regress/sql/inherit.sql @@ -806,7 +806,8 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; select * from inhpar order by f1; -- tuple order might be unstable here drop table inhpar cascade; diff --git a/src/test/regress/sql/insert_conflict.sql b/src/test/regress/sql/insert_conflict.sql index 549c46452ec..8d1ca65715c 100644 --- a/src/test/regress/sql/insert_conflict.sql +++ b/src/test/regress/sql/insert_conflict.sql @@ -101,8 +101,7 @@ insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -- Only suggest <table>.* column when inference element misspelled: @@ -374,8 +373,11 @@ insert into excluded values(1, '2') on conflict (key) do update set data = exclu insert into excluded AS target values(1, '2') on conflict (key) do update set data = excluded.data RETURNING *; -- ok, aliased insert into excluded AS target values(1, '2') on conflict (key) do update set data = target.data RETURNING *; --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; -- clean up drop table excluded; diff --git a/src/test/regress/sql/updatable_views.sql b/src/test/regress/sql/updatable_views.sql index c071fffc116..03f57774edc 100644 --- a/src/test/regress/sql/updatable_views.sql +++ b/src/test/regress/sql/updatable_views.sql @@ -1858,10 +1858,12 @@ create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; -- OK to access view columns that are not present in underlying base diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 32d6e718adc..bf9336a86f1 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2563,6 +2563,7 @@ ReturnSetInfo ReturnStmt ReturningClause ReturningExpr +ReturningExprKind ReturningOption ReturningOptionKind RevmapContents -- 2.43.0
^ permalink raw reply [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2025-06-30 17:18  Dean Rasheed <dean.a.rasheed@gmail.com>
  parent: Dean Rasheed <dean.a.rasheed@gmail.com>
  0 siblings, 1 reply; 17+ messages in thread

From: Dean Rasheed @ 2025-06-30 17:18 UTC (permalink / raw)
  To: pgsql-hackers

On Tue, 24 Jun 2025 at 19:49, Dean Rasheed <dean.a.rasheed@gmail.com> wrote:
>
> The attached patch allows EXCLUDED values to appear in the RETURNING
> list of INSERT ... ON CONFLICT DO UPDATE.
>
> I still have a lot more testing to do, and docs to update, but so far
> the results look promising. I'll add this to the next CF.
>

v2 attached, now with docs and more test cases.

Regards,
Dean

Attachments:

v2-0001-Allow-EXCLUDED-in-RETURNING-list-of-INSERT-ON-CON.patch (text/x-patch, 100.6K) download From 8983ab34fa9fc6ad5e0df91fd33b4060234a2a48 Mon Sep 17 00:00:00 2001 From: Dean Rasheed <dean.a.rasheed@gmail.com> Date: Mon, 23 Jun 2025 17:20:02 +0100 Subject: [PATCH v2] Allow EXCLUDED in RETURNING list of INSERT ON CONFLICT DO UPDATE. This allows an INSERT ... ON CONFLICT DO UPDATE command to return the excluded values, when conflicts occur. For rows that do not conflict, the values returned are NULL. This builds on the infrastructure added to support OLD/NEW values in the RETURNING list, except that in the case of EXCLUDED, there is no need for the special syntax to change the name of the excluded pseudo-relation in the RETURNING list. (That was required for OLD/NEW, because those names were already used in some situations, such as trigger functions, but there is no such problem with excluded.) --- doc/src/sgml/dml.sgml | 13 +++ doc/src/sgml/ref/insert.sgml | 8 ++ src/backend/executor/execExpr.c | 44 +++++++-- src/backend/executor/execExprInterp.c | 21 ++++- src/backend/executor/execPartition.c | 14 +++ src/backend/executor/nodeModifyTable.c | 51 +++++++--- src/backend/optimizer/path/allpaths.c | 3 +- src/backend/optimizer/plan/setrefs.c | 77 ++++++++++------ src/backend/optimizer/prep/prepjointree.c | 21 +++-- src/backend/optimizer/prep/preptlist.c | 9 +- src/backend/optimizer/util/clauses.c | 2 +- src/backend/optimizer/util/var.c | 11 ++- src/backend/parser/analyze.c | 17 +++- src/backend/parser/parse_expr.c | 2 +- src/backend/parser/parse_relation.c | 4 +- src/backend/rewrite/rewriteHandler.c | 42 +++++---- src/backend/rewrite/rewriteManip.c | 69 ++++++++------ src/include/executor/execExpr.h | 7 +- src/include/nodes/execnodes.h | 2 + src/include/nodes/primnodes.h | 26 ++++-- src/include/parser/parse_node.h | 7 +- src/include/rewrite/rewriteManip.h | 4 +- src/test/regress/expected/arrays.out | 26 ++++-- .../regress/expected/generated_stored.out | 48 ++++++---- .../regress/expected/generated_virtual.out | 48 ++++++---- src/test/regress/expected/inherit.out | 9 +- src/test/regress/expected/insert_conflict.out | 92 +++++++++++++------ src/test/regress/expected/returning.out | 22 +++-- src/test/regress/expected/rules.out | 61 ++++++++++++ src/test/regress/expected/triggers.out | 74 ++++++++++++--- src/test/regress/expected/updatable_views.out | 27 +++++- src/test/regress/sql/arrays.sql | 9 +- src/test/regress/sql/generated_stored.sql | 4 + src/test/regress/sql/generated_virtual.sql | 4 + src/test/regress/sql/inherit.sql | 3 +- src/test/regress/sql/insert_conflict.sql | 29 +++--- src/test/regress/sql/returning.sql | 8 +- src/test/regress/sql/rules.sql | 27 ++++++ src/test/regress/sql/triggers.sql | 17 ++-- src/test/regress/sql/updatable_views.sql | 12 ++- src/tools/pgindent/typedefs.list | 1 + 41 files changed, 717 insertions(+), 258 deletions(-) diff --git a/doc/src/sgml/dml.sgml b/doc/src/sgml/dml.sgml index 458aee788b7..4712a49071b 100644 --- a/doc/src/sgml/dml.sgml +++ b/doc/src/sgml/dml.sgml @@ -392,6 +392,19 @@ UPDATE products SET price = price * 1.10 the new values may be non-<literal>NULL</literal>. </para> + <para> + In an <command>INSERT</command> with an <literal>ON CONFLICT DO UPDATE</literal> + clause, it is also possible to return the values excluded, if there is a + conflict. For example: +<programlisting> +INSERT INTO products AS p SELECT * FROM new_products + ON CONFLICT (product_no) DO UPDATE SET name = excluded.name + RETURNING p.product_no, p.name, excluded.price; +</programlisting> + Excluded values will be <literal>NULL</literal> for rows that do not + conflict. + </para> + <para> If there are triggers (<xref linkend="triggers"/>) on the target table, the data available to <literal>RETURNING</literal> is the row as modified by diff --git a/doc/src/sgml/ref/insert.sgml b/doc/src/sgml/ref/insert.sgml index 3f139917790..2f4345e710c 100644 --- a/doc/src/sgml/ref/insert.sgml +++ b/doc/src/sgml/ref/insert.sgml @@ -343,6 +343,14 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac with an <literal>ON CONFLICT DO UPDATE</literal> clause, the old values may be non-<literal>NULL</literal>. </para> + + <para> + If the <command>INSERT</command> has an + <literal>ON CONFLICT DO UPDATE</literal> clause, a column name or + <literal>*</literal> may be qualified using + <literal>EXCLUDED</literal> to return the excluded values; if there + is no conflict, the excluded values will be <literal>NULL</literal>. + </para> </listitem> </varlistentry> diff --git a/src/backend/executor/execExpr.c b/src/backend/executor/execExpr.c index f1569879b52..d13c82bdd30 100644 --- a/src/backend/executor/execExpr.c +++ b/src/backend/executor/execExpr.c @@ -455,6 +455,7 @@ ExecBuildProjectionInfo(List *targetList, /* * Get the tuple from the relation being scanned, or the * old/new tuple slot, if old/new values were requested. + * Should not see EXCLUDED here (should be INNER_VAR). */ switch (variable->varreturningtype) { @@ -469,6 +470,10 @@ ExecBuildProjectionInfo(List *targetList, scratch.opcode = EEOP_ASSIGN_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -972,6 +977,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_SYSVAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -1007,6 +1016,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -2638,10 +2651,23 @@ ExecInitExprRec(Expr *node, ExprState *state, ReturningExpr *rexpr = (ReturningExpr *) node; int retstep; - /* Skip expression evaluation if OLD/NEW row doesn't exist */ + /* + * Skip expression evaluation if OLD/NEW/EXCLUDED row doesn't + * exist. + */ scratch.opcode = EEOP_RETURNINGEXPR; - scratch.d.returningexpr.nullflag = rexpr->retold ? - EEO_FLAG_OLD_IS_NULL : EEO_FLAG_NEW_IS_NULL; + switch (rexpr->retkind) + { + case RETURNING_OLD_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_OLD_IS_NULL; + break; + case RETURNING_NEW_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_NEW_IS_NULL; + break; + case RETURNING_EXCLUDED_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_INNER_IS_NULL; + break; + } scratch.d.returningexpr.jumpdone = -1; /* set below */ ExprEvalPushStep(state, &scratch); retstep = state->steps_len - 1; @@ -2649,14 +2675,15 @@ ExecInitExprRec(Expr *node, ExprState *state, /* Steps to evaluate expression to return */ ExecInitExprRec(rexpr->retexpr, state, resv, resnull); - /* Jump target used if OLD/NEW row doesn't exist */ + /* Jump target used if OLD/NEW/EXCLUDED row doesn't exist */ state->steps[retstep].d.returningexpr.jumpdone = state->steps_len; /* Update ExprState flags */ - if (rexpr->retold) + if (rexpr->retkind == RETURNING_OLD_EXPR) state->flags |= EEO_FLAG_HAS_OLD; - else + else if (rexpr->retkind == RETURNING_NEW_EXPR) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ break; } @@ -3013,6 +3040,10 @@ expr_setup_walker(Node *node, ExprSetupInfo *info) case VAR_RETURNING_NEW: info->last_new = Max(info->last_new, attnum); break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -3178,6 +3209,7 @@ ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable, ExprState *state) state->flags |= EEO_FLAG_HAS_OLD; else if (variable->varreturningtype == VAR_RETURNING_NEW) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ /* * If the input tuple came from a subquery, it might contain "resjunk" diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c index 8a72b5e70a4..2e8ecd8b30a 100644 --- a/src/backend/executor/execExprInterp.c +++ b/src/backend/executor/execExprInterp.c @@ -5340,7 +5340,21 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) switch (variable->varno) { case INNER_VAR: - /* get the tuple from the inner node */ + + /* + * Get the tuple from the inner node. + * + * In a RETURNING expression, this is used for EXCLUDED values in + * an INSERT ... ON CONFLICT DO UPDATE. If the non-conflicting + * branch is taken, the EXCLUDED row is NULL, and we return NULL + * rather than an all-NULL record. + */ + if (state->flags & EEO_FLAG_INNER_IS_NULL) + { + *op->resvalue = (Datum) 0; + *op->resnull = true; + return; + } slot = econtext->ecxt_innertuple; break; @@ -5385,6 +5399,11 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) } slot = econtext->ecxt_newtuple; break; + + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } diff --git a/src/backend/executor/execPartition.c b/src/backend/executor/execPartition.c index 514eae1037d..6adc07cbed3 100644 --- a/src/backend/executor/execPartition.c +++ b/src/backend/executor/execPartition.c @@ -642,12 +642,26 @@ ExecInitPartitionInfo(ModifyTableState *mtstate, EState *estate, /* * Convert Vars in it to contain this partition's attribute numbers. + * If we're doing an INSERT ... ON CONFLICT DO UPDATE, the RETURNING + * list might contain references to the EXCLUDED pseudo-relation + * (INNER_VAR), so we must map their attribute numbers too. */ if (part_attmap == NULL) part_attmap = build_attrmap_by_name(RelationGetDescr(partrel), RelationGetDescr(firstResultRel), false); + + if (node->onConflictAction == ONCONFLICT_UPDATE) + { + returningList = (List *) + map_variable_attnos((Node *) returningList, + INNER_VAR, 0, + part_attmap, + RelationGetForm(partrel)->reltype, + &found_whole_row); + /* We ignore the value of found_whole_row. */ + } returningList = (List *) map_variable_attnos((Node *) returningList, firstVarno, 0, diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c index 54da8e7995b..1e09ceb00da 100644 --- a/src/backend/executor/nodeModifyTable.c +++ b/src/backend/executor/nodeModifyTable.c @@ -277,6 +277,7 @@ ExecCheckPlanOutput(Relation resultRel, List *targetList) * oldSlot: slot holding old tuple deleted or updated * newSlot: slot holding new tuple inserted or updated * planSlot: slot holding tuple returned by top subplan node + * exclSlot: slot holding EXCLUDED tuple (for INSERT ... ON CONFLICT ...) * * Note: If oldSlot and newSlot are NULL, the FDW should have already provided * econtext's scan tuple and its old & new tuples are not needed (FDW direct- @@ -290,8 +291,11 @@ ExecProcessReturning(ModifyTableContext *context, CmdType cmdType, TupleTableSlot *oldSlot, TupleTableSlot *newSlot, - TupleTableSlot *planSlot) + TupleTableSlot *planSlot, + TupleTableSlot *exclSlot) { + ModifyTableState *mtstate = context->mtstate; + ModifyTable *node = (ModifyTable *) mtstate->ps.plan; EState *estate = context->estate; ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning; ExprContext *econtext = projectReturning->pi_exprContext; @@ -332,10 +336,18 @@ ExecProcessReturning(ModifyTableContext *context, else econtext->ecxt_newtuple = NULL; /* No references to NEW columns */ + /* Make EXCLUDED tuple available to ExecProject, if required */ + if (exclSlot) + econtext->ecxt_innertuple = exclSlot; + else if (cmdType == CMD_INSERT && node->onConflictAction == ONCONFLICT_UPDATE) + econtext->ecxt_innertuple = ExecGetAllNullSlot(estate, resultRelInfo); + else + econtext->ecxt_innertuple = NULL; + /* - * Tell ExecProject whether or not the OLD/NEW rows actually exist. This - * information is required to evaluate ReturningExpr nodes and also in - * ExecEvalSysVar() and ExecEvalWholeRowVar(). + * Tell ExecProject whether or not the OLD/NEW/EXCLUDED rows actually + * exist. This information is required to evaluate ReturningExpr nodes + * and also in ExecEvalSysVar() and ExecEvalWholeRowVar(). */ if (oldSlot == NULL) projectReturning->pi_state.flags |= EEO_FLAG_OLD_IS_NULL; @@ -347,6 +359,11 @@ ExecProcessReturning(ModifyTableContext *context, else projectReturning->pi_state.flags &= ~EEO_FLAG_NEW_IS_NULL; + if (exclSlot == NULL) + projectReturning->pi_state.flags |= EEO_FLAG_INNER_IS_NULL; + else + projectReturning->pi_state.flags &= ~EEO_FLAG_INNER_IS_NULL; + /* Compute the RETURNING expressions */ return ExecProject(projectReturning); } @@ -1330,7 +1347,7 @@ ExecInsert(ModifyTableContext *context, } result = ExecProcessReturning(context, resultRelInfo, CMD_INSERT, - oldSlot, slot, planSlot); + oldSlot, slot, planSlot, NULL); /* * For a cross-partition UPDATE, release the old tuple, first making @@ -1890,7 +1907,7 @@ ldelete: } rslot = ExecProcessReturning(context, resultRelInfo, CMD_DELETE, - slot, NULL, context->planSlot); + slot, NULL, context->planSlot, NULL); /* * Before releasing the target tuple again, make sure rslot has a @@ -2449,6 +2466,8 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, * planSlot is the output of the ModifyTable's subplan; we use it * to access values from other input tables (for RETURNING), * row-ID junk columns, etc. + * exclSlot contains the EXCLUDED tuple if this is the auxiliary + * UPDATE of an INSERT ... ON CONFLICT DO UPDATE. * * Returns RETURNING result if any, otherwise NULL. On exit, if tupleid * had identified the tuple to update, it will identify the tuple @@ -2458,7 +2477,7 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, static TupleTableSlot * ExecUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *oldSlot, - TupleTableSlot *slot, bool canSetTag) + TupleTableSlot *slot, TupleTableSlot *exclSlot, bool canSetTag) { EState *estate = context->estate; Relation resultRelationDesc = resultRelInfo->ri_RelationDesc; @@ -2691,7 +2710,8 @@ redo_act: /* Process RETURNING if present */ if (resultRelInfo->ri_projectReturning) return ExecProcessReturning(context, resultRelInfo, CMD_UPDATE, - oldSlot, slot, context->planSlot); + oldSlot, slot, context->planSlot, + exclSlot); return NULL; } @@ -2913,6 +2933,7 @@ ExecOnConflictUpdate(ModifyTableContext *context, *returning = ExecUpdate(context, resultRelInfo, conflictTid, NULL, existing, resultRelInfo->ri_onConflict->oc_ProjSlot, + excludedSlot, canSetTag); /* @@ -3537,7 +3558,8 @@ lmerge_matched: CMD_UPDATE, resultRelInfo->ri_oldTupleSlot, newslot, - context->planSlot); + context->planSlot, + NULL); break; case CMD_DELETE: @@ -3546,7 +3568,8 @@ lmerge_matched: CMD_DELETE, resultRelInfo->ri_oldTupleSlot, NULL, - context->planSlot); + context->planSlot, + NULL); break; case CMD_NOTHING: @@ -4310,12 +4333,16 @@ ExecModifyTable(PlanState *pstate) * provide it here. The individual old and new slots are not * needed, since direct-modify is disabled if the RETURNING list * refers to OLD/NEW values. + * + * Currently, foreign tables do not support UNIQUE constraints, + * and therefore they do not support INSERT ... ON CONFLICT, and + * so the EXCLUDED slot is also not needed. */ Assert((resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD) == 0 && (resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_NEW) == 0); slot = ExecProcessReturning(&context, resultRelInfo, operation, - NULL, NULL, context.planSlot); + NULL, NULL, context.planSlot, NULL); return slot; } @@ -4505,7 +4532,7 @@ ExecModifyTable(PlanState *pstate) /* Now apply the update. */ slot = ExecUpdate(&context, resultRelInfo, tupleid, oldtuple, - oldSlot, slot, node->canSetTag); + oldSlot, slot, NULL, node->canSetTag); if (tuplock) UnlockTuple(resultRelInfo->ri_RelationDesc, tupleid, InplaceUpdateTupleLock); diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index 6cc6966b060..017a685959b 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -4013,8 +4013,7 @@ subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual) * each component query gets its own copy of the qual. */ qual = ReplaceVarsFromTargetList(qual, rti, 0, rte, - subquery->targetList, - subquery->resultRelation, + subquery->targetList, 0, REPLACEVARS_REPORT_ERROR, 0, &subquery->hasSubLinks); diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c index 846e44186c3..6d45e6e0c40 100644 --- a/src/backend/optimizer/plan/setrefs.c +++ b/src/backend/optimizer/plan/setrefs.c @@ -206,6 +206,8 @@ static List *set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset); static List *set_windowagg_runcondition_references(PlannerInfo *root, List *runcondition, @@ -1061,10 +1063,14 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) { ModifyTable *splan = (ModifyTable *) plan; Plan *subplan = outerPlan(splan); + indexed_tlist *excl_itlist = NULL; Assert(splan->plan.targetlist == NIL); Assert(splan->plan.qual == NIL); + if (splan->onConflictSet) + excl_itlist = build_tlist_index(splan->exclRelTlist); + splan->withCheckOptionLists = fix_scan_list(root, splan->withCheckOptionLists, rtoffset, 1); @@ -1090,6 +1096,8 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) rlist, subplan, resultrel, + splan->exclRelRTI, + excl_itlist, rtoffset); newRL = lappend(newRL, rlist); } @@ -1117,23 +1125,19 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) */ if (splan->onConflictSet) { - indexed_tlist *itlist; - - itlist = build_tlist_index(splan->exclRelTlist); - splan->onConflictSet = fix_join_expr(root, splan->onConflictSet, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); splan->onConflictWhere = (Node *) fix_join_expr(root, (List *) splan->onConflictWhere, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); - pfree(itlist); + pfree(excl_itlist); splan->exclRelTlist = fix_scan_list(root, splan->exclRelTlist, rtoffset, 1); @@ -2798,12 +2802,12 @@ build_tlist_index(List *tlist) * build_tlist_index_other_vars --- build a restricted tlist index * * This is like build_tlist_index, but we only index tlist entries that - * are Vars belonging to some rel other than the one specified. We will set + * are Vars belonging to some rel other than the ones specified. We will set * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars * (so nothing other than Vars and PlaceHolderVars can be matched). */ static indexed_tlist * -build_tlist_index_other_vars(List *tlist, int ignore_rel) +build_tlist_index_other_vars(List *tlist, int ignore_rel1, int ignore_rel2) { indexed_tlist *itlist; tlist_vinfo *vinfo; @@ -2828,7 +2832,7 @@ build_tlist_index_other_vars(List *tlist, int ignore_rel) { Var *var = (Var *) tle->expr; - if (var->varno != ignore_rel) + if (var->varno != ignore_rel1 && var->varno != ignore_rel2) { vinfo->varno = var->varno; vinfo->varattno = var->varattno; @@ -3067,10 +3071,14 @@ search_indexed_tlist_for_sortgroupref(Expr *node, * acceptable_rel should be zero so that any failure to match a Var will be * reported as an error. * 2) RETURNING clauses, which may contain both Vars of the target relation - * and Vars of other relations. In this case we want to replace the - * other-relation Vars by OUTER_VAR references, while leaving target Vars - * alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the - * target relation should be passed. + * and Vars of other relations, including the EXCLUDED pseudo-relation in + * an INSERT ... ON CONFLICT DO UPDATE command. In this case, we want to + * replace references to EXCLUDED with INNER_VAR references, and + * other-relation Vars with OUTER_VAR references, while leaving target Vars + * alone. Thus inner_itlist is to be EXCLUDED elements, if this is an + * INSERT with an ON CONFLICT DO UPDATE clause, outer_itlist is any other + * non-target relation elements, and acceptable_rel = the ID of the target + * relation. * 3) ON CONFLICT UPDATE SET/WHERE clauses. Here references to EXCLUDED are * to be replaced with INNER_VAR references, while leaving target Vars (the * to-be-updated relation) alone. Correspondingly inner_itlist is to be @@ -3131,15 +3139,16 @@ fix_join_expr_mutator(Node *node, fix_join_expr_context *context) /* * Verify that Vars with non-default varreturningtype only appear in - * the RETURNING list, and refer to the target relation. + * the RETURNING list, and that OLD/NEW Vars refer to the target + * relation. */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { - if (context->inner_itlist != NULL || - context->outer_itlist == NULL || + if (context->outer_itlist == NULL || context->acceptable_rel == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); - if (var->varno != context->acceptable_rel) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list"); + if (var->varreturningtype != VAR_RETURNING_EXCLUDED && + var->varno != context->acceptable_rel) elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new", var->varno, context->acceptable_rel); } @@ -3369,11 +3378,14 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * * If the query involves more than just the result table, we have to * adjust any Vars that refer to other tables to reference junk tlist - * entries in the top subplan's targetlist. Vars referencing the result - * table should be left alone, however (the executor will evaluate them - * using the actual heap tuple, after firing triggers if any). In the - * adjusted RETURNING list, result-table Vars will have their original - * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR. + * entries in the top subplan's targetlist. Vars referencing the EXCLUDED + * pseudo-relation of an INSERT ... ON CONFLICT DO UPDATE command should be + * adjusted to reference INNER_VAR, and Vars referencing the result table + * should be left alone (the executor will evaluate them using the actual heap + * tuple, after firing triggers if any). In the adjusted RETURNING list, + * result-table Vars will have their original varno (plus rtoffset), but Vars + * for the EXCLUDED pseudo-relation and other rels will have varno INNER_VAR + * and OUTER_VAR espectively. * * We also must perform opcode lookup and add regclass OIDs to * root->glob->relationOids. @@ -3382,6 +3394,8 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * 'topplan': the top subplan node that will be just below the ModifyTable * node (note it's not yet passed through set_plan_refs) * 'resultRelation': RT index of the associated result relation + * 'exclRelRTI': RT index of EXCLUDED pseudo-relation + * 'excl_itlist': EXCLUDED pseudo-relation elements (or NULL) * 'rtoffset': how much to increment varnos by * * Note: the given 'root' is for the parent query level, not the 'topplan'. @@ -3396,6 +3410,8 @@ set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset) { indexed_tlist *itlist; @@ -3403,9 +3419,11 @@ set_returning_clause_references(PlannerInfo *root, /* * We can perform the desired Var fixup by abusing the fix_join_expr * machinery that formerly handled inner indexscan fixup. We search the - * top plan's targetlist for Vars of non-result relations, and use - * fix_join_expr to convert RETURNING Vars into references to those tlist - * entries, while leaving result-rel Vars as-is. + * top plan's targetlist for Vars of non-result relations (other than + * EXCLUDED), and use fix_join_expr to convert RETURNING Vars into + * references to those tlist entries, and convert RETURNING EXCLUDED Vars + * into references to excl_itlist entries, while leaving result-rel Vars + * as-is. * * PlaceHolderVars will also be sought in the targetlist, but no * more-complex expressions will be. Note that it is not possible for a @@ -3414,12 +3432,13 @@ set_returning_clause_references(PlannerInfo *root, * prepared to pick apart the PlaceHolderVar and evaluate its contained * expression instead. */ - itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation); + itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation, + exclRelRTI); rlist = fix_join_expr(root, rlist, itlist, - NULL, + excl_itlist, resultRelation, rtoffset, NRM_EQUAL, diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index 87dc6f56b57..00de20b0d49 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -71,8 +71,7 @@ typedef struct pullup_replace_vars_context PlannerInfo *root; List *targetlist; /* tlist of subquery being pulled up */ RangeTblEntry *target_rte; /* RTE of subquery */ - int result_relation; /* the index of the result relation in the - * rewritten query */ + int new_target_varno; /* see ReplaceVarFromTargetList() */ Relids relids; /* relids within subquery, as numbered after * pullup (set only if target_rte->lateral) */ nullingrel_info *nullinfo; /* per-RTE nullingrel info (set only if @@ -1034,11 +1033,19 @@ expand_virtual_generated_columns(PlannerInfo *root) * to insert into the query, except that we may need to wrap them * in PlaceHolderVars. Set up required context data for * pullup_replace_vars. + * + * new_target_varno should equal rt_index if this is the result + * relation or the EXCLUDED pseudo-relation. Otherwise, it should + * be 0. See comments in ReplaceVarFromTargetList(). */ rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = parse->resultRelation; + if (rt_index == parse->resultRelation || + (parse->onConflict && rt_index == parse->onConflict->exclRelIndex)) + rvcontext.new_target_varno = rt_index; + else + rvcontext.new_target_varno = 0; /* won't need these values */ rvcontext.relids = NULL; rvcontext.nullinfo = NULL; @@ -1436,7 +1443,7 @@ pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte, rvcontext.root = root; rvcontext.targetlist = subquery->targetList; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; if (rte->lateral) { rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree, @@ -1987,7 +1994,7 @@ pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte) rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; rvcontext.relids = NULL; /* can't be any lateral references here */ rvcontext.nullinfo = NULL; rvcontext.outer_hasSubLinks = &parse->hasSubLinks; @@ -2147,7 +2154,7 @@ pull_up_constant_function(PlannerInfo *root, Node *jtnode, NULL, /* resname */ false)); /* resjunk */ rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; /* * Since this function was reduced to a Const, it doesn't contain any @@ -2681,7 +2688,7 @@ pullup_replace_vars_callback(Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, REPLACEVARS_REPORT_ERROR, 0); diff --git a/src/backend/optimizer/prep/preptlist.c b/src/backend/optimizer/prep/preptlist.c index ffc9d6c3f30..098d8f8498a 100644 --- a/src/backend/optimizer/prep/preptlist.c +++ b/src/backend/optimizer/prep/preptlist.c @@ -291,7 +291,10 @@ preprocess_targetlist(PlannerInfo *root) * used in RETURNING that belong to other relations. We need to do this * to make these Vars available for the RETURNING calculation. Vars that * belong to the result rel don't need to be added, because they will be - * made to refer to the actual heap tuple. + * made to refer to the actual heap tuple. Vars that refer to the + * EXCLUDED pseudo-relation of an INSERT ... ON CONFLICT DO UPDATE command + * are also not needed, because they are handled specially in the + * executor. */ if (parse->returningList && list_length(parse->rtable) > 1) { @@ -308,7 +311,9 @@ preprocess_targetlist(PlannerInfo *root) TargetEntry *tle; if (IsA(var, Var) && - var->varno == result_relation) + (var->varno == result_relation || + (parse->onConflict && + var->varno == parse->onConflict->exclRelIndex))) continue; /* don't need it */ if (tlist_member((Expr *) var, tlist)) diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 26a3e050086..dc50f0a5c84 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -3407,7 +3407,7 @@ eval_const_expressions_mutator(Node *node, fselect->resulttypmod, fselect->resultcollid, ((Var *) arg)->varlevelsup); - /* New Var has same OLD/NEW returning as old one */ + /* New Var has same returningtype as old one */ newvar->varreturningtype = ((Var *) arg)->varreturningtype; /* New Var is nullable by same rels as the old one */ newvar->varnullingrels = ((Var *) arg)->varnullingrels; diff --git a/src/backend/optimizer/util/var.c b/src/backend/optimizer/util/var.c index 8065237a189..c2642c88e92 100644 --- a/src/backend/optimizer/util/var.c +++ b/src/backend/optimizer/util/var.c @@ -501,8 +501,8 @@ contain_vars_of_level_walker(Node *node, int *sublevels_up) * * Returns true if any found. * - * Any ReturningExprs are also detected --- if an OLD/NEW Var was rewritten, - * we still regard this as a clause that returns OLD/NEW values. + * Any ReturningExprs are also checked --- if an OLD/NEW Var was rewritten, we + * still regard this as a clause that returns OLD/NEW values. * * Does not examine subqueries, therefore must only be used after reduction * of sublinks to subplans! @@ -521,13 +521,16 @@ contain_vars_returning_old_or_new_walker(Node *node, void *context) if (IsA(node, Var)) { if (((Var *) node)->varlevelsup == 0 && - ((Var *) node)->varreturningtype != VAR_RETURNING_DEFAULT) + (((Var *) node)->varreturningtype == VAR_RETURNING_OLD || + ((Var *) node)->varreturningtype == VAR_RETURNING_NEW)) return true; /* abort the tree traversal and return true */ return false; } if (IsA(node, ReturningExpr)) { - if (((ReturningExpr *) node)->retlevelsup == 0) + if (((ReturningExpr *) node)->retlevelsup == 0 && + (((ReturningExpr *) node)->retkind == RETURNING_OLD_EXPR || + ((ReturningExpr *) node)->retkind == RETURNING_NEW_EXPR)) return true; /* abort the tree traversal and return true */ return false; } diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index 34f7c17f576..bf7ee465a14 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -1234,12 +1234,21 @@ transformOnConflictClause(ParseState *pstate, EXPR_KIND_WHERE, "WHERE"); /* - * Remove the EXCLUDED pseudo relation from the query namespace, since - * it's not supposed to be available in RETURNING. (Maybe someday we - * could allow that, and drop this step.) + * Leave the EXCLUDED pseudo relation in the query namespace so that + * it is available in RETURNING expressions, but change it to be a + * table-only item so that its columns are only accessible using + * qualified names. This ensures that columns from the target + * relation can be accessed using unqualified names without ambiguity. + * + * Also, set its returning_type so that any RETURNING list Vars + * referencing it are marked correctly. */ Assert((ParseNamespaceItem *) llast(pstate->p_namespace) == exclNSItem); - pstate->p_namespace = list_delete_last(pstate->p_namespace); + exclNSItem->p_cols_visible = false; + + exclNSItem->p_returning_type = VAR_RETURNING_EXCLUDED; + for (int i = 0; i < list_length(exclNSItem->p_names->colnames); i++) + exclNSItem->p_nscolumns[i].p_varreturningtype = VAR_RETURNING_EXCLUDED; } /* Finally, build ON CONFLICT DO [NOTHING | UPDATE] expression */ diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c index d66276801c6..e551c0bd7a1 100644 --- a/src/backend/parser/parse_expr.c +++ b/src/backend/parser/parse_expr.c @@ -2653,7 +2653,7 @@ transformWholeRowRef(ParseState *pstate, ParseNamespaceItem *nsitem, result = makeWholeRowVar(nsitem->p_rte, nsitem->p_rtindex, sublevels_up, true); - /* mark Var for RETURNING OLD/NEW, as necessary */ + /* mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ result->varreturningtype = nsitem->p_returning_type; /* location is not filled in by makeWholeRowVar */ diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c index 04ecf64b1fc..1651c52eb87 100644 --- a/src/backend/parser/parse_relation.c +++ b/src/backend/parser/parse_relation.c @@ -258,7 +258,7 @@ scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location) /* If not inside LATERAL, ignore lateral-only items */ if (nsitem->p_lateral_only && !pstate->p_lateral_active) continue; - /* Ignore OLD/NEW namespace items that can appear in RETURNING */ + /* Ignore OLD/NEW/EXCLUDED namespace items in RETURNING */ if (nsitem->p_returning_type != VAR_RETURNING_DEFAULT) continue; @@ -775,7 +775,7 @@ scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem, } var->location = location; - /* Mark Var for RETURNING OLD/NEW, as necessary */ + /* Mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ var->varreturningtype = nsitem->p_returning_type; /* Mark Var if it's nulled by any outer joins */ diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c index 2ef0e7fbf3a..98a02167f23 100644 --- a/src/backend/rewrite/rewriteHandler.c +++ b/src/backend/rewrite/rewriteHandler.c @@ -97,7 +97,7 @@ static List *matchLocks(CmdType event, Relation relation, static Query *fireRIRrules(Query *parsetree, List *activeRIRs); static Bitmapset *adjust_view_column_set(Bitmapset *cols, List *targetlist); static Node *expand_generated_columns_internal(Node *node, Relation rel, int rt_index, - RangeTblEntry *rte, int result_relation); + RangeTblEntry *rte); /* @@ -643,7 +643,7 @@ rewriteRuleAction(Query *parsetree, 0, rt_fetch(new_varno, sub_action->rtable), parsetree->targetList, - sub_action->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -2345,7 +2345,7 @@ CopyAndAddInvertedQual(Query *parsetree, rt_fetch(rt_index, parsetree->rtable), parsetree->targetList, - parsetree->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -3704,12 +3704,12 @@ rewriteTargetView(Query *parsetree, Relation view) BuildOnConflictExcludedTargetlist(base_rel, new_exclRelIndex); /* - * Update all Vars in the ON CONFLICT clause that refer to the old - * EXCLUDED pseudo-relation. We want to use the column mappings - * defined in the view targetlist, but we need the outputs to refer to - * the new EXCLUDED pseudo-relation rather than the new target RTE. - * Also notice that "EXCLUDED.*" will be expanded using the view's - * rowtype, which seems correct. + * Update all Vars in the ON CONFLICT clause and RETURNING list that + * refer to the old EXCLUDED pseudo-relation. We want to use the + * column mappings defined in the view targetlist, but we need the + * outputs to refer to the new EXCLUDED pseudo-relation rather than + * the new target RTE. Also notice that "EXCLUDED.*" will be expanded + * using the view's rowtype, which seems correct. */ tmp_tlist = copyObject(view_targetlist); @@ -3722,7 +3722,18 @@ rewriteTargetView(Query *parsetree, Relation view) 0, view_rte, tmp_tlist, - new_rt_index, + 0, + REPLACEVARS_REPORT_ERROR, + 0, + &parsetree->hasSubLinks); + + parsetree->returningList = (List *) + ReplaceVarsFromTargetList((Node *) parsetree->returningList, + old_exclRelIndex, + 0, + view_rte, + tmp_tlist, + new_exclRelIndex, REPLACEVARS_REPORT_ERROR, 0, &parsetree->hasSubLinks); @@ -4420,13 +4431,11 @@ RewriteQuery(Query *parsetree, List *rewrite_events, int orig_rt_length) * virtual generated column expressions from rel, if there are any. * * The caller must also provide rte, the RTE describing the target relation, - * in order to handle any whole-row Vars referencing the target, and - * result_relation, the index of the result relation, if this is part of an - * INSERT/UPDATE/DELETE/MERGE query. + * in order to handle any whole-row Vars referencing the target. */ static Node * expand_generated_columns_internal(Node *node, Relation rel, int rt_index, - RangeTblEntry *rte, int result_relation) + RangeTblEntry *rte) { TupleDesc tupdesc; @@ -4454,8 +4463,7 @@ expand_generated_columns_internal(Node *node, Relation rel, int rt_index, Assert(list_length(tlist) > 0); - node = ReplaceVarsFromTargetList(node, rt_index, 0, rte, tlist, - result_relation, + node = ReplaceVarsFromTargetList(node, rt_index, 0, rte, tlist, 0, REPLACEVARS_CHANGE_VARNO, rt_index, NULL); } @@ -4484,7 +4492,7 @@ expand_generated_columns_in_expr(Node *node, Relation rel, int rt_index) rte->rtekind = RTE_RELATION; rte->relid = RelationGetRelid(rel); - node = expand_generated_columns_internal(node, rel, rt_index, rte, 0); + node = expand_generated_columns_internal(node, rel, rt_index, rte); } return node; diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index cd786aa4112..e5f85116f79 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -921,7 +921,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, /* * SetVarReturningType - adjust Var nodes for a specified varreturningtype. * - * Find all Var nodes referring to the specified result relation in the given + * Find all Var nodes referring to the specified relation in the given * expression and set their varreturningtype to the specified value. * * NOTE: although this has the form of a walker, we cheat and modify the @@ -931,7 +931,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, typedef struct { - int result_relation; + int target_varno; int sublevels_up; VarReturningType returning_type; } SetVarReturningType_context; @@ -945,7 +945,7 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) { Var *var = (Var *) node; - if (var->varno == context->result_relation && + if (var->varno == context->target_varno && var->varlevelsup == context->sublevels_up) var->varreturningtype = context->returning_type; @@ -967,12 +967,12 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) } static void -SetVarReturningType(Node *node, int result_relation, int sublevels_up, +SetVarReturningType(Node *node, int target_varno, int sublevels_up, VarReturningType returning_type) { SetVarReturningType_context context; - context.result_relation = result_relation; + context.target_varno = target_varno; context.sublevels_up = sublevels_up; context.returning_type = returning_type; @@ -1744,14 +1744,29 @@ map_variable_attnos(Node *node, * relation. This is needed to handle whole-row Vars referencing the target. * We expand such Vars into RowExpr constructs. * - * In addition, for INSERT/UPDATE/DELETE/MERGE queries, the caller must - * provide result_relation, the index of the result relation in the rewritten - * query. This is needed to handle OLD/NEW RETURNING list Vars referencing - * target_varno. When such Vars are expanded, their varreturningtype is - * copied onto any replacement Vars referencing result_relation. In addition, - * if the replacement expression from the targetlist is not simply a Var - * referencing result_relation, it is wrapped in a ReturningExpr node (causing - * the executor to return NULL if the OLD/NEW row doesn't exist). + * In addition, the caller should provide new_target_varno, which is needed to + * handle any OLD/NEW/EXCLUDED RETURNING list Vars (Vars with non-default + * varreturningtype) referencing target_varno. When such Vars are expanded, + * their varreturningtype is copied onto any Vars that reference + * new_target_varno in the replacement expression from the targetlist. In + * addition, if the replacement expression is not simply a Var referencing + * new_target_varno, it is wrapped in a ReturningExpr node (causing the + * executor to return NULL if the OLD/NEW/EXCLUDED row doesn't exist). The + * caller should set new_target_varno as follows: + * + * If the input node contains Vars from the RETURNING list of a query, and + * target_varno is the resultRelation of that query, then new_target_varno + * should be the (possibly new) resultRelation of the rewritten query. + * + * If the input node contains Vars from the RETURNING list of an INSERT ... + * ON CONFLICT DO UPDATE query, and target_varno is the index of the + * EXCLUDED pseudo-relation, then new_target_varno should be the (possibly + * new) index of the EXCLUDED pseudo-relation in the rewritten query. + * + * Otherwise, new_target_varno should be set to 0 in order to detect any + * Vars with non-default varreturningtype outside the RETURNING list, or + * referencing a relation other than the result relation or the EXCLUDED + * pseudo-relation. * * Note that ReplaceVarFromTargetList always generates the replacement * expression with varlevelsup = 0. The caller is responsible for adjusting @@ -1765,7 +1780,7 @@ typedef struct { RangeTblEntry *target_rte; List *targetlist; - int result_relation; + int new_target_varno; ReplaceVarsNoMatchOption nomatch_option; int nomatch_varno; } ReplaceVarsFromTargetList_context; @@ -1780,7 +1795,7 @@ ReplaceVarsFromTargetList_callback(Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, rcon->nomatch_option, rcon->nomatch_varno); @@ -1795,7 +1810,7 @@ Node * ReplaceVarFromTargetList(Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno) { @@ -1844,7 +1859,7 @@ ReplaceVarFromTargetList(Var *var, field = ReplaceVarFromTargetList((Var *) field, target_rte, targetlist, - result_relation, + new_target_varno, nomatch_option, nomatch_varno); rowexpr->args = lappend(rowexpr->args, field); @@ -1856,7 +1871,7 @@ ReplaceVarFromTargetList(Var *var, ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = (Expr *) rowexpr; return (Node *) rexpr; @@ -1925,28 +1940,28 @@ ReplaceVarFromTargetList(Var *var, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("NEW variables in ON UPDATE rules cannot reference columns that are part of a multiple assignment in the subject UPDATE command"))); - /* Handle any OLD/NEW RETURNING list Vars */ + /* Handle any OLD/NEW/EXCLUDED RETURNING list Vars */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { /* * Copy varreturningtype onto any Vars in the tlist item that - * refer to result_relation (which had better be non-zero). + * refer to new_target_varno (which had better be non-zero). */ - if (result_relation == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); + if (new_target_varno == 0) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list, or referencing a relation other than the result relation or the EXCLUDED pseudo-relation"); - SetVarReturningType((Node *) newnode, result_relation, + SetVarReturningType((Node *) newnode, new_target_varno, 0, var->varreturningtype); /* Wrap it in a ReturningExpr, if needed, per comments above */ if (!IsA(newnode, Var) || - ((Var *) newnode)->varno != result_relation || + ((Var *) newnode)->varno != new_target_varno || ((Var *) newnode)->varlevelsup != 0) { ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = newnode; newnode = (Expr *) rexpr; @@ -1962,7 +1977,7 @@ ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks) @@ -1971,7 +1986,7 @@ ReplaceVarsFromTargetList(Node *node, context.target_rte = target_rte; context.targetlist = targetlist; - context.result_relation = result_relation; + context.new_target_varno = new_target_varno; context.nomatch_option = nomatch_option; context.nomatch_varno = nomatch_varno; diff --git a/src/include/executor/execExpr.h b/src/include/executor/execExpr.h index 75366203706..1ce4d98afce 100644 --- a/src/include/executor/execExpr.h +++ b/src/include/executor/execExpr.h @@ -26,9 +26,9 @@ struct JsonConstructorExprState; /* Bits in ExprState->flags (see also execnodes.h for public flag bits): */ /* expression's interpreter has been initialized */ -#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 5) +#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 6) /* jump-threading is in use */ -#define EEO_FLAG_DIRECT_THREADED (1 << 6) +#define EEO_FLAG_DIRECT_THREADED (1 << 7) /* Typical API for out-of-line evaluation subroutines */ typedef void (*ExecEvalSubroutine) (ExprState *state, @@ -338,7 +338,8 @@ typedef struct ExprEvalStep /* but it's just the normal (negative) attr number for SYSVAR */ int attnum; Oid vartype; /* type OID of variable */ - VarReturningType varreturningtype; /* return old/new/default */ + /* if not default, return old/new/excluded value */ + VarReturningType varreturningtype; } var; /* for EEOP_WHOLEROW */ diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index 2492282213f..cac584a88d4 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -82,6 +82,8 @@ typedef Datum (*ExprStateEvalFunc) (struct ExprState *expression, #define EEO_FLAG_OLD_IS_NULL (1 << 3) /* NEW table row is NULL in RETURNING list */ #define EEO_FLAG_NEW_IS_NULL (1 << 4) +/* INNER (EXCLUDED) table row is NULL in RETURNING list */ +#define EEO_FLAG_INNER_IS_NULL (1 << 5) typedef struct ExprState { diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h index 6dfca3cb35b..a867814cd8f 100644 --- a/src/include/nodes/primnodes.h +++ b/src/include/nodes/primnodes.h @@ -227,7 +227,9 @@ typedef struct Expr * varreturningtype is used for Vars that refer to the target relation in the * RETURNING list of data-modifying queries. The default behavior is to * return old values for DELETE and new values for INSERT and UPDATE, but it - * is also possible to explicitly request old or new values. + * is also possible to explicitly request old or new values. For INSERT ... + * ON CONFLICT DO UPDATE, varreturningtype is also used for Vars in the + * RETURNING list that refer to the EXCLUDED pseudo-relation. * * In the parser, varnosyn and varattnosyn are either identical to * varno/varattno, or they specify the column's position in an aliased JOIN @@ -256,6 +258,7 @@ typedef enum VarReturningType VAR_RETURNING_DEFAULT, /* return OLD for DELETE, else return NEW */ VAR_RETURNING_OLD, /* return OLD for DELETE/UPDATE, else NULL */ VAR_RETURNING_NEW, /* return NEW for INSERT/UPDATE, else NULL */ + VAR_RETURNING_EXCLUDED, /* return EXCLUDED on conflict, else NULL */ } VarReturningType; typedef struct Var @@ -2140,14 +2143,15 @@ typedef struct InferenceElem } InferenceElem; /* - * ReturningExpr - return OLD/NEW.(expression) in RETURNING list + * ReturningExpr - return OLD/NEW/EXCLUDED.(expression) in RETURNING list * * This is used when updating an auto-updatable view and returning a view * column that is not simply a Var referring to the base relation. In such - * cases, OLD/NEW.viewcol can expand to an arbitrary expression, but the - * result is required to be NULL if the OLD/NEW row doesn't exist. To handle - * this, the rewriter wraps the expanded expression in a ReturningExpr, which - * is equivalent to "CASE WHEN (OLD/NEW row exists) THEN (expr) ELSE NULL". + * cases, OLD/NEW/EXCLUDED.viewcol can expand to an arbitrary expression, but + * the result is required to be NULL if the OLD/NEW/EXCLUDED row doesn't + * exist. To handle this, the rewriter wraps the expanded expression in a + * ReturningExpr, which is equivalent to "CASE WHEN (OLD/NEW/EXCLUDED row + * exists) THEN (expr) ELSE NULL". * * A similar situation can arise when rewriting the RETURNING clause of a * rule, which may also contain arbitrary expressions. @@ -2155,11 +2159,19 @@ typedef struct InferenceElem * ReturningExpr nodes never appear in a parsed Query --- they are only ever * inserted by the rewriter and the planner. */ +typedef enum ReturningExprKind +{ + /* values here match non-default VarReturningType values */ + RETURNING_OLD_EXPR = VAR_RETURNING_OLD, + RETURNING_NEW_EXPR = VAR_RETURNING_NEW, + RETURNING_EXCLUDED_EXPR = VAR_RETURNING_EXCLUDED, +} ReturningExprKind; + typedef struct ReturningExpr { Expr xpr; int retlevelsup; /* > 0 if it belongs to outer query */ - bool retold; /* true for OLD, false for NEW */ + ReturningExprKind retkind; /* return OLD/NEW/EXCLUDED expression */ Expr *retexpr; /* expression to be returned */ } ReturningExpr; diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h index f7d07c84542..1f0c21543b2 100644 --- a/src/include/parser/parse_node.h +++ b/src/include/parser/parse_node.h @@ -280,7 +280,8 @@ struct ParseState * forbid LATERAL references to an UPDATE/DELETE target table. * * While processing the RETURNING clause, special namespace items are added to - * refer to the OLD and NEW state of the result relation. These namespace + * refer to the OLD and NEW state of the result relation, and the EXCLUDED + * pseudo-relation for an INSERT ... ON CONFLICT DO UPDATE. These namespace * items have p_returning_type set appropriately, for use when creating Vars. * For convenience, this information is duplicated on each namespace column. * @@ -301,7 +302,7 @@ struct ParseNamespaceItem bool p_cols_visible; /* Column names visible as unqualified refs? */ bool p_lateral_only; /* Is only visible to LATERAL expressions? */ bool p_lateral_ok; /* If so, does join type allow use? */ - VarReturningType p_returning_type; /* Is OLD/NEW for use in RETURNING? */ + VarReturningType p_returning_type; /* for RETURNING OLD/NEW/EXCLUDED */ }; /* @@ -332,7 +333,7 @@ struct ParseNamespaceColumn Oid p_vartype; /* pg_type OID */ int32 p_vartypmod; /* type modifier value */ Oid p_varcollid; /* OID of collation, or InvalidOid */ - VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW */ + VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW/EXCLUDED */ Index p_varnosyn; /* rangetable index of syntactic referent */ AttrNumber p_varattnosyn; /* attribute number of syntactic referent */ bool p_dontexpand; /* not included in star expansion */ diff --git a/src/include/rewrite/rewriteManip.h b/src/include/rewrite/rewriteManip.h index 7c018f2a4e3..81a1493ad31 100644 --- a/src/include/rewrite/rewriteManip.h +++ b/src/include/rewrite/rewriteManip.h @@ -107,14 +107,14 @@ extern Node *map_variable_attnos(Node *node, extern Node *ReplaceVarFromTargetList(Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno); extern Node *ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks); diff --git a/src/test/regress/expected/arrays.out b/src/test/regress/expected/arrays.out index b815473f414..5a5a06e6a06 100644 --- a/src/test/regress/expected/arrays.out +++ b/src/test/regress/expected/arrays.out @@ -1398,20 +1398,30 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+--------- - 1 | {3,2,5} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+---------+------------- + 1 | {3,2,5} | {3,4,5} (1 row) insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+------------ - 1 | {6,7,NULL} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+------------+------------- + 1 | {6,7,NULL} | {6,7} +(1 row) + +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+----------------+------------- + 1 | {NULL,10,NULL} | [2:2]={10} (1 row) -- note: if above selects don't produce the expected tuple order, diff --git a/src/test/regress/expected/generated_stored.out b/src/test/regress/expected/generated_stored.out index 16de30ab191..0a41db57f9f 100644 --- a/src/test/regress/expected/generated_stored.out +++ b/src/test/regress/expected/generated_stored.out @@ -114,32 +114,44 @@ INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error ERROR: cannot insert a non-DEFAULT value into column "b" DETAIL: Column "b" is a generated column. INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + a | b | a | b | a | b +---+---+-----+-----+---+--- + 4 | 8 | 104 | 208 | 4 | 8 + | | 5 | 10 | | +(2 rows) + SELECT * FROM gtest1 ORDER BY a; - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference - gtest1 --------- + gtest1 +----------- (1,2) (2,4) (3,6) - (4,8) -(4 rows) + (5,10) + (104,208) +(5 rows) SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) DELETE FROM gtest1 WHERE a >= 3; UPDATE gtest1 SET b = DEFAULT WHERE a = 1; diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index df704b5166f..90fe70a9709 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -114,32 +114,44 @@ INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error ERROR: cannot insert a non-DEFAULT value into column "b" DETAIL: Column "b" is a generated column. INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + a | b | a | b | a | b +---+---+-----+-----+---+--- + 4 | 8 | 104 | 208 | 4 | 8 + | | 5 | 10 | | +(2 rows) + SELECT * FROM gtest1 ORDER BY a; - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference - gtest1 --------- + gtest1 +----------- (1,2) (2,4) (3,6) - (4,8) -(4 rows) + (5,10) + (104,208) +(5 rows) SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) DELETE FROM gtest1 WHERE a >= 3; UPDATE gtest1 SET b = DEFAULT WHERE a = 1; diff --git a/src/test/regress/expected/inherit.out b/src/test/regress/expected/inherit.out index 78dead65325..733ec9522ca 100644 --- a/src/test/regress/expected/inherit.out +++ b/src/test/regress/expected/inherit.out @@ -2123,7 +2123,14 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; + old | new | excluded +--------+---------+---------- + (3,3-) | (3,3-+) | (3,) + (7,7-) | (7,7-+) | (7,) +(2 rows) + select * from inhpar order by f1; -- tuple order might be unstable here f1 | f2 ----+----- diff --git a/src/test/regress/expected/insert_conflict.out b/src/test/regress/expected/insert_conflict.out index fdd0f6c8f25..58017bb0eb6 100644 --- a/src/test/regress/expected/insert_conflict.out +++ b/src/test/regress/expected/insert_conflict.out @@ -249,13 +249,13 @@ insert into insertconflicttest values (2, 'Orange') on conflict (key, key, key) insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -ERROR: invalid reference to FROM-clause entry for table "excluded" -LINE 1: ...y) do update set fruit = excluded.fruit RETURNING excluded.f... - ^ -DETAIL: There is an entry for table "excluded", but it cannot be referenced from this part of the query. + fruit +------- + Apple +(1 row) + -- Only suggest <table>.* column when inference element misspelled: insert into insertconflicttest values (1, 'Apple') on conflict (keyy) do update set fruit = excluded.fruit; ERROR: column "keyy" does not exist @@ -408,33 +408,33 @@ drop index partial_key_index; create unique index plain on insertconflicttest(key); -- Succeeds, updates existing row: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; - key | fruit ------+----------- - 23 | Jackfruit + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-----------+----------+---------- + 23 | Jackfruit | f | t (1 row) -- No update this time, though: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; - key | fruit ------+------- + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-------+----------+---------- (0 rows) -- Predicate changed to require match rather than non-match, so updates once more: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* = excluded.* returning *; - key | fruit ------+----------- - 23 | Jackfruit + where i.* = excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-----------+----------+---------- + 23 | Jackfruit | t | t (1 row) -- Assign: insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text - returning *; - key | fruit ------+-------------- - 23 | (23,Avocado) + returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+--------------+----------+---------- + 23 | (23,Avocado) | f | f (1 row) -- deparse whole row var in WHERE and SET clauses: @@ -472,6 +472,10 @@ insert into syscolconflicttest values (1) on conflict (key) do update set data = ERROR: column excluded.ctid does not exist LINE 1: ...values (1) on conflict (key) do update set data = excluded.c... ^ +insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.data returning excluded.ctid; +ERROR: column excluded.ctid does not exist +LINE 1: ...key) do update set data = excluded.data returning excluded.c... + ^ drop table syscolconflicttest; -- -- Previous tests all managed to not test any expressions requiring @@ -546,7 +550,13 @@ select * from capitals; -- Succeeds: insert into cities values ('Las Vegas', 2.583E+5, 2174) on conflict do nothing; -insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; + name | population | altitude | state | name | population | altitude | state | name | population | altitude | state +------------+------------+----------+-------+------------+------------+----------+-------+------------+------------+----------+------- + Sacramento | 369400 | 30 | CA | Sacramento | 466400000 | 30 | CA | Sacramento | 466400000 | 30 | CA +(1 row) + -- Wrong "Sacramento", so do nothing: insert into capitals values ('Sacramento', 50, 2267, 'NE') on conflict (name) do nothing; select * from capitals; @@ -556,7 +566,13 @@ select * from capitals; Sacramento | 466400000 | 30 | CA (2 rows) -insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; + name | population | altitude | name | population | altitude | name | population | altitude +-----------+------------+----------+-----------+------------+----------+-----------+------------+---------- + Las Vegas | 258300 | 2174 | Las Vegas | 583000 | 2001 | Las Vegas | 583000 | 2001 +(1 row) + select tableoid::regclass, * from cities; tableoid | name | population | altitude ----------+---------------+------------+---------- @@ -567,7 +583,13 @@ select tableoid::regclass, * from cities; capitals | Sacramento | 466400000 | 30 (5 rows) -insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; + name | population | altitude | state | name | population | altitude | state | name | population | altitude | state +------+------------+----------+-------+-----------+------------+----------+-------+------+------------+----------+------- + | | | | Las Vegas | 583000 | 2222 | NV | | | | +(1 row) + -- Capitals will contain new capital, Las Vegas: select * from capitals; name | population | altitude | state @@ -591,7 +613,13 @@ select tableoid::regclass, * from cities; (6 rows) -- This only affects "cities" version of "Las Vegas": -insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; + name | population | altitude | name | population | altitude | name | population | altitude +-----------+------------+----------+-----------+------------+----------+-----------+------------+---------- + Las Vegas | 583000 | 2001 | Las Vegas | 586000 | 2223 | Las Vegas | 586000 | 2223 +(1 row) + select tableoid::regclass, * from cities; tableoid | name | population | altitude ----------+---------------+------------+---------- @@ -628,11 +656,17 @@ insert into excluded AS target values(1, '2') on conflict (key) do update set da 1 | 2 (1 row) --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; - key | data ------+------ - 1 | 3 +ERROR: table reference "excluded" is ambiguous +LINE 1: ...n conflict (key) do update set data = 3 RETURNING excluded.*... + ^ +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; + key | data | key | data +-----+------+-----+------ + 1 | 3 | 1 | 2 (1 row) -- clean up diff --git a/src/test/regress/expected/returning.out b/src/test/regress/expected/returning.out index 341b689f766..4ad70c171b5 100644 --- a/src/test/regress/expected/returning.out +++ b/src/test/regress/expected/returning.out @@ -461,18 +461,19 @@ INSERT INTO foo VALUES (4) | | | | | | foo | (0,4) | 4 | | 42 | 99 | 4 | | 42 | 99 (1 row) --- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW +-- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW (and EXLCUDED) CREATE UNIQUE INDEX foo_f1_idx ON foo (f1); EXPLAIN (verbose, costs off) INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; - QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------------- + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Insert on pg_temp.foo - Output: (o.tableoid)::regclass, o.ctid, o.f1, o.f2, o.f3, o.f4, (n.tableoid)::regclass, n.ctid, n.f1, n.f2, n.f3, n.f4, foo.f1, foo.f2, foo.f3, foo.f4 + Output: (o.tableoid)::regclass, o.ctid, o.f1, o.f2, o.f3, o.f4, (n.tableoid)::regclass, n.ctid, n.f1, n.f2, n.f3, n.f4, foo.f1, foo.f2, foo.f3, foo.f4, excluded.f1, excluded.f2, excluded.f3, excluded.f4 Conflict Resolution: UPDATE Conflict Arbiter Indexes: foo_f1_idx -> Values Scan on "*VALUES*" @@ -483,11 +484,12 @@ INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; - tableoid | ctid | f1 | f2 | f3 | f4 | tableoid | ctid | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 -----------+-------+----+----+----+----+----------+-------+----+------------+----+----+----+------------+----+---- - foo | (0,4) | 4 | | 42 | 99 | foo | (0,5) | 4 | conflicted | -1 | 99 | 4 | conflicted | -1 | 99 - | | | | | | foo | (0,6) | 5 | ok | 42 | 99 | 5 | ok | 42 | 99 + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; + tableoid | ctid | f1 | f2 | f3 | f4 | tableoid | ctid | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 +----------+-------+----+----+----+----+----------+-------+----+------------+----+----+----+------------+----+----+----+----------+----+---- + foo | (0,4) | 4 | | 42 | 99 | foo | (0,5) | 4 | conflicted | -1 | 99 | 4 | conflicted | -1 | 99 | 4 | conflict | 42 | 99 + | | | | | | foo | (0,6) | 5 | ok | 42 | 99 | 5 | ok | 42 | 99 | | | | (2 rows) -- UPDATE has OLD and NEW diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index 6cf828ca8d0..d0e29060401 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -3527,6 +3527,67 @@ SELECT * FROM hat_data WHERE hat_name IN ('h8', 'h9', 'h7') ORDER BY hat_name; h9 | blue (3 rows) +DROP RULE hat_upsert ON hats; +-- DO UPDATE ... RETURNING excluded values +CREATE RULE hat_upsert AS ON INSERT TO hats + DO INSTEAD + INSERT INTO hat_data VALUES ( + NEW.hat_name, + NEW.hat_color) + ON CONFLICT (hat_name) + DO UPDATE + SET hat_name = hat_data.hat_name, hat_color = 'Excl: '||excluded.hat_color + WHERE excluded.hat_color <> 'forbidden' AND hat_data.* != excluded.* + RETURNING excluded.*; +SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename; + definition +--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE RULE hat_upsert AS + + ON INSERT TO public.hats DO INSTEAD INSERT INTO hat_data (hat_name, hat_color) + + VALUES (new.hat_name, new.hat_color) ON CONFLICT(hat_name) DO UPDATE SET hat_name = hat_data.hat_name, hat_color = ('Excl: '::text || (excluded.hat_color)::text)+ + WHERE ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) + + RETURNING excluded.hat_name, + + excluded.hat_color; +(1 row) + +-- EXCLUDED not allowed in plain INSERT +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING excluded.*; +ERROR: missing FROM-clause entry for table "excluded" +LINE 2: RETURNING excluded.*; + ^ +-- OLD/NEW have no effect on EXCLUDED +EXPLAIN (verbose, costs off) +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------- + Insert on public.hat_data + Output: excluded.hat_name, excluded.hat_color, excluded.hat_name, excluded.hat_color, excluded.hat_name, excluded.hat_color + Conflict Resolution: UPDATE + Conflict Arbiter Indexes: hat_data_unique_idx + Conflict Filter: ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) + -> Values Scan on "*VALUES*" + Output: "*VALUES*".column1, "*VALUES*".column2 +(7 rows) + +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; + hat_name | hat_color | hat_name | hat_color | hat_name | hat_color +------------+------------+------------+------------+------------+------------ + | | | | | + h8 | red | h8 | red | h8 | red +(2 rows) + +SELECT * FROM hat_data ORDER BY hat_name; + hat_name | hat_color +------------+------------ + h6 | black + h7 | black + h8 | Excl: red + h9 | blue +(4 rows) + DROP RULE hat_upsert ON hats; drop table hats; drop table hat_data; diff --git a/src/test/regress/expected/triggers.out b/src/test/regress/expected/triggers.out index 2bf0e77d61e..6874792bb08 100644 --- a/src/test/regress/expected/triggers.out +++ b/src/test/regress/expected/triggers.out @@ -1708,51 +1708,103 @@ end; $$; create trigger upsert_after_trig after insert or update on upsert for each row execute procedure upsert_after_func(); -insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color; +insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (1,black) WARNING: after insert (new): (1,black) -insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+-------+-----+------- + | | 1 | black | | +(1 row) + +insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (2,red) WARNING: before insert (new, modified): (3,"red trig modified") WARNING: after insert (new): (3,"red trig modified") -insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+-------------------+-----+------- + | | 3 | red trig modified | | +(1 row) + +insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (3,orange) WARNING: before update (old): (3,"red trig modified") WARNING: before update (new): (3,"updated red trig modified") WARNING: after update (old): (3,"red trig modified") WARNING: after update (new): (3,"updated red trig modified") -insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------------------+-----+---------------------------+-----+-------- + 3 | red trig modified | 3 | updated red trig modified | 3 | orange +(1 row) + +insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (4,green) WARNING: before insert (new, modified): (5,"green trig modified") WARNING: after insert (new): (5,"green trig modified") -insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+---------------------+-----+------- + | | 5 | green trig modified | | +(1 row) + +insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (5,purple) WARNING: before update (old): (5,"green trig modified") WARNING: before update (new): (5,"updated green trig modified") WARNING: after update (old): (5,"green trig modified") WARNING: after update (new): (5,"updated green trig modified") -insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+---------------------+-----+-----------------------------+-----+-------- + 5 | green trig modified | 5 | updated green trig modified | 5 | purple +(1 row) + +insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (6,white) WARNING: before insert (new, modified): (7,"white trig modified") WARNING: after insert (new): (7,"white trig modified") -insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+---------------------+-----+------- + | | 7 | white trig modified | | +(1 row) + +insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (7,pink) WARNING: before update (old): (7,"white trig modified") WARNING: before update (new): (7,"updated white trig modified") WARNING: after update (old): (7,"white trig modified") WARNING: after update (new): (7,"updated white trig modified") -insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+---------------------+-----+-----------------------------+-----+------- + 7 | white trig modified | 7 | updated white trig modified | 7 | pink +(1 row) + +insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (8,yellow) WARNING: before insert (new, modified): (9,"yellow trig modified") WARNING: after insert (new): (9,"yellow trig modified") + key | color | key | color | key | color +-----+-------+-----+----------------------+-----+------- + | | 9 | yellow trig modified | | +(1 row) + +insert into upsert values(8, 'gold') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +WARNING: before insert (new): (8,gold) +WARNING: before insert (new, modified): (9,"gold trig modified") +WARNING: before update (old): (9,"yellow trig modified") +WARNING: before update (new): (9,"updated yellow trig modified") +WARNING: after update (old): (9,"yellow trig modified") +WARNING: after update (new): (9,"updated yellow trig modified") + key | color | key | color | key | color +-----+----------------------+-----+------------------------------+-----+-------------------- + 9 | yellow trig modified | 9 | updated yellow trig modified | 9 | gold trig modified +(1 row) + select * from upsert; - key | color ------+----------------------------- + key | color +-----+------------------------------ 1 | black 3 | updated red trig modified 5 | updated green trig modified 7 | updated white trig modified - 9 | yellow trig modified + 9 | updated yellow trig modified (5 rows) drop table upsert; diff --git a/src/test/regress/expected/updatable_views.out b/src/test/regress/expected/updatable_views.out index 095df0a670c..e1bdcfb80bc 100644 --- a/src/test/regress/expected/updatable_views.out +++ b/src/test/regress/expected/updatable_views.out @@ -3653,7 +3653,13 @@ insert into uv_iocu_tab values ('xyxyxy', 0); create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- @@ -3661,7 +3667,13 @@ select * from uv_iocu_tab; (1 row) insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- @@ -3710,7 +3722,8 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; QUERY PLAN --------------------------------------------------------------------------------------------------------- Insert on uv_iocu_tab @@ -3724,7 +3737,13 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; + ?column? | ?column? | ?column? +--------------------+------------------------------------------------------------------------------+------------------------- + Old: (x,1,"(1,x)") | New: ("Rejected: (y,1,""(1,y)"")",1,"(1,""Rejected: (y,1,""""(1,y)"""")"")") | Excluded: (y,1,"(1,y)") +(1 row) + select * from uv_iocu_view; bb | aa | cc -------------------------+----+--------------------------------- diff --git a/src/test/regress/sql/arrays.sql b/src/test/regress/sql/arrays.sql index 47d62c1d38d..47a5d7c9d72 100644 --- a/src/test/regress/sql/arrays.sql +++ b/src/test/regress/sql/arrays.sql @@ -426,12 +426,17 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; -- note: if above selects don't produce the expected tuple order, -- then you didn't get an indexscan plan, and something is busted. diff --git a/src/test/regress/sql/generated_stored.sql b/src/test/regress/sql/generated_stored.sql index 4ec155f2da9..ea35c02649b 100644 --- a/src/test/regress/sql/generated_stored.sql +++ b/src/test/regress/sql/generated_stored.sql @@ -58,6 +58,10 @@ INSERT INTO gtest1 VALUES (3, DEFAULT), (4, 44); -- error INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + SELECT * FROM gtest1 ORDER BY a; SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index 6fa986515b9..55057fcdeac 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -58,6 +58,10 @@ INSERT INTO gtest1 VALUES (3, DEFAULT), (4, 44); -- error INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + SELECT * FROM gtest1 ORDER BY a; SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink diff --git a/src/test/regress/sql/inherit.sql b/src/test/regress/sql/inherit.sql index 699e8ac09c8..da1d418abfc 100644 --- a/src/test/regress/sql/inherit.sql +++ b/src/test/regress/sql/inherit.sql @@ -806,7 +806,8 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; select * from inhpar order by f1; -- tuple order might be unstable here drop table inhpar cascade; diff --git a/src/test/regress/sql/insert_conflict.sql b/src/test/regress/sql/insert_conflict.sql index 549c46452ec..738dea09e44 100644 --- a/src/test/regress/sql/insert_conflict.sql +++ b/src/test/regress/sql/insert_conflict.sql @@ -101,8 +101,7 @@ insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -- Only suggest <table>.* column when inference element misspelled: @@ -238,16 +237,16 @@ create unique index plain on insertconflicttest(key); -- Succeeds, updates existing row: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- No update this time, though: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- Predicate changed to require match rather than non-match, so updates once more: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* = excluded.* returning *; + where i.* = excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- Assign: insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text - returning *; + returning *, excluded.* = old.*, excluded.* = new.*; -- deparse whole row var in WHERE and SET clauses: explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.fruit where excluded.* is null; explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text; @@ -267,6 +266,7 @@ drop table insertconflicttest; create table syscolconflicttest(key int4, data text); insert into syscolconflicttest values (1); insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.ctid::text; +insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.data returning excluded.ctid; drop table syscolconflicttest; -- @@ -344,20 +344,24 @@ select * from capitals; -- Succeeds: insert into cities values ('Las Vegas', 2.583E+5, 2174) on conflict do nothing; -insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; -- Wrong "Sacramento", so do nothing: insert into capitals values ('Sacramento', 50, 2267, 'NE') on conflict (name) do nothing; select * from capitals; -insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; select tableoid::regclass, * from cities; -insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; -- Capitals will contain new capital, Las Vegas: select * from capitals; -- Cities contains two instances of "Las Vegas", since unique constraints don't -- work across inheritance: select tableoid::regclass, * from cities; -- This only affects "cities" version of "Las Vegas": -insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; select tableoid::regclass, * from cities; -- clean up @@ -374,8 +378,11 @@ insert into excluded values(1, '2') on conflict (key) do update set data = exclu insert into excluded AS target values(1, '2') on conflict (key) do update set data = excluded.data RETURNING *; -- ok, aliased insert into excluded AS target values(1, '2') on conflict (key) do update set data = target.data RETURNING *; --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; -- clean up drop table excluded; diff --git a/src/test/regress/sql/returning.sql b/src/test/regress/sql/returning.sql index cc99cb53f63..00fa8a78c3d 100644 --- a/src/test/regress/sql/returning.sql +++ b/src/test/regress/sql/returning.sql @@ -209,19 +209,21 @@ INSERT INTO foo VALUES (4) RETURNING old.tableoid::regclass, old.ctid, old.*, new.tableoid::regclass, new.ctid, new.*, *; --- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW +-- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW (and EXLCUDED) CREATE UNIQUE INDEX foo_f1_idx ON foo (f1); EXPLAIN (verbose, costs off) INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; -- UPDATE has OLD and NEW EXPLAIN (verbose, costs off) diff --git a/src/test/regress/sql/rules.sql b/src/test/regress/sql/rules.sql index fdd3ff1d161..ed60cecbe7f 100644 --- a/src/test/regress/sql/rules.sql +++ b/src/test/regress/sql/rules.sql @@ -1205,6 +1205,33 @@ SELECT * FROM hat_data WHERE hat_name IN ('h8', 'h9', 'h7') ORDER BY hat_name; DROP RULE hat_upsert ON hats; +-- DO UPDATE ... RETURNING excluded values +CREATE RULE hat_upsert AS ON INSERT TO hats + DO INSTEAD + INSERT INTO hat_data VALUES ( + NEW.hat_name, + NEW.hat_color) + ON CONFLICT (hat_name) + DO UPDATE + SET hat_name = hat_data.hat_name, hat_color = 'Excl: '||excluded.hat_color + WHERE excluded.hat_color <> 'forbidden' AND hat_data.* != excluded.* + RETURNING excluded.*; +SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename; + +-- EXCLUDED not allowed in plain INSERT +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING excluded.*; + +-- OLD/NEW have no effect on EXCLUDED +EXPLAIN (verbose, costs off) +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; +SELECT * FROM hat_data ORDER BY hat_name; + +DROP RULE hat_upsert ON hats; + drop table hats; drop table hat_data; diff --git a/src/test/regress/sql/triggers.sql b/src/test/regress/sql/triggers.sql index 9ffd318385f..d76652b730c 100644 --- a/src/test/regress/sql/triggers.sql +++ b/src/test/regress/sql/triggers.sql @@ -1189,14 +1189,15 @@ $$; create trigger upsert_after_trig after insert or update on upsert for each row execute procedure upsert_after_func(); -insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color; +insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(8, 'gold') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; select * from upsert; diff --git a/src/test/regress/sql/updatable_views.sql b/src/test/regress/sql/updatable_views.sql index c071fffc116..91f45fa4509 100644 --- a/src/test/regress/sql/updatable_views.sql +++ b/src/test/regress/sql/updatable_views.sql @@ -1858,10 +1858,12 @@ create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; -- OK to access view columns that are not present in underlying base @@ -1892,12 +1894,14 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; select * from uv_iocu_view; -- Test omitting a column of the base relation diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 32d6e718adc..bf9336a86f1 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2563,6 +2563,7 @@ ReturnSetInfo ReturnStmt ReturningClause ReturningExpr +ReturningExprKind ReturningOption ReturningOptionKind RevmapContents -- 2.43.0
^ permalink raw reply [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2025-07-07 10:38  Jim Jones <jim.jones@uni-muenster.de>
  parent: Dean Rasheed <dean.a.rasheed@gmail.com>
  0 siblings, 1 reply; 17+ messages in thread

From: Jim Jones @ 2025-07-07 10:38 UTC (permalink / raw)
  To: Dean Rasheed <dean.a.rasheed@gmail.com>; pgsql-hackers

Hi Dean

On 30.06.25 19:18, Dean Rasheed wrote:
> v2 attached, now with docs and more test cases.

I'm wondering if the current behaviour with DEFAULT columns should be
mentioned in the docs.

CREATE TABLE t2 (a int PRIMARY KEY, b text DEFAULT 'default value');
INSERT INTO t2 VALUES (1, 'old value');

INSERT INTO t2 VALUES (1)
ON CONFLICT (a) DO UPDATE SET b = 'new value'
RETURNING a, old.b, new.b, excluded.b;
CREATE TABLE
INSERT 0 1
 a |     b     |     b     |       b       
---+-----------+-----------+---------------
 1 | old value | new value | default value
(1 row)


While it may seem intuitive, it's possible that it could cause confusion
for some users.

Best, Jim





^ permalink  raw  reply  [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2025-07-07 17:52  Dean Rasheed <dean.a.rasheed@gmail.com>
  parent: Jim Jones <jim.jones@uni-muenster.de>
  0 siblings, 1 reply; 17+ messages in thread

From: Dean Rasheed @ 2025-07-07 17:52 UTC (permalink / raw)
  To: Jim Jones <jim.jones@uni-muenster.de>; +Cc: pgsql-hackers

On Mon, 7 Jul 2025 at 11:38, Jim Jones <jim.jones@uni-muenster.de> wrote:
>
> I'm wondering if the current behaviour with DEFAULT columns should be
> mentioned in the docs.

Hmm, perhaps. On the INSERT page, under "conflict_action", we currently say

    Note that the effects of all per-row BEFORE INSERT triggers are
    reflected in excluded values, since those effects may have
    contributed to the row being excluded from insertion.

perhaps that should say

    Note that any values that were supplied by defaults, as well as
    the effects of all per-row BEFORE INSERT triggers are reflected
    in excluded values, since that may have contributed to the row
    being excluded from insertion.

Regards,
Dean





^ permalink  raw  reply  [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2025-07-07 18:09  Jim Jones <jim.jones@uni-muenster.de>
  parent: Dean Rasheed <dean.a.rasheed@gmail.com>
  0 siblings, 1 reply; 17+ messages in thread

From: Jim Jones @ 2025-07-07 18:09 UTC (permalink / raw)
  To: Dean Rasheed <dean.a.rasheed@gmail.com>; +Cc: pgsql-hackers


On 07.07.25 19:52, Dean Rasheed wrote:
> perhaps that should say
>
>     Note that any values that were supplied by defaults, as well as
>     the effects of all per-row BEFORE INSERT triggers are reflected
>     in excluded values, since that may have contributed to the row
>     being excluded from insertion.

+1

IMO a short mention at insert.sgml also wouldn't hurt, e.g.

If the INSERT has an ON CONFLICT DO UPDATE clause, a column name or *
may be qualified using EXCLUDED to return the values that would have
been inserted. These values include any DEFAULT expressions or computed
expressions from the INSERT clause. If there is no conflict, then all
EXCLUDED values will be NULL.

Best, Jim





^ permalink  raw  reply  [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2025-07-09 12:13  Dean Rasheed <dean.a.rasheed@gmail.com>
  parent: Jim Jones <jim.jones@uni-muenster.de>
  0 siblings, 1 reply; 17+ messages in thread

From: Dean Rasheed @ 2025-07-09 12:13 UTC (permalink / raw)
  To: Jim Jones <jim.jones@uni-muenster.de>; +Cc: pgsql-hackers

On Mon, 7 Jul 2025 at 19:09, Jim Jones <jim.jones@uni-muenster.de> wrote:
>
> On 07.07.25 19:52, Dean Rasheed wrote:
> > perhaps that should say
> >
> >     Note that any values that were supplied by defaults, as well as
> >     the effects of all per-row BEFORE INSERT triggers are reflected
> >     in excluded values, since that may have contributed to the row
> >     being excluded from insertion.
>
> +1
>
> IMO a short mention at insert.sgml also wouldn't hurt, e.g.
>
> If the INSERT has an ON CONFLICT DO UPDATE clause, a column name or *
> may be qualified using EXCLUDED to return the values that would have
> been inserted. These values include any DEFAULT expressions or computed
> expressions from the INSERT clause. If there is no conflict, then all
> EXCLUDED values will be NULL.

Thanks. I like some of this text better than what I originally wrote.
However, I don't like repeating different fragments of information in
different places on the same page. I think it's better to have a
single place on that page that describes all the properties of the
special excluded table, and then refer to that. In the attached v3,
I've done that in the form of a <note>, which makes it stand out more,
and is easier to refer to.

Regards,
Dean

Attachments:

v3-0001-Allow-EXCLUDED-in-RETURNING-list-of-INSERT-ON-CON.patch (text/x-patch, 103.2K) download From 826f185cdf7a5b6277c3a9abf14f821deab3c3a6 Mon Sep 17 00:00:00 2001 From: Dean Rasheed <dean.a.rasheed@gmail.com> Date: Mon, 23 Jun 2025 17:20:02 +0100 Subject: [PATCH v3] Allow EXCLUDED in RETURNING list of INSERT ON CONFLICT DO UPDATE. This allows an INSERT ... ON CONFLICT DO UPDATE command to return the excluded values, when conflicts occur. For rows that do not conflict, the values returned are NULL. This builds on the infrastructure added to support OLD/NEW values in the RETURNING list, except that in the case of EXCLUDED, there is no need for the special syntax to change the name of the excluded pseudo-relation in the RETURNING list. (That was required for OLD/NEW, because those names were already used in some situations, such as trigger functions, but there is no such problem with excluded.) --- doc/src/sgml/dml.sgml | 13 +++ doc/src/sgml/ref/insert.sgml | 42 ++++++--- src/backend/executor/execExpr.c | 44 +++++++-- src/backend/executor/execExprInterp.c | 21 ++++- src/backend/executor/execPartition.c | 14 +++ src/backend/executor/nodeModifyTable.c | 51 +++++++--- src/backend/optimizer/path/allpaths.c | 3 +- src/backend/optimizer/plan/setrefs.c | 77 ++++++++++------ src/backend/optimizer/prep/prepjointree.c | 21 +++-- src/backend/optimizer/prep/preptlist.c | 9 +- src/backend/optimizer/util/clauses.c | 2 +- src/backend/optimizer/util/var.c | 11 ++- src/backend/parser/analyze.c | 17 +++- src/backend/parser/parse_expr.c | 2 +- src/backend/parser/parse_relation.c | 4 +- src/backend/rewrite/rewriteHandler.c | 42 +++++---- src/backend/rewrite/rewriteManip.c | 69 ++++++++------ src/include/executor/execExpr.h | 7 +- src/include/nodes/execnodes.h | 2 + src/include/nodes/primnodes.h | 26 ++++-- src/include/parser/parse_node.h | 7 +- src/include/rewrite/rewriteManip.h | 4 +- src/test/regress/expected/arrays.out | 26 ++++-- .../regress/expected/generated_stored.out | 48 ++++++---- .../regress/expected/generated_virtual.out | 48 ++++++---- src/test/regress/expected/inherit.out | 9 +- src/test/regress/expected/insert_conflict.out | 92 +++++++++++++------ src/test/regress/expected/returning.out | 22 +++-- src/test/regress/expected/rules.out | 61 ++++++++++++ src/test/regress/expected/triggers.out | 74 ++++++++++++--- src/test/regress/expected/updatable_views.out | 27 +++++- src/test/regress/sql/arrays.sql | 9 +- src/test/regress/sql/generated_stored.sql | 4 + src/test/regress/sql/generated_virtual.sql | 4 + src/test/regress/sql/inherit.sql | 3 +- src/test/regress/sql/insert_conflict.sql | 29 +++--- src/test/regress/sql/returning.sql | 8 +- src/test/regress/sql/rules.sql | 27 ++++++ src/test/regress/sql/triggers.sql | 17 ++-- src/test/regress/sql/updatable_views.sql | 12 ++- src/tools/pgindent/typedefs.list | 1 + 41 files changed, 740 insertions(+), 269 deletions(-) diff --git a/doc/src/sgml/dml.sgml b/doc/src/sgml/dml.sgml index 458aee788b7..4712a49071b 100644 --- a/doc/src/sgml/dml.sgml +++ b/doc/src/sgml/dml.sgml @@ -392,6 +392,19 @@ UPDATE products SET price = price * 1.10 the new values may be non-<literal>NULL</literal>. </para> + <para> + In an <command>INSERT</command> with an <literal>ON CONFLICT DO UPDATE</literal> + clause, it is also possible to return the values excluded, if there is a + conflict. For example: +<programlisting> +INSERT INTO products AS p SELECT * FROM new_products + ON CONFLICT (product_no) DO UPDATE SET name = excluded.name + RETURNING p.product_no, p.name, excluded.price; +</programlisting> + Excluded values will be <literal>NULL</literal> for rows that do not + conflict. + </para> + <para> If there are triggers (<xref linkend="triggers"/>) on the target table, the data available to <literal>RETURNING</literal> is the row as modified by diff --git a/doc/src/sgml/ref/insert.sgml b/doc/src/sgml/ref/insert.sgml index 3f139917790..d1c056296a1 100644 --- a/doc/src/sgml/ref/insert.sgml +++ b/doc/src/sgml/ref/insert.sgml @@ -183,7 +183,7 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac This is particularly useful when <literal>ON CONFLICT DO UPDATE</literal> targets a table named <varname>excluded</varname>, since that will otherwise be taken as the name of the special table representing the row proposed - for insertion. + for insertion (see note below). </para> </listitem> </varlistentry> @@ -343,6 +343,35 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac with an <literal>ON CONFLICT DO UPDATE</literal> clause, the old values may be non-<literal>NULL</literal>. </para> + + <para> + If the <command>INSERT</command> has an <literal>ON CONFLICT DO + UPDATE</literal> clause, a column name or <literal>*</literal> may be + qualified using <literal>EXCLUDED</literal> to return the values + excluded from insertion, in the event of a conflict. If there is no + conflict, then all excluded values will be <literal>NULL</literal>. + </para> + + <note> + <para> + The special <varname>excluded</varname> table is made available + whenever an <command>INSERT</command> has an <literal>ON CONFLICT DO + UPDATE</literal> clause. It has the same columns as the target + table, and in the event of a conflict, it is populated with the + values that would have been inserted. This includes any values that + were supplied by defaults, as well as the effects of any per-row + <literal>BEFORE INSERT</literal> triggers, since those may have + contributed to the row being excluded from insertion. + </para> + <para> + The <varname>excluded</varname> table is accessible from the + <literal>SET</literal> and <literal>WHERE</literal> clauses of the + <literal>ON CONFLICT DO UPDATE</literal> action, and the + <literal>RETURNING</literal> list. <literal>SELECT</literal> + privilege is required on any columns in the target table where the + corresponding <varname>excluded</varname> columns are read. + </para> + </note> </listitem> </varlistentry> @@ -440,16 +469,7 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac <literal>WHERE</literal> clauses in <literal>ON CONFLICT DO UPDATE</literal> have access to the existing row using the table's name (or an alias), and to the row proposed for insertion - using the special <varname>excluded</varname> table. - <literal>SELECT</literal> privilege is required on any column in the - target table where corresponding <varname>excluded</varname> - columns are read. - </para> - <para> - Note that the effects of all per-row <literal>BEFORE - INSERT</literal> triggers are reflected in - <varname>excluded</varname> values, since those effects may - have contributed to the row being excluded from insertion. + using the special <varname>excluded</varname> table (see note above). </para> </listitem> </varlistentry> diff --git a/src/backend/executor/execExpr.c b/src/backend/executor/execExpr.c index f1569879b52..d13c82bdd30 100644 --- a/src/backend/executor/execExpr.c +++ b/src/backend/executor/execExpr.c @@ -455,6 +455,7 @@ ExecBuildProjectionInfo(List *targetList, /* * Get the tuple from the relation being scanned, or the * old/new tuple slot, if old/new values were requested. + * Should not see EXCLUDED here (should be INNER_VAR). */ switch (variable->varreturningtype) { @@ -469,6 +470,10 @@ ExecBuildProjectionInfo(List *targetList, scratch.opcode = EEOP_ASSIGN_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -972,6 +977,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_SYSVAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -1007,6 +1016,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -2638,10 +2651,23 @@ ExecInitExprRec(Expr *node, ExprState *state, ReturningExpr *rexpr = (ReturningExpr *) node; int retstep; - /* Skip expression evaluation if OLD/NEW row doesn't exist */ + /* + * Skip expression evaluation if OLD/NEW/EXCLUDED row doesn't + * exist. + */ scratch.opcode = EEOP_RETURNINGEXPR; - scratch.d.returningexpr.nullflag = rexpr->retold ? - EEO_FLAG_OLD_IS_NULL : EEO_FLAG_NEW_IS_NULL; + switch (rexpr->retkind) + { + case RETURNING_OLD_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_OLD_IS_NULL; + break; + case RETURNING_NEW_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_NEW_IS_NULL; + break; + case RETURNING_EXCLUDED_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_INNER_IS_NULL; + break; + } scratch.d.returningexpr.jumpdone = -1; /* set below */ ExprEvalPushStep(state, &scratch); retstep = state->steps_len - 1; @@ -2649,14 +2675,15 @@ ExecInitExprRec(Expr *node, ExprState *state, /* Steps to evaluate expression to return */ ExecInitExprRec(rexpr->retexpr, state, resv, resnull); - /* Jump target used if OLD/NEW row doesn't exist */ + /* Jump target used if OLD/NEW/EXCLUDED row doesn't exist */ state->steps[retstep].d.returningexpr.jumpdone = state->steps_len; /* Update ExprState flags */ - if (rexpr->retold) + if (rexpr->retkind == RETURNING_OLD_EXPR) state->flags |= EEO_FLAG_HAS_OLD; - else + else if (rexpr->retkind == RETURNING_NEW_EXPR) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ break; } @@ -3013,6 +3040,10 @@ expr_setup_walker(Node *node, ExprSetupInfo *info) case VAR_RETURNING_NEW: info->last_new = Max(info->last_new, attnum); break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -3178,6 +3209,7 @@ ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable, ExprState *state) state->flags |= EEO_FLAG_HAS_OLD; else if (variable->varreturningtype == VAR_RETURNING_NEW) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ /* * If the input tuple came from a subquery, it might contain "resjunk" diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c index 8a72b5e70a4..2e8ecd8b30a 100644 --- a/src/backend/executor/execExprInterp.c +++ b/src/backend/executor/execExprInterp.c @@ -5340,7 +5340,21 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) switch (variable->varno) { case INNER_VAR: - /* get the tuple from the inner node */ + + /* + * Get the tuple from the inner node. + * + * In a RETURNING expression, this is used for EXCLUDED values in + * an INSERT ... ON CONFLICT DO UPDATE. If the non-conflicting + * branch is taken, the EXCLUDED row is NULL, and we return NULL + * rather than an all-NULL record. + */ + if (state->flags & EEO_FLAG_INNER_IS_NULL) + { + *op->resvalue = (Datum) 0; + *op->resnull = true; + return; + } slot = econtext->ecxt_innertuple; break; @@ -5385,6 +5399,11 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) } slot = econtext->ecxt_newtuple; break; + + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } diff --git a/src/backend/executor/execPartition.c b/src/backend/executor/execPartition.c index 514eae1037d..6adc07cbed3 100644 --- a/src/backend/executor/execPartition.c +++ b/src/backend/executor/execPartition.c @@ -642,12 +642,26 @@ ExecInitPartitionInfo(ModifyTableState *mtstate, EState *estate, /* * Convert Vars in it to contain this partition's attribute numbers. + * If we're doing an INSERT ... ON CONFLICT DO UPDATE, the RETURNING + * list might contain references to the EXCLUDED pseudo-relation + * (INNER_VAR), so we must map their attribute numbers too. */ if (part_attmap == NULL) part_attmap = build_attrmap_by_name(RelationGetDescr(partrel), RelationGetDescr(firstResultRel), false); + + if (node->onConflictAction == ONCONFLICT_UPDATE) + { + returningList = (List *) + map_variable_attnos((Node *) returningList, + INNER_VAR, 0, + part_attmap, + RelationGetForm(partrel)->reltype, + &found_whole_row); + /* We ignore the value of found_whole_row. */ + } returningList = (List *) map_variable_attnos((Node *) returningList, firstVarno, 0, diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c index 54da8e7995b..1e09ceb00da 100644 --- a/src/backend/executor/nodeModifyTable.c +++ b/src/backend/executor/nodeModifyTable.c @@ -277,6 +277,7 @@ ExecCheckPlanOutput(Relation resultRel, List *targetList) * oldSlot: slot holding old tuple deleted or updated * newSlot: slot holding new tuple inserted or updated * planSlot: slot holding tuple returned by top subplan node + * exclSlot: slot holding EXCLUDED tuple (for INSERT ... ON CONFLICT ...) * * Note: If oldSlot and newSlot are NULL, the FDW should have already provided * econtext's scan tuple and its old & new tuples are not needed (FDW direct- @@ -290,8 +291,11 @@ ExecProcessReturning(ModifyTableContext *context, CmdType cmdType, TupleTableSlot *oldSlot, TupleTableSlot *newSlot, - TupleTableSlot *planSlot) + TupleTableSlot *planSlot, + TupleTableSlot *exclSlot) { + ModifyTableState *mtstate = context->mtstate; + ModifyTable *node = (ModifyTable *) mtstate->ps.plan; EState *estate = context->estate; ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning; ExprContext *econtext = projectReturning->pi_exprContext; @@ -332,10 +336,18 @@ ExecProcessReturning(ModifyTableContext *context, else econtext->ecxt_newtuple = NULL; /* No references to NEW columns */ + /* Make EXCLUDED tuple available to ExecProject, if required */ + if (exclSlot) + econtext->ecxt_innertuple = exclSlot; + else if (cmdType == CMD_INSERT && node->onConflictAction == ONCONFLICT_UPDATE) + econtext->ecxt_innertuple = ExecGetAllNullSlot(estate, resultRelInfo); + else + econtext->ecxt_innertuple = NULL; + /* - * Tell ExecProject whether or not the OLD/NEW rows actually exist. This - * information is required to evaluate ReturningExpr nodes and also in - * ExecEvalSysVar() and ExecEvalWholeRowVar(). + * Tell ExecProject whether or not the OLD/NEW/EXCLUDED rows actually + * exist. This information is required to evaluate ReturningExpr nodes + * and also in ExecEvalSysVar() and ExecEvalWholeRowVar(). */ if (oldSlot == NULL) projectReturning->pi_state.flags |= EEO_FLAG_OLD_IS_NULL; @@ -347,6 +359,11 @@ ExecProcessReturning(ModifyTableContext *context, else projectReturning->pi_state.flags &= ~EEO_FLAG_NEW_IS_NULL; + if (exclSlot == NULL) + projectReturning->pi_state.flags |= EEO_FLAG_INNER_IS_NULL; + else + projectReturning->pi_state.flags &= ~EEO_FLAG_INNER_IS_NULL; + /* Compute the RETURNING expressions */ return ExecProject(projectReturning); } @@ -1330,7 +1347,7 @@ ExecInsert(ModifyTableContext *context, } result = ExecProcessReturning(context, resultRelInfo, CMD_INSERT, - oldSlot, slot, planSlot); + oldSlot, slot, planSlot, NULL); /* * For a cross-partition UPDATE, release the old tuple, first making @@ -1890,7 +1907,7 @@ ldelete: } rslot = ExecProcessReturning(context, resultRelInfo, CMD_DELETE, - slot, NULL, context->planSlot); + slot, NULL, context->planSlot, NULL); /* * Before releasing the target tuple again, make sure rslot has a @@ -2449,6 +2466,8 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, * planSlot is the output of the ModifyTable's subplan; we use it * to access values from other input tables (for RETURNING), * row-ID junk columns, etc. + * exclSlot contains the EXCLUDED tuple if this is the auxiliary + * UPDATE of an INSERT ... ON CONFLICT DO UPDATE. * * Returns RETURNING result if any, otherwise NULL. On exit, if tupleid * had identified the tuple to update, it will identify the tuple @@ -2458,7 +2477,7 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, static TupleTableSlot * ExecUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *oldSlot, - TupleTableSlot *slot, bool canSetTag) + TupleTableSlot *slot, TupleTableSlot *exclSlot, bool canSetTag) { EState *estate = context->estate; Relation resultRelationDesc = resultRelInfo->ri_RelationDesc; @@ -2691,7 +2710,8 @@ redo_act: /* Process RETURNING if present */ if (resultRelInfo->ri_projectReturning) return ExecProcessReturning(context, resultRelInfo, CMD_UPDATE, - oldSlot, slot, context->planSlot); + oldSlot, slot, context->planSlot, + exclSlot); return NULL; } @@ -2913,6 +2933,7 @@ ExecOnConflictUpdate(ModifyTableContext *context, *returning = ExecUpdate(context, resultRelInfo, conflictTid, NULL, existing, resultRelInfo->ri_onConflict->oc_ProjSlot, + excludedSlot, canSetTag); /* @@ -3537,7 +3558,8 @@ lmerge_matched: CMD_UPDATE, resultRelInfo->ri_oldTupleSlot, newslot, - context->planSlot); + context->planSlot, + NULL); break; case CMD_DELETE: @@ -3546,7 +3568,8 @@ lmerge_matched: CMD_DELETE, resultRelInfo->ri_oldTupleSlot, NULL, - context->planSlot); + context->planSlot, + NULL); break; case CMD_NOTHING: @@ -4310,12 +4333,16 @@ ExecModifyTable(PlanState *pstate) * provide it here. The individual old and new slots are not * needed, since direct-modify is disabled if the RETURNING list * refers to OLD/NEW values. + * + * Currently, foreign tables do not support UNIQUE constraints, + * and therefore they do not support INSERT ... ON CONFLICT, and + * so the EXCLUDED slot is also not needed. */ Assert((resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD) == 0 && (resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_NEW) == 0); slot = ExecProcessReturning(&context, resultRelInfo, operation, - NULL, NULL, context.planSlot); + NULL, NULL, context.planSlot, NULL); return slot; } @@ -4505,7 +4532,7 @@ ExecModifyTable(PlanState *pstate) /* Now apply the update. */ slot = ExecUpdate(&context, resultRelInfo, tupleid, oldtuple, - oldSlot, slot, node->canSetTag); + oldSlot, slot, NULL, node->canSetTag); if (tuplock) UnlockTuple(resultRelInfo->ri_RelationDesc, tupleid, InplaceUpdateTupleLock); diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index 6cc6966b060..017a685959b 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -4013,8 +4013,7 @@ subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual) * each component query gets its own copy of the qual. */ qual = ReplaceVarsFromTargetList(qual, rti, 0, rte, - subquery->targetList, - subquery->resultRelation, + subquery->targetList, 0, REPLACEVARS_REPORT_ERROR, 0, &subquery->hasSubLinks); diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c index 846e44186c3..6d45e6e0c40 100644 --- a/src/backend/optimizer/plan/setrefs.c +++ b/src/backend/optimizer/plan/setrefs.c @@ -206,6 +206,8 @@ static List *set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset); static List *set_windowagg_runcondition_references(PlannerInfo *root, List *runcondition, @@ -1061,10 +1063,14 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) { ModifyTable *splan = (ModifyTable *) plan; Plan *subplan = outerPlan(splan); + indexed_tlist *excl_itlist = NULL; Assert(splan->plan.targetlist == NIL); Assert(splan->plan.qual == NIL); + if (splan->onConflictSet) + excl_itlist = build_tlist_index(splan->exclRelTlist); + splan->withCheckOptionLists = fix_scan_list(root, splan->withCheckOptionLists, rtoffset, 1); @@ -1090,6 +1096,8 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) rlist, subplan, resultrel, + splan->exclRelRTI, + excl_itlist, rtoffset); newRL = lappend(newRL, rlist); } @@ -1117,23 +1125,19 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) */ if (splan->onConflictSet) { - indexed_tlist *itlist; - - itlist = build_tlist_index(splan->exclRelTlist); - splan->onConflictSet = fix_join_expr(root, splan->onConflictSet, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); splan->onConflictWhere = (Node *) fix_join_expr(root, (List *) splan->onConflictWhere, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); - pfree(itlist); + pfree(excl_itlist); splan->exclRelTlist = fix_scan_list(root, splan->exclRelTlist, rtoffset, 1); @@ -2798,12 +2802,12 @@ build_tlist_index(List *tlist) * build_tlist_index_other_vars --- build a restricted tlist index * * This is like build_tlist_index, but we only index tlist entries that - * are Vars belonging to some rel other than the one specified. We will set + * are Vars belonging to some rel other than the ones specified. We will set * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars * (so nothing other than Vars and PlaceHolderVars can be matched). */ static indexed_tlist * -build_tlist_index_other_vars(List *tlist, int ignore_rel) +build_tlist_index_other_vars(List *tlist, int ignore_rel1, int ignore_rel2) { indexed_tlist *itlist; tlist_vinfo *vinfo; @@ -2828,7 +2832,7 @@ build_tlist_index_other_vars(List *tlist, int ignore_rel) { Var *var = (Var *) tle->expr; - if (var->varno != ignore_rel) + if (var->varno != ignore_rel1 && var->varno != ignore_rel2) { vinfo->varno = var->varno; vinfo->varattno = var->varattno; @@ -3067,10 +3071,14 @@ search_indexed_tlist_for_sortgroupref(Expr *node, * acceptable_rel should be zero so that any failure to match a Var will be * reported as an error. * 2) RETURNING clauses, which may contain both Vars of the target relation - * and Vars of other relations. In this case we want to replace the - * other-relation Vars by OUTER_VAR references, while leaving target Vars - * alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the - * target relation should be passed. + * and Vars of other relations, including the EXCLUDED pseudo-relation in + * an INSERT ... ON CONFLICT DO UPDATE command. In this case, we want to + * replace references to EXCLUDED with INNER_VAR references, and + * other-relation Vars with OUTER_VAR references, while leaving target Vars + * alone. Thus inner_itlist is to be EXCLUDED elements, if this is an + * INSERT with an ON CONFLICT DO UPDATE clause, outer_itlist is any other + * non-target relation elements, and acceptable_rel = the ID of the target + * relation. * 3) ON CONFLICT UPDATE SET/WHERE clauses. Here references to EXCLUDED are * to be replaced with INNER_VAR references, while leaving target Vars (the * to-be-updated relation) alone. Correspondingly inner_itlist is to be @@ -3131,15 +3139,16 @@ fix_join_expr_mutator(Node *node, fix_join_expr_context *context) /* * Verify that Vars with non-default varreturningtype only appear in - * the RETURNING list, and refer to the target relation. + * the RETURNING list, and that OLD/NEW Vars refer to the target + * relation. */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { - if (context->inner_itlist != NULL || - context->outer_itlist == NULL || + if (context->outer_itlist == NULL || context->acceptable_rel == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); - if (var->varno != context->acceptable_rel) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list"); + if (var->varreturningtype != VAR_RETURNING_EXCLUDED && + var->varno != context->acceptable_rel) elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new", var->varno, context->acceptable_rel); } @@ -3369,11 +3378,14 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * * If the query involves more than just the result table, we have to * adjust any Vars that refer to other tables to reference junk tlist - * entries in the top subplan's targetlist. Vars referencing the result - * table should be left alone, however (the executor will evaluate them - * using the actual heap tuple, after firing triggers if any). In the - * adjusted RETURNING list, result-table Vars will have their original - * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR. + * entries in the top subplan's targetlist. Vars referencing the EXCLUDED + * pseudo-relation of an INSERT ... ON CONFLICT DO UPDATE command should be + * adjusted to reference INNER_VAR, and Vars referencing the result table + * should be left alone (the executor will evaluate them using the actual heap + * tuple, after firing triggers if any). In the adjusted RETURNING list, + * result-table Vars will have their original varno (plus rtoffset), but Vars + * for the EXCLUDED pseudo-relation and other rels will have varno INNER_VAR + * and OUTER_VAR espectively. * * We also must perform opcode lookup and add regclass OIDs to * root->glob->relationOids. @@ -3382,6 +3394,8 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * 'topplan': the top subplan node that will be just below the ModifyTable * node (note it's not yet passed through set_plan_refs) * 'resultRelation': RT index of the associated result relation + * 'exclRelRTI': RT index of EXCLUDED pseudo-relation + * 'excl_itlist': EXCLUDED pseudo-relation elements (or NULL) * 'rtoffset': how much to increment varnos by * * Note: the given 'root' is for the parent query level, not the 'topplan'. @@ -3396,6 +3410,8 @@ set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset) { indexed_tlist *itlist; @@ -3403,9 +3419,11 @@ set_returning_clause_references(PlannerInfo *root, /* * We can perform the desired Var fixup by abusing the fix_join_expr * machinery that formerly handled inner indexscan fixup. We search the - * top plan's targetlist for Vars of non-result relations, and use - * fix_join_expr to convert RETURNING Vars into references to those tlist - * entries, while leaving result-rel Vars as-is. + * top plan's targetlist for Vars of non-result relations (other than + * EXCLUDED), and use fix_join_expr to convert RETURNING Vars into + * references to those tlist entries, and convert RETURNING EXCLUDED Vars + * into references to excl_itlist entries, while leaving result-rel Vars + * as-is. * * PlaceHolderVars will also be sought in the targetlist, but no * more-complex expressions will be. Note that it is not possible for a @@ -3414,12 +3432,13 @@ set_returning_clause_references(PlannerInfo *root, * prepared to pick apart the PlaceHolderVar and evaluate its contained * expression instead. */ - itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation); + itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation, + exclRelRTI); rlist = fix_join_expr(root, rlist, itlist, - NULL, + excl_itlist, resultRelation, rtoffset, NRM_EQUAL, diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index 87dc6f56b57..00de20b0d49 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -71,8 +71,7 @@ typedef struct pullup_replace_vars_context PlannerInfo *root; List *targetlist; /* tlist of subquery being pulled up */ RangeTblEntry *target_rte; /* RTE of subquery */ - int result_relation; /* the index of the result relation in the - * rewritten query */ + int new_target_varno; /* see ReplaceVarFromTargetList() */ Relids relids; /* relids within subquery, as numbered after * pullup (set only if target_rte->lateral) */ nullingrel_info *nullinfo; /* per-RTE nullingrel info (set only if @@ -1034,11 +1033,19 @@ expand_virtual_generated_columns(PlannerInfo *root) * to insert into the query, except that we may need to wrap them * in PlaceHolderVars. Set up required context data for * pullup_replace_vars. + * + * new_target_varno should equal rt_index if this is the result + * relation or the EXCLUDED pseudo-relation. Otherwise, it should + * be 0. See comments in ReplaceVarFromTargetList(). */ rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = parse->resultRelation; + if (rt_index == parse->resultRelation || + (parse->onConflict && rt_index == parse->onConflict->exclRelIndex)) + rvcontext.new_target_varno = rt_index; + else + rvcontext.new_target_varno = 0; /* won't need these values */ rvcontext.relids = NULL; rvcontext.nullinfo = NULL; @@ -1436,7 +1443,7 @@ pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte, rvcontext.root = root; rvcontext.targetlist = subquery->targetList; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; if (rte->lateral) { rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree, @@ -1987,7 +1994,7 @@ pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte) rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; rvcontext.relids = NULL; /* can't be any lateral references here */ rvcontext.nullinfo = NULL; rvcontext.outer_hasSubLinks = &parse->hasSubLinks; @@ -2147,7 +2154,7 @@ pull_up_constant_function(PlannerInfo *root, Node *jtnode, NULL, /* resname */ false)); /* resjunk */ rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; /* * Since this function was reduced to a Const, it doesn't contain any @@ -2681,7 +2688,7 @@ pullup_replace_vars_callback(Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, REPLACEVARS_REPORT_ERROR, 0); diff --git a/src/backend/optimizer/prep/preptlist.c b/src/backend/optimizer/prep/preptlist.c index ffc9d6c3f30..098d8f8498a 100644 --- a/src/backend/optimizer/prep/preptlist.c +++ b/src/backend/optimizer/prep/preptlist.c @@ -291,7 +291,10 @@ preprocess_targetlist(PlannerInfo *root) * used in RETURNING that belong to other relations. We need to do this * to make these Vars available for the RETURNING calculation. Vars that * belong to the result rel don't need to be added, because they will be - * made to refer to the actual heap tuple. + * made to refer to the actual heap tuple. Vars that refer to the + * EXCLUDED pseudo-relation of an INSERT ... ON CONFLICT DO UPDATE command + * are also not needed, because they are handled specially in the + * executor. */ if (parse->returningList && list_length(parse->rtable) > 1) { @@ -308,7 +311,9 @@ preprocess_targetlist(PlannerInfo *root) TargetEntry *tle; if (IsA(var, Var) && - var->varno == result_relation) + (var->varno == result_relation || + (parse->onConflict && + var->varno == parse->onConflict->exclRelIndex))) continue; /* don't need it */ if (tlist_member((Expr *) var, tlist)) diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index f45131c34c5..0571c05fdf6 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -3414,7 +3414,7 @@ eval_const_expressions_mutator(Node *node, fselect->resulttypmod, fselect->resultcollid, ((Var *) arg)->varlevelsup); - /* New Var has same OLD/NEW returning as old one */ + /* New Var has same returningtype as old one */ newvar->varreturningtype = ((Var *) arg)->varreturningtype; /* New Var is nullable by same rels as the old one */ newvar->varnullingrels = ((Var *) arg)->varnullingrels; diff --git a/src/backend/optimizer/util/var.c b/src/backend/optimizer/util/var.c index 8065237a189..c2642c88e92 100644 --- a/src/backend/optimizer/util/var.c +++ b/src/backend/optimizer/util/var.c @@ -501,8 +501,8 @@ contain_vars_of_level_walker(Node *node, int *sublevels_up) * * Returns true if any found. * - * Any ReturningExprs are also detected --- if an OLD/NEW Var was rewritten, - * we still regard this as a clause that returns OLD/NEW values. + * Any ReturningExprs are also checked --- if an OLD/NEW Var was rewritten, we + * still regard this as a clause that returns OLD/NEW values. * * Does not examine subqueries, therefore must only be used after reduction * of sublinks to subplans! @@ -521,13 +521,16 @@ contain_vars_returning_old_or_new_walker(Node *node, void *context) if (IsA(node, Var)) { if (((Var *) node)->varlevelsup == 0 && - ((Var *) node)->varreturningtype != VAR_RETURNING_DEFAULT) + (((Var *) node)->varreturningtype == VAR_RETURNING_OLD || + ((Var *) node)->varreturningtype == VAR_RETURNING_NEW)) return true; /* abort the tree traversal and return true */ return false; } if (IsA(node, ReturningExpr)) { - if (((ReturningExpr *) node)->retlevelsup == 0) + if (((ReturningExpr *) node)->retlevelsup == 0 && + (((ReturningExpr *) node)->retkind == RETURNING_OLD_EXPR || + ((ReturningExpr *) node)->retkind == RETURNING_NEW_EXPR)) return true; /* abort the tree traversal and return true */ return false; } diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index 34f7c17f576..bf7ee465a14 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -1234,12 +1234,21 @@ transformOnConflictClause(ParseState *pstate, EXPR_KIND_WHERE, "WHERE"); /* - * Remove the EXCLUDED pseudo relation from the query namespace, since - * it's not supposed to be available in RETURNING. (Maybe someday we - * could allow that, and drop this step.) + * Leave the EXCLUDED pseudo relation in the query namespace so that + * it is available in RETURNING expressions, but change it to be a + * table-only item so that its columns are only accessible using + * qualified names. This ensures that columns from the target + * relation can be accessed using unqualified names without ambiguity. + * + * Also, set its returning_type so that any RETURNING list Vars + * referencing it are marked correctly. */ Assert((ParseNamespaceItem *) llast(pstate->p_namespace) == exclNSItem); - pstate->p_namespace = list_delete_last(pstate->p_namespace); + exclNSItem->p_cols_visible = false; + + exclNSItem->p_returning_type = VAR_RETURNING_EXCLUDED; + for (int i = 0; i < list_length(exclNSItem->p_names->colnames); i++) + exclNSItem->p_nscolumns[i].p_varreturningtype = VAR_RETURNING_EXCLUDED; } /* Finally, build ON CONFLICT DO [NOTHING | UPDATE] expression */ diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c index d66276801c6..e551c0bd7a1 100644 --- a/src/backend/parser/parse_expr.c +++ b/src/backend/parser/parse_expr.c @@ -2653,7 +2653,7 @@ transformWholeRowRef(ParseState *pstate, ParseNamespaceItem *nsitem, result = makeWholeRowVar(nsitem->p_rte, nsitem->p_rtindex, sublevels_up, true); - /* mark Var for RETURNING OLD/NEW, as necessary */ + /* mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ result->varreturningtype = nsitem->p_returning_type; /* location is not filled in by makeWholeRowVar */ diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c index 04ecf64b1fc..1651c52eb87 100644 --- a/src/backend/parser/parse_relation.c +++ b/src/backend/parser/parse_relation.c @@ -258,7 +258,7 @@ scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location) /* If not inside LATERAL, ignore lateral-only items */ if (nsitem->p_lateral_only && !pstate->p_lateral_active) continue; - /* Ignore OLD/NEW namespace items that can appear in RETURNING */ + /* Ignore OLD/NEW/EXCLUDED namespace items in RETURNING */ if (nsitem->p_returning_type != VAR_RETURNING_DEFAULT) continue; @@ -775,7 +775,7 @@ scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem, } var->location = location; - /* Mark Var for RETURNING OLD/NEW, as necessary */ + /* Mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ var->varreturningtype = nsitem->p_returning_type; /* Mark Var if it's nulled by any outer joins */ diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c index adc9e7600e1..7e24f2bd20e 100644 --- a/src/backend/rewrite/rewriteHandler.c +++ b/src/backend/rewrite/rewriteHandler.c @@ -97,7 +97,7 @@ static List *matchLocks(CmdType event, Relation relation, static Query *fireRIRrules(Query *parsetree, List *activeRIRs); static Bitmapset *adjust_view_column_set(Bitmapset *cols, List *targetlist); static Node *expand_generated_columns_internal(Node *node, Relation rel, int rt_index, - RangeTblEntry *rte, int result_relation); + RangeTblEntry *rte); /* @@ -643,7 +643,7 @@ rewriteRuleAction(Query *parsetree, 0, rt_fetch(new_varno, sub_action->rtable), parsetree->targetList, - sub_action->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -2346,7 +2346,7 @@ CopyAndAddInvertedQual(Query *parsetree, rt_fetch(rt_index, parsetree->rtable), parsetree->targetList, - parsetree->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -3705,12 +3705,12 @@ rewriteTargetView(Query *parsetree, Relation view) BuildOnConflictExcludedTargetlist(base_rel, new_exclRelIndex); /* - * Update all Vars in the ON CONFLICT clause that refer to the old - * EXCLUDED pseudo-relation. We want to use the column mappings - * defined in the view targetlist, but we need the outputs to refer to - * the new EXCLUDED pseudo-relation rather than the new target RTE. - * Also notice that "EXCLUDED.*" will be expanded using the view's - * rowtype, which seems correct. + * Update all Vars in the ON CONFLICT clause and RETURNING list that + * refer to the old EXCLUDED pseudo-relation. We want to use the + * column mappings defined in the view targetlist, but we need the + * outputs to refer to the new EXCLUDED pseudo-relation rather than + * the new target RTE. Also notice that "EXCLUDED.*" will be expanded + * using the view's rowtype, which seems correct. */ tmp_tlist = copyObject(view_targetlist); @@ -3723,7 +3723,18 @@ rewriteTargetView(Query *parsetree, Relation view) 0, view_rte, tmp_tlist, - new_rt_index, + 0, + REPLACEVARS_REPORT_ERROR, + 0, + &parsetree->hasSubLinks); + + parsetree->returningList = (List *) + ReplaceVarsFromTargetList((Node *) parsetree->returningList, + old_exclRelIndex, + 0, + view_rte, + tmp_tlist, + new_exclRelIndex, REPLACEVARS_REPORT_ERROR, 0, &parsetree->hasSubLinks); @@ -4421,13 +4432,11 @@ RewriteQuery(Query *parsetree, List *rewrite_events, int orig_rt_length) * virtual generated column expressions from rel, if there are any. * * The caller must also provide rte, the RTE describing the target relation, - * in order to handle any whole-row Vars referencing the target, and - * result_relation, the index of the result relation, if this is part of an - * INSERT/UPDATE/DELETE/MERGE query. + * in order to handle any whole-row Vars referencing the target. */ static Node * expand_generated_columns_internal(Node *node, Relation rel, int rt_index, - RangeTblEntry *rte, int result_relation) + RangeTblEntry *rte) { TupleDesc tupdesc; @@ -4455,8 +4464,7 @@ expand_generated_columns_internal(Node *node, Relation rel, int rt_index, Assert(list_length(tlist) > 0); - node = ReplaceVarsFromTargetList(node, rt_index, 0, rte, tlist, - result_relation, + node = ReplaceVarsFromTargetList(node, rt_index, 0, rte, tlist, 0, REPLACEVARS_CHANGE_VARNO, rt_index, NULL); } @@ -4485,7 +4493,7 @@ expand_generated_columns_in_expr(Node *node, Relation rel, int rt_index) rte->rtekind = RTE_RELATION; rte->relid = RelationGetRelid(rel); - node = expand_generated_columns_internal(node, rel, rt_index, rte, 0); + node = expand_generated_columns_internal(node, rel, rt_index, rte); } return node; diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index cd786aa4112..e5f85116f79 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -921,7 +921,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, /* * SetVarReturningType - adjust Var nodes for a specified varreturningtype. * - * Find all Var nodes referring to the specified result relation in the given + * Find all Var nodes referring to the specified relation in the given * expression and set their varreturningtype to the specified value. * * NOTE: although this has the form of a walker, we cheat and modify the @@ -931,7 +931,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, typedef struct { - int result_relation; + int target_varno; int sublevels_up; VarReturningType returning_type; } SetVarReturningType_context; @@ -945,7 +945,7 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) { Var *var = (Var *) node; - if (var->varno == context->result_relation && + if (var->varno == context->target_varno && var->varlevelsup == context->sublevels_up) var->varreturningtype = context->returning_type; @@ -967,12 +967,12 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) } static void -SetVarReturningType(Node *node, int result_relation, int sublevels_up, +SetVarReturningType(Node *node, int target_varno, int sublevels_up, VarReturningType returning_type) { SetVarReturningType_context context; - context.result_relation = result_relation; + context.target_varno = target_varno; context.sublevels_up = sublevels_up; context.returning_type = returning_type; @@ -1744,14 +1744,29 @@ map_variable_attnos(Node *node, * relation. This is needed to handle whole-row Vars referencing the target. * We expand such Vars into RowExpr constructs. * - * In addition, for INSERT/UPDATE/DELETE/MERGE queries, the caller must - * provide result_relation, the index of the result relation in the rewritten - * query. This is needed to handle OLD/NEW RETURNING list Vars referencing - * target_varno. When such Vars are expanded, their varreturningtype is - * copied onto any replacement Vars referencing result_relation. In addition, - * if the replacement expression from the targetlist is not simply a Var - * referencing result_relation, it is wrapped in a ReturningExpr node (causing - * the executor to return NULL if the OLD/NEW row doesn't exist). + * In addition, the caller should provide new_target_varno, which is needed to + * handle any OLD/NEW/EXCLUDED RETURNING list Vars (Vars with non-default + * varreturningtype) referencing target_varno. When such Vars are expanded, + * their varreturningtype is copied onto any Vars that reference + * new_target_varno in the replacement expression from the targetlist. In + * addition, if the replacement expression is not simply a Var referencing + * new_target_varno, it is wrapped in a ReturningExpr node (causing the + * executor to return NULL if the OLD/NEW/EXCLUDED row doesn't exist). The + * caller should set new_target_varno as follows: + * + * If the input node contains Vars from the RETURNING list of a query, and + * target_varno is the resultRelation of that query, then new_target_varno + * should be the (possibly new) resultRelation of the rewritten query. + * + * If the input node contains Vars from the RETURNING list of an INSERT ... + * ON CONFLICT DO UPDATE query, and target_varno is the index of the + * EXCLUDED pseudo-relation, then new_target_varno should be the (possibly + * new) index of the EXCLUDED pseudo-relation in the rewritten query. + * + * Otherwise, new_target_varno should be set to 0 in order to detect any + * Vars with non-default varreturningtype outside the RETURNING list, or + * referencing a relation other than the result relation or the EXCLUDED + * pseudo-relation. * * Note that ReplaceVarFromTargetList always generates the replacement * expression with varlevelsup = 0. The caller is responsible for adjusting @@ -1765,7 +1780,7 @@ typedef struct { RangeTblEntry *target_rte; List *targetlist; - int result_relation; + int new_target_varno; ReplaceVarsNoMatchOption nomatch_option; int nomatch_varno; } ReplaceVarsFromTargetList_context; @@ -1780,7 +1795,7 @@ ReplaceVarsFromTargetList_callback(Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, rcon->nomatch_option, rcon->nomatch_varno); @@ -1795,7 +1810,7 @@ Node * ReplaceVarFromTargetList(Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno) { @@ -1844,7 +1859,7 @@ ReplaceVarFromTargetList(Var *var, field = ReplaceVarFromTargetList((Var *) field, target_rte, targetlist, - result_relation, + new_target_varno, nomatch_option, nomatch_varno); rowexpr->args = lappend(rowexpr->args, field); @@ -1856,7 +1871,7 @@ ReplaceVarFromTargetList(Var *var, ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = (Expr *) rowexpr; return (Node *) rexpr; @@ -1925,28 +1940,28 @@ ReplaceVarFromTargetList(Var *var, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("NEW variables in ON UPDATE rules cannot reference columns that are part of a multiple assignment in the subject UPDATE command"))); - /* Handle any OLD/NEW RETURNING list Vars */ + /* Handle any OLD/NEW/EXCLUDED RETURNING list Vars */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { /* * Copy varreturningtype onto any Vars in the tlist item that - * refer to result_relation (which had better be non-zero). + * refer to new_target_varno (which had better be non-zero). */ - if (result_relation == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); + if (new_target_varno == 0) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list, or referencing a relation other than the result relation or the EXCLUDED pseudo-relation"); - SetVarReturningType((Node *) newnode, result_relation, + SetVarReturningType((Node *) newnode, new_target_varno, 0, var->varreturningtype); /* Wrap it in a ReturningExpr, if needed, per comments above */ if (!IsA(newnode, Var) || - ((Var *) newnode)->varno != result_relation || + ((Var *) newnode)->varno != new_target_varno || ((Var *) newnode)->varlevelsup != 0) { ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = newnode; newnode = (Expr *) rexpr; @@ -1962,7 +1977,7 @@ ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks) @@ -1971,7 +1986,7 @@ ReplaceVarsFromTargetList(Node *node, context.target_rte = target_rte; context.targetlist = targetlist; - context.result_relation = result_relation; + context.new_target_varno = new_target_varno; context.nomatch_option = nomatch_option; context.nomatch_varno = nomatch_varno; diff --git a/src/include/executor/execExpr.h b/src/include/executor/execExpr.h index 75366203706..1ce4d98afce 100644 --- a/src/include/executor/execExpr.h +++ b/src/include/executor/execExpr.h @@ -26,9 +26,9 @@ struct JsonConstructorExprState; /* Bits in ExprState->flags (see also execnodes.h for public flag bits): */ /* expression's interpreter has been initialized */ -#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 5) +#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 6) /* jump-threading is in use */ -#define EEO_FLAG_DIRECT_THREADED (1 << 6) +#define EEO_FLAG_DIRECT_THREADED (1 << 7) /* Typical API for out-of-line evaluation subroutines */ typedef void (*ExecEvalSubroutine) (ExprState *state, @@ -338,7 +338,8 @@ typedef struct ExprEvalStep /* but it's just the normal (negative) attr number for SYSVAR */ int attnum; Oid vartype; /* type OID of variable */ - VarReturningType varreturningtype; /* return old/new/default */ + /* if not default, return old/new/excluded value */ + VarReturningType varreturningtype; } var; /* for EEOP_WHOLEROW */ diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index e107d6e5f81..b40e76f2e2d 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -82,6 +82,8 @@ typedef Datum (*ExprStateEvalFunc) (struct ExprState *expression, #define EEO_FLAG_OLD_IS_NULL (1 << 3) /* NEW table row is NULL in RETURNING list */ #define EEO_FLAG_NEW_IS_NULL (1 << 4) +/* INNER (EXCLUDED) table row is NULL in RETURNING list */ +#define EEO_FLAG_INNER_IS_NULL (1 << 5) typedef struct ExprState { diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h index 6dfca3cb35b..a867814cd8f 100644 --- a/src/include/nodes/primnodes.h +++ b/src/include/nodes/primnodes.h @@ -227,7 +227,9 @@ typedef struct Expr * varreturningtype is used for Vars that refer to the target relation in the * RETURNING list of data-modifying queries. The default behavior is to * return old values for DELETE and new values for INSERT and UPDATE, but it - * is also possible to explicitly request old or new values. + * is also possible to explicitly request old or new values. For INSERT ... + * ON CONFLICT DO UPDATE, varreturningtype is also used for Vars in the + * RETURNING list that refer to the EXCLUDED pseudo-relation. * * In the parser, varnosyn and varattnosyn are either identical to * varno/varattno, or they specify the column's position in an aliased JOIN @@ -256,6 +258,7 @@ typedef enum VarReturningType VAR_RETURNING_DEFAULT, /* return OLD for DELETE, else return NEW */ VAR_RETURNING_OLD, /* return OLD for DELETE/UPDATE, else NULL */ VAR_RETURNING_NEW, /* return NEW for INSERT/UPDATE, else NULL */ + VAR_RETURNING_EXCLUDED, /* return EXCLUDED on conflict, else NULL */ } VarReturningType; typedef struct Var @@ -2140,14 +2143,15 @@ typedef struct InferenceElem } InferenceElem; /* - * ReturningExpr - return OLD/NEW.(expression) in RETURNING list + * ReturningExpr - return OLD/NEW/EXCLUDED.(expression) in RETURNING list * * This is used when updating an auto-updatable view and returning a view * column that is not simply a Var referring to the base relation. In such - * cases, OLD/NEW.viewcol can expand to an arbitrary expression, but the - * result is required to be NULL if the OLD/NEW row doesn't exist. To handle - * this, the rewriter wraps the expanded expression in a ReturningExpr, which - * is equivalent to "CASE WHEN (OLD/NEW row exists) THEN (expr) ELSE NULL". + * cases, OLD/NEW/EXCLUDED.viewcol can expand to an arbitrary expression, but + * the result is required to be NULL if the OLD/NEW/EXCLUDED row doesn't + * exist. To handle this, the rewriter wraps the expanded expression in a + * ReturningExpr, which is equivalent to "CASE WHEN (OLD/NEW/EXCLUDED row + * exists) THEN (expr) ELSE NULL". * * A similar situation can arise when rewriting the RETURNING clause of a * rule, which may also contain arbitrary expressions. @@ -2155,11 +2159,19 @@ typedef struct InferenceElem * ReturningExpr nodes never appear in a parsed Query --- they are only ever * inserted by the rewriter and the planner. */ +typedef enum ReturningExprKind +{ + /* values here match non-default VarReturningType values */ + RETURNING_OLD_EXPR = VAR_RETURNING_OLD, + RETURNING_NEW_EXPR = VAR_RETURNING_NEW, + RETURNING_EXCLUDED_EXPR = VAR_RETURNING_EXCLUDED, +} ReturningExprKind; + typedef struct ReturningExpr { Expr xpr; int retlevelsup; /* > 0 if it belongs to outer query */ - bool retold; /* true for OLD, false for NEW */ + ReturningExprKind retkind; /* return OLD/NEW/EXCLUDED expression */ Expr *retexpr; /* expression to be returned */ } ReturningExpr; diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h index f7d07c84542..1f0c21543b2 100644 --- a/src/include/parser/parse_node.h +++ b/src/include/parser/parse_node.h @@ -280,7 +280,8 @@ struct ParseState * forbid LATERAL references to an UPDATE/DELETE target table. * * While processing the RETURNING clause, special namespace items are added to - * refer to the OLD and NEW state of the result relation. These namespace + * refer to the OLD and NEW state of the result relation, and the EXCLUDED + * pseudo-relation for an INSERT ... ON CONFLICT DO UPDATE. These namespace * items have p_returning_type set appropriately, for use when creating Vars. * For convenience, this information is duplicated on each namespace column. * @@ -301,7 +302,7 @@ struct ParseNamespaceItem bool p_cols_visible; /* Column names visible as unqualified refs? */ bool p_lateral_only; /* Is only visible to LATERAL expressions? */ bool p_lateral_ok; /* If so, does join type allow use? */ - VarReturningType p_returning_type; /* Is OLD/NEW for use in RETURNING? */ + VarReturningType p_returning_type; /* for RETURNING OLD/NEW/EXCLUDED */ }; /* @@ -332,7 +333,7 @@ struct ParseNamespaceColumn Oid p_vartype; /* pg_type OID */ int32 p_vartypmod; /* type modifier value */ Oid p_varcollid; /* OID of collation, or InvalidOid */ - VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW */ + VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW/EXCLUDED */ Index p_varnosyn; /* rangetable index of syntactic referent */ AttrNumber p_varattnosyn; /* attribute number of syntactic referent */ bool p_dontexpand; /* not included in star expansion */ diff --git a/src/include/rewrite/rewriteManip.h b/src/include/rewrite/rewriteManip.h index 7c018f2a4e3..81a1493ad31 100644 --- a/src/include/rewrite/rewriteManip.h +++ b/src/include/rewrite/rewriteManip.h @@ -107,14 +107,14 @@ extern Node *map_variable_attnos(Node *node, extern Node *ReplaceVarFromTargetList(Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno); extern Node *ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks); diff --git a/src/test/regress/expected/arrays.out b/src/test/regress/expected/arrays.out index b815473f414..5a5a06e6a06 100644 --- a/src/test/regress/expected/arrays.out +++ b/src/test/regress/expected/arrays.out @@ -1398,20 +1398,30 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+--------- - 1 | {3,2,5} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+---------+------------- + 1 | {3,2,5} | {3,4,5} (1 row) insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+------------ - 1 | {6,7,NULL} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+------------+------------- + 1 | {6,7,NULL} | {6,7} +(1 row) + +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+----------------+------------- + 1 | {NULL,10,NULL} | [2:2]={10} (1 row) -- note: if above selects don't produce the expected tuple order, diff --git a/src/test/regress/expected/generated_stored.out b/src/test/regress/expected/generated_stored.out index adac2cedfb2..5eae1029550 100644 --- a/src/test/regress/expected/generated_stored.out +++ b/src/test/regress/expected/generated_stored.out @@ -114,32 +114,44 @@ INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error ERROR: cannot insert a non-DEFAULT value into column "b" DETAIL: Column "b" is a generated column. INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + a | b | a | b | a | b +---+---+-----+-----+---+--- + 4 | 8 | 104 | 208 | 4 | 8 + | | 5 | 10 | | +(2 rows) + SELECT * FROM gtest1 ORDER BY a; - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference - gtest1 --------- + gtest1 +----------- (1,2) (2,4) (3,6) - (4,8) -(4 rows) + (5,10) + (104,208) +(5 rows) SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) DELETE FROM gtest1 WHERE a >= 3; UPDATE gtest1 SET b = DEFAULT WHERE a = 1; diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index 3b40e15a95a..8284502705b 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -114,32 +114,44 @@ INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error ERROR: cannot insert a non-DEFAULT value into column "b" DETAIL: Column "b" is a generated column. INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + a | b | a | b | a | b +---+---+-----+-----+---+--- + 4 | 8 | 104 | 208 | 4 | 8 + | | 5 | 10 | | +(2 rows) + SELECT * FROM gtest1 ORDER BY a; - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference - gtest1 --------- + gtest1 +----------- (1,2) (2,4) (3,6) - (4,8) -(4 rows) + (5,10) + (104,208) +(5 rows) SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) DELETE FROM gtest1 WHERE a >= 3; UPDATE gtest1 SET b = DEFAULT WHERE a = 1; diff --git a/src/test/regress/expected/inherit.out b/src/test/regress/expected/inherit.out index 5b5055babdc..d32cd36bba0 100644 --- a/src/test/regress/expected/inherit.out +++ b/src/test/regress/expected/inherit.out @@ -2125,7 +2125,14 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; + old | new | excluded +--------+---------+---------- + (3,3-) | (3,3-+) | (3,) + (7,7-) | (7,7-+) | (7,) +(2 rows) + select * from inhpar order by f1; -- tuple order might be unstable here f1 | f2 ----+----- diff --git a/src/test/regress/expected/insert_conflict.out b/src/test/regress/expected/insert_conflict.out index fdd0f6c8f25..58017bb0eb6 100644 --- a/src/test/regress/expected/insert_conflict.out +++ b/src/test/regress/expected/insert_conflict.out @@ -249,13 +249,13 @@ insert into insertconflicttest values (2, 'Orange') on conflict (key, key, key) insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -ERROR: invalid reference to FROM-clause entry for table "excluded" -LINE 1: ...y) do update set fruit = excluded.fruit RETURNING excluded.f... - ^ -DETAIL: There is an entry for table "excluded", but it cannot be referenced from this part of the query. + fruit +------- + Apple +(1 row) + -- Only suggest <table>.* column when inference element misspelled: insert into insertconflicttest values (1, 'Apple') on conflict (keyy) do update set fruit = excluded.fruit; ERROR: column "keyy" does not exist @@ -408,33 +408,33 @@ drop index partial_key_index; create unique index plain on insertconflicttest(key); -- Succeeds, updates existing row: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; - key | fruit ------+----------- - 23 | Jackfruit + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-----------+----------+---------- + 23 | Jackfruit | f | t (1 row) -- No update this time, though: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; - key | fruit ------+------- + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-------+----------+---------- (0 rows) -- Predicate changed to require match rather than non-match, so updates once more: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* = excluded.* returning *; - key | fruit ------+----------- - 23 | Jackfruit + where i.* = excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-----------+----------+---------- + 23 | Jackfruit | t | t (1 row) -- Assign: insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text - returning *; - key | fruit ------+-------------- - 23 | (23,Avocado) + returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+--------------+----------+---------- + 23 | (23,Avocado) | f | f (1 row) -- deparse whole row var in WHERE and SET clauses: @@ -472,6 +472,10 @@ insert into syscolconflicttest values (1) on conflict (key) do update set data = ERROR: column excluded.ctid does not exist LINE 1: ...values (1) on conflict (key) do update set data = excluded.c... ^ +insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.data returning excluded.ctid; +ERROR: column excluded.ctid does not exist +LINE 1: ...key) do update set data = excluded.data returning excluded.c... + ^ drop table syscolconflicttest; -- -- Previous tests all managed to not test any expressions requiring @@ -546,7 +550,13 @@ select * from capitals; -- Succeeds: insert into cities values ('Las Vegas', 2.583E+5, 2174) on conflict do nothing; -insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; + name | population | altitude | state | name | population | altitude | state | name | population | altitude | state +------------+------------+----------+-------+------------+------------+----------+-------+------------+------------+----------+------- + Sacramento | 369400 | 30 | CA | Sacramento | 466400000 | 30 | CA | Sacramento | 466400000 | 30 | CA +(1 row) + -- Wrong "Sacramento", so do nothing: insert into capitals values ('Sacramento', 50, 2267, 'NE') on conflict (name) do nothing; select * from capitals; @@ -556,7 +566,13 @@ select * from capitals; Sacramento | 466400000 | 30 | CA (2 rows) -insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; + name | population | altitude | name | population | altitude | name | population | altitude +-----------+------------+----------+-----------+------------+----------+-----------+------------+---------- + Las Vegas | 258300 | 2174 | Las Vegas | 583000 | 2001 | Las Vegas | 583000 | 2001 +(1 row) + select tableoid::regclass, * from cities; tableoid | name | population | altitude ----------+---------------+------------+---------- @@ -567,7 +583,13 @@ select tableoid::regclass, * from cities; capitals | Sacramento | 466400000 | 30 (5 rows) -insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; + name | population | altitude | state | name | population | altitude | state | name | population | altitude | state +------+------------+----------+-------+-----------+------------+----------+-------+------+------------+----------+------- + | | | | Las Vegas | 583000 | 2222 | NV | | | | +(1 row) + -- Capitals will contain new capital, Las Vegas: select * from capitals; name | population | altitude | state @@ -591,7 +613,13 @@ select tableoid::regclass, * from cities; (6 rows) -- This only affects "cities" version of "Las Vegas": -insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; + name | population | altitude | name | population | altitude | name | population | altitude +-----------+------------+----------+-----------+------------+----------+-----------+------------+---------- + Las Vegas | 583000 | 2001 | Las Vegas | 586000 | 2223 | Las Vegas | 586000 | 2223 +(1 row) + select tableoid::regclass, * from cities; tableoid | name | population | altitude ----------+---------------+------------+---------- @@ -628,11 +656,17 @@ insert into excluded AS target values(1, '2') on conflict (key) do update set da 1 | 2 (1 row) --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; - key | data ------+------ - 1 | 3 +ERROR: table reference "excluded" is ambiguous +LINE 1: ...n conflict (key) do update set data = 3 RETURNING excluded.*... + ^ +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; + key | data | key | data +-----+------+-----+------ + 1 | 3 | 1 | 2 (1 row) -- clean up diff --git a/src/test/regress/expected/returning.out b/src/test/regress/expected/returning.out index 341b689f766..4ad70c171b5 100644 --- a/src/test/regress/expected/returning.out +++ b/src/test/regress/expected/returning.out @@ -461,18 +461,19 @@ INSERT INTO foo VALUES (4) | | | | | | foo | (0,4) | 4 | | 42 | 99 | 4 | | 42 | 99 (1 row) --- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW +-- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW (and EXLCUDED) CREATE UNIQUE INDEX foo_f1_idx ON foo (f1); EXPLAIN (verbose, costs off) INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; - QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------------- + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Insert on pg_temp.foo - Output: (o.tableoid)::regclass, o.ctid, o.f1, o.f2, o.f3, o.f4, (n.tableoid)::regclass, n.ctid, n.f1, n.f2, n.f3, n.f4, foo.f1, foo.f2, foo.f3, foo.f4 + Output: (o.tableoid)::regclass, o.ctid, o.f1, o.f2, o.f3, o.f4, (n.tableoid)::regclass, n.ctid, n.f1, n.f2, n.f3, n.f4, foo.f1, foo.f2, foo.f3, foo.f4, excluded.f1, excluded.f2, excluded.f3, excluded.f4 Conflict Resolution: UPDATE Conflict Arbiter Indexes: foo_f1_idx -> Values Scan on "*VALUES*" @@ -483,11 +484,12 @@ INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; - tableoid | ctid | f1 | f2 | f3 | f4 | tableoid | ctid | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 -----------+-------+----+----+----+----+----------+-------+----+------------+----+----+----+------------+----+---- - foo | (0,4) | 4 | | 42 | 99 | foo | (0,5) | 4 | conflicted | -1 | 99 | 4 | conflicted | -1 | 99 - | | | | | | foo | (0,6) | 5 | ok | 42 | 99 | 5 | ok | 42 | 99 + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; + tableoid | ctid | f1 | f2 | f3 | f4 | tableoid | ctid | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 +----------+-------+----+----+----+----+----------+-------+----+------------+----+----+----+------------+----+----+----+----------+----+---- + foo | (0,4) | 4 | | 42 | 99 | foo | (0,5) | 4 | conflicted | -1 | 99 | 4 | conflicted | -1 | 99 | 4 | conflict | 42 | 99 + | | | | | | foo | (0,6) | 5 | ok | 42 | 99 | 5 | ok | 42 | 99 | | | | (2 rows) -- UPDATE has OLD and NEW diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index 6cf828ca8d0..d0e29060401 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -3527,6 +3527,67 @@ SELECT * FROM hat_data WHERE hat_name IN ('h8', 'h9', 'h7') ORDER BY hat_name; h9 | blue (3 rows) +DROP RULE hat_upsert ON hats; +-- DO UPDATE ... RETURNING excluded values +CREATE RULE hat_upsert AS ON INSERT TO hats + DO INSTEAD + INSERT INTO hat_data VALUES ( + NEW.hat_name, + NEW.hat_color) + ON CONFLICT (hat_name) + DO UPDATE + SET hat_name = hat_data.hat_name, hat_color = 'Excl: '||excluded.hat_color + WHERE excluded.hat_color <> 'forbidden' AND hat_data.* != excluded.* + RETURNING excluded.*; +SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename; + definition +--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE RULE hat_upsert AS + + ON INSERT TO public.hats DO INSTEAD INSERT INTO hat_data (hat_name, hat_color) + + VALUES (new.hat_name, new.hat_color) ON CONFLICT(hat_name) DO UPDATE SET hat_name = hat_data.hat_name, hat_color = ('Excl: '::text || (excluded.hat_color)::text)+ + WHERE ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) + + RETURNING excluded.hat_name, + + excluded.hat_color; +(1 row) + +-- EXCLUDED not allowed in plain INSERT +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING excluded.*; +ERROR: missing FROM-clause entry for table "excluded" +LINE 2: RETURNING excluded.*; + ^ +-- OLD/NEW have no effect on EXCLUDED +EXPLAIN (verbose, costs off) +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------- + Insert on public.hat_data + Output: excluded.hat_name, excluded.hat_color, excluded.hat_name, excluded.hat_color, excluded.hat_name, excluded.hat_color + Conflict Resolution: UPDATE + Conflict Arbiter Indexes: hat_data_unique_idx + Conflict Filter: ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) + -> Values Scan on "*VALUES*" + Output: "*VALUES*".column1, "*VALUES*".column2 +(7 rows) + +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; + hat_name | hat_color | hat_name | hat_color | hat_name | hat_color +------------+------------+------------+------------+------------+------------ + | | | | | + h8 | red | h8 | red | h8 | red +(2 rows) + +SELECT * FROM hat_data ORDER BY hat_name; + hat_name | hat_color +------------+------------ + h6 | black + h7 | black + h8 | Excl: red + h9 | blue +(4 rows) + DROP RULE hat_upsert ON hats; drop table hats; drop table hat_data; diff --git a/src/test/regress/expected/triggers.out b/src/test/regress/expected/triggers.out index 872b9100e1a..3aa1c11e670 100644 --- a/src/test/regress/expected/triggers.out +++ b/src/test/regress/expected/triggers.out @@ -1708,51 +1708,103 @@ end; $$; create trigger upsert_after_trig after insert or update on upsert for each row execute procedure upsert_after_func(); -insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color; +insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (1,black) WARNING: after insert (new): (1,black) -insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+-------+-----+------- + | | 1 | black | | +(1 row) + +insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (2,red) WARNING: before insert (new, modified): (3,"red trig modified") WARNING: after insert (new): (3,"red trig modified") -insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+-------------------+-----+------- + | | 3 | red trig modified | | +(1 row) + +insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (3,orange) WARNING: before update (old): (3,"red trig modified") WARNING: before update (new): (3,"updated red trig modified") WARNING: after update (old): (3,"red trig modified") WARNING: after update (new): (3,"updated red trig modified") -insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------------------+-----+---------------------------+-----+-------- + 3 | red trig modified | 3 | updated red trig modified | 3 | orange +(1 row) + +insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (4,green) WARNING: before insert (new, modified): (5,"green trig modified") WARNING: after insert (new): (5,"green trig modified") -insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+---------------------+-----+------- + | | 5 | green trig modified | | +(1 row) + +insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (5,purple) WARNING: before update (old): (5,"green trig modified") WARNING: before update (new): (5,"updated green trig modified") WARNING: after update (old): (5,"green trig modified") WARNING: after update (new): (5,"updated green trig modified") -insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+---------------------+-----+-----------------------------+-----+-------- + 5 | green trig modified | 5 | updated green trig modified | 5 | purple +(1 row) + +insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (6,white) WARNING: before insert (new, modified): (7,"white trig modified") WARNING: after insert (new): (7,"white trig modified") -insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+---------------------+-----+------- + | | 7 | white trig modified | | +(1 row) + +insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (7,pink) WARNING: before update (old): (7,"white trig modified") WARNING: before update (new): (7,"updated white trig modified") WARNING: after update (old): (7,"white trig modified") WARNING: after update (new): (7,"updated white trig modified") -insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+---------------------+-----+-----------------------------+-----+------- + 7 | white trig modified | 7 | updated white trig modified | 7 | pink +(1 row) + +insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (8,yellow) WARNING: before insert (new, modified): (9,"yellow trig modified") WARNING: after insert (new): (9,"yellow trig modified") + key | color | key | color | key | color +-----+-------+-----+----------------------+-----+------- + | | 9 | yellow trig modified | | +(1 row) + +insert into upsert values(8, 'gold') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +WARNING: before insert (new): (8,gold) +WARNING: before insert (new, modified): (9,"gold trig modified") +WARNING: before update (old): (9,"yellow trig modified") +WARNING: before update (new): (9,"updated yellow trig modified") +WARNING: after update (old): (9,"yellow trig modified") +WARNING: after update (new): (9,"updated yellow trig modified") + key | color | key | color | key | color +-----+----------------------+-----+------------------------------+-----+-------------------- + 9 | yellow trig modified | 9 | updated yellow trig modified | 9 | gold trig modified +(1 row) + select * from upsert; - key | color ------+----------------------------- + key | color +-----+------------------------------ 1 | black 3 | updated red trig modified 5 | updated green trig modified 7 | updated white trig modified - 9 | yellow trig modified + 9 | updated yellow trig modified (5 rows) drop table upsert; diff --git a/src/test/regress/expected/updatable_views.out b/src/test/regress/expected/updatable_views.out index 095df0a670c..e1bdcfb80bc 100644 --- a/src/test/regress/expected/updatable_views.out +++ b/src/test/regress/expected/updatable_views.out @@ -3653,7 +3653,13 @@ insert into uv_iocu_tab values ('xyxyxy', 0); create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- @@ -3661,7 +3667,13 @@ select * from uv_iocu_tab; (1 row) insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- @@ -3710,7 +3722,8 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; QUERY PLAN --------------------------------------------------------------------------------------------------------- Insert on uv_iocu_tab @@ -3724,7 +3737,13 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; + ?column? | ?column? | ?column? +--------------------+------------------------------------------------------------------------------+------------------------- + Old: (x,1,"(1,x)") | New: ("Rejected: (y,1,""(1,y)"")",1,"(1,""Rejected: (y,1,""""(1,y)"""")"")") | Excluded: (y,1,"(1,y)") +(1 row) + select * from uv_iocu_view; bb | aa | cc -------------------------+----+--------------------------------- diff --git a/src/test/regress/sql/arrays.sql b/src/test/regress/sql/arrays.sql index 47d62c1d38d..47a5d7c9d72 100644 --- a/src/test/regress/sql/arrays.sql +++ b/src/test/regress/sql/arrays.sql @@ -426,12 +426,17 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; -- note: if above selects don't produce the expected tuple order, -- then you didn't get an indexscan plan, and something is busted. diff --git a/src/test/regress/sql/generated_stored.sql b/src/test/regress/sql/generated_stored.sql index f56fde8d4e5..de3ceb7e8ad 100644 --- a/src/test/regress/sql/generated_stored.sql +++ b/src/test/regress/sql/generated_stored.sql @@ -58,6 +58,10 @@ INSERT INTO gtest1 VALUES (3, DEFAULT), (4, 44); -- error INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + SELECT * FROM gtest1 ORDER BY a; SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index e2b31853e01..9bbcbd4a20d 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -58,6 +58,10 @@ INSERT INTO gtest1 VALUES (3, DEFAULT), (4, 44); -- error INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + SELECT * FROM gtest1 ORDER BY a; SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink diff --git a/src/test/regress/sql/inherit.sql b/src/test/regress/sql/inherit.sql index 699e8ac09c8..da1d418abfc 100644 --- a/src/test/regress/sql/inherit.sql +++ b/src/test/regress/sql/inherit.sql @@ -806,7 +806,8 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; select * from inhpar order by f1; -- tuple order might be unstable here drop table inhpar cascade; diff --git a/src/test/regress/sql/insert_conflict.sql b/src/test/regress/sql/insert_conflict.sql index 549c46452ec..738dea09e44 100644 --- a/src/test/regress/sql/insert_conflict.sql +++ b/src/test/regress/sql/insert_conflict.sql @@ -101,8 +101,7 @@ insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -- Only suggest <table>.* column when inference element misspelled: @@ -238,16 +237,16 @@ create unique index plain on insertconflicttest(key); -- Succeeds, updates existing row: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- No update this time, though: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- Predicate changed to require match rather than non-match, so updates once more: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* = excluded.* returning *; + where i.* = excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- Assign: insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text - returning *; + returning *, excluded.* = old.*, excluded.* = new.*; -- deparse whole row var in WHERE and SET clauses: explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.fruit where excluded.* is null; explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text; @@ -267,6 +266,7 @@ drop table insertconflicttest; create table syscolconflicttest(key int4, data text); insert into syscolconflicttest values (1); insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.ctid::text; +insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.data returning excluded.ctid; drop table syscolconflicttest; -- @@ -344,20 +344,24 @@ select * from capitals; -- Succeeds: insert into cities values ('Las Vegas', 2.583E+5, 2174) on conflict do nothing; -insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; -- Wrong "Sacramento", so do nothing: insert into capitals values ('Sacramento', 50, 2267, 'NE') on conflict (name) do nothing; select * from capitals; -insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; select tableoid::regclass, * from cities; -insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; -- Capitals will contain new capital, Las Vegas: select * from capitals; -- Cities contains two instances of "Las Vegas", since unique constraints don't -- work across inheritance: select tableoid::regclass, * from cities; -- This only affects "cities" version of "Las Vegas": -insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; select tableoid::regclass, * from cities; -- clean up @@ -374,8 +378,11 @@ insert into excluded values(1, '2') on conflict (key) do update set data = exclu insert into excluded AS target values(1, '2') on conflict (key) do update set data = excluded.data RETURNING *; -- ok, aliased insert into excluded AS target values(1, '2') on conflict (key) do update set data = target.data RETURNING *; --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; -- clean up drop table excluded; diff --git a/src/test/regress/sql/returning.sql b/src/test/regress/sql/returning.sql index cc99cb53f63..00fa8a78c3d 100644 --- a/src/test/regress/sql/returning.sql +++ b/src/test/regress/sql/returning.sql @@ -209,19 +209,21 @@ INSERT INTO foo VALUES (4) RETURNING old.tableoid::regclass, old.ctid, old.*, new.tableoid::regclass, new.ctid, new.*, *; --- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW +-- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW (and EXLCUDED) CREATE UNIQUE INDEX foo_f1_idx ON foo (f1); EXPLAIN (verbose, costs off) INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; -- UPDATE has OLD and NEW EXPLAIN (verbose, costs off) diff --git a/src/test/regress/sql/rules.sql b/src/test/regress/sql/rules.sql index fdd3ff1d161..ed60cecbe7f 100644 --- a/src/test/regress/sql/rules.sql +++ b/src/test/regress/sql/rules.sql @@ -1205,6 +1205,33 @@ SELECT * FROM hat_data WHERE hat_name IN ('h8', 'h9', 'h7') ORDER BY hat_name; DROP RULE hat_upsert ON hats; +-- DO UPDATE ... RETURNING excluded values +CREATE RULE hat_upsert AS ON INSERT TO hats + DO INSTEAD + INSERT INTO hat_data VALUES ( + NEW.hat_name, + NEW.hat_color) + ON CONFLICT (hat_name) + DO UPDATE + SET hat_name = hat_data.hat_name, hat_color = 'Excl: '||excluded.hat_color + WHERE excluded.hat_color <> 'forbidden' AND hat_data.* != excluded.* + RETURNING excluded.*; +SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename; + +-- EXCLUDED not allowed in plain INSERT +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING excluded.*; + +-- OLD/NEW have no effect on EXCLUDED +EXPLAIN (verbose, costs off) +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; +SELECT * FROM hat_data ORDER BY hat_name; + +DROP RULE hat_upsert ON hats; + drop table hats; drop table hat_data; diff --git a/src/test/regress/sql/triggers.sql b/src/test/regress/sql/triggers.sql index d674b25c83b..88fbcd61c0f 100644 --- a/src/test/regress/sql/triggers.sql +++ b/src/test/regress/sql/triggers.sql @@ -1189,14 +1189,15 @@ $$; create trigger upsert_after_trig after insert or update on upsert for each row execute procedure upsert_after_func(); -insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color; +insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(8, 'gold') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; select * from upsert; diff --git a/src/test/regress/sql/updatable_views.sql b/src/test/regress/sql/updatable_views.sql index c071fffc116..91f45fa4509 100644 --- a/src/test/regress/sql/updatable_views.sql +++ b/src/test/regress/sql/updatable_views.sql @@ -1858,10 +1858,12 @@ create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; -- OK to access view columns that are not present in underlying base @@ -1892,12 +1894,14 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; select * from uv_iocu_view; -- Test omitting a column of the base relation diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 83192038571..c37554b6013 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2569,6 +2569,7 @@ ReturnSetInfo ReturnStmt ReturningClause ReturningExpr +ReturningExprKind ReturningOption ReturningOptionKind RevmapContents -- 2.43.0
^ permalink raw reply [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2025-07-25 08:42  Dean Rasheed <dean.a.rasheed@gmail.com>
  parent: Dean Rasheed <dean.a.rasheed@gmail.com>
  0 siblings, 1 reply; 17+ messages in thread

From: Dean Rasheed @ 2025-07-25 08:42 UTC (permalink / raw)
  To: Jim Jones <jim.jones@uni-muenster.de>; +Cc: pgsql-hackers

Rebased version attached, following 904f6a593a0.

Regards,
Dean

Attachments:

v4-0001-Allow-EXCLUDED-in-RETURNING-list-of-INSERT-ON-CON.patch (text/x-patch, 103.4K) download From a47423cc29abc8dc197fb895b55aace66d9da885 Mon Sep 17 00:00:00 2001 From: Dean Rasheed <dean.a.rasheed@gmail.com> Date: Fri, 25 Jul 2025 08:57:03 +0100 Subject: [PATCH v4] Allow EXCLUDED in RETURNING list of INSERT ON CONFLICT DO UPDATE. This allows an INSERT ... ON CONFLICT DO UPDATE command to return the excluded values, when conflicts occur. For rows that do not conflict, the excluded values returned are NULL. This builds on the infrastructure added to support OLD/NEW values in the RETURNING list, except that in the case of EXCLUDED, there is no need for the special syntax to change the name of the excluded pseudo-relation in the RETURNING list. (That was required for OLD/NEW, because those names were already used in some situations, such as trigger functions, but there is no such problem with excluded.) Discussion: https://postgr.es/m/CAEZATCXXu2ohYmn=4YrRQa9yNwD_fdEEOTBPgM_5jhQOFcaQ4g@mail.gmail.com --- doc/src/sgml/dml.sgml | 13 +++ doc/src/sgml/ref/insert.sgml | 42 ++++++--- src/backend/executor/execExpr.c | 44 +++++++-- src/backend/executor/execExprInterp.c | 21 ++++- src/backend/executor/execPartition.c | 14 +++ src/backend/executor/nodeModifyTable.c | 51 +++++++--- src/backend/optimizer/path/allpaths.c | 3 +- src/backend/optimizer/plan/setrefs.c | 77 ++++++++++------ src/backend/optimizer/prep/prepjointree.c | 22 +++-- src/backend/optimizer/prep/preptlist.c | 9 +- src/backend/optimizer/util/clauses.c | 2 +- src/backend/optimizer/util/var.c | 11 ++- src/backend/parser/analyze.c | 17 +++- src/backend/parser/parse_expr.c | 2 +- src/backend/parser/parse_relation.c | 4 +- src/backend/rewrite/rewriteHandler.c | 42 +++++---- src/backend/rewrite/rewriteManip.c | 69 ++++++++------ src/include/executor/execExpr.h | 7 +- src/include/nodes/execnodes.h | 2 + src/include/nodes/primnodes.h | 26 ++++-- src/include/parser/parse_node.h | 7 +- src/include/rewrite/rewriteManip.h | 4 +- src/test/regress/expected/arrays.out | 26 ++++-- .../regress/expected/generated_stored.out | 48 ++++++---- .../regress/expected/generated_virtual.out | 48 ++++++---- src/test/regress/expected/inherit.out | 9 +- src/test/regress/expected/insert_conflict.out | 92 +++++++++++++------ src/test/regress/expected/returning.out | 22 +++-- src/test/regress/expected/rules.out | 61 ++++++++++++ src/test/regress/expected/triggers.out | 74 ++++++++++++--- src/test/regress/expected/updatable_views.out | 27 +++++- src/test/regress/sql/arrays.sql | 9 +- src/test/regress/sql/generated_stored.sql | 4 + src/test/regress/sql/generated_virtual.sql | 4 + src/test/regress/sql/inherit.sql | 3 +- src/test/regress/sql/insert_conflict.sql | 29 +++--- src/test/regress/sql/returning.sql | 8 +- src/test/regress/sql/rules.sql | 27 ++++++ src/test/regress/sql/triggers.sql | 17 ++-- src/test/regress/sql/updatable_views.sql | 12 ++- src/tools/pgindent/typedefs.list | 1 + 41 files changed, 741 insertions(+), 269 deletions(-) diff --git a/doc/src/sgml/dml.sgml b/doc/src/sgml/dml.sgml index 458aee788b7..4712a49071b 100644 --- a/doc/src/sgml/dml.sgml +++ b/doc/src/sgml/dml.sgml @@ -392,6 +392,19 @@ UPDATE products SET price = price * 1.10 the new values may be non-<literal>NULL</literal>. </para> + <para> + In an <command>INSERT</command> with an <literal>ON CONFLICT DO UPDATE</literal> + clause, it is also possible to return the values excluded, if there is a + conflict. For example: +<programlisting> +INSERT INTO products AS p SELECT * FROM new_products + ON CONFLICT (product_no) DO UPDATE SET name = excluded.name + RETURNING p.product_no, p.name, excluded.price; +</programlisting> + Excluded values will be <literal>NULL</literal> for rows that do not + conflict. + </para> + <para> If there are triggers (<xref linkend="triggers"/>) on the target table, the data available to <literal>RETURNING</literal> is the row as modified by diff --git a/doc/src/sgml/ref/insert.sgml b/doc/src/sgml/ref/insert.sgml index 3f139917790..d1c056296a1 100644 --- a/doc/src/sgml/ref/insert.sgml +++ b/doc/src/sgml/ref/insert.sgml @@ -183,7 +183,7 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac This is particularly useful when <literal>ON CONFLICT DO UPDATE</literal> targets a table named <varname>excluded</varname>, since that will otherwise be taken as the name of the special table representing the row proposed - for insertion. + for insertion (see note below). </para> </listitem> </varlistentry> @@ -343,6 +343,35 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac with an <literal>ON CONFLICT DO UPDATE</literal> clause, the old values may be non-<literal>NULL</literal>. </para> + + <para> + If the <command>INSERT</command> has an <literal>ON CONFLICT DO + UPDATE</literal> clause, a column name or <literal>*</literal> may be + qualified using <literal>EXCLUDED</literal> to return the values + excluded from insertion, in the event of a conflict. If there is no + conflict, then all excluded values will be <literal>NULL</literal>. + </para> + + <note> + <para> + The special <varname>excluded</varname> table is made available + whenever an <command>INSERT</command> has an <literal>ON CONFLICT DO + UPDATE</literal> clause. It has the same columns as the target + table, and in the event of a conflict, it is populated with the + values that would have been inserted. This includes any values that + were supplied by defaults, as well as the effects of any per-row + <literal>BEFORE INSERT</literal> triggers, since those may have + contributed to the row being excluded from insertion. + </para> + <para> + The <varname>excluded</varname> table is accessible from the + <literal>SET</literal> and <literal>WHERE</literal> clauses of the + <literal>ON CONFLICT DO UPDATE</literal> action, and the + <literal>RETURNING</literal> list. <literal>SELECT</literal> + privilege is required on any columns in the target table where the + corresponding <varname>excluded</varname> columns are read. + </para> + </note> </listitem> </varlistentry> @@ -440,16 +469,7 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac <literal>WHERE</literal> clauses in <literal>ON CONFLICT DO UPDATE</literal> have access to the existing row using the table's name (or an alias), and to the row proposed for insertion - using the special <varname>excluded</varname> table. - <literal>SELECT</literal> privilege is required on any column in the - target table where corresponding <varname>excluded</varname> - columns are read. - </para> - <para> - Note that the effects of all per-row <literal>BEFORE - INSERT</literal> triggers are reflected in - <varname>excluded</varname> values, since those effects may - have contributed to the row being excluded from insertion. + using the special <varname>excluded</varname> table (see note above). </para> </listitem> </varlistentry> diff --git a/src/backend/executor/execExpr.c b/src/backend/executor/execExpr.c index f1569879b52..d13c82bdd30 100644 --- a/src/backend/executor/execExpr.c +++ b/src/backend/executor/execExpr.c @@ -455,6 +455,7 @@ ExecBuildProjectionInfo(List *targetList, /* * Get the tuple from the relation being scanned, or the * old/new tuple slot, if old/new values were requested. + * Should not see EXCLUDED here (should be INNER_VAR). */ switch (variable->varreturningtype) { @@ -469,6 +470,10 @@ ExecBuildProjectionInfo(List *targetList, scratch.opcode = EEOP_ASSIGN_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -972,6 +977,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_SYSVAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -1007,6 +1016,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -2638,10 +2651,23 @@ ExecInitExprRec(Expr *node, ExprState *state, ReturningExpr *rexpr = (ReturningExpr *) node; int retstep; - /* Skip expression evaluation if OLD/NEW row doesn't exist */ + /* + * Skip expression evaluation if OLD/NEW/EXCLUDED row doesn't + * exist. + */ scratch.opcode = EEOP_RETURNINGEXPR; - scratch.d.returningexpr.nullflag = rexpr->retold ? - EEO_FLAG_OLD_IS_NULL : EEO_FLAG_NEW_IS_NULL; + switch (rexpr->retkind) + { + case RETURNING_OLD_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_OLD_IS_NULL; + break; + case RETURNING_NEW_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_NEW_IS_NULL; + break; + case RETURNING_EXCLUDED_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_INNER_IS_NULL; + break; + } scratch.d.returningexpr.jumpdone = -1; /* set below */ ExprEvalPushStep(state, &scratch); retstep = state->steps_len - 1; @@ -2649,14 +2675,15 @@ ExecInitExprRec(Expr *node, ExprState *state, /* Steps to evaluate expression to return */ ExecInitExprRec(rexpr->retexpr, state, resv, resnull); - /* Jump target used if OLD/NEW row doesn't exist */ + /* Jump target used if OLD/NEW/EXCLUDED row doesn't exist */ state->steps[retstep].d.returningexpr.jumpdone = state->steps_len; /* Update ExprState flags */ - if (rexpr->retold) + if (rexpr->retkind == RETURNING_OLD_EXPR) state->flags |= EEO_FLAG_HAS_OLD; - else + else if (rexpr->retkind == RETURNING_NEW_EXPR) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ break; } @@ -3013,6 +3040,10 @@ expr_setup_walker(Node *node, ExprSetupInfo *info) case VAR_RETURNING_NEW: info->last_new = Max(info->last_new, attnum); break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -3178,6 +3209,7 @@ ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable, ExprState *state) state->flags |= EEO_FLAG_HAS_OLD; else if (variable->varreturningtype == VAR_RETURNING_NEW) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ /* * If the input tuple came from a subquery, it might contain "resjunk" diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c index 1a37737d4a2..4f5dece2aac 100644 --- a/src/backend/executor/execExprInterp.c +++ b/src/backend/executor/execExprInterp.c @@ -5339,7 +5339,21 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) switch (variable->varno) { case INNER_VAR: - /* get the tuple from the inner node */ + + /* + * Get the tuple from the inner node. + * + * In a RETURNING expression, this is used for EXCLUDED values in + * an INSERT ... ON CONFLICT DO UPDATE. If the non-conflicting + * branch is taken, the EXCLUDED row is NULL, and we return NULL + * rather than an all-NULL record. + */ + if (state->flags & EEO_FLAG_INNER_IS_NULL) + { + *op->resvalue = (Datum) 0; + *op->resnull = true; + return; + } slot = econtext->ecxt_innertuple; break; @@ -5384,6 +5398,11 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) } slot = econtext->ecxt_newtuple; break; + + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } diff --git a/src/backend/executor/execPartition.c b/src/backend/executor/execPartition.c index 514eae1037d..6adc07cbed3 100644 --- a/src/backend/executor/execPartition.c +++ b/src/backend/executor/execPartition.c @@ -642,12 +642,26 @@ ExecInitPartitionInfo(ModifyTableState *mtstate, EState *estate, /* * Convert Vars in it to contain this partition's attribute numbers. + * If we're doing an INSERT ... ON CONFLICT DO UPDATE, the RETURNING + * list might contain references to the EXCLUDED pseudo-relation + * (INNER_VAR), so we must map their attribute numbers too. */ if (part_attmap == NULL) part_attmap = build_attrmap_by_name(RelationGetDescr(partrel), RelationGetDescr(firstResultRel), false); + + if (node->onConflictAction == ONCONFLICT_UPDATE) + { + returningList = (List *) + map_variable_attnos((Node *) returningList, + INNER_VAR, 0, + part_attmap, + RelationGetForm(partrel)->reltype, + &found_whole_row); + /* We ignore the value of found_whole_row. */ + } returningList = (List *) map_variable_attnos((Node *) returningList, firstVarno, 0, diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c index 7c6c2c1f6e4..3a86c14ab2a 100644 --- a/src/backend/executor/nodeModifyTable.c +++ b/src/backend/executor/nodeModifyTable.c @@ -277,6 +277,7 @@ ExecCheckPlanOutput(Relation resultRel, List *targetList) * oldSlot: slot holding old tuple deleted or updated * newSlot: slot holding new tuple inserted or updated * planSlot: slot holding tuple returned by top subplan node + * exclSlot: slot holding EXCLUDED tuple (for INSERT ... ON CONFLICT ...) * * Note: If oldSlot and newSlot are NULL, the FDW should have already provided * econtext's scan tuple and its old & new tuples are not needed (FDW direct- @@ -290,8 +291,11 @@ ExecProcessReturning(ModifyTableContext *context, CmdType cmdType, TupleTableSlot *oldSlot, TupleTableSlot *newSlot, - TupleTableSlot *planSlot) + TupleTableSlot *planSlot, + TupleTableSlot *exclSlot) { + ModifyTableState *mtstate = context->mtstate; + ModifyTable *node = (ModifyTable *) mtstate->ps.plan; EState *estate = context->estate; ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning; ExprContext *econtext = projectReturning->pi_exprContext; @@ -332,10 +336,18 @@ ExecProcessReturning(ModifyTableContext *context, else econtext->ecxt_newtuple = NULL; /* No references to NEW columns */ + /* Make EXCLUDED tuple available to ExecProject, if required */ + if (exclSlot) + econtext->ecxt_innertuple = exclSlot; + else if (cmdType == CMD_INSERT && node->onConflictAction == ONCONFLICT_UPDATE) + econtext->ecxt_innertuple = ExecGetAllNullSlot(estate, resultRelInfo); + else + econtext->ecxt_innertuple = NULL; + /* - * Tell ExecProject whether or not the OLD/NEW rows actually exist. This - * information is required to evaluate ReturningExpr nodes and also in - * ExecEvalSysVar() and ExecEvalWholeRowVar(). + * Tell ExecProject whether or not the OLD/NEW/EXCLUDED rows actually + * exist. This information is required to evaluate ReturningExpr nodes + * and also in ExecEvalSysVar() and ExecEvalWholeRowVar(). */ if (oldSlot == NULL) projectReturning->pi_state.flags |= EEO_FLAG_OLD_IS_NULL; @@ -347,6 +359,11 @@ ExecProcessReturning(ModifyTableContext *context, else projectReturning->pi_state.flags &= ~EEO_FLAG_NEW_IS_NULL; + if (exclSlot == NULL) + projectReturning->pi_state.flags |= EEO_FLAG_INNER_IS_NULL; + else + projectReturning->pi_state.flags &= ~EEO_FLAG_INNER_IS_NULL; + /* Compute the RETURNING expressions */ return ExecProject(projectReturning); } @@ -1330,7 +1347,7 @@ ExecInsert(ModifyTableContext *context, } result = ExecProcessReturning(context, resultRelInfo, CMD_INSERT, - oldSlot, slot, planSlot); + oldSlot, slot, planSlot, NULL); /* * For a cross-partition UPDATE, release the old tuple, first making @@ -1891,7 +1908,7 @@ ldelete: } rslot = ExecProcessReturning(context, resultRelInfo, CMD_DELETE, - slot, NULL, context->planSlot); + slot, NULL, context->planSlot, NULL); /* * Before releasing the target tuple again, make sure rslot has a @@ -2451,6 +2468,8 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, * planSlot is the output of the ModifyTable's subplan; we use it * to access values from other input tables (for RETURNING), * row-ID junk columns, etc. + * exclSlot contains the EXCLUDED tuple if this is the auxiliary + * UPDATE of an INSERT ... ON CONFLICT DO UPDATE. * * Returns RETURNING result if any, otherwise NULL. On exit, if tupleid * had identified the tuple to update, it will identify the tuple @@ -2460,7 +2479,7 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, static TupleTableSlot * ExecUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *oldSlot, - TupleTableSlot *slot, bool canSetTag) + TupleTableSlot *slot, TupleTableSlot *exclSlot, bool canSetTag) { EState *estate = context->estate; Relation resultRelationDesc = resultRelInfo->ri_RelationDesc; @@ -2693,7 +2712,8 @@ redo_act: /* Process RETURNING if present */ if (resultRelInfo->ri_projectReturning) return ExecProcessReturning(context, resultRelInfo, CMD_UPDATE, - oldSlot, slot, context->planSlot); + oldSlot, slot, context->planSlot, + exclSlot); return NULL; } @@ -2915,6 +2935,7 @@ ExecOnConflictUpdate(ModifyTableContext *context, *returning = ExecUpdate(context, resultRelInfo, conflictTid, NULL, existing, resultRelInfo->ri_onConflict->oc_ProjSlot, + excludedSlot, canSetTag); /* @@ -3539,7 +3560,8 @@ lmerge_matched: CMD_UPDATE, resultRelInfo->ri_oldTupleSlot, newslot, - context->planSlot); + context->planSlot, + NULL); break; case CMD_DELETE: @@ -3548,7 +3570,8 @@ lmerge_matched: CMD_DELETE, resultRelInfo->ri_oldTupleSlot, NULL, - context->planSlot); + context->planSlot, + NULL); break; case CMD_NOTHING: @@ -4312,12 +4335,16 @@ ExecModifyTable(PlanState *pstate) * provide it here. The individual old and new slots are not * needed, since direct-modify is disabled if the RETURNING list * refers to OLD/NEW values. + * + * Currently, foreign tables do not support UNIQUE constraints, + * and therefore they do not support INSERT ... ON CONFLICT, and + * so the EXCLUDED slot is also not needed. */ Assert((resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD) == 0 && (resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_NEW) == 0); slot = ExecProcessReturning(&context, resultRelInfo, operation, - NULL, NULL, context.planSlot); + NULL, NULL, context.planSlot, NULL); return slot; } @@ -4507,7 +4534,7 @@ ExecModifyTable(PlanState *pstate) /* Now apply the update. */ slot = ExecUpdate(&context, resultRelInfo, tupleid, oldtuple, - oldSlot, slot, node->canSetTag); + oldSlot, slot, NULL, node->canSetTag); if (tuplock) UnlockTuple(resultRelInfo->ri_RelationDesc, tupleid, InplaceUpdateTupleLock); diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index 6cc6966b060..017a685959b 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -4013,8 +4013,7 @@ subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual) * each component query gets its own copy of the qual. */ qual = ReplaceVarsFromTargetList(qual, rti, 0, rte, - subquery->targetList, - subquery->resultRelation, + subquery->targetList, 0, REPLACEVARS_REPORT_ERROR, 0, &subquery->hasSubLinks); diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c index 846e44186c3..6d45e6e0c40 100644 --- a/src/backend/optimizer/plan/setrefs.c +++ b/src/backend/optimizer/plan/setrefs.c @@ -206,6 +206,8 @@ static List *set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset); static List *set_windowagg_runcondition_references(PlannerInfo *root, List *runcondition, @@ -1061,10 +1063,14 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) { ModifyTable *splan = (ModifyTable *) plan; Plan *subplan = outerPlan(splan); + indexed_tlist *excl_itlist = NULL; Assert(splan->plan.targetlist == NIL); Assert(splan->plan.qual == NIL); + if (splan->onConflictSet) + excl_itlist = build_tlist_index(splan->exclRelTlist); + splan->withCheckOptionLists = fix_scan_list(root, splan->withCheckOptionLists, rtoffset, 1); @@ -1090,6 +1096,8 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) rlist, subplan, resultrel, + splan->exclRelRTI, + excl_itlist, rtoffset); newRL = lappend(newRL, rlist); } @@ -1117,23 +1125,19 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) */ if (splan->onConflictSet) { - indexed_tlist *itlist; - - itlist = build_tlist_index(splan->exclRelTlist); - splan->onConflictSet = fix_join_expr(root, splan->onConflictSet, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); splan->onConflictWhere = (Node *) fix_join_expr(root, (List *) splan->onConflictWhere, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); - pfree(itlist); + pfree(excl_itlist); splan->exclRelTlist = fix_scan_list(root, splan->exclRelTlist, rtoffset, 1); @@ -2798,12 +2802,12 @@ build_tlist_index(List *tlist) * build_tlist_index_other_vars --- build a restricted tlist index * * This is like build_tlist_index, but we only index tlist entries that - * are Vars belonging to some rel other than the one specified. We will set + * are Vars belonging to some rel other than the ones specified. We will set * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars * (so nothing other than Vars and PlaceHolderVars can be matched). */ static indexed_tlist * -build_tlist_index_other_vars(List *tlist, int ignore_rel) +build_tlist_index_other_vars(List *tlist, int ignore_rel1, int ignore_rel2) { indexed_tlist *itlist; tlist_vinfo *vinfo; @@ -2828,7 +2832,7 @@ build_tlist_index_other_vars(List *tlist, int ignore_rel) { Var *var = (Var *) tle->expr; - if (var->varno != ignore_rel) + if (var->varno != ignore_rel1 && var->varno != ignore_rel2) { vinfo->varno = var->varno; vinfo->varattno = var->varattno; @@ -3067,10 +3071,14 @@ search_indexed_tlist_for_sortgroupref(Expr *node, * acceptable_rel should be zero so that any failure to match a Var will be * reported as an error. * 2) RETURNING clauses, which may contain both Vars of the target relation - * and Vars of other relations. In this case we want to replace the - * other-relation Vars by OUTER_VAR references, while leaving target Vars - * alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the - * target relation should be passed. + * and Vars of other relations, including the EXCLUDED pseudo-relation in + * an INSERT ... ON CONFLICT DO UPDATE command. In this case, we want to + * replace references to EXCLUDED with INNER_VAR references, and + * other-relation Vars with OUTER_VAR references, while leaving target Vars + * alone. Thus inner_itlist is to be EXCLUDED elements, if this is an + * INSERT with an ON CONFLICT DO UPDATE clause, outer_itlist is any other + * non-target relation elements, and acceptable_rel = the ID of the target + * relation. * 3) ON CONFLICT UPDATE SET/WHERE clauses. Here references to EXCLUDED are * to be replaced with INNER_VAR references, while leaving target Vars (the * to-be-updated relation) alone. Correspondingly inner_itlist is to be @@ -3131,15 +3139,16 @@ fix_join_expr_mutator(Node *node, fix_join_expr_context *context) /* * Verify that Vars with non-default varreturningtype only appear in - * the RETURNING list, and refer to the target relation. + * the RETURNING list, and that OLD/NEW Vars refer to the target + * relation. */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { - if (context->inner_itlist != NULL || - context->outer_itlist == NULL || + if (context->outer_itlist == NULL || context->acceptable_rel == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); - if (var->varno != context->acceptable_rel) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list"); + if (var->varreturningtype != VAR_RETURNING_EXCLUDED && + var->varno != context->acceptable_rel) elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new", var->varno, context->acceptable_rel); } @@ -3369,11 +3378,14 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * * If the query involves more than just the result table, we have to * adjust any Vars that refer to other tables to reference junk tlist - * entries in the top subplan's targetlist. Vars referencing the result - * table should be left alone, however (the executor will evaluate them - * using the actual heap tuple, after firing triggers if any). In the - * adjusted RETURNING list, result-table Vars will have their original - * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR. + * entries in the top subplan's targetlist. Vars referencing the EXCLUDED + * pseudo-relation of an INSERT ... ON CONFLICT DO UPDATE command should be + * adjusted to reference INNER_VAR, and Vars referencing the result table + * should be left alone (the executor will evaluate them using the actual heap + * tuple, after firing triggers if any). In the adjusted RETURNING list, + * result-table Vars will have their original varno (plus rtoffset), but Vars + * for the EXCLUDED pseudo-relation and other rels will have varno INNER_VAR + * and OUTER_VAR espectively. * * We also must perform opcode lookup and add regclass OIDs to * root->glob->relationOids. @@ -3382,6 +3394,8 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * 'topplan': the top subplan node that will be just below the ModifyTable * node (note it's not yet passed through set_plan_refs) * 'resultRelation': RT index of the associated result relation + * 'exclRelRTI': RT index of EXCLUDED pseudo-relation + * 'excl_itlist': EXCLUDED pseudo-relation elements (or NULL) * 'rtoffset': how much to increment varnos by * * Note: the given 'root' is for the parent query level, not the 'topplan'. @@ -3396,6 +3410,8 @@ set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset) { indexed_tlist *itlist; @@ -3403,9 +3419,11 @@ set_returning_clause_references(PlannerInfo *root, /* * We can perform the desired Var fixup by abusing the fix_join_expr * machinery that formerly handled inner indexscan fixup. We search the - * top plan's targetlist for Vars of non-result relations, and use - * fix_join_expr to convert RETURNING Vars into references to those tlist - * entries, while leaving result-rel Vars as-is. + * top plan's targetlist for Vars of non-result relations (other than + * EXCLUDED), and use fix_join_expr to convert RETURNING Vars into + * references to those tlist entries, and convert RETURNING EXCLUDED Vars + * into references to excl_itlist entries, while leaving result-rel Vars + * as-is. * * PlaceHolderVars will also be sought in the targetlist, but no * more-complex expressions will be. Note that it is not possible for a @@ -3414,12 +3432,13 @@ set_returning_clause_references(PlannerInfo *root, * prepared to pick apart the PlaceHolderVar and evaluate its contained * expression instead. */ - itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation); + itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation, + exclRelRTI); rlist = fix_join_expr(root, rlist, itlist, - NULL, + excl_itlist, resultRelation, rtoffset, NRM_EQUAL, diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index 35e8d3c183b..b859b30ba14 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -72,8 +72,7 @@ typedef struct pullup_replace_vars_context PlannerInfo *root; List *targetlist; /* tlist of subquery being pulled up */ RangeTblEntry *target_rte; /* RTE of subquery */ - int result_relation; /* the index of the result relation in the - * rewritten query */ + int new_target_varno; /* see ReplaceVarFromTargetList() */ Relids relids; /* relids within subquery, as numbered after * pullup (set only if target_rte->lateral) */ nullingrel_info *nullinfo; /* per-RTE nullingrel info (set only if @@ -537,11 +536,20 @@ expand_virtual_generated_columns(PlannerInfo *root, Query *parse, * insert into the query, except that we may need to wrap them in * PlaceHolderVars. Set up required context data for * pullup_replace_vars. + * + * In order to handle any Vars with non-default varreturningtype, + * new_target_varno should equal rt_index if it is the result relation + * or the EXCLUDED pseudo-relation. Otherwise, it should be 0. See + * comments in ReplaceVarFromTargetList(). */ rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = parse->resultRelation; + if (rt_index == parse->resultRelation || + (parse->onConflict && rt_index == parse->onConflict->exclRelIndex)) + rvcontext.new_target_varno = rt_index; + else + rvcontext.new_target_varno = 0; /* won't need these values */ rvcontext.relids = NULL; rvcontext.nullinfo = NULL; @@ -1496,7 +1504,7 @@ pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte, rvcontext.root = root; rvcontext.targetlist = subquery->targetList; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; if (rte->lateral) { rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree, @@ -2047,7 +2055,7 @@ pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte) rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; rvcontext.relids = NULL; /* can't be any lateral references here */ rvcontext.nullinfo = NULL; rvcontext.outer_hasSubLinks = &parse->hasSubLinks; @@ -2207,7 +2215,7 @@ pull_up_constant_function(PlannerInfo *root, Node *jtnode, NULL, /* resname */ false)); /* resjunk */ rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; /* * Since this function was reduced to a Const, it doesn't contain any @@ -2741,7 +2749,7 @@ pullup_replace_vars_callback(Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, REPLACEVARS_REPORT_ERROR, 0); diff --git a/src/backend/optimizer/prep/preptlist.c b/src/backend/optimizer/prep/preptlist.c index ffc9d6c3f30..098d8f8498a 100644 --- a/src/backend/optimizer/prep/preptlist.c +++ b/src/backend/optimizer/prep/preptlist.c @@ -291,7 +291,10 @@ preprocess_targetlist(PlannerInfo *root) * used in RETURNING that belong to other relations. We need to do this * to make these Vars available for the RETURNING calculation. Vars that * belong to the result rel don't need to be added, because they will be - * made to refer to the actual heap tuple. + * made to refer to the actual heap tuple. Vars that refer to the + * EXCLUDED pseudo-relation of an INSERT ... ON CONFLICT DO UPDATE command + * are also not needed, because they are handled specially in the + * executor. */ if (parse->returningList && list_length(parse->rtable) > 1) { @@ -308,7 +311,9 @@ preprocess_targetlist(PlannerInfo *root) TargetEntry *tle; if (IsA(var, Var) && - var->varno == result_relation) + (var->varno == result_relation || + (parse->onConflict && + var->varno == parse->onConflict->exclRelIndex))) continue; /* don't need it */ if (tlist_member((Expr *) var, tlist)) diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 6f0b338d2cd..20153b4f112 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -3418,7 +3418,7 @@ eval_const_expressions_mutator(Node *node, fselect->resulttypmod, fselect->resultcollid, ((Var *) arg)->varlevelsup); - /* New Var has same OLD/NEW returning as old one */ + /* New Var has same returningtype as old one */ newvar->varreturningtype = ((Var *) arg)->varreturningtype; /* New Var is nullable by same rels as the old one */ newvar->varnullingrels = ((Var *) arg)->varnullingrels; diff --git a/src/backend/optimizer/util/var.c b/src/backend/optimizer/util/var.c index 8065237a189..c2642c88e92 100644 --- a/src/backend/optimizer/util/var.c +++ b/src/backend/optimizer/util/var.c @@ -501,8 +501,8 @@ contain_vars_of_level_walker(Node *node, int *sublevels_up) * * Returns true if any found. * - * Any ReturningExprs are also detected --- if an OLD/NEW Var was rewritten, - * we still regard this as a clause that returns OLD/NEW values. + * Any ReturningExprs are also checked --- if an OLD/NEW Var was rewritten, we + * still regard this as a clause that returns OLD/NEW values. * * Does not examine subqueries, therefore must only be used after reduction * of sublinks to subplans! @@ -521,13 +521,16 @@ contain_vars_returning_old_or_new_walker(Node *node, void *context) if (IsA(node, Var)) { if (((Var *) node)->varlevelsup == 0 && - ((Var *) node)->varreturningtype != VAR_RETURNING_DEFAULT) + (((Var *) node)->varreturningtype == VAR_RETURNING_OLD || + ((Var *) node)->varreturningtype == VAR_RETURNING_NEW)) return true; /* abort the tree traversal and return true */ return false; } if (IsA(node, ReturningExpr)) { - if (((ReturningExpr *) node)->retlevelsup == 0) + if (((ReturningExpr *) node)->retlevelsup == 0 && + (((ReturningExpr *) node)->retkind == RETURNING_OLD_EXPR || + ((ReturningExpr *) node)->retkind == RETURNING_NEW_EXPR)) return true; /* abort the tree traversal and return true */ return false; } diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index 34f7c17f576..bf7ee465a14 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -1234,12 +1234,21 @@ transformOnConflictClause(ParseState *pstate, EXPR_KIND_WHERE, "WHERE"); /* - * Remove the EXCLUDED pseudo relation from the query namespace, since - * it's not supposed to be available in RETURNING. (Maybe someday we - * could allow that, and drop this step.) + * Leave the EXCLUDED pseudo relation in the query namespace so that + * it is available in RETURNING expressions, but change it to be a + * table-only item so that its columns are only accessible using + * qualified names. This ensures that columns from the target + * relation can be accessed using unqualified names without ambiguity. + * + * Also, set its returning_type so that any RETURNING list Vars + * referencing it are marked correctly. */ Assert((ParseNamespaceItem *) llast(pstate->p_namespace) == exclNSItem); - pstate->p_namespace = list_delete_last(pstate->p_namespace); + exclNSItem->p_cols_visible = false; + + exclNSItem->p_returning_type = VAR_RETURNING_EXCLUDED; + for (int i = 0; i < list_length(exclNSItem->p_names->colnames); i++) + exclNSItem->p_nscolumns[i].p_varreturningtype = VAR_RETURNING_EXCLUDED; } /* Finally, build ON CONFLICT DO [NOTHING | UPDATE] expression */ diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c index d66276801c6..e551c0bd7a1 100644 --- a/src/backend/parser/parse_expr.c +++ b/src/backend/parser/parse_expr.c @@ -2653,7 +2653,7 @@ transformWholeRowRef(ParseState *pstate, ParseNamespaceItem *nsitem, result = makeWholeRowVar(nsitem->p_rte, nsitem->p_rtindex, sublevels_up, true); - /* mark Var for RETURNING OLD/NEW, as necessary */ + /* mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ result->varreturningtype = nsitem->p_returning_type; /* location is not filled in by makeWholeRowVar */ diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c index 04ecf64b1fc..1651c52eb87 100644 --- a/src/backend/parser/parse_relation.c +++ b/src/backend/parser/parse_relation.c @@ -258,7 +258,7 @@ scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location) /* If not inside LATERAL, ignore lateral-only items */ if (nsitem->p_lateral_only && !pstate->p_lateral_active) continue; - /* Ignore OLD/NEW namespace items that can appear in RETURNING */ + /* Ignore OLD/NEW/EXCLUDED namespace items in RETURNING */ if (nsitem->p_returning_type != VAR_RETURNING_DEFAULT) continue; @@ -775,7 +775,7 @@ scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem, } var->location = location; - /* Mark Var for RETURNING OLD/NEW, as necessary */ + /* Mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ var->varreturningtype = nsitem->p_returning_type; /* Mark Var if it's nulled by any outer joins */ diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c index adc9e7600e1..7e24f2bd20e 100644 --- a/src/backend/rewrite/rewriteHandler.c +++ b/src/backend/rewrite/rewriteHandler.c @@ -97,7 +97,7 @@ static List *matchLocks(CmdType event, Relation relation, static Query *fireRIRrules(Query *parsetree, List *activeRIRs); static Bitmapset *adjust_view_column_set(Bitmapset *cols, List *targetlist); static Node *expand_generated_columns_internal(Node *node, Relation rel, int rt_index, - RangeTblEntry *rte, int result_relation); + RangeTblEntry *rte); /* @@ -643,7 +643,7 @@ rewriteRuleAction(Query *parsetree, 0, rt_fetch(new_varno, sub_action->rtable), parsetree->targetList, - sub_action->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -2346,7 +2346,7 @@ CopyAndAddInvertedQual(Query *parsetree, rt_fetch(rt_index, parsetree->rtable), parsetree->targetList, - parsetree->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -3705,12 +3705,12 @@ rewriteTargetView(Query *parsetree, Relation view) BuildOnConflictExcludedTargetlist(base_rel, new_exclRelIndex); /* - * Update all Vars in the ON CONFLICT clause that refer to the old - * EXCLUDED pseudo-relation. We want to use the column mappings - * defined in the view targetlist, but we need the outputs to refer to - * the new EXCLUDED pseudo-relation rather than the new target RTE. - * Also notice that "EXCLUDED.*" will be expanded using the view's - * rowtype, which seems correct. + * Update all Vars in the ON CONFLICT clause and RETURNING list that + * refer to the old EXCLUDED pseudo-relation. We want to use the + * column mappings defined in the view targetlist, but we need the + * outputs to refer to the new EXCLUDED pseudo-relation rather than + * the new target RTE. Also notice that "EXCLUDED.*" will be expanded + * using the view's rowtype, which seems correct. */ tmp_tlist = copyObject(view_targetlist); @@ -3723,7 +3723,18 @@ rewriteTargetView(Query *parsetree, Relation view) 0, view_rte, tmp_tlist, - new_rt_index, + 0, + REPLACEVARS_REPORT_ERROR, + 0, + &parsetree->hasSubLinks); + + parsetree->returningList = (List *) + ReplaceVarsFromTargetList((Node *) parsetree->returningList, + old_exclRelIndex, + 0, + view_rte, + tmp_tlist, + new_exclRelIndex, REPLACEVARS_REPORT_ERROR, 0, &parsetree->hasSubLinks); @@ -4421,13 +4432,11 @@ RewriteQuery(Query *parsetree, List *rewrite_events, int orig_rt_length) * virtual generated column expressions from rel, if there are any. * * The caller must also provide rte, the RTE describing the target relation, - * in order to handle any whole-row Vars referencing the target, and - * result_relation, the index of the result relation, if this is part of an - * INSERT/UPDATE/DELETE/MERGE query. + * in order to handle any whole-row Vars referencing the target. */ static Node * expand_generated_columns_internal(Node *node, Relation rel, int rt_index, - RangeTblEntry *rte, int result_relation) + RangeTblEntry *rte) { TupleDesc tupdesc; @@ -4455,8 +4464,7 @@ expand_generated_columns_internal(Node *node, Relation rel, int rt_index, Assert(list_length(tlist) > 0); - node = ReplaceVarsFromTargetList(node, rt_index, 0, rte, tlist, - result_relation, + node = ReplaceVarsFromTargetList(node, rt_index, 0, rte, tlist, 0, REPLACEVARS_CHANGE_VARNO, rt_index, NULL); } @@ -4485,7 +4493,7 @@ expand_generated_columns_in_expr(Node *node, Relation rel, int rt_index) rte->rtekind = RTE_RELATION; rte->relid = RelationGetRelid(rel); - node = expand_generated_columns_internal(node, rel, rt_index, rte, 0); + node = expand_generated_columns_internal(node, rel, rt_index, rte); } return node; diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index cd786aa4112..e5f85116f79 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -921,7 +921,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, /* * SetVarReturningType - adjust Var nodes for a specified varreturningtype. * - * Find all Var nodes referring to the specified result relation in the given + * Find all Var nodes referring to the specified relation in the given * expression and set their varreturningtype to the specified value. * * NOTE: although this has the form of a walker, we cheat and modify the @@ -931,7 +931,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, typedef struct { - int result_relation; + int target_varno; int sublevels_up; VarReturningType returning_type; } SetVarReturningType_context; @@ -945,7 +945,7 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) { Var *var = (Var *) node; - if (var->varno == context->result_relation && + if (var->varno == context->target_varno && var->varlevelsup == context->sublevels_up) var->varreturningtype = context->returning_type; @@ -967,12 +967,12 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) } static void -SetVarReturningType(Node *node, int result_relation, int sublevels_up, +SetVarReturningType(Node *node, int target_varno, int sublevels_up, VarReturningType returning_type) { SetVarReturningType_context context; - context.result_relation = result_relation; + context.target_varno = target_varno; context.sublevels_up = sublevels_up; context.returning_type = returning_type; @@ -1744,14 +1744,29 @@ map_variable_attnos(Node *node, * relation. This is needed to handle whole-row Vars referencing the target. * We expand such Vars into RowExpr constructs. * - * In addition, for INSERT/UPDATE/DELETE/MERGE queries, the caller must - * provide result_relation, the index of the result relation in the rewritten - * query. This is needed to handle OLD/NEW RETURNING list Vars referencing - * target_varno. When such Vars are expanded, their varreturningtype is - * copied onto any replacement Vars referencing result_relation. In addition, - * if the replacement expression from the targetlist is not simply a Var - * referencing result_relation, it is wrapped in a ReturningExpr node (causing - * the executor to return NULL if the OLD/NEW row doesn't exist). + * In addition, the caller should provide new_target_varno, which is needed to + * handle any OLD/NEW/EXCLUDED RETURNING list Vars (Vars with non-default + * varreturningtype) referencing target_varno. When such Vars are expanded, + * their varreturningtype is copied onto any Vars that reference + * new_target_varno in the replacement expression from the targetlist. In + * addition, if the replacement expression is not simply a Var referencing + * new_target_varno, it is wrapped in a ReturningExpr node (causing the + * executor to return NULL if the OLD/NEW/EXCLUDED row doesn't exist). The + * caller should set new_target_varno as follows: + * + * If the input node contains Vars from the RETURNING list of a query, and + * target_varno is the resultRelation of that query, then new_target_varno + * should be the (possibly new) resultRelation of the rewritten query. + * + * If the input node contains Vars from the RETURNING list of an INSERT ... + * ON CONFLICT DO UPDATE query, and target_varno is the index of the + * EXCLUDED pseudo-relation, then new_target_varno should be the (possibly + * new) index of the EXCLUDED pseudo-relation in the rewritten query. + * + * Otherwise, new_target_varno should be set to 0 in order to detect any + * Vars with non-default varreturningtype outside the RETURNING list, or + * referencing a relation other than the result relation or the EXCLUDED + * pseudo-relation. * * Note that ReplaceVarFromTargetList always generates the replacement * expression with varlevelsup = 0. The caller is responsible for adjusting @@ -1765,7 +1780,7 @@ typedef struct { RangeTblEntry *target_rte; List *targetlist; - int result_relation; + int new_target_varno; ReplaceVarsNoMatchOption nomatch_option; int nomatch_varno; } ReplaceVarsFromTargetList_context; @@ -1780,7 +1795,7 @@ ReplaceVarsFromTargetList_callback(Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, rcon->nomatch_option, rcon->nomatch_varno); @@ -1795,7 +1810,7 @@ Node * ReplaceVarFromTargetList(Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno) { @@ -1844,7 +1859,7 @@ ReplaceVarFromTargetList(Var *var, field = ReplaceVarFromTargetList((Var *) field, target_rte, targetlist, - result_relation, + new_target_varno, nomatch_option, nomatch_varno); rowexpr->args = lappend(rowexpr->args, field); @@ -1856,7 +1871,7 @@ ReplaceVarFromTargetList(Var *var, ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = (Expr *) rowexpr; return (Node *) rexpr; @@ -1925,28 +1940,28 @@ ReplaceVarFromTargetList(Var *var, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("NEW variables in ON UPDATE rules cannot reference columns that are part of a multiple assignment in the subject UPDATE command"))); - /* Handle any OLD/NEW RETURNING list Vars */ + /* Handle any OLD/NEW/EXCLUDED RETURNING list Vars */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { /* * Copy varreturningtype onto any Vars in the tlist item that - * refer to result_relation (which had better be non-zero). + * refer to new_target_varno (which had better be non-zero). */ - if (result_relation == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); + if (new_target_varno == 0) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list, or referencing a relation other than the result relation or the EXCLUDED pseudo-relation"); - SetVarReturningType((Node *) newnode, result_relation, + SetVarReturningType((Node *) newnode, new_target_varno, 0, var->varreturningtype); /* Wrap it in a ReturningExpr, if needed, per comments above */ if (!IsA(newnode, Var) || - ((Var *) newnode)->varno != result_relation || + ((Var *) newnode)->varno != new_target_varno || ((Var *) newnode)->varlevelsup != 0) { ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = newnode; newnode = (Expr *) rexpr; @@ -1962,7 +1977,7 @@ ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks) @@ -1971,7 +1986,7 @@ ReplaceVarsFromTargetList(Node *node, context.target_rte = target_rte; context.targetlist = targetlist; - context.result_relation = result_relation; + context.new_target_varno = new_target_varno; context.nomatch_option = nomatch_option; context.nomatch_varno = nomatch_varno; diff --git a/src/include/executor/execExpr.h b/src/include/executor/execExpr.h index 75366203706..1ce4d98afce 100644 --- a/src/include/executor/execExpr.h +++ b/src/include/executor/execExpr.h @@ -26,9 +26,9 @@ struct JsonConstructorExprState; /* Bits in ExprState->flags (see also execnodes.h for public flag bits): */ /* expression's interpreter has been initialized */ -#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 5) +#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 6) /* jump-threading is in use */ -#define EEO_FLAG_DIRECT_THREADED (1 << 6) +#define EEO_FLAG_DIRECT_THREADED (1 << 7) /* Typical API for out-of-line evaluation subroutines */ typedef void (*ExecEvalSubroutine) (ExprState *state, @@ -338,7 +338,8 @@ typedef struct ExprEvalStep /* but it's just the normal (negative) attr number for SYSVAR */ int attnum; Oid vartype; /* type OID of variable */ - VarReturningType varreturningtype; /* return old/new/default */ + /* if not default, return old/new/excluded value */ + VarReturningType varreturningtype; } var; /* for EEOP_WHOLEROW */ diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index e107d6e5f81..b40e76f2e2d 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -82,6 +82,8 @@ typedef Datum (*ExprStateEvalFunc) (struct ExprState *expression, #define EEO_FLAG_OLD_IS_NULL (1 << 3) /* NEW table row is NULL in RETURNING list */ #define EEO_FLAG_NEW_IS_NULL (1 << 4) +/* INNER (EXCLUDED) table row is NULL in RETURNING list */ +#define EEO_FLAG_INNER_IS_NULL (1 << 5) typedef struct ExprState { diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h index 6dfca3cb35b..a867814cd8f 100644 --- a/src/include/nodes/primnodes.h +++ b/src/include/nodes/primnodes.h @@ -227,7 +227,9 @@ typedef struct Expr * varreturningtype is used for Vars that refer to the target relation in the * RETURNING list of data-modifying queries. The default behavior is to * return old values for DELETE and new values for INSERT and UPDATE, but it - * is also possible to explicitly request old or new values. + * is also possible to explicitly request old or new values. For INSERT ... + * ON CONFLICT DO UPDATE, varreturningtype is also used for Vars in the + * RETURNING list that refer to the EXCLUDED pseudo-relation. * * In the parser, varnosyn and varattnosyn are either identical to * varno/varattno, or they specify the column's position in an aliased JOIN @@ -256,6 +258,7 @@ typedef enum VarReturningType VAR_RETURNING_DEFAULT, /* return OLD for DELETE, else return NEW */ VAR_RETURNING_OLD, /* return OLD for DELETE/UPDATE, else NULL */ VAR_RETURNING_NEW, /* return NEW for INSERT/UPDATE, else NULL */ + VAR_RETURNING_EXCLUDED, /* return EXCLUDED on conflict, else NULL */ } VarReturningType; typedef struct Var @@ -2140,14 +2143,15 @@ typedef struct InferenceElem } InferenceElem; /* - * ReturningExpr - return OLD/NEW.(expression) in RETURNING list + * ReturningExpr - return OLD/NEW/EXCLUDED.(expression) in RETURNING list * * This is used when updating an auto-updatable view and returning a view * column that is not simply a Var referring to the base relation. In such - * cases, OLD/NEW.viewcol can expand to an arbitrary expression, but the - * result is required to be NULL if the OLD/NEW row doesn't exist. To handle - * this, the rewriter wraps the expanded expression in a ReturningExpr, which - * is equivalent to "CASE WHEN (OLD/NEW row exists) THEN (expr) ELSE NULL". + * cases, OLD/NEW/EXCLUDED.viewcol can expand to an arbitrary expression, but + * the result is required to be NULL if the OLD/NEW/EXCLUDED row doesn't + * exist. To handle this, the rewriter wraps the expanded expression in a + * ReturningExpr, which is equivalent to "CASE WHEN (OLD/NEW/EXCLUDED row + * exists) THEN (expr) ELSE NULL". * * A similar situation can arise when rewriting the RETURNING clause of a * rule, which may also contain arbitrary expressions. @@ -2155,11 +2159,19 @@ typedef struct InferenceElem * ReturningExpr nodes never appear in a parsed Query --- they are only ever * inserted by the rewriter and the planner. */ +typedef enum ReturningExprKind +{ + /* values here match non-default VarReturningType values */ + RETURNING_OLD_EXPR = VAR_RETURNING_OLD, + RETURNING_NEW_EXPR = VAR_RETURNING_NEW, + RETURNING_EXCLUDED_EXPR = VAR_RETURNING_EXCLUDED, +} ReturningExprKind; + typedef struct ReturningExpr { Expr xpr; int retlevelsup; /* > 0 if it belongs to outer query */ - bool retold; /* true for OLD, false for NEW */ + ReturningExprKind retkind; /* return OLD/NEW/EXCLUDED expression */ Expr *retexpr; /* expression to be returned */ } ReturningExpr; diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h index f7d07c84542..1f0c21543b2 100644 --- a/src/include/parser/parse_node.h +++ b/src/include/parser/parse_node.h @@ -280,7 +280,8 @@ struct ParseState * forbid LATERAL references to an UPDATE/DELETE target table. * * While processing the RETURNING clause, special namespace items are added to - * refer to the OLD and NEW state of the result relation. These namespace + * refer to the OLD and NEW state of the result relation, and the EXCLUDED + * pseudo-relation for an INSERT ... ON CONFLICT DO UPDATE. These namespace * items have p_returning_type set appropriately, for use when creating Vars. * For convenience, this information is duplicated on each namespace column. * @@ -301,7 +302,7 @@ struct ParseNamespaceItem bool p_cols_visible; /* Column names visible as unqualified refs? */ bool p_lateral_only; /* Is only visible to LATERAL expressions? */ bool p_lateral_ok; /* If so, does join type allow use? */ - VarReturningType p_returning_type; /* Is OLD/NEW for use in RETURNING? */ + VarReturningType p_returning_type; /* for RETURNING OLD/NEW/EXCLUDED */ }; /* @@ -332,7 +333,7 @@ struct ParseNamespaceColumn Oid p_vartype; /* pg_type OID */ int32 p_vartypmod; /* type modifier value */ Oid p_varcollid; /* OID of collation, or InvalidOid */ - VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW */ + VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW/EXCLUDED */ Index p_varnosyn; /* rangetable index of syntactic referent */ AttrNumber p_varattnosyn; /* attribute number of syntactic referent */ bool p_dontexpand; /* not included in star expansion */ diff --git a/src/include/rewrite/rewriteManip.h b/src/include/rewrite/rewriteManip.h index 7c018f2a4e3..81a1493ad31 100644 --- a/src/include/rewrite/rewriteManip.h +++ b/src/include/rewrite/rewriteManip.h @@ -107,14 +107,14 @@ extern Node *map_variable_attnos(Node *node, extern Node *ReplaceVarFromTargetList(Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno); extern Node *ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks); diff --git a/src/test/regress/expected/arrays.out b/src/test/regress/expected/arrays.out index b815473f414..5a5a06e6a06 100644 --- a/src/test/regress/expected/arrays.out +++ b/src/test/regress/expected/arrays.out @@ -1398,20 +1398,30 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+--------- - 1 | {3,2,5} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+---------+------------- + 1 | {3,2,5} | {3,4,5} (1 row) insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+------------ - 1 | {6,7,NULL} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+------------+------------- + 1 | {6,7,NULL} | {6,7} +(1 row) + +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+----------------+------------- + 1 | {NULL,10,NULL} | [2:2]={10} (1 row) -- note: if above selects don't produce the expected tuple order, diff --git a/src/test/regress/expected/generated_stored.out b/src/test/regress/expected/generated_stored.out index adac2cedfb2..5eae1029550 100644 --- a/src/test/regress/expected/generated_stored.out +++ b/src/test/regress/expected/generated_stored.out @@ -114,32 +114,44 @@ INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error ERROR: cannot insert a non-DEFAULT value into column "b" DETAIL: Column "b" is a generated column. INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + a | b | a | b | a | b +---+---+-----+-----+---+--- + 4 | 8 | 104 | 208 | 4 | 8 + | | 5 | 10 | | +(2 rows) + SELECT * FROM gtest1 ORDER BY a; - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference - gtest1 --------- + gtest1 +----------- (1,2) (2,4) (3,6) - (4,8) -(4 rows) + (5,10) + (104,208) +(5 rows) SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) DELETE FROM gtest1 WHERE a >= 3; UPDATE gtest1 SET b = DEFAULT WHERE a = 1; diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index aca6347babe..2d15dcee07e 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -114,32 +114,44 @@ INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error ERROR: cannot insert a non-DEFAULT value into column "b" DETAIL: Column "b" is a generated column. INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + a | b | a | b | a | b +---+---+-----+-----+---+--- + 4 | 8 | 104 | 208 | 4 | 8 + | | 5 | 10 | | +(2 rows) + SELECT * FROM gtest1 ORDER BY a; - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference - gtest1 --------- + gtest1 +----------- (1,2) (2,4) (3,6) - (4,8) -(4 rows) + (5,10) + (104,208) +(5 rows) SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) DELETE FROM gtest1 WHERE a >= 3; UPDATE gtest1 SET b = DEFAULT WHERE a = 1; diff --git a/src/test/regress/expected/inherit.out b/src/test/regress/expected/inherit.out index 5b5055babdc..d32cd36bba0 100644 --- a/src/test/regress/expected/inherit.out +++ b/src/test/regress/expected/inherit.out @@ -2125,7 +2125,14 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; + old | new | excluded +--------+---------+---------- + (3,3-) | (3,3-+) | (3,) + (7,7-) | (7,7-+) | (7,) +(2 rows) + select * from inhpar order by f1; -- tuple order might be unstable here f1 | f2 ----+----- diff --git a/src/test/regress/expected/insert_conflict.out b/src/test/regress/expected/insert_conflict.out index fdd0f6c8f25..58017bb0eb6 100644 --- a/src/test/regress/expected/insert_conflict.out +++ b/src/test/regress/expected/insert_conflict.out @@ -249,13 +249,13 @@ insert into insertconflicttest values (2, 'Orange') on conflict (key, key, key) insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -ERROR: invalid reference to FROM-clause entry for table "excluded" -LINE 1: ...y) do update set fruit = excluded.fruit RETURNING excluded.f... - ^ -DETAIL: There is an entry for table "excluded", but it cannot be referenced from this part of the query. + fruit +------- + Apple +(1 row) + -- Only suggest <table>.* column when inference element misspelled: insert into insertconflicttest values (1, 'Apple') on conflict (keyy) do update set fruit = excluded.fruit; ERROR: column "keyy" does not exist @@ -408,33 +408,33 @@ drop index partial_key_index; create unique index plain on insertconflicttest(key); -- Succeeds, updates existing row: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; - key | fruit ------+----------- - 23 | Jackfruit + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-----------+----------+---------- + 23 | Jackfruit | f | t (1 row) -- No update this time, though: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; - key | fruit ------+------- + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-------+----------+---------- (0 rows) -- Predicate changed to require match rather than non-match, so updates once more: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* = excluded.* returning *; - key | fruit ------+----------- - 23 | Jackfruit + where i.* = excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-----------+----------+---------- + 23 | Jackfruit | t | t (1 row) -- Assign: insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text - returning *; - key | fruit ------+-------------- - 23 | (23,Avocado) + returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+--------------+----------+---------- + 23 | (23,Avocado) | f | f (1 row) -- deparse whole row var in WHERE and SET clauses: @@ -472,6 +472,10 @@ insert into syscolconflicttest values (1) on conflict (key) do update set data = ERROR: column excluded.ctid does not exist LINE 1: ...values (1) on conflict (key) do update set data = excluded.c... ^ +insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.data returning excluded.ctid; +ERROR: column excluded.ctid does not exist +LINE 1: ...key) do update set data = excluded.data returning excluded.c... + ^ drop table syscolconflicttest; -- -- Previous tests all managed to not test any expressions requiring @@ -546,7 +550,13 @@ select * from capitals; -- Succeeds: insert into cities values ('Las Vegas', 2.583E+5, 2174) on conflict do nothing; -insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; + name | population | altitude | state | name | population | altitude | state | name | population | altitude | state +------------+------------+----------+-------+------------+------------+----------+-------+------------+------------+----------+------- + Sacramento | 369400 | 30 | CA | Sacramento | 466400000 | 30 | CA | Sacramento | 466400000 | 30 | CA +(1 row) + -- Wrong "Sacramento", so do nothing: insert into capitals values ('Sacramento', 50, 2267, 'NE') on conflict (name) do nothing; select * from capitals; @@ -556,7 +566,13 @@ select * from capitals; Sacramento | 466400000 | 30 | CA (2 rows) -insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; + name | population | altitude | name | population | altitude | name | population | altitude +-----------+------------+----------+-----------+------------+----------+-----------+------------+---------- + Las Vegas | 258300 | 2174 | Las Vegas | 583000 | 2001 | Las Vegas | 583000 | 2001 +(1 row) + select tableoid::regclass, * from cities; tableoid | name | population | altitude ----------+---------------+------------+---------- @@ -567,7 +583,13 @@ select tableoid::regclass, * from cities; capitals | Sacramento | 466400000 | 30 (5 rows) -insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; + name | population | altitude | state | name | population | altitude | state | name | population | altitude | state +------+------------+----------+-------+-----------+------------+----------+-------+------+------------+----------+------- + | | | | Las Vegas | 583000 | 2222 | NV | | | | +(1 row) + -- Capitals will contain new capital, Las Vegas: select * from capitals; name | population | altitude | state @@ -591,7 +613,13 @@ select tableoid::regclass, * from cities; (6 rows) -- This only affects "cities" version of "Las Vegas": -insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; + name | population | altitude | name | population | altitude | name | population | altitude +-----------+------------+----------+-----------+------------+----------+-----------+------------+---------- + Las Vegas | 583000 | 2001 | Las Vegas | 586000 | 2223 | Las Vegas | 586000 | 2223 +(1 row) + select tableoid::regclass, * from cities; tableoid | name | population | altitude ----------+---------------+------------+---------- @@ -628,11 +656,17 @@ insert into excluded AS target values(1, '2') on conflict (key) do update set da 1 | 2 (1 row) --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; - key | data ------+------ - 1 | 3 +ERROR: table reference "excluded" is ambiguous +LINE 1: ...n conflict (key) do update set data = 3 RETURNING excluded.*... + ^ +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; + key | data | key | data +-----+------+-----+------ + 1 | 3 | 1 | 2 (1 row) -- clean up diff --git a/src/test/regress/expected/returning.out b/src/test/regress/expected/returning.out index 341b689f766..4ad70c171b5 100644 --- a/src/test/regress/expected/returning.out +++ b/src/test/regress/expected/returning.out @@ -461,18 +461,19 @@ INSERT INTO foo VALUES (4) | | | | | | foo | (0,4) | 4 | | 42 | 99 | 4 | | 42 | 99 (1 row) --- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW +-- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW (and EXLCUDED) CREATE UNIQUE INDEX foo_f1_idx ON foo (f1); EXPLAIN (verbose, costs off) INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; - QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------------- + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Insert on pg_temp.foo - Output: (o.tableoid)::regclass, o.ctid, o.f1, o.f2, o.f3, o.f4, (n.tableoid)::regclass, n.ctid, n.f1, n.f2, n.f3, n.f4, foo.f1, foo.f2, foo.f3, foo.f4 + Output: (o.tableoid)::regclass, o.ctid, o.f1, o.f2, o.f3, o.f4, (n.tableoid)::regclass, n.ctid, n.f1, n.f2, n.f3, n.f4, foo.f1, foo.f2, foo.f3, foo.f4, excluded.f1, excluded.f2, excluded.f3, excluded.f4 Conflict Resolution: UPDATE Conflict Arbiter Indexes: foo_f1_idx -> Values Scan on "*VALUES*" @@ -483,11 +484,12 @@ INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; - tableoid | ctid | f1 | f2 | f3 | f4 | tableoid | ctid | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 -----------+-------+----+----+----+----+----------+-------+----+------------+----+----+----+------------+----+---- - foo | (0,4) | 4 | | 42 | 99 | foo | (0,5) | 4 | conflicted | -1 | 99 | 4 | conflicted | -1 | 99 - | | | | | | foo | (0,6) | 5 | ok | 42 | 99 | 5 | ok | 42 | 99 + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; + tableoid | ctid | f1 | f2 | f3 | f4 | tableoid | ctid | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 +----------+-------+----+----+----+----+----------+-------+----+------------+----+----+----+------------+----+----+----+----------+----+---- + foo | (0,4) | 4 | | 42 | 99 | foo | (0,5) | 4 | conflicted | -1 | 99 | 4 | conflicted | -1 | 99 | 4 | conflict | 42 | 99 + | | | | | | foo | (0,6) | 5 | ok | 42 | 99 | 5 | ok | 42 | 99 | | | | (2 rows) -- UPDATE has OLD and NEW diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index dce8c672b40..e6c693cfde8 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -3531,6 +3531,67 @@ SELECT * FROM hat_data WHERE hat_name IN ('h8', 'h9', 'h7') ORDER BY hat_name; h9 | blue (3 rows) +DROP RULE hat_upsert ON hats; +-- DO UPDATE ... RETURNING excluded values +CREATE RULE hat_upsert AS ON INSERT TO hats + DO INSTEAD + INSERT INTO hat_data VALUES ( + NEW.hat_name, + NEW.hat_color) + ON CONFLICT (hat_name) + DO UPDATE + SET hat_name = hat_data.hat_name, hat_color = 'Excl: '||excluded.hat_color + WHERE excluded.hat_color <> 'forbidden' AND hat_data.* != excluded.* + RETURNING excluded.*; +SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename; + definition +--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE RULE hat_upsert AS + + ON INSERT TO public.hats DO INSTEAD INSERT INTO hat_data (hat_name, hat_color) + + VALUES (new.hat_name, new.hat_color) ON CONFLICT(hat_name) DO UPDATE SET hat_name = hat_data.hat_name, hat_color = ('Excl: '::text || (excluded.hat_color)::text)+ + WHERE ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) + + RETURNING excluded.hat_name, + + excluded.hat_color; +(1 row) + +-- EXCLUDED not allowed in plain INSERT +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING excluded.*; +ERROR: missing FROM-clause entry for table "excluded" +LINE 2: RETURNING excluded.*; + ^ +-- OLD/NEW have no effect on EXCLUDED +EXPLAIN (verbose, costs off) +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------- + Insert on public.hat_data + Output: excluded.hat_name, excluded.hat_color, excluded.hat_name, excluded.hat_color, excluded.hat_name, excluded.hat_color + Conflict Resolution: UPDATE + Conflict Arbiter Indexes: hat_data_unique_idx + Conflict Filter: ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) + -> Values Scan on "*VALUES*" + Output: "*VALUES*".column1, "*VALUES*".column2 +(7 rows) + +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; + hat_name | hat_color | hat_name | hat_color | hat_name | hat_color +------------+------------+------------+------------+------------+------------ + | | | | | + h8 | red | h8 | red | h8 | red +(2 rows) + +SELECT * FROM hat_data ORDER BY hat_name; + hat_name | hat_color +------------+------------ + h6 | black + h7 | black + h8 | Excl: red + h9 | blue +(4 rows) + DROP RULE hat_upsert ON hats; drop table hats; drop table hat_data; diff --git a/src/test/regress/expected/triggers.out b/src/test/regress/expected/triggers.out index 872b9100e1a..3aa1c11e670 100644 --- a/src/test/regress/expected/triggers.out +++ b/src/test/regress/expected/triggers.out @@ -1708,51 +1708,103 @@ end; $$; create trigger upsert_after_trig after insert or update on upsert for each row execute procedure upsert_after_func(); -insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color; +insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (1,black) WARNING: after insert (new): (1,black) -insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+-------+-----+------- + | | 1 | black | | +(1 row) + +insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (2,red) WARNING: before insert (new, modified): (3,"red trig modified") WARNING: after insert (new): (3,"red trig modified") -insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+-------------------+-----+------- + | | 3 | red trig modified | | +(1 row) + +insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (3,orange) WARNING: before update (old): (3,"red trig modified") WARNING: before update (new): (3,"updated red trig modified") WARNING: after update (old): (3,"red trig modified") WARNING: after update (new): (3,"updated red trig modified") -insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------------------+-----+---------------------------+-----+-------- + 3 | red trig modified | 3 | updated red trig modified | 3 | orange +(1 row) + +insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (4,green) WARNING: before insert (new, modified): (5,"green trig modified") WARNING: after insert (new): (5,"green trig modified") -insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+---------------------+-----+------- + | | 5 | green trig modified | | +(1 row) + +insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (5,purple) WARNING: before update (old): (5,"green trig modified") WARNING: before update (new): (5,"updated green trig modified") WARNING: after update (old): (5,"green trig modified") WARNING: after update (new): (5,"updated green trig modified") -insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+---------------------+-----+-----------------------------+-----+-------- + 5 | green trig modified | 5 | updated green trig modified | 5 | purple +(1 row) + +insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (6,white) WARNING: before insert (new, modified): (7,"white trig modified") WARNING: after insert (new): (7,"white trig modified") -insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+---------------------+-----+------- + | | 7 | white trig modified | | +(1 row) + +insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (7,pink) WARNING: before update (old): (7,"white trig modified") WARNING: before update (new): (7,"updated white trig modified") WARNING: after update (old): (7,"white trig modified") WARNING: after update (new): (7,"updated white trig modified") -insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+---------------------+-----+-----------------------------+-----+------- + 7 | white trig modified | 7 | updated white trig modified | 7 | pink +(1 row) + +insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (8,yellow) WARNING: before insert (new, modified): (9,"yellow trig modified") WARNING: after insert (new): (9,"yellow trig modified") + key | color | key | color | key | color +-----+-------+-----+----------------------+-----+------- + | | 9 | yellow trig modified | | +(1 row) + +insert into upsert values(8, 'gold') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +WARNING: before insert (new): (8,gold) +WARNING: before insert (new, modified): (9,"gold trig modified") +WARNING: before update (old): (9,"yellow trig modified") +WARNING: before update (new): (9,"updated yellow trig modified") +WARNING: after update (old): (9,"yellow trig modified") +WARNING: after update (new): (9,"updated yellow trig modified") + key | color | key | color | key | color +-----+----------------------+-----+------------------------------+-----+-------------------- + 9 | yellow trig modified | 9 | updated yellow trig modified | 9 | gold trig modified +(1 row) + select * from upsert; - key | color ------+----------------------------- + key | color +-----+------------------------------ 1 | black 3 | updated red trig modified 5 | updated green trig modified 7 | updated white trig modified - 9 | yellow trig modified + 9 | updated yellow trig modified (5 rows) drop table upsert; diff --git a/src/test/regress/expected/updatable_views.out b/src/test/regress/expected/updatable_views.out index 095df0a670c..e1bdcfb80bc 100644 --- a/src/test/regress/expected/updatable_views.out +++ b/src/test/regress/expected/updatable_views.out @@ -3653,7 +3653,13 @@ insert into uv_iocu_tab values ('xyxyxy', 0); create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- @@ -3661,7 +3667,13 @@ select * from uv_iocu_tab; (1 row) insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- @@ -3710,7 +3722,8 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; QUERY PLAN --------------------------------------------------------------------------------------------------------- Insert on uv_iocu_tab @@ -3724,7 +3737,13 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; + ?column? | ?column? | ?column? +--------------------+------------------------------------------------------------------------------+------------------------- + Old: (x,1,"(1,x)") | New: ("Rejected: (y,1,""(1,y)"")",1,"(1,""Rejected: (y,1,""""(1,y)"""")"")") | Excluded: (y,1,"(1,y)") +(1 row) + select * from uv_iocu_view; bb | aa | cc -------------------------+----+--------------------------------- diff --git a/src/test/regress/sql/arrays.sql b/src/test/regress/sql/arrays.sql index 47d62c1d38d..47a5d7c9d72 100644 --- a/src/test/regress/sql/arrays.sql +++ b/src/test/regress/sql/arrays.sql @@ -426,12 +426,17 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; -- note: if above selects don't produce the expected tuple order, -- then you didn't get an indexscan plan, and something is busted. diff --git a/src/test/regress/sql/generated_stored.sql b/src/test/regress/sql/generated_stored.sql index f56fde8d4e5..de3ceb7e8ad 100644 --- a/src/test/regress/sql/generated_stored.sql +++ b/src/test/regress/sql/generated_stored.sql @@ -58,6 +58,10 @@ INSERT INTO gtest1 VALUES (3, DEFAULT), (4, 44); -- error INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + SELECT * FROM gtest1 ORDER BY a; SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index ba19bc4c701..f5cba5dd8f3 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -58,6 +58,10 @@ INSERT INTO gtest1 VALUES (3, DEFAULT), (4, 44); -- error INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + SELECT * FROM gtest1 ORDER BY a; SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink diff --git a/src/test/regress/sql/inherit.sql b/src/test/regress/sql/inherit.sql index 699e8ac09c8..da1d418abfc 100644 --- a/src/test/regress/sql/inherit.sql +++ b/src/test/regress/sql/inherit.sql @@ -806,7 +806,8 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; select * from inhpar order by f1; -- tuple order might be unstable here drop table inhpar cascade; diff --git a/src/test/regress/sql/insert_conflict.sql b/src/test/regress/sql/insert_conflict.sql index 549c46452ec..738dea09e44 100644 --- a/src/test/regress/sql/insert_conflict.sql +++ b/src/test/regress/sql/insert_conflict.sql @@ -101,8 +101,7 @@ insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -- Only suggest <table>.* column when inference element misspelled: @@ -238,16 +237,16 @@ create unique index plain on insertconflicttest(key); -- Succeeds, updates existing row: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- No update this time, though: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- Predicate changed to require match rather than non-match, so updates once more: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* = excluded.* returning *; + where i.* = excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- Assign: insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text - returning *; + returning *, excluded.* = old.*, excluded.* = new.*; -- deparse whole row var in WHERE and SET clauses: explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.fruit where excluded.* is null; explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text; @@ -267,6 +266,7 @@ drop table insertconflicttest; create table syscolconflicttest(key int4, data text); insert into syscolconflicttest values (1); insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.ctid::text; +insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.data returning excluded.ctid; drop table syscolconflicttest; -- @@ -344,20 +344,24 @@ select * from capitals; -- Succeeds: insert into cities values ('Las Vegas', 2.583E+5, 2174) on conflict do nothing; -insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; -- Wrong "Sacramento", so do nothing: insert into capitals values ('Sacramento', 50, 2267, 'NE') on conflict (name) do nothing; select * from capitals; -insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; select tableoid::regclass, * from cities; -insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; -- Capitals will contain new capital, Las Vegas: select * from capitals; -- Cities contains two instances of "Las Vegas", since unique constraints don't -- work across inheritance: select tableoid::regclass, * from cities; -- This only affects "cities" version of "Las Vegas": -insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; select tableoid::regclass, * from cities; -- clean up @@ -374,8 +378,11 @@ insert into excluded values(1, '2') on conflict (key) do update set data = exclu insert into excluded AS target values(1, '2') on conflict (key) do update set data = excluded.data RETURNING *; -- ok, aliased insert into excluded AS target values(1, '2') on conflict (key) do update set data = target.data RETURNING *; --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; -- clean up drop table excluded; diff --git a/src/test/regress/sql/returning.sql b/src/test/regress/sql/returning.sql index cc99cb53f63..00fa8a78c3d 100644 --- a/src/test/regress/sql/returning.sql +++ b/src/test/regress/sql/returning.sql @@ -209,19 +209,21 @@ INSERT INTO foo VALUES (4) RETURNING old.tableoid::regclass, old.ctid, old.*, new.tableoid::regclass, new.ctid, new.*, *; --- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW +-- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW (and EXLCUDED) CREATE UNIQUE INDEX foo_f1_idx ON foo (f1); EXPLAIN (verbose, costs off) INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; -- UPDATE has OLD and NEW EXPLAIN (verbose, costs off) diff --git a/src/test/regress/sql/rules.sql b/src/test/regress/sql/rules.sql index fdd3ff1d161..ed60cecbe7f 100644 --- a/src/test/regress/sql/rules.sql +++ b/src/test/regress/sql/rules.sql @@ -1205,6 +1205,33 @@ SELECT * FROM hat_data WHERE hat_name IN ('h8', 'h9', 'h7') ORDER BY hat_name; DROP RULE hat_upsert ON hats; +-- DO UPDATE ... RETURNING excluded values +CREATE RULE hat_upsert AS ON INSERT TO hats + DO INSTEAD + INSERT INTO hat_data VALUES ( + NEW.hat_name, + NEW.hat_color) + ON CONFLICT (hat_name) + DO UPDATE + SET hat_name = hat_data.hat_name, hat_color = 'Excl: '||excluded.hat_color + WHERE excluded.hat_color <> 'forbidden' AND hat_data.* != excluded.* + RETURNING excluded.*; +SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename; + +-- EXCLUDED not allowed in plain INSERT +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING excluded.*; + +-- OLD/NEW have no effect on EXCLUDED +EXPLAIN (verbose, costs off) +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; +SELECT * FROM hat_data ORDER BY hat_name; + +DROP RULE hat_upsert ON hats; + drop table hats; drop table hat_data; diff --git a/src/test/regress/sql/triggers.sql b/src/test/regress/sql/triggers.sql index d674b25c83b..88fbcd61c0f 100644 --- a/src/test/regress/sql/triggers.sql +++ b/src/test/regress/sql/triggers.sql @@ -1189,14 +1189,15 @@ $$; create trigger upsert_after_trig after insert or update on upsert for each row execute procedure upsert_after_func(); -insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color; +insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(8, 'gold') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; select * from upsert; diff --git a/src/test/regress/sql/updatable_views.sql b/src/test/regress/sql/updatable_views.sql index c071fffc116..91f45fa4509 100644 --- a/src/test/regress/sql/updatable_views.sql +++ b/src/test/regress/sql/updatable_views.sql @@ -1858,10 +1858,12 @@ create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; -- OK to access view columns that are not present in underlying base @@ -1892,12 +1894,14 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; select * from uv_iocu_view; -- Test omitting a column of the base relation diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 4353befab99..eacdd69010d 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2573,6 +2573,7 @@ ReturnSetInfo ReturnStmt ReturningClause ReturningExpr +ReturningExprKind ReturningOption ReturningOptionKind RevmapContents -- 2.43.0
^ permalink raw reply [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2025-10-07 13:55  Viktor Holmberg <v@viktorh.net>
  0 siblings, 1 reply; 17+ messages in thread

From: Viktor Holmberg @ 2025-10-07 13:55 UTC (permalink / raw)
  To: pgsql-hackers

I’ve looked through this patch. As far as I can tell, everything looks good, working and well commented.
The only nitpick I could find is a mispelling "EXLCUDED" → "EXCLUDED" in src/test/regress/expected/returning.out:464.

A maybe bigger question, is it nice that EXCLUDED is null when no conflict occurred? I can see the logic, but I think ergonomics wise it’d be nicer to have the proposed values in EXCLUDED, no matter what happened later. Then one can check EXCLUDED.value = NEW.value to see if one’s changes were added, for example.

/Viktor
On 7 Oct 2025 at 15:43 +0200, Dean Rasheed <dean.a.rasheed@gmail.com>, wrote:
> Rebased version attached, following 904f6a593a0.
>
> Regards,
> Dean

^ permalink  raw  reply  [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2025-10-07 21:52  Dean Rasheed <dean.a.rasheed@gmail.com>
  parent: Viktor Holmberg <v@viktorh.net>
  0 siblings, 1 reply; 17+ messages in thread

From: Dean Rasheed @ 2025-10-07 21:52 UTC (permalink / raw)
  To: Viktor Holmberg <v@viktorh.net>; +Cc: pgsql-hackers

On Tue, 7 Oct 2025 at 14:56, Viktor Holmberg <v@viktorh.net> wrote:
>
> I’ve looked through this patch. As far as I can tell, everything looks good, working and well commented.
> The only nitpick I could find is a mispelling "EXLCUDED" → "EXCLUDED" in src/test/regress/expected/returning.out:464.

Thanks for looking. I'm also glad to see that you picked up the INSERT
... ON CONFLICT DO SELECT patch, because I think these 2 features
should work well together. I'll take another look at that one, but I'm
not going to have any time this week.

> A maybe bigger question, is it nice that EXCLUDED is null when no conflict occurred? I can see the logic, but I think ergonomics wise it’d be nicer to have the proposed values in EXCLUDED, no matter what happened later. Then one can check EXCLUDED.value = NEW.value to see if one’s changes were added, for example.

Hmm, I'm not sure. I think it would be counter-intuitive to have
non-null EXCLUDED values for rows that weren't excluded, and I think
it's just as easy to check what values were added either way.

Regards,
Dean





^ permalink  raw  reply  [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2025-10-08 08:51  v@viktorh.net <v@viktorh.net>
  parent: Dean Rasheed <dean.a.rasheed@gmail.com>
  0 siblings, 0 replies; 17+ messages in thread

From: v@viktorh.net @ 2025-10-08 08:51 UTC (permalink / raw)
  To: Dean Rasheed <dean.a.rasheed@gmail.com>; +Cc: Jim Jones <jim.jones@uni-muenster.de>; pgsql-hackers

(I realised I created a new thread by mistake, hopefully now I’ll get things back into the main one)

On 7 Oct 2025 at 23:52 +0200, Dean Rasheed <dean.a.rasheed@gmail.com>, wrote:
On Tue, 7 Oct 2025 at 14:56, Viktor Holmberg <v@viktorh.net> wrote:

I’ve looked through this patch. As far as I can tell, everything looks good, working and well commented.
The only nitpick I could find is a mispelling "EXLCUDED" → "EXCLUDED" in src/test/regress/expected/returning.out:464.

Thanks for looking. I'm also glad to see that you picked up the INSERT
... ON CONFLICT DO SELECT patch, because I think these 2 features
should work well together. I'll take another look at that one, but I'm
not going to have any time this week.
Agree. It’d be great if you could have a look, but no rush - I’m going on holiday now for a week anyway.

A maybe bigger question, is it nice that EXCLUDED is null when no conflict occurred? I can see the logic, but I think ergonomics wise it’d be nicer to have the proposed values in EXCLUDED, no matter what happened later. Then one can check EXCLUDED.value = NEW.value to see if one’s changes were added, for example.

Hmm, I'm not sure. I think it would be counter-intuitive to have
non-null EXCLUDED values for rows that weren't excluded, and I think
it's just as easy to check what values were added either way.
I see the point - I guess I think about EXCLUDED more as “PROPOSED”. I don’t have any examples at hand that would substantiate my point of view so it’s not a strong objection. In my opinion this patch adds value regardless, and you’re right that adapting the code to either case isn’t a big deal.

^ permalink  raw  reply  [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2025-10-08 09:20  Vik Fearing <vik@postgresfriends.org>
  parent: Dean Rasheed <dean.a.rasheed@gmail.com>
  0 siblings, 1 reply; 17+ messages in thread

From: Vik Fearing @ 2025-10-08 09:20 UTC (permalink / raw)
  To: Dean Rasheed <dean.a.rasheed@gmail.com>; Viktor Holmberg <v@viktorh.net>; +Cc: pgsql-hackers


On 07/10/2025 23:52, Dean Rasheed wrote:
> On Tue, 7 Oct 2025 at 14:56, Viktor Holmberg <v@viktorh.net> wrote:
>> A maybe bigger question, is it nice that EXCLUDED is null when no conflict occurred? I can see the logic, but I think ergonomics wise it’d be nicer to have the proposed values in EXCLUDED, no matter what happened later. Then one can check EXCLUDED.value = NEW.value to see if one’s changes were added, for example.
> Hmm, I'm not sure. I think it would be counter-intuitive to have
> non-null EXCLUDED values for rows that weren't excluded, and I think
> it's just as easy to check what values were added either way.


Agreed.  EXCLUDED should be null or even inaccessible if the row wasn't 
excluded.

-- 

Vik Fearing






^ permalink  raw  reply  [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2026-02-12 11:11  Dean Rasheed <dean.a.rasheed@gmail.com>
  parent: Vik Fearing <vik@postgresfriends.org>
  0 siblings, 1 reply; 17+ messages in thread

From: Dean Rasheed @ 2026-02-12 11:11 UTC (permalink / raw)
  To: Vik Fearing <vik@postgresfriends.org>; +Cc: Viktor Holmberg <v@viktorh.net>; pgsql-hackers

Rebased version attached (now also works with ON CONFLICT DO SELECT).

Regards,
Dean

Attachments:

v5-0001-Allow-EXCLUDED-in-RETURNING-list-of-INSERT-ON-CON.patch (text/x-patch, 106.8K) download From b81b24b0941895d91860cca5c4f41eda28a89da5 Mon Sep 17 00:00:00 2001 From: Dean Rasheed <dean.a.rasheed@gmail.com> Date: Thu, 12 Feb 2026 10:53:16 +0000 Subject: [PATCH v5] Allow EXCLUDED in RETURNING list of INSERT ON CONFLICT DO SELECT/UPDATE. This allows an INSERT ... ON CONFLICT DO SELECT/UPDATE command to return the excluded values, when conflicts occur. For rows that do not conflict, the excluded values returned are NULL. This builds on the infrastructure added to support OLD/NEW values in the RETURNING list, except that in the case of EXCLUDED, there is no need for the special syntax to change the name of the excluded pseudo-relation in the RETURNING list. (That was required for OLD/NEW, because those names were already used in some situations, such as trigger functions, but there is no such problem with excluded.) Discussion: https://postgr.es/m/CAEZATCXXu2ohYmn=4YrRQa9yNwD_fdEEOTBPgM_5jhQOFcaQ4g@mail.gmail.com --- doc/src/sgml/dml.sgml | 13 +++ doc/src/sgml/ref/insert.sgml | 45 ++++++-- src/backend/executor/execExpr.c | 44 ++++++- src/backend/executor/execExprInterp.c | 21 +++- src/backend/executor/execPartition.c | 15 +++ src/backend/executor/nodeModifyTable.c | 54 ++++++--- src/backend/optimizer/path/allpaths.c | 3 +- src/backend/optimizer/plan/setrefs.c | 78 ++++++++----- src/backend/optimizer/prep/prepjointree.c | 22 ++-- src/backend/optimizer/prep/preptlist.c | 9 +- src/backend/optimizer/util/clauses.c | 2 +- src/backend/optimizer/util/var.c | 11 +- src/backend/parser/analyze.c | 17 ++- src/backend/parser/parse_expr.c | 2 +- src/backend/parser/parse_relation.c | 4 +- src/backend/rewrite/rewriteHandler.c | 42 ++++--- src/backend/rewrite/rewriteManip.c | 69 ++++++----- src/include/executor/execExpr.h | 7 +- src/include/nodes/execnodes.h | 2 + src/include/nodes/primnodes.h | 26 +++-- src/include/parser/parse_node.h | 7 +- src/include/rewrite/rewriteManip.h | 4 +- src/test/regress/expected/arrays.out | 26 +++-- .../regress/expected/generated_stored.out | 48 +++++--- .../regress/expected/generated_virtual.out | 48 +++++--- src/test/regress/expected/inherit.out | 9 +- src/test/regress/expected/insert_conflict.out | 108 ++++++++++++------ src/test/regress/expected/returning.out | 22 ++-- src/test/regress/expected/rules.out | 61 ++++++++++ src/test/regress/expected/triggers.out | 64 +++++++++-- src/test/regress/expected/updatable_views.out | 27 ++++- src/test/regress/sql/arrays.sql | 9 +- src/test/regress/sql/generated_stored.sql | 4 + src/test/regress/sql/generated_virtual.sql | 4 + src/test/regress/sql/inherit.sql | 3 +- src/test/regress/sql/insert_conflict.sql | 33 +++--- src/test/regress/sql/returning.sql | 8 +- src/test/regress/sql/rules.sql | 27 +++++ src/test/regress/sql/triggers.sql | 18 +-- src/test/regress/sql/updatable_views.sql | 12 +- src/tools/pgindent/typedefs.list | 1 + 41 files changed, 747 insertions(+), 282 deletions(-) diff --git a/doc/src/sgml/dml.sgml b/doc/src/sgml/dml.sgml index cd348d5773a..89ffec1d4fe 100644 --- a/doc/src/sgml/dml.sgml +++ b/doc/src/sgml/dml.sgml @@ -392,6 +392,19 @@ UPDATE products SET price = price * 1.10 the new values may be non-<literal>NULL</literal>. </para> + <para> + In an <command>INSERT</command> with an + <literal>ON CONFLICT DO SELECT/UPDATE</literal> clause, it is also possible + to return the values excluded, if there is a conflict. For example: +<programlisting> +INSERT INTO products AS p SELECT * FROM new_products + ON CONFLICT (product_no) DO UPDATE SET name = excluded.name + RETURNING p.product_no, p.name, excluded.price; +</programlisting> + Excluded values will be <literal>NULL</literal> for rows that do not + conflict. + </para> + <para> If there are triggers (<xref linkend="triggers"/>) on the target table, the data available to <literal>RETURNING</literal> is the row as modified by diff --git a/doc/src/sgml/ref/insert.sgml b/doc/src/sgml/ref/insert.sgml index 121a9edcb99..753f51e3d56 100644 --- a/doc/src/sgml/ref/insert.sgml +++ b/doc/src/sgml/ref/insert.sgml @@ -187,10 +187,10 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac A substitute name for <replaceable class="parameter">table_name</replaceable>. When an alias is provided, it completely hides the actual name of the table. - This is particularly useful when <literal>ON CONFLICT DO UPDATE</literal> + This is particularly useful when <literal>ON CONFLICT DO SELECT/UPDATE</literal> targets a table named <varname>excluded</varname>, since that will otherwise be taken as the name of the special table representing the row proposed - for insertion. + for insertion (see note below). </para> </listitem> </varlistentry> @@ -353,6 +353,37 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac <literal>SELECT</literal> path is taken, the new values will be identical to the old values, since no modification takes place. </para> + + <para> + If the <command>INSERT</command> has an <literal>ON CONFLICT DO + SELECT/UPDATE</literal> clause, a column name or <literal>*</literal> + may be qualified using <literal>EXCLUDED</literal> to return the + values excluded from insertion, in the event of a conflict. If there + is no conflict, then all excluded values will be <literal>NULL</literal>. + </para> + + <note> + <para> + The special <varname>excluded</varname> table is made available + whenever an <command>INSERT</command> has an <literal>ON CONFLICT DO + SELECT/UPDATE</literal> clause. It has the same columns as the + target table, and in the event of a conflict, it is populated with + the values that would have been inserted. This includes any values + that were supplied by defaults, as well as the effects of any per-row + <literal>BEFORE INSERT</literal> triggers, since those may have + contributed to the row being excluded from insertion. + </para> + <para> + The <varname>excluded</varname> table is accessible from the + <literal>SET</literal> and <literal>WHERE</literal> clauses of an + <literal>ON CONFLICT DO UPDATE</literal> action, the + <literal>WHERE</literal> clause of an <literal>ON CONFLICT DO + SELECT</literal> action, and the <literal>RETURNING</literal> list. + <literal>SELECT</literal> privilege is required on any columns in the + target table where the corresponding <varname>excluded</varname> + columns are read. + </para> + </note> </listitem> </varlistentry> @@ -468,15 +499,7 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac <literal>DO SELECT</literal> and <literal>DO UPDATE</literal> have access to the existing row using the table's name (or an alias), and to the row proposed for insertion using the special - <varname>excluded</varname> table. <literal>SELECT</literal> - privilege is required on any column in the target table where - corresponding <varname>excluded</varname> columns are read. - </para> - <para> - Note that the effects of all per-row <literal>BEFORE - INSERT</literal> triggers are reflected in - <varname>excluded</varname> values, since those effects may - have contributed to the row being excluded from insertion. + <varname>excluded</varname> table (see note above). </para> </listitem> </varlistentry> diff --git a/src/backend/executor/execExpr.c b/src/backend/executor/execExpr.c index 088eca24021..6027af125ab 100644 --- a/src/backend/executor/execExpr.c +++ b/src/backend/executor/execExpr.c @@ -455,6 +455,7 @@ ExecBuildProjectionInfo(List *targetList, /* * Get the tuple from the relation being scanned, or the * old/new tuple slot, if old/new values were requested. + * Should not see EXCLUDED here (should be INNER_VAR). */ switch (variable->varreturningtype) { @@ -469,6 +470,10 @@ ExecBuildProjectionInfo(List *targetList, scratch.opcode = EEOP_ASSIGN_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -972,6 +977,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_SYSVAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -1007,6 +1016,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -2631,10 +2644,23 @@ ExecInitExprRec(Expr *node, ExprState *state, ReturningExpr *rexpr = (ReturningExpr *) node; int retstep; - /* Skip expression evaluation if OLD/NEW row doesn't exist */ + /* + * Skip expression evaluation if OLD/NEW/EXCLUDED row doesn't + * exist. + */ scratch.opcode = EEOP_RETURNINGEXPR; - scratch.d.returningexpr.nullflag = rexpr->retold ? - EEO_FLAG_OLD_IS_NULL : EEO_FLAG_NEW_IS_NULL; + switch (rexpr->retkind) + { + case RETURNING_OLD_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_OLD_IS_NULL; + break; + case RETURNING_NEW_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_NEW_IS_NULL; + break; + case RETURNING_EXCLUDED_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_INNER_IS_NULL; + break; + } scratch.d.returningexpr.jumpdone = -1; /* set below */ ExprEvalPushStep(state, &scratch); retstep = state->steps_len - 1; @@ -2642,14 +2668,15 @@ ExecInitExprRec(Expr *node, ExprState *state, /* Steps to evaluate expression to return */ ExecInitExprRec(rexpr->retexpr, state, resv, resnull); - /* Jump target used if OLD/NEW row doesn't exist */ + /* Jump target used if OLD/NEW/EXCLUDED row doesn't exist */ state->steps[retstep].d.returningexpr.jumpdone = state->steps_len; /* Update ExprState flags */ - if (rexpr->retold) + if (rexpr->retkind == RETURNING_OLD_EXPR) state->flags |= EEO_FLAG_HAS_OLD; - else + else if (rexpr->retkind == RETURNING_NEW_EXPR) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ break; } @@ -3008,6 +3035,10 @@ expr_setup_walker(Node *node, ExprSetupInfo *info) case VAR_RETURNING_NEW: info->last_new = Max(info->last_new, attnum); break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -3173,6 +3204,7 @@ ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable, ExprState *state) state->flags |= EEO_FLAG_HAS_OLD; else if (variable->varreturningtype == VAR_RETURNING_NEW) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ /* * If the input tuple came from a subquery, it might contain "resjunk" diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c index 61ff5ddc74c..f59405265f1 100644 --- a/src/backend/executor/execExprInterp.c +++ b/src/backend/executor/execExprInterp.c @@ -5343,7 +5343,21 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) switch (variable->varno) { case INNER_VAR: - /* get the tuple from the inner node */ + + /* + * Get the tuple from the inner node. + * + * In a RETURNING expression, this is used for EXCLUDED values in + * an INSERT ... ON CONFLICT DO SELECT/UPDATE. If the + * non-conflicting branch is taken, the EXCLUDED row is NULL, and + * we return NULL rather than an all-NULL record. + */ + if (state->flags & EEO_FLAG_INNER_IS_NULL) + { + *op->resvalue = (Datum) 0; + *op->resnull = true; + return; + } slot = econtext->ecxt_innertuple; break; @@ -5388,6 +5402,11 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) } slot = econtext->ecxt_newtuple; break; + + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } diff --git a/src/backend/executor/execPartition.c b/src/backend/executor/execPartition.c index bab294f5e91..6ce7eb7046b 100644 --- a/src/backend/executor/execPartition.c +++ b/src/backend/executor/execPartition.c @@ -708,12 +708,27 @@ ExecInitPartitionInfo(ModifyTableState *mtstate, EState *estate, /* * Convert Vars in it to contain this partition's attribute numbers. + * If we're doing an INSERT ... ON CONFLICT DO SELECT/UPDATE, the + * RETURNING list might contain references to the EXCLUDED + * pseudo-relation (INNER_VAR), so we must map their attribute numbers + * too. */ if (part_attmap == NULL) part_attmap = build_attrmap_by_name(RelationGetDescr(partrel), RelationGetDescr(firstResultRel), false); + + if (node->onConflictAction != ONCONFLICT_NONE) + { + returningList = (List *) + map_variable_attnos((Node *) returningList, + INNER_VAR, 0, + part_attmap, + RelationGetForm(partrel)->reltype, + &found_whole_row); + /* We ignore the value of found_whole_row. */ + } returningList = (List *) map_variable_attnos((Node *) returningList, firstVarno, 0, diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c index 6802fc13e95..d86a5d7194a 100644 --- a/src/backend/executor/nodeModifyTable.c +++ b/src/backend/executor/nodeModifyTable.c @@ -290,6 +290,7 @@ ExecCheckPlanOutput(Relation resultRel, List *targetList) * oldSlot: slot holding old tuple deleted or updated * newSlot: slot holding new tuple inserted or updated * planSlot: slot holding tuple returned by top subplan node + * exclSlot: slot holding EXCLUDED tuple (for INSERT ... ON CONFLICT ...) * * Note: If oldSlot and newSlot are NULL, the FDW should have already provided * econtext's scan tuple and its old & new tuples are not needed (FDW direct- @@ -306,8 +307,11 @@ ExecProcessReturning(ModifyTableContext *context, bool isDelete, TupleTableSlot *oldSlot, TupleTableSlot *newSlot, - TupleTableSlot *planSlot) + TupleTableSlot *planSlot, + TupleTableSlot *exclSlot) { + ModifyTableState *mtstate = context->mtstate; + ModifyTable *node = (ModifyTable *) mtstate->ps.plan; EState *estate = context->estate; ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning; ExprContext *econtext = projectReturning->pi_exprContext; @@ -342,10 +346,18 @@ ExecProcessReturning(ModifyTableContext *context, else econtext->ecxt_newtuple = NULL; /* No references to NEW columns */ + /* Make EXCLUDED tuple available to ExecProject, if required */ + if (exclSlot) + econtext->ecxt_innertuple = exclSlot; + else if (node->onConflictAction != ONCONFLICT_NONE) + econtext->ecxt_innertuple = ExecGetAllNullSlot(estate, resultRelInfo); + else + econtext->ecxt_innertuple = NULL; + /* - * Tell ExecProject whether or not the OLD/NEW rows actually exist. This - * information is required to evaluate ReturningExpr nodes and also in - * ExecEvalSysVar() and ExecEvalWholeRowVar(). + * Tell ExecProject whether or not the OLD/NEW/EXCLUDED rows actually + * exist. This information is required to evaluate ReturningExpr nodes + * and also in ExecEvalSysVar() and ExecEvalWholeRowVar(). */ if (oldSlot == NULL) projectReturning->pi_state.flags |= EEO_FLAG_OLD_IS_NULL; @@ -357,6 +369,11 @@ ExecProcessReturning(ModifyTableContext *context, else projectReturning->pi_state.flags &= ~EEO_FLAG_NEW_IS_NULL; + if (exclSlot == NULL) + projectReturning->pi_state.flags |= EEO_FLAG_INNER_IS_NULL; + else + projectReturning->pi_state.flags &= ~EEO_FLAG_INNER_IS_NULL; + /* Compute the RETURNING expressions */ return ExecProject(projectReturning); } @@ -1359,7 +1376,7 @@ ExecInsert(ModifyTableContext *context, } result = ExecProcessReturning(context, resultRelInfo, false, - oldSlot, slot, planSlot); + oldSlot, slot, planSlot, NULL); /* * For a cross-partition UPDATE, release the old tuple, first making @@ -1920,7 +1937,7 @@ ldelete: } rslot = ExecProcessReturning(context, resultRelInfo, true, - slot, NULL, context->planSlot); + slot, NULL, context->planSlot, NULL); /* * Before releasing the target tuple again, make sure rslot has a @@ -2480,6 +2497,8 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, * planSlot is the output of the ModifyTable's subplan; we use it * to access values from other input tables (for RETURNING), * row-ID junk columns, etc. + * exclSlot contains the EXCLUDED tuple if this is the auxiliary + * UPDATE of an INSERT ... ON CONFLICT DO SELECT/UPDATE. * * Returns RETURNING result if any, otherwise NULL. On exit, if tupleid * had identified the tuple to update, it will identify the tuple @@ -2489,7 +2508,7 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, static TupleTableSlot * ExecUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *oldSlot, - TupleTableSlot *slot, bool canSetTag) + TupleTableSlot *slot, TupleTableSlot *exclSlot, bool canSetTag) { EState *estate = context->estate; Relation resultRelationDesc = resultRelInfo->ri_RelationDesc; @@ -2722,7 +2741,8 @@ redo_act: /* Process RETURNING if present */ if (resultRelInfo->ri_projectReturning) return ExecProcessReturning(context, resultRelInfo, false, - oldSlot, slot, context->planSlot); + oldSlot, slot, context->planSlot, + exclSlot); return NULL; } @@ -2962,6 +2982,7 @@ ExecOnConflictUpdate(ModifyTableContext *context, *returning = ExecUpdate(context, resultRelInfo, conflictTid, NULL, existing, resultRelInfo->ri_onConflict->oc_ProjSlot, + excludedSlot, canSetTag); /* @@ -3094,7 +3115,8 @@ ExecOnConflictSelect(ModifyTableContext *context, Assert(resultRelInfo->ri_projectReturning); *returning = ExecProcessReturning(context, resultRelInfo, false, - existing, existing, context->planSlot); + existing, existing, context->planSlot, + excludedSlot); if (canSetTag) context->estate->es_processed++; @@ -3743,7 +3765,8 @@ lmerge_matched: false, resultRelInfo->ri_oldTupleSlot, newslot, - context->planSlot); + context->planSlot, + NULL); break; case CMD_DELETE: @@ -3752,7 +3775,8 @@ lmerge_matched: true, resultRelInfo->ri_oldTupleSlot, NULL, - context->planSlot); + context->planSlot, + NULL); break; case CMD_NOTHING: @@ -4516,13 +4540,17 @@ ExecModifyTable(PlanState *pstate) * provide it here. The individual old and new slots are not * needed, since direct-modify is disabled if the RETURNING list * refers to OLD/NEW values. + * + * Currently, foreign tables do not support UNIQUE constraints, + * and therefore they do not support INSERT ... ON CONFLICT DO + * SELECT/UPDATE, and so the EXCLUDED slot is also not needed. */ Assert((resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD) == 0 && (resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_NEW) == 0); slot = ExecProcessReturning(&context, resultRelInfo, operation == CMD_DELETE, - NULL, NULL, context.planSlot); + NULL, NULL, context.planSlot, NULL); return slot; } @@ -4716,7 +4744,7 @@ ExecModifyTable(PlanState *pstate) /* Now apply the update. */ slot = ExecUpdate(&context, resultRelInfo, tupleid, oldtuple, - oldSlot, slot, node->canSetTag); + oldSlot, slot, NULL, node->canSetTag); if (tuplock) UnlockTuple(resultRelInfo->ri_RelationDesc, tupleid, InplaceUpdateTupleLock); diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index 90275e25872..ab6c4e1fadc 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -4548,8 +4548,7 @@ subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual) * each component query gets its own copy of the qual. */ qual = ReplaceVarsFromTargetList(qual, rti, 0, rte, - subquery->targetList, - subquery->resultRelation, + subquery->targetList, 0, REPLACEVARS_REPORT_ERROR, 0, &subquery->hasSubLinks); diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c index 1b5b9b5ed9c..d86053a49e7 100644 --- a/src/backend/optimizer/plan/setrefs.c +++ b/src/backend/optimizer/plan/setrefs.c @@ -206,6 +206,8 @@ static List *set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset); static List *set_windowagg_runcondition_references(PlannerInfo *root, List *runcondition, @@ -1109,10 +1111,15 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) { ModifyTable *splan = (ModifyTable *) plan; Plan *subplan = outerPlan(splan); + indexed_tlist *excl_itlist = NULL; Assert(splan->plan.targetlist == NIL); Assert(splan->plan.qual == NIL); + if (splan->onConflictAction == ONCONFLICT_UPDATE || + splan->onConflictAction == ONCONFLICT_SELECT) + excl_itlist = build_tlist_index(splan->exclRelTlist); + splan->withCheckOptionLists = fix_scan_list(root, splan->withCheckOptionLists, rtoffset, 1); @@ -1138,6 +1145,8 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) rlist, subplan, resultrel, + splan->exclRelRTI, + excl_itlist, rtoffset); newRL = lappend(newRL, rlist); } @@ -1166,23 +1175,19 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) if (splan->onConflictAction == ONCONFLICT_UPDATE || splan->onConflictAction == ONCONFLICT_SELECT) { - indexed_tlist *itlist; - - itlist = build_tlist_index(splan->exclRelTlist); - splan->onConflictSet = fix_join_expr(root, splan->onConflictSet, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); splan->onConflictWhere = (Node *) fix_join_expr(root, (List *) splan->onConflictWhere, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); - pfree(itlist); + pfree(excl_itlist); splan->exclRelTlist = fix_scan_list(root, splan->exclRelTlist, rtoffset, 1); @@ -2874,12 +2879,12 @@ build_tlist_index(List *tlist) * build_tlist_index_other_vars --- build a restricted tlist index * * This is like build_tlist_index, but we only index tlist entries that - * are Vars belonging to some rel other than the one specified. We will set + * are Vars belonging to some rel other than the ones specified. We will set * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars * (so nothing other than Vars and PlaceHolderVars can be matched). */ static indexed_tlist * -build_tlist_index_other_vars(List *tlist, int ignore_rel) +build_tlist_index_other_vars(List *tlist, int ignore_rel1, int ignore_rel2) { indexed_tlist *itlist; tlist_vinfo *vinfo; @@ -2904,7 +2909,7 @@ build_tlist_index_other_vars(List *tlist, int ignore_rel) { Var *var = (Var *) tle->expr; - if (var->varno != ignore_rel) + if (var->varno != ignore_rel1 && var->varno != ignore_rel2) { vinfo->varno = var->varno; vinfo->varattno = var->varattno; @@ -3143,10 +3148,14 @@ search_indexed_tlist_for_sortgroupref(Expr *node, * acceptable_rel should be zero so that any failure to match a Var will be * reported as an error. * 2) RETURNING clauses, which may contain both Vars of the target relation - * and Vars of other relations. In this case we want to replace the - * other-relation Vars by OUTER_VAR references, while leaving target Vars - * alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the - * target relation should be passed. + * and Vars of other relations, including the EXCLUDED pseudo-relation in + * an INSERT ... ON CONFLICT DO SELECT/UPDATE command. In this case, we + * want to replace references to EXCLUDED with INNER_VAR references, and + * other-relation Vars with OUTER_VAR references, while leaving target Vars + * alone. Thus inner_itlist is to be EXCLUDED elements, if this is an + * INSERT with an ON CONFLICT DO SELECT/UPDATE clause, outer_itlist is any + * other non-target relation elements, and acceptable_rel = the ID of the + * target relation. * 3) ON CONFLICT SET and WHERE clauses. Here references to EXCLUDED are * to be replaced with INNER_VAR references, while leaving target Vars (the * to-be-updated relation) alone. Correspondingly inner_itlist is to be @@ -3207,15 +3216,16 @@ fix_join_expr_mutator(Node *node, fix_join_expr_context *context) /* * Verify that Vars with non-default varreturningtype only appear in - * the RETURNING list, and refer to the target relation. + * the RETURNING list, and that OLD/NEW Vars refer to the target + * relation. */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { - if (context->inner_itlist != NULL || - context->outer_itlist == NULL || + if (context->outer_itlist == NULL || context->acceptable_rel == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); - if (var->varno != context->acceptable_rel) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list"); + if (var->varreturningtype != VAR_RETURNING_EXCLUDED && + var->varno != context->acceptable_rel) elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new", var->varno, context->acceptable_rel); } @@ -3445,11 +3455,14 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * * If the query involves more than just the result table, we have to * adjust any Vars that refer to other tables to reference junk tlist - * entries in the top subplan's targetlist. Vars referencing the result - * table should be left alone, however (the executor will evaluate them - * using the actual heap tuple, after firing triggers if any). In the - * adjusted RETURNING list, result-table Vars will have their original - * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR. + * entries in the top subplan's targetlist. Vars referencing the EXCLUDED + * pseudo-relation of an INSERT ... ON CONFLICT DO SELECT/UPDATE command + * should be adjusted to reference INNER_VAR, and Vars referencing the result + * table should be left alone (the executor will evaluate them using the + * actual heap tuple, after firing triggers if any). In the adjusted RETURNING + * list, result-table Vars will have their original varno (plus rtoffset), but + * Vars for the EXCLUDED pseudo-relation and other rels will have varno + * INNER_VAR and OUTER_VAR espectively. * * We also must perform opcode lookup and add regclass OIDs to * root->glob->relationOids. @@ -3458,6 +3471,8 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * 'topplan': the top subplan node that will be just below the ModifyTable * node (note it's not yet passed through set_plan_refs) * 'resultRelation': RT index of the associated result relation + * 'exclRelRTI': RT index of EXCLUDED pseudo-relation + * 'excl_itlist': EXCLUDED pseudo-relation elements (or NULL) * 'rtoffset': how much to increment varnos by * * Note: the given 'root' is for the parent query level, not the 'topplan'. @@ -3472,6 +3487,8 @@ set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset) { indexed_tlist *itlist; @@ -3479,9 +3496,11 @@ set_returning_clause_references(PlannerInfo *root, /* * We can perform the desired Var fixup by abusing the fix_join_expr * machinery that formerly handled inner indexscan fixup. We search the - * top plan's targetlist for Vars of non-result relations, and use - * fix_join_expr to convert RETURNING Vars into references to those tlist - * entries, while leaving result-rel Vars as-is. + * top plan's targetlist for Vars of non-result relations (other than + * EXCLUDED), and use fix_join_expr to convert RETURNING Vars into + * references to those tlist entries, and convert RETURNING EXCLUDED Vars + * into references to excl_itlist entries, while leaving result-rel Vars + * as-is. * * PlaceHolderVars will also be sought in the targetlist, but no * more-complex expressions will be. Note that it is not possible for a @@ -3490,12 +3509,13 @@ set_returning_clause_references(PlannerInfo *root, * prepared to pick apart the PlaceHolderVar and evaluate its contained * expression instead. */ - itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation); + itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation, + exclRelRTI); rlist = fix_join_expr(root, rlist, itlist, - NULL, + excl_itlist, resultRelation, rtoffset, NRM_EQUAL, diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index c90f4b32733..a5d9823e3b1 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -72,8 +72,7 @@ typedef struct pullup_replace_vars_context PlannerInfo *root; List *targetlist; /* tlist of subquery being pulled up */ RangeTblEntry *target_rte; /* RTE of subquery */ - int result_relation; /* the index of the result relation in the - * rewritten query */ + int new_target_varno; /* see ReplaceVarFromTargetList() */ Relids relids; /* relids within subquery, as numbered after * pullup (set only if target_rte->lateral) */ nullingrel_info *nullinfo; /* per-RTE nullingrel info (set only if @@ -541,11 +540,20 @@ expand_virtual_generated_columns(PlannerInfo *root, Query *parse, * insert into the query, except that we may need to wrap them in * PlaceHolderVars. Set up required context data for * pullup_replace_vars. + * + * In order to handle any Vars with non-default varreturningtype, + * new_target_varno should equal rt_index if it is the result relation + * or the EXCLUDED pseudo-relation. Otherwise, it should be 0. See + * comments in ReplaceVarFromTargetList(). */ rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = parse->resultRelation; + if (rt_index == parse->resultRelation || + (parse->onConflict && rt_index == parse->onConflict->exclRelIndex)) + rvcontext.new_target_varno = rt_index; + else + rvcontext.new_target_varno = 0; /* won't need these values */ rvcontext.relids = NULL; rvcontext.nullinfo = NULL; @@ -1504,7 +1512,7 @@ pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte, rvcontext.root = root; rvcontext.targetlist = subquery->targetList; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; if (rte->lateral) { rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree, @@ -2055,7 +2063,7 @@ pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte) rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; rvcontext.relids = NULL; /* can't be any lateral references here */ rvcontext.nullinfo = NULL; rvcontext.outer_hasSubLinks = &parse->hasSubLinks; @@ -2215,7 +2223,7 @@ pull_up_constant_function(PlannerInfo *root, Node *jtnode, NULL, /* resname */ false)); /* resjunk */ rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; /* * Since this function was reduced to a Const, it doesn't contain any @@ -2749,7 +2757,7 @@ pullup_replace_vars_callback(Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, REPLACEVARS_REPORT_ERROR, 0); diff --git a/src/backend/optimizer/prep/preptlist.c b/src/backend/optimizer/prep/preptlist.c index ff9c7c4fb96..a22b65af2b3 100644 --- a/src/backend/optimizer/prep/preptlist.c +++ b/src/backend/optimizer/prep/preptlist.c @@ -291,7 +291,10 @@ preprocess_targetlist(PlannerInfo *root) * used in RETURNING that belong to other relations. We need to do this * to make these Vars available for the RETURNING calculation. Vars that * belong to the result rel don't need to be added, because they will be - * made to refer to the actual heap tuple. + * made to refer to the actual heap tuple. Vars that refer to the + * EXCLUDED pseudo-relation of an INSERT ... ON CONFLICT DO SELECT/UPDATE + * command are also not needed, because they are handled specially in the + * executor. */ if (parse->returningList && list_length(parse->rtable) > 1) { @@ -308,7 +311,9 @@ preprocess_targetlist(PlannerInfo *root) TargetEntry *tle; if (IsA(var, Var) && - var->varno == result_relation) + (var->varno == result_relation || + (parse->onConflict && + var->varno == parse->onConflict->exclRelIndex))) continue; /* don't need it */ if (tlist_member((Expr *) var, tlist)) diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 504a30d8836..943725234ae 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -3519,7 +3519,7 @@ eval_const_expressions_mutator(Node *node, fselect->resulttypmod, fselect->resultcollid, ((Var *) arg)->varlevelsup); - /* New Var has same OLD/NEW returning as old one */ + /* New Var has same returningtype as old one */ newvar->varreturningtype = ((Var *) arg)->varreturningtype; /* New Var is nullable by same rels as the old one */ newvar->varnullingrels = ((Var *) arg)->varnullingrels; diff --git a/src/backend/optimizer/util/var.c b/src/backend/optimizer/util/var.c index 66f5b598f0c..020b86d5e06 100644 --- a/src/backend/optimizer/util/var.c +++ b/src/backend/optimizer/util/var.c @@ -501,8 +501,8 @@ contain_vars_of_level_walker(Node *node, int *sublevels_up) * * Returns true if any found. * - * Any ReturningExprs are also detected --- if an OLD/NEW Var was rewritten, - * we still regard this as a clause that returns OLD/NEW values. + * Any ReturningExprs are also checked --- if an OLD/NEW Var was rewritten, we + * still regard this as a clause that returns OLD/NEW values. * * Does not examine subqueries, therefore must only be used after reduction * of sublinks to subplans! @@ -521,13 +521,16 @@ contain_vars_returning_old_or_new_walker(Node *node, void *context) if (IsA(node, Var)) { if (((Var *) node)->varlevelsup == 0 && - ((Var *) node)->varreturningtype != VAR_RETURNING_DEFAULT) + (((Var *) node)->varreturningtype == VAR_RETURNING_OLD || + ((Var *) node)->varreturningtype == VAR_RETURNING_NEW)) return true; /* abort the tree traversal and return true */ return false; } if (IsA(node, ReturningExpr)) { - if (((ReturningExpr *) node)->retlevelsup == 0) + if (((ReturningExpr *) node)->retlevelsup == 0 && + (((ReturningExpr *) node)->retkind == RETURNING_OLD_EXPR || + ((ReturningExpr *) node)->retkind == RETURNING_NEW_EXPR)) return true; /* abort the tree traversal and return true */ return false; } diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index 539c16c4f79..9eccef62424 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -1255,12 +1255,21 @@ transformOnConflictClause(ParseState *pstate, EXPR_KIND_WHERE, "WHERE"); /* - * Remove the EXCLUDED pseudo relation from the query namespace, since - * it's not supposed to be available in RETURNING. (Maybe someday we - * could allow that, and drop this step.) + * Leave the EXCLUDED pseudo relation in the query namespace so that + * it is available in RETURNING expressions, but change it to be a + * table-only item so that its columns are only accessible using + * qualified names. This ensures that columns from the target + * relation can be accessed using unqualified names without ambiguity. + * + * Also, set its returning_type so that any RETURNING list Vars + * referencing it are marked correctly. */ Assert((ParseNamespaceItem *) llast(pstate->p_namespace) == exclNSItem); - pstate->p_namespace = list_delete_last(pstate->p_namespace); + exclNSItem->p_cols_visible = false; + + exclNSItem->p_returning_type = VAR_RETURNING_EXCLUDED; + for (int i = 0; i < list_length(exclNSItem->p_names->colnames); i++) + exclNSItem->p_nscolumns[i].p_varreturningtype = VAR_RETURNING_EXCLUDED; } /* Finally, build ON CONFLICT DO [NOTHING | SELECT | UPDATE] expression */ diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c index dcfe1acc4c3..7b58f279522 100644 --- a/src/backend/parser/parse_expr.c +++ b/src/backend/parser/parse_expr.c @@ -2664,7 +2664,7 @@ transformWholeRowRef(ParseState *pstate, ParseNamespaceItem *nsitem, result = makeWholeRowVar(nsitem->p_rte, nsitem->p_rtindex, sublevels_up, true); - /* mark Var for RETURNING OLD/NEW, as necessary */ + /* mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ result->varreturningtype = nsitem->p_returning_type; /* location is not filled in by makeWholeRowVar */ diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c index 3ec8d8de011..0005a6edaab 100644 --- a/src/backend/parser/parse_relation.c +++ b/src/backend/parser/parse_relation.c @@ -254,7 +254,7 @@ scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location) /* If not inside LATERAL, ignore lateral-only items */ if (nsitem->p_lateral_only && !pstate->p_lateral_active) continue; - /* Ignore OLD/NEW namespace items that can appear in RETURNING */ + /* Ignore OLD/NEW/EXCLUDED namespace items in RETURNING */ if (nsitem->p_returning_type != VAR_RETURNING_DEFAULT) continue; @@ -771,7 +771,7 @@ scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem, } var->location = location; - /* Mark Var for RETURNING OLD/NEW, as necessary */ + /* Mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ var->varreturningtype = nsitem->p_returning_type; /* Mark Var if it's nulled by any outer joins */ diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c index 7c99290be4d..e4bf25a4beb 100644 --- a/src/backend/rewrite/rewriteHandler.c +++ b/src/backend/rewrite/rewriteHandler.c @@ -97,7 +97,7 @@ static List *matchLocks(CmdType event, Relation relation, static Query *fireRIRrules(Query *parsetree, List *activeRIRs); static Bitmapset *adjust_view_column_set(Bitmapset *cols, List *targetlist); static Node *expand_generated_columns_internal(Node *node, Relation rel, int rt_index, - RangeTblEntry *rte, int result_relation); + RangeTblEntry *rte); /* @@ -646,7 +646,7 @@ rewriteRuleAction(Query *parsetree, 0, rt_fetch(new_varno, sub_action->rtable), parsetree->targetList, - sub_action->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -2362,7 +2362,7 @@ CopyAndAddInvertedQual(Query *parsetree, rt_fetch(rt_index, parsetree->rtable), parsetree->targetList, - parsetree->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -3721,12 +3721,12 @@ rewriteTargetView(Query *parsetree, Relation view) BuildOnConflictExcludedTargetlist(base_rel, new_exclRelIndex); /* - * Update all Vars in the ON CONFLICT clause that refer to the old - * EXCLUDED pseudo-relation. We want to use the column mappings - * defined in the view targetlist, but we need the outputs to refer to - * the new EXCLUDED pseudo-relation rather than the new target RTE. - * Also notice that "EXCLUDED.*" will be expanded using the view's - * rowtype, which seems correct. + * Update all Vars in the ON CONFLICT clause and RETURNING list that + * refer to the old EXCLUDED pseudo-relation. We want to use the + * column mappings defined in the view targetlist, but we need the + * outputs to refer to the new EXCLUDED pseudo-relation rather than + * the new target RTE. Also notice that "EXCLUDED.*" will be expanded + * using the view's rowtype, which seems correct. */ tmp_tlist = copyObject(view_targetlist); @@ -3739,7 +3739,18 @@ rewriteTargetView(Query *parsetree, Relation view) 0, view_rte, tmp_tlist, - new_rt_index, + 0, + REPLACEVARS_REPORT_ERROR, + 0, + &parsetree->hasSubLinks); + + parsetree->returningList = (List *) + ReplaceVarsFromTargetList((Node *) parsetree->returningList, + old_exclRelIndex, + 0, + view_rte, + tmp_tlist, + new_exclRelIndex, REPLACEVARS_REPORT_ERROR, 0, &parsetree->hasSubLinks); @@ -4455,13 +4466,11 @@ RewriteQuery(Query *parsetree, List *rewrite_events, int orig_rt_length, * virtual generated column expressions from rel, if there are any. * * The caller must also provide rte, the RTE describing the target relation, - * in order to handle any whole-row Vars referencing the target, and - * result_relation, the index of the result relation, if this is part of an - * INSERT/UPDATE/DELETE/MERGE query. + * in order to handle any whole-row Vars referencing the target. */ static Node * expand_generated_columns_internal(Node *node, Relation rel, int rt_index, - RangeTblEntry *rte, int result_relation) + RangeTblEntry *rte) { TupleDesc tupdesc; @@ -4489,8 +4498,7 @@ expand_generated_columns_internal(Node *node, Relation rel, int rt_index, Assert(list_length(tlist) > 0); - node = ReplaceVarsFromTargetList(node, rt_index, 0, rte, tlist, - result_relation, + node = ReplaceVarsFromTargetList(node, rt_index, 0, rte, tlist, 0, REPLACEVARS_CHANGE_VARNO, rt_index, NULL); } @@ -4519,7 +4527,7 @@ expand_generated_columns_in_expr(Node *node, Relation rel, int rt_index) rte->rtekind = RTE_RELATION; rte->relid = RelationGetRelid(rel); - node = expand_generated_columns_internal(node, rel, rt_index, rte, 0); + node = expand_generated_columns_internal(node, rel, rt_index, rte); } return node; diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index 6fa174412f2..168db9d6b0d 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -918,7 +918,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, /* * SetVarReturningType - adjust Var nodes for a specified varreturningtype. * - * Find all Var nodes referring to the specified result relation in the given + * Find all Var nodes referring to the specified relation in the given * expression and set their varreturningtype to the specified value. * * NOTE: although this has the form of a walker, we cheat and modify the @@ -928,7 +928,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, typedef struct { - int result_relation; + int target_varno; int sublevels_up; VarReturningType returning_type; } SetVarReturningType_context; @@ -942,7 +942,7 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) { Var *var = (Var *) node; - if (var->varno == context->result_relation && + if (var->varno == context->target_varno && var->varlevelsup == context->sublevels_up) var->varreturningtype = context->returning_type; @@ -964,12 +964,12 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) } static void -SetVarReturningType(Node *node, int result_relation, int sublevels_up, +SetVarReturningType(Node *node, int target_varno, int sublevels_up, VarReturningType returning_type) { SetVarReturningType_context context; - context.result_relation = result_relation; + context.target_varno = target_varno; context.sublevels_up = sublevels_up; context.returning_type = returning_type; @@ -1741,14 +1741,29 @@ map_variable_attnos(Node *node, * relation. This is needed to handle whole-row Vars referencing the target. * We expand such Vars into RowExpr constructs. * - * In addition, for INSERT/UPDATE/DELETE/MERGE queries, the caller must - * provide result_relation, the index of the result relation in the rewritten - * query. This is needed to handle OLD/NEW RETURNING list Vars referencing - * target_varno. When such Vars are expanded, their varreturningtype is - * copied onto any replacement Vars referencing result_relation. In addition, - * if the replacement expression from the targetlist is not simply a Var - * referencing result_relation, it is wrapped in a ReturningExpr node (causing - * the executor to return NULL if the OLD/NEW row doesn't exist). + * In addition, the caller should provide new_target_varno, which is needed to + * handle any OLD/NEW/EXCLUDED RETURNING list Vars (Vars with non-default + * varreturningtype) referencing target_varno. When such Vars are expanded, + * their varreturningtype is copied onto any Vars that reference + * new_target_varno in the replacement expression from the targetlist. In + * addition, if the replacement expression is not simply a Var referencing + * new_target_varno, it is wrapped in a ReturningExpr node (causing the + * executor to return NULL if the OLD/NEW/EXCLUDED row doesn't exist). The + * caller should set new_target_varno as follows: + * + * If the input node contains Vars from the RETURNING list of a query, and + * target_varno is the resultRelation of that query, then new_target_varno + * should be the (possibly new) resultRelation of the rewritten query. + * + * If the input node contains Vars from the RETURNING list of an INSERT ... + * ON CONFLICT DO SELECT/UPDATE query, and target_varno is the index of the + * EXCLUDED pseudo-relation, then new_target_varno should be the (possibly + * new) index of the EXCLUDED pseudo-relation in the rewritten query. + * + * Otherwise, new_target_varno should be set to 0 in order to detect any + * Vars with non-default varreturningtype outside the RETURNING list, or + * referencing a relation other than the result relation or the EXCLUDED + * pseudo-relation. * * Note that ReplaceVarFromTargetList always generates the replacement * expression with varlevelsup = 0. The caller is responsible for adjusting @@ -1762,7 +1777,7 @@ typedef struct { RangeTblEntry *target_rte; List *targetlist; - int result_relation; + int new_target_varno; ReplaceVarsNoMatchOption nomatch_option; int nomatch_varno; } ReplaceVarsFromTargetList_context; @@ -1777,7 +1792,7 @@ ReplaceVarsFromTargetList_callback(Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, rcon->nomatch_option, rcon->nomatch_varno); @@ -1792,7 +1807,7 @@ Node * ReplaceVarFromTargetList(Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno) { @@ -1841,7 +1856,7 @@ ReplaceVarFromTargetList(Var *var, field = ReplaceVarFromTargetList((Var *) field, target_rte, targetlist, - result_relation, + new_target_varno, nomatch_option, nomatch_varno); rowexpr->args = lappend(rowexpr->args, field); @@ -1853,7 +1868,7 @@ ReplaceVarFromTargetList(Var *var, ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = (Expr *) rowexpr; return (Node *) rexpr; @@ -1922,28 +1937,28 @@ ReplaceVarFromTargetList(Var *var, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("NEW variables in ON UPDATE rules cannot reference columns that are part of a multiple assignment in the subject UPDATE command"))); - /* Handle any OLD/NEW RETURNING list Vars */ + /* Handle any OLD/NEW/EXCLUDED RETURNING list Vars */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { /* * Copy varreturningtype onto any Vars in the tlist item that - * refer to result_relation (which had better be non-zero). + * refer to new_target_varno (which had better be non-zero). */ - if (result_relation == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); + if (new_target_varno == 0) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list, or referencing a relation other than the result relation or the EXCLUDED pseudo-relation"); - SetVarReturningType((Node *) newnode, result_relation, + SetVarReturningType((Node *) newnode, new_target_varno, 0, var->varreturningtype); /* Wrap it in a ReturningExpr, if needed, per comments above */ if (!IsA(newnode, Var) || - ((Var *) newnode)->varno != result_relation || + ((Var *) newnode)->varno != new_target_varno || ((Var *) newnode)->varlevelsup != 0) { ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = newnode; newnode = (Expr *) rexpr; @@ -1959,7 +1974,7 @@ ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks) @@ -1968,7 +1983,7 @@ ReplaceVarsFromTargetList(Node *node, context.target_rte = target_rte; context.targetlist = targetlist; - context.result_relation = result_relation; + context.new_target_varno = new_target_varno; context.nomatch_option = nomatch_option; context.nomatch_varno = nomatch_varno; diff --git a/src/include/executor/execExpr.h b/src/include/executor/execExpr.h index aa9b361fa31..c3d79a0bdc5 100644 --- a/src/include/executor/execExpr.h +++ b/src/include/executor/execExpr.h @@ -26,9 +26,9 @@ struct JsonConstructorExprState; /* Bits in ExprState->flags (see also execnodes.h for public flag bits): */ /* expression's interpreter has been initialized */ -#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 5) +#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 6) /* jump-threading is in use */ -#define EEO_FLAG_DIRECT_THREADED (1 << 6) +#define EEO_FLAG_DIRECT_THREADED (1 << 7) /* Typical API for out-of-line evaluation subroutines */ typedef void (*ExecEvalSubroutine) (ExprState *state, @@ -338,7 +338,8 @@ typedef struct ExprEvalStep /* but it's just the normal (negative) attr number for SYSVAR */ int attnum; Oid vartype; /* type OID of variable */ - VarReturningType varreturningtype; /* return old/new/default */ + /* if not default, return old/new/excluded value */ + VarReturningType varreturningtype; } var; /* for EEOP_WHOLEROW */ diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index 63c067d5aae..511d4a58c37 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -82,6 +82,8 @@ typedef Datum (*ExprStateEvalFunc) (ExprState *expression, #define EEO_FLAG_OLD_IS_NULL (1 << 3) /* NEW table row is NULL in RETURNING list */ #define EEO_FLAG_NEW_IS_NULL (1 << 4) +/* INNER (EXCLUDED) table row is NULL in RETURNING list */ +#define EEO_FLAG_INNER_IS_NULL (1 << 5) typedef struct ExprState { diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h index 384df50c80a..4dfeaa34f3e 100644 --- a/src/include/nodes/primnodes.h +++ b/src/include/nodes/primnodes.h @@ -228,7 +228,9 @@ typedef struct Expr * varreturningtype is used for Vars that refer to the target relation in the * RETURNING list of data-modifying queries. The default behavior is to * return old values for DELETE and new values for INSERT and UPDATE, but it - * is also possible to explicitly request old or new values. + * is also possible to explicitly request old or new values. For INSERT ... + * ON CONFLICT DO SELECT/UPDATE, varreturningtype is also used for Vars in the + * RETURNING list that refer to the EXCLUDED pseudo-relation. * * In the parser, varnosyn and varattnosyn are either identical to * varno/varattno, or they specify the column's position in an aliased JOIN @@ -257,6 +259,7 @@ typedef enum VarReturningType VAR_RETURNING_DEFAULT, /* return OLD for DELETE, else return NEW */ VAR_RETURNING_OLD, /* return OLD for DELETE/UPDATE, else NULL */ VAR_RETURNING_NEW, /* return NEW for INSERT/UPDATE, else NULL */ + VAR_RETURNING_EXCLUDED, /* return EXCLUDED on conflict, else NULL */ } VarReturningType; typedef struct Var @@ -2155,14 +2158,15 @@ typedef struct InferenceElem } InferenceElem; /* - * ReturningExpr - return OLD/NEW.(expression) in RETURNING list + * ReturningExpr - return OLD/NEW/EXCLUDED.(expression) in RETURNING list * * This is used when updating an auto-updatable view and returning a view * column that is not simply a Var referring to the base relation. In such - * cases, OLD/NEW.viewcol can expand to an arbitrary expression, but the - * result is required to be NULL if the OLD/NEW row doesn't exist. To handle - * this, the rewriter wraps the expanded expression in a ReturningExpr, which - * is equivalent to "CASE WHEN (OLD/NEW row exists) THEN (expr) ELSE NULL". + * cases, OLD/NEW/EXCLUDED.viewcol can expand to an arbitrary expression, but + * the result is required to be NULL if the OLD/NEW/EXCLUDED row doesn't + * exist. To handle this, the rewriter wraps the expanded expression in a + * ReturningExpr, which is equivalent to "CASE WHEN (OLD/NEW/EXCLUDED row + * exists) THEN (expr) ELSE NULL". * * A similar situation can arise when rewriting the RETURNING clause of a * rule, which may also contain arbitrary expressions. @@ -2170,11 +2174,19 @@ typedef struct InferenceElem * ReturningExpr nodes never appear in a parsed Query --- they are only ever * inserted by the rewriter and the planner. */ +typedef enum ReturningExprKind +{ + /* values here match non-default VarReturningType values */ + RETURNING_OLD_EXPR = VAR_RETURNING_OLD, + RETURNING_NEW_EXPR = VAR_RETURNING_NEW, + RETURNING_EXCLUDED_EXPR = VAR_RETURNING_EXCLUDED, +} ReturningExprKind; + typedef struct ReturningExpr { Expr xpr; int retlevelsup; /* > 0 if it belongs to outer query */ - bool retold; /* true for OLD, false for NEW */ + ReturningExprKind retkind; /* return OLD/NEW/EXCLUDED expression */ Expr *retexpr; /* expression to be returned */ } ReturningExpr; diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h index f23e21f318b..1cdd77b4a04 100644 --- a/src/include/parser/parse_node.h +++ b/src/include/parser/parse_node.h @@ -275,7 +275,8 @@ struct ParseState * forbid LATERAL references to an UPDATE/DELETE target table. * * While processing the RETURNING clause, special namespace items are added to - * refer to the OLD and NEW state of the result relation. These namespace + * refer to the OLD and NEW state of the result relation, and EXCLUDED pseudo- + * relation for INSERT ... ON CONFLICT DO SELECT/UPDATE. These namespace * items have p_returning_type set appropriately, for use when creating Vars. * For convenience, this information is duplicated on each namespace column. * @@ -296,7 +297,7 @@ struct ParseNamespaceItem bool p_cols_visible; /* Column names visible as unqualified refs? */ bool p_lateral_only; /* Is only visible to LATERAL expressions? */ bool p_lateral_ok; /* If so, does join type allow use? */ - VarReturningType p_returning_type; /* Is OLD/NEW for use in RETURNING? */ + VarReturningType p_returning_type; /* for RETURNING OLD/NEW/EXCLUDED */ }; /* @@ -327,7 +328,7 @@ struct ParseNamespaceColumn Oid p_vartype; /* pg_type OID */ int32 p_vartypmod; /* type modifier value */ Oid p_varcollid; /* OID of collation, or InvalidOid */ - VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW */ + VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW/EXCLUDED */ Index p_varnosyn; /* rangetable index of syntactic referent */ AttrNumber p_varattnosyn; /* attribute number of syntactic referent */ bool p_dontexpand; /* not included in star expansion */ diff --git a/src/include/rewrite/rewriteManip.h b/src/include/rewrite/rewriteManip.h index f8216c22fb7..194bee9e407 100644 --- a/src/include/rewrite/rewriteManip.h +++ b/src/include/rewrite/rewriteManip.h @@ -107,14 +107,14 @@ extern Node *map_variable_attnos(Node *node, extern Node *ReplaceVarFromTargetList(Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno); extern Node *ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks); diff --git a/src/test/regress/expected/arrays.out b/src/test/regress/expected/arrays.out index 66439d427a3..12b5a7be7af 100644 --- a/src/test/regress/expected/arrays.out +++ b/src/test/regress/expected/arrays.out @@ -1398,20 +1398,30 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+--------- - 1 | {3,2,5} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+---------+------------- + 1 | {3,2,5} | {3,4,5} (1 row) insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+------------ - 1 | {6,7,NULL} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+------------+------------- + 1 | {6,7,NULL} | {6,7} +(1 row) + +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+----------------+------------- + 1 | {NULL,10,NULL} | [2:2]={10} (1 row) -- note: if above selects don't produce the expected tuple order, diff --git a/src/test/regress/expected/generated_stored.out b/src/test/regress/expected/generated_stored.out index 8b7a71d8f0c..39b6a26444f 100644 --- a/src/test/regress/expected/generated_stored.out +++ b/src/test/regress/expected/generated_stored.out @@ -114,32 +114,44 @@ INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error ERROR: cannot insert a non-DEFAULT value into column "b" DETAIL: Column "b" is a generated column. INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + a | b | a | b | a | b +---+---+-----+-----+---+--- + 4 | 8 | 104 | 208 | 4 | 8 + | | 5 | 10 | | +(2 rows) + SELECT * FROM gtest1 ORDER BY a; - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference - gtest1 --------- + gtest1 +----------- (1,2) (2,4) (3,6) - (4,8) -(4 rows) + (5,10) + (104,208) +(5 rows) SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) DELETE FROM gtest1 WHERE a >= 3; UPDATE gtest1 SET b = DEFAULT WHERE a = 1; diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index 249e68be654..700f5719fda 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -114,32 +114,44 @@ INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error ERROR: cannot insert a non-DEFAULT value into column "b" DETAIL: Column "b" is a generated column. INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + a | b | a | b | a | b +---+---+-----+-----+---+--- + 4 | 8 | 104 | 208 | 4 | 8 + | | 5 | 10 | | +(2 rows) + SELECT * FROM gtest1 ORDER BY a; - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference - gtest1 --------- + gtest1 +----------- (1,2) (2,4) (3,6) - (4,8) -(4 rows) + (5,10) + (104,208) +(5 rows) SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) DELETE FROM gtest1 WHERE a >= 3; UPDATE gtest1 SET b = DEFAULT WHERE a = 1; diff --git a/src/test/regress/expected/inherit.out b/src/test/regress/expected/inherit.out index 0490a746555..6c57548661f 100644 --- a/src/test/regress/expected/inherit.out +++ b/src/test/regress/expected/inherit.out @@ -2131,7 +2131,14 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; + old | new | excluded +--------+---------+---------- + (3,3-) | (3,3-+) | (3,) + (7,7-) | (7,7-+) | (7,) +(2 rows) + select * from inhpar order by f1; -- tuple order might be unstable here f1 | f2 ----+----- diff --git a/src/test/regress/expected/insert_conflict.out b/src/test/regress/expected/insert_conflict.out index 34e2e7ee355..5976dee1e4d 100644 --- a/src/test/regress/expected/insert_conflict.out +++ b/src/test/regress/expected/insert_conflict.out @@ -281,13 +281,13 @@ insert into insertconflicttest values (2, 'Orange') on conflict (key, key, key) insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -ERROR: invalid reference to FROM-clause entry for table "excluded" -LINE 1: ...y) do update set fruit = excluded.fruit RETURNING excluded.f... - ^ -DETAIL: There is an entry for table "excluded", but it cannot be referenced from this part of the query. + fruit +------- + Apple +(1 row) + -- Only suggest <table>.* column when inference element misspelled: insert into insertconflicttest values (1, 'Apple') on conflict (keyy) do update set fruit = excluded.fruit; ERROR: column "keyy" does not exist @@ -482,33 +482,33 @@ drop index partial_key_index; create unique index plain on insertconflicttest(key); -- Succeeds, updates existing row: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; - key | fruit ------+----------- - 23 | Jackfruit + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-----------+----------+---------- + 23 | Jackfruit | f | t (1 row) -- No update this time, though: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; - key | fruit ------+------- + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-------+----------+---------- (0 rows) -- Predicate changed to require match rather than non-match, so updates once more: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* = excluded.* returning *; - key | fruit ------+----------- - 23 | Jackfruit + where i.* = excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-----------+----------+---------- + 23 | Jackfruit | t | t (1 row) -- Assign: insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text - returning *; - key | fruit ------+-------------- - 23 | (23,Avocado) + returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+--------------+----------+---------- + 23 | (23,Avocado) | f | f (1 row) -- deparse whole row var in WHERE and SET clauses: @@ -546,6 +546,10 @@ insert into syscolconflicttest values (1) on conflict (key) do update set data = ERROR: column excluded.ctid does not exist LINE 1: ...values (1) on conflict (key) do update set data = excluded.c... ^ +insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.data returning excluded.ctid; +ERROR: column excluded.ctid does not exist +LINE 1: ...key) do update set data = excluded.data returning excluded.c... + ^ drop table syscolconflicttest; -- -- Previous tests all managed to not test any expressions requiring @@ -620,7 +624,13 @@ select * from capitals; -- Succeeds: insert into cities values ('Las Vegas', 2.583E+5, 2174) on conflict do nothing; -insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; + name | population | altitude | state | name | population | altitude | state | name | population | altitude | state +------------+------------+----------+-------+------------+------------+----------+-------+------------+------------+----------+------- + Sacramento | 369400 | 30 | CA | Sacramento | 466400000 | 30 | CA | Sacramento | 466400000 | 30 | CA +(1 row) + -- Wrong "Sacramento", so do nothing: insert into capitals values ('Sacramento', 50, 2267, 'NE') on conflict (name) do nothing; select * from capitals; @@ -630,7 +640,13 @@ select * from capitals; Sacramento | 466400000 | 30 | CA (2 rows) -insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old, new, excluded; + old | new | excluded +---------------------------+---------------------------+--------------------------- + ("Las Vegas",258300,2174) | ("Las Vegas",583000,2001) | ("Las Vegas",583000,2001) +(1 row) + select tableoid::regclass, * from cities; tableoid | name | population | altitude ----------+---------------+------------+---------- @@ -641,7 +657,13 @@ select tableoid::regclass, * from cities; capitals | Sacramento | 466400000 | 30 (5 rows) -insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population + returning old, new, excluded; + old | new | excluded +-----+------------------------------+---------- + | ("Las Vegas",583000,2222,NV) | +(1 row) + -- Capitals will contain new capital, Las Vegas: select * from capitals; name | population | altitude | state @@ -665,7 +687,13 @@ select tableoid::regclass, * from cities; (6 rows) -- This only affects "cities" version of "Las Vegas": -insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; + name | population | altitude | name | population | altitude | name | population | altitude +-----------+------------+----------+-----------+------------+----------+-----------+------------+---------- + Las Vegas | 583000 | 2001 | Las Vegas | 586000 | 2223 | Las Vegas | 586000 | 2223 +(1 row) + select tableoid::regclass, * from cities; tableoid | name | population | altitude ----------+---------------+------------+---------- @@ -702,11 +730,17 @@ insert into excluded AS target values(1, '2') on conflict (key) do update set da 1 | 2 (1 row) --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; - key | data ------+------ - 1 | 3 +ERROR: table reference "excluded" is ambiguous +LINE 1: ...n conflict (key) do update set data = 3 RETURNING excluded.*... + ^ +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; + key | data | key | data +-----+------+-----+------ + 1 | 3 | 1 | 2 (1 row) -- clean up @@ -925,10 +959,10 @@ insert into parted_conflict_test values (3, 'a') on conflict (a) do select where (3,b) (1 row) -insert into parted_conflict_test values (3, 'a') on conflict (a) do select where parted_conflict_test.b = 'b' returning b; - b ---- - b +insert into parted_conflict_test values (3, 'a') on conflict (a) do select where parted_conflict_test.b = 'b' returning b, excluded; + b | excluded +---+---------- + b | (3,a) (1 row) -- should see (3, 'b') @@ -944,10 +978,10 @@ create table parted_conflict_test_3 partition of parted_conflict_test for values truncate parted_conflict_test; insert into parted_conflict_test (a, b) values (4, 'a') on conflict (a) do update set b = excluded.b; insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do update set b = excluded.b where parted_conflict_test.b = 'a'; -insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do select returning b; - b ---- - b +insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do select returning b, excluded; + b | excluded +---+---------- + b | (4,b) (1 row) -- should see (4, 'b') diff --git a/src/test/regress/expected/returning.out b/src/test/regress/expected/returning.out index cfaaf015bb3..cd19195d2ce 100644 --- a/src/test/regress/expected/returning.out +++ b/src/test/regress/expected/returning.out @@ -463,18 +463,19 @@ INSERT INTO foo VALUES (4) | | | | | | foo | (0,4) | 4 | | 42 | 99 | 4 | | 42 | 99 (1 row) --- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW +-- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW (and EXLCUDED) CREATE UNIQUE INDEX foo_f1_idx ON foo (f1); EXPLAIN (verbose, costs off) INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; - QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------------- + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Insert on pg_temp.foo - Output: (o.tableoid)::regclass, o.ctid, o.f1, o.f2, o.f3, o.f4, (n.tableoid)::regclass, n.ctid, n.f1, n.f2, n.f3, n.f4, foo.f1, foo.f2, foo.f3, foo.f4 + Output: (o.tableoid)::regclass, o.ctid, o.f1, o.f2, o.f3, o.f4, (n.tableoid)::regclass, n.ctid, n.f1, n.f2, n.f3, n.f4, foo.f1, foo.f2, foo.f3, foo.f4, excluded.f1, excluded.f2, excluded.f3, excluded.f4 Conflict Resolution: UPDATE Conflict Arbiter Indexes: foo_f1_idx -> Values Scan on "*VALUES*" @@ -485,11 +486,12 @@ INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; - tableoid | ctid | f1 | f2 | f3 | f4 | tableoid | ctid | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 -----------+-------+----+----+----+----+----------+-------+----+------------+----+----+----+------------+----+---- - foo | (0,4) | 4 | | 42 | 99 | foo | (0,5) | 4 | conflicted | -1 | 99 | 4 | conflicted | -1 | 99 - | | | | | | foo | (0,6) | 5 | ok | 42 | 99 | 5 | ok | 42 | 99 + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; + tableoid | ctid | f1 | f2 | f3 | f4 | tableoid | ctid | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 +----------+-------+----+----+----+----+----------+-------+----+------------+----+----+----+------------+----+----+----+----------+----+---- + foo | (0,4) | 4 | | 42 | 99 | foo | (0,5) | 4 | conflicted | -1 | 99 | 4 | conflicted | -1 | 99 | 4 | conflict | 42 | 99 + | | | | | | foo | (0,6) | 5 | ok | 42 | 99 | 5 | ok | 42 | 99 | | | | (2 rows) -- UPDATE has OLD and NEW diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index 78a37d9fc8f..b35e1029eb2 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -3607,6 +3607,67 @@ SELECT * FROM hat_data WHERE hat_name IN ('h8', 'h9', 'h7') ORDER BY hat_name; h9 | blue (3 rows) +DROP RULE hat_upsert ON hats; +-- DO UPDATE ... RETURNING excluded values +CREATE RULE hat_upsert AS ON INSERT TO hats + DO INSTEAD + INSERT INTO hat_data VALUES ( + NEW.hat_name, + NEW.hat_color) + ON CONFLICT (hat_name) + DO UPDATE + SET hat_name = hat_data.hat_name, hat_color = 'Excl: '||excluded.hat_color + WHERE excluded.hat_color <> 'forbidden' AND hat_data.* != excluded.* + RETURNING excluded.*; +SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename; + definition +--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE RULE hat_upsert AS + + ON INSERT TO public.hats DO INSTEAD INSERT INTO hat_data (hat_name, hat_color) + + VALUES (new.hat_name, new.hat_color) ON CONFLICT(hat_name) DO UPDATE SET hat_name = hat_data.hat_name, hat_color = ('Excl: '::text || (excluded.hat_color)::text)+ + WHERE ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) + + RETURNING excluded.hat_name, + + excluded.hat_color; +(1 row) + +-- EXCLUDED not allowed in plain INSERT +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING excluded.*; +ERROR: missing FROM-clause entry for table "excluded" +LINE 2: RETURNING excluded.*; + ^ +-- OLD/NEW have no effect on EXCLUDED +EXPLAIN (verbose, costs off) +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------- + Insert on public.hat_data + Output: excluded.hat_name, excluded.hat_color, excluded.hat_name, excluded.hat_color, excluded.hat_name, excluded.hat_color + Conflict Resolution: UPDATE + Conflict Arbiter Indexes: hat_data_unique_idx + Conflict Filter: ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) + -> Values Scan on "*VALUES*" + Output: "*VALUES*".column1, "*VALUES*".column2 +(7 rows) + +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; + hat_name | hat_color | hat_name | hat_color | hat_name | hat_color +------------+------------+------------+------------+------------+------------ + | | | | | + h8 | red | h8 | red | h8 | red +(2 rows) + +SELECT * FROM hat_data ORDER BY hat_name; + hat_name | hat_color +------------+------------ + h6 | black + h7 | black + h8 | Excl: red + h9 | blue +(4 rows) + DROP RULE hat_upsert ON hats; -- DO SELECT with a WHERE clause CREATE RULE hat_confsel AS ON INSERT TO hats diff --git a/src/test/regress/expected/triggers.out b/src/test/regress/expected/triggers.out index 98dee63b50a..316f0225de6 100644 --- a/src/test/regress/expected/triggers.out +++ b/src/test/regress/expected/triggers.out @@ -1708,49 +1708,89 @@ end; $$; create trigger upsert_after_trig after insert or update on upsert for each row execute procedure upsert_after_func(); -insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color; +insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (1,black) WARNING: after insert (new): (1,black) -insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+-------+-----+------- + | | 1 | black | | +(1 row) + +insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (2,red) WARNING: before insert (new, modified): (3,"red trig modified") WARNING: after insert (new): (3,"red trig modified") -insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+-------------------+-----+------- + | | 3 | red trig modified | | +(1 row) + +insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (3,orange) WARNING: before update (old): (3,"red trig modified") WARNING: before update (new): (3,"updated red trig modified") WARNING: after update (old): (3,"red trig modified") WARNING: after update (new): (3,"updated red trig modified") -insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------------------+-----+---------------------------+-----+-------- + 3 | red trig modified | 3 | updated red trig modified | 3 | orange +(1 row) + +insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (4,green) WARNING: before insert (new, modified): (5,"green trig modified") WARNING: after insert (new): (5,"green trig modified") -insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+---------------------+-----+------- + | | 5 | green trig modified | | +(1 row) + +insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (5,purple) WARNING: before update (old): (5,"green trig modified") WARNING: before update (new): (5,"updated green trig modified") WARNING: after update (old): (5,"green trig modified") WARNING: after update (new): (5,"updated green trig modified") -insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+---------------------+-----+-----------------------------+-----+-------- + 5 | green trig modified | 5 | updated green trig modified | 5 | purple +(1 row) + +insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (6,white) WARNING: before insert (new, modified): (7,"white trig modified") WARNING: after insert (new): (7,"white trig modified") -insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+---------------------+-----+------- + | | 7 | white trig modified | | +(1 row) + +insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (7,pink) WARNING: before update (old): (7,"white trig modified") WARNING: before update (new): (7,"updated white trig modified") WARNING: after update (old): (7,"white trig modified") WARNING: after update (new): (7,"updated white trig modified") -insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+---------------------+-----+-----------------------------+-----+------- + 7 | white trig modified | 7 | updated white trig modified | 7 | pink +(1 row) + +insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (8,yellow) WARNING: before insert (new, modified): (9,"yellow trig modified") WARNING: after insert (new): (9,"yellow trig modified") -insert into upsert values(8, 'blue') on conflict (key) do select for update where upsert.color = 'yellow trig modified' returning old.*, new.*, upsert.*; + key | color | key | color | key | color +-----+-------+-----+----------------------+-----+------- + | | 9 | yellow trig modified | | +(1 row) + +insert into upsert values(8, 'blue') on conflict (key) do select for update where upsert.color = 'yellow trig modified' returning old.*, new.*, upsert.*, excluded.*; WARNING: before insert (new): (8,blue) WARNING: before insert (new, modified): (9,"blue trig modified") - key | color | key | color | key | color ------+----------------------+-----+----------------------+-----+---------------------- - 9 | yellow trig modified | 9 | yellow trig modified | 9 | yellow trig modified + key | color | key | color | key | color | key | color +-----+----------------------+-----+----------------------+-----+----------------------+-----+-------------------- + 9 | yellow trig modified | 9 | yellow trig modified | 9 | yellow trig modified | 9 | blue trig modified (1 row) select * from upsert; diff --git a/src/test/regress/expected/updatable_views.out b/src/test/regress/expected/updatable_views.out index 9cea538b8e8..33727d62b95 100644 --- a/src/test/regress/expected/updatable_views.out +++ b/src/test/regress/expected/updatable_views.out @@ -3668,7 +3668,13 @@ insert into uv_iocu_tab values ('xyxyxy', 0); create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- @@ -3676,7 +3682,13 @@ select * from uv_iocu_tab; (1 row) insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- @@ -3732,7 +3744,8 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; QUERY PLAN --------------------------------------------------------------------------------------------------------- Insert on uv_iocu_tab @@ -3746,7 +3759,13 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; + ?column? | ?column? | ?column? +--------------------+------------------------------------------------------------------------------+------------------------- + Old: (x,1,"(1,x)") | New: ("Rejected: (y,1,""(1,y)"")",1,"(1,""Rejected: (y,1,""""(1,y)"""")"")") | Excluded: (y,1,"(1,y)") +(1 row) + select * from uv_iocu_view; bb | aa | cc -------------------------+----+--------------------------------- diff --git a/src/test/regress/sql/arrays.sql b/src/test/regress/sql/arrays.sql index 82837af7c4a..8a5f94ae6a4 100644 --- a/src/test/regress/sql/arrays.sql +++ b/src/test/regress/sql/arrays.sql @@ -426,12 +426,17 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; -- note: if above selects don't produce the expected tuple order, -- then you didn't get an indexscan plan, and something is busted. diff --git a/src/test/regress/sql/generated_stored.sql b/src/test/regress/sql/generated_stored.sql index 2001a47bcc6..eae93d618b7 100644 --- a/src/test/regress/sql/generated_stored.sql +++ b/src/test/regress/sql/generated_stored.sql @@ -58,6 +58,10 @@ INSERT INTO gtest1 VALUES (3, DEFAULT), (4, 44); -- error INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + SELECT * FROM gtest1 ORDER BY a; SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index 81152b39a79..157ff85b14f 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -58,6 +58,10 @@ INSERT INTO gtest1 VALUES (3, DEFAULT), (4, 44); -- error INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + SELECT * FROM gtest1 ORDER BY a; SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink diff --git a/src/test/regress/sql/inherit.sql b/src/test/regress/sql/inherit.sql index 699e8ac09c8..da1d418abfc 100644 --- a/src/test/regress/sql/inherit.sql +++ b/src/test/regress/sql/inherit.sql @@ -806,7 +806,8 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; select * from inhpar order by f1; -- tuple order might be unstable here drop table inhpar cascade; diff --git a/src/test/regress/sql/insert_conflict.sql b/src/test/regress/sql/insert_conflict.sql index a5a84d1d4b8..2bb71dfa510 100644 --- a/src/test/regress/sql/insert_conflict.sql +++ b/src/test/regress/sql/insert_conflict.sql @@ -109,8 +109,7 @@ insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -- Only suggest <table>.* column when inference element misspelled: @@ -258,16 +257,16 @@ create unique index plain on insertconflicttest(key); -- Succeeds, updates existing row: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- No update this time, though: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- Predicate changed to require match rather than non-match, so updates once more: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* = excluded.* returning *; + where i.* = excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- Assign: insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text - returning *; + returning *, excluded.* = old.*, excluded.* = new.*; -- deparse whole row var in WHERE and SET clauses: explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.fruit where excluded.* is null; explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text; @@ -287,6 +286,7 @@ drop table insertconflicttest; create table syscolconflicttest(key int4, data text); insert into syscolconflicttest values (1); insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.ctid::text; +insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.data returning excluded.ctid; drop table syscolconflicttest; -- @@ -364,20 +364,24 @@ select * from capitals; -- Succeeds: insert into cities values ('Las Vegas', 2.583E+5, 2174) on conflict do nothing; -insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; -- Wrong "Sacramento", so do nothing: insert into capitals values ('Sacramento', 50, 2267, 'NE') on conflict (name) do nothing; select * from capitals; -insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old, new, excluded; select tableoid::regclass, * from cities; -insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population + returning old, new, excluded; -- Capitals will contain new capital, Las Vegas: select * from capitals; -- Cities contains two instances of "Las Vegas", since unique constraints don't -- work across inheritance: select tableoid::regclass, * from cities; -- This only affects "cities" version of "Las Vegas": -insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; select tableoid::regclass, * from cities; -- clean up @@ -394,8 +398,11 @@ insert into excluded values(1, '2') on conflict (key) do update set data = exclu insert into excluded AS target values(1, '2') on conflict (key) do update set data = excluded.data RETURNING *; -- ok, aliased insert into excluded AS target values(1, '2') on conflict (key) do update set data = target.data RETURNING *; --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; -- clean up drop table excluded; @@ -539,7 +546,7 @@ insert into parted_conflict_test values (3, 'a') on conflict (a) do update set b insert into parted_conflict_test values (3, 'b') on conflict (a) do update set b = excluded.b; insert into parted_conflict_test values (3, 'a') on conflict (a) do select returning b; insert into parted_conflict_test values (3, 'a') on conflict (a) do select where excluded.b = 'a' returning parted_conflict_test; -insert into parted_conflict_test values (3, 'a') on conflict (a) do select where parted_conflict_test.b = 'b' returning b; +insert into parted_conflict_test values (3, 'a') on conflict (a) do select where parted_conflict_test.b = 'b' returning b, excluded; -- should see (3, 'b') select * from parted_conflict_test order by a; @@ -550,7 +557,7 @@ create table parted_conflict_test_3 partition of parted_conflict_test for values truncate parted_conflict_test; insert into parted_conflict_test (a, b) values (4, 'a') on conflict (a) do update set b = excluded.b; insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do update set b = excluded.b where parted_conflict_test.b = 'a'; -insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do select returning b; +insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do select returning b, excluded; -- should see (4, 'b') select * from parted_conflict_test order by a; diff --git a/src/test/regress/sql/returning.sql b/src/test/regress/sql/returning.sql index cc99cb53f63..00fa8a78c3d 100644 --- a/src/test/regress/sql/returning.sql +++ b/src/test/regress/sql/returning.sql @@ -209,19 +209,21 @@ INSERT INTO foo VALUES (4) RETURNING old.tableoid::regclass, old.ctid, old.*, new.tableoid::regclass, new.ctid, new.*, *; --- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW +-- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW (and EXLCUDED) CREATE UNIQUE INDEX foo_f1_idx ON foo (f1); EXPLAIN (verbose, costs off) INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; -- UPDATE has OLD and NEW EXPLAIN (verbose, costs off) diff --git a/src/test/regress/sql/rules.sql b/src/test/regress/sql/rules.sql index 40f5c16e540..952be1f9bfc 100644 --- a/src/test/regress/sql/rules.sql +++ b/src/test/regress/sql/rules.sql @@ -1205,6 +1205,33 @@ SELECT * FROM hat_data WHERE hat_name IN ('h8', 'h9', 'h7') ORDER BY hat_name; DROP RULE hat_upsert ON hats; +-- DO UPDATE ... RETURNING excluded values +CREATE RULE hat_upsert AS ON INSERT TO hats + DO INSTEAD + INSERT INTO hat_data VALUES ( + NEW.hat_name, + NEW.hat_color) + ON CONFLICT (hat_name) + DO UPDATE + SET hat_name = hat_data.hat_name, hat_color = 'Excl: '||excluded.hat_color + WHERE excluded.hat_color <> 'forbidden' AND hat_data.* != excluded.* + RETURNING excluded.*; +SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename; + +-- EXCLUDED not allowed in plain INSERT +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING excluded.*; + +-- OLD/NEW have no effect on EXCLUDED +EXPLAIN (verbose, costs off) +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; +SELECT * FROM hat_data ORDER BY hat_name; + +DROP RULE hat_upsert ON hats; + -- DO SELECT with a WHERE clause CREATE RULE hat_confsel AS ON INSERT TO hats DO INSTEAD diff --git a/src/test/regress/sql/triggers.sql b/src/test/regress/sql/triggers.sql index ea39817ee3d..05ee87f6803 100644 --- a/src/test/regress/sql/triggers.sql +++ b/src/test/regress/sql/triggers.sql @@ -1189,15 +1189,15 @@ $$; create trigger upsert_after_trig after insert or update on upsert for each row execute procedure upsert_after_func(); -insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(8, 'blue') on conflict (key) do select for update where upsert.color = 'yellow trig modified' returning old.*, new.*, upsert.*; +insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(8, 'blue') on conflict (key) do select for update where upsert.color = 'yellow trig modified' returning old.*, new.*, upsert.*, excluded.*; select * from upsert; diff --git a/src/test/regress/sql/updatable_views.sql b/src/test/regress/sql/updatable_views.sql index 1635adde2d4..ba9ed61b6cf 100644 --- a/src/test/regress/sql/updatable_views.sql +++ b/src/test/regress/sql/updatable_views.sql @@ -1864,10 +1864,12 @@ create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) on conflict (a) do select where uv_iocu_view.c = 2 and excluded.c = 2 returning *; @@ -1900,12 +1902,14 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; select * from uv_iocu_view; explain (costs off) insert into uv_iocu_view (aa,bb) values (1,'Rejected: (y,1,"(1,y)")') diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index 6e2d876a40f..211485ccfca 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2619,6 +2619,7 @@ ReturnSetInfo ReturnStmt ReturningClause ReturningExpr +ReturningExprKind ReturningOption ReturningOptionKind RevmapContents -- 2.51.0
^ permalink raw reply [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2026-02-12 12:23  Dean Rasheed <dean.a.rasheed@gmail.com>
  parent: Dean Rasheed <dean.a.rasheed@gmail.com>
  0 siblings, 1 reply; 17+ messages in thread

From: Dean Rasheed @ 2026-02-12 12:23 UTC (permalink / raw)
  To: Vik Fearing <vik@postgresfriends.org>; +Cc: Viktor Holmberg <v@viktorh.net>; pgsql-hackers

On Thu, 12 Feb 2026 at 11:11, Dean Rasheed <dean.a.rasheed@gmail.com> wrote:
>
> Rebased version attached (now also works with ON CONFLICT DO SELECT).
>

Something else to consider is the fact that this patch allows both
colname and EXCLUDED.colname to appear in the RETURNING list, where
the former refers to the target relation as it always has done. We're
pretty-much forced into that position, in order that people don't have
to rewrite all their existing queries (the same was true when support
for OLD/NEW was added to RETURNING).

But that then leads to the odd situation where colname has to be
qualified when it appears on the RHS of a SET clause, or in the WHERE
clause of INSERT ON CONFLICT, but not when it appears in the RETURNING
list.

There was a separate discussion [1] about whether we should remove
this requirement for colname to be qualified elsewhere in INSERT ON
CONFLICT, and I think this patch adds more weight to that argument.

[1] https://www.postgresql.org/message-id/flat/a31a76b6-b176-47fe-8778-9dfece231341@wikimedia.org

So should we do that, and allow unqualified column names in ON
CONFLICT SET and WHERE?

Regards,
Dean





^ permalink  raw  reply  [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2026-02-13 14:16  Viktor Holmberg <v@viktorh.net>
  parent: Dean Rasheed <dean.a.rasheed@gmail.com>
  0 siblings, 1 reply; 17+ messages in thread

From: Viktor Holmberg @ 2026-02-13 14:16 UTC (permalink / raw)
  To: Vik Fearing <vik@postgresfriends.org>; Dean Rasheed <dean.a.rasheed@gmail.com>; +Cc: pgsql-hackers

On 12 Feb 2026 at 13:23 +0100, Dean Rasheed <dean.a.rasheed@gmail.com>, wrote:
> On Thu, 12 Feb 2026 at 11:11, Dean Rasheed <dean.a.rasheed@gmail.com> wrote:
> >
> > Rebased version attached (now also works with ON CONFLICT DO SELECT).
> >
>
> Something else to consider is the fact that this patch allows both
> colname and EXCLUDED.colname to appear in the RETURNING list, where
> the former refers to the target relation as it always has done. We're
> pretty-much forced into that position, in order that people don't have
> to rewrite all their existing queries (the same was true when support
> for OLD/NEW was added to RETURNING).
>
> But that then leads to the odd situation where colname has to be
> qualified when it appears on the RHS of a SET clause, or in the WHERE
> clause of INSERT ON CONFLICT, but not when it appears in the RETURNING
> list.
>
> There was a separate discussion [1] about whether we should remove
> this requirement for colname to be qualified elsewhere in INSERT ON
> CONFLICT, and I think this patch adds more weight to that argument.
>
> [1] https://www.postgresql.org/message-id/flat/a31a76b6-b176-47fe-8778-9dfece231341@wikimedia.org
>
> So should we do that, and allow unqualified column names in ON
> CONFLICT SET and WHERE?
In my opinion, yes. Qualifying with the table name doesn’t really make it much clearer which version of the table you’re referring to than having it unqualified.

^ permalink  raw  reply  [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2026-06-22 10:13  Dean Rasheed <dean.a.rasheed@gmail.com>
  parent: Viktor Holmberg <v@viktorh.net>
  0 siblings, 1 reply; 17+ messages in thread

From: Dean Rasheed @ 2026-06-22 10:13 UTC (permalink / raw)
  To: Viktor Holmberg <v@viktorh.net>; +Cc: Vik Fearing <vik@postgresfriends.org>; pgsql-hackers

Rebased version attached, with no other changes.

Regards,
Dean

Attachments:

v6-0001-Allow-EXCLUDED-in-RETURNING-list-of-INSERT-ON-CON.patch (text/x-patch, 106.4K) download From 0316db29339f13de94e9765f6d7a3dfa6b18d7f1 Mon Sep 17 00:00:00 2001 From: Dean Rasheed <dean.a.rasheed@gmail.com> Date: Thu, 12 Feb 2026 10:53:16 +0000 Subject: [PATCH v6] Allow EXCLUDED in RETURNING list of INSERT ON CONFLICT DO SELECT/UPDATE. This allows an INSERT ... ON CONFLICT DO SELECT/UPDATE command to return the excluded values, when conflicts occur. For rows that do not conflict, the excluded values returned are NULL. This builds on the infrastructure added to support OLD/NEW values in the RETURNING list, except that in the case of EXCLUDED, there is no need for the special syntax to change the name of the excluded pseudo-relation in the RETURNING list. (That was required for OLD/NEW, because those names were already used in some situations, such as trigger functions, but there is no such problem with excluded.) Discussion: https://postgr.es/m/CAEZATCXXu2ohYmn=4YrRQa9yNwD_fdEEOTBPgM_5jhQOFcaQ4g@mail.gmail.com --- doc/src/sgml/dml.sgml | 13 +++ doc/src/sgml/ref/insert.sgml | 45 ++++++-- src/backend/executor/execExpr.c | 44 ++++++- src/backend/executor/execExprInterp.c | 21 +++- src/backend/executor/execPartition.c | 15 +++ src/backend/executor/nodeModifyTable.c | 54 ++++++--- src/backend/optimizer/path/allpaths.c | 3 +- src/backend/optimizer/plan/setrefs.c | 78 ++++++++----- src/backend/optimizer/prep/prepjointree.c | 22 ++-- src/backend/optimizer/prep/preptlist.c | 9 +- src/backend/optimizer/util/appendinfo.c | 4 +- src/backend/optimizer/util/clauses.c | 2 +- src/backend/optimizer/util/var.c | 11 +- src/backend/parser/analyze.c | 17 ++- src/backend/parser/parse_expr.c | 2 +- src/backend/parser/parse_relation.c | 4 +- src/backend/rewrite/rewriteHandler.c | 33 ++++-- src/backend/rewrite/rewriteManip.c | 69 ++++++----- src/include/executor/execExpr.h | 7 +- src/include/nodes/execnodes.h | 2 + src/include/nodes/primnodes.h | 26 +++-- src/include/parser/parse_node.h | 7 +- src/include/rewrite/rewriteManip.h | 4 +- src/test/regress/expected/arrays.out | 26 +++-- .../regress/expected/generated_stored.out | 48 +++++--- .../regress/expected/generated_virtual.out | 48 +++++--- src/test/regress/expected/inherit.out | 9 +- src/test/regress/expected/insert_conflict.out | 108 ++++++++++++------ src/test/regress/expected/returning.out | 22 ++-- src/test/regress/expected/rules.out | 61 ++++++++++ src/test/regress/expected/triggers.out | 64 +++++++++-- src/test/regress/expected/updatable_views.out | 27 ++++- src/test/regress/sql/arrays.sql | 9 +- src/test/regress/sql/generated_stored.sql | 4 + src/test/regress/sql/generated_virtual.sql | 4 + src/test/regress/sql/inherit.sql | 3 +- src/test/regress/sql/insert_conflict.sql | 33 +++--- src/test/regress/sql/returning.sql | 8 +- src/test/regress/sql/rules.sql | 27 +++++ src/test/regress/sql/triggers.sql | 18 +-- src/test/regress/sql/updatable_views.sql | 12 +- src/tools/pgindent/typedefs.list | 1 + 42 files changed, 746 insertions(+), 278 deletions(-) diff --git a/doc/src/sgml/dml.sgml b/doc/src/sgml/dml.sgml index 429aae9bd7b..fbf42a11362 100644 --- a/doc/src/sgml/dml.sgml +++ b/doc/src/sgml/dml.sgml @@ -565,6 +565,19 @@ UPDATE products SET price = price * 1.10 the new values may be non-<literal>NULL</literal>. </para> + <para> + In an <command>INSERT</command> with an + <literal>ON CONFLICT DO SELECT/UPDATE</literal> clause, it is also possible + to return the values excluded, if there is a conflict. For example: +<programlisting> +INSERT INTO products AS p SELECT * FROM new_products + ON CONFLICT (product_no) DO UPDATE SET name = excluded.name + RETURNING p.product_no, p.name, excluded.price; +</programlisting> + Excluded values will be <literal>NULL</literal> for rows that do not + conflict. + </para> + <para> If there are triggers (<xref linkend="triggers"/>) on the target table, the data available to <literal>RETURNING</literal> is the row as modified by diff --git a/doc/src/sgml/ref/insert.sgml b/doc/src/sgml/ref/insert.sgml index 121a9edcb99..753f51e3d56 100644 --- a/doc/src/sgml/ref/insert.sgml +++ b/doc/src/sgml/ref/insert.sgml @@ -187,10 +187,10 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac A substitute name for <replaceable class="parameter">table_name</replaceable>. When an alias is provided, it completely hides the actual name of the table. - This is particularly useful when <literal>ON CONFLICT DO UPDATE</literal> + This is particularly useful when <literal>ON CONFLICT DO SELECT/UPDATE</literal> targets a table named <varname>excluded</varname>, since that will otherwise be taken as the name of the special table representing the row proposed - for insertion. + for insertion (see note below). </para> </listitem> </varlistentry> @@ -353,6 +353,37 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac <literal>SELECT</literal> path is taken, the new values will be identical to the old values, since no modification takes place. </para> + + <para> + If the <command>INSERT</command> has an <literal>ON CONFLICT DO + SELECT/UPDATE</literal> clause, a column name or <literal>*</literal> + may be qualified using <literal>EXCLUDED</literal> to return the + values excluded from insertion, in the event of a conflict. If there + is no conflict, then all excluded values will be <literal>NULL</literal>. + </para> + + <note> + <para> + The special <varname>excluded</varname> table is made available + whenever an <command>INSERT</command> has an <literal>ON CONFLICT DO + SELECT/UPDATE</literal> clause. It has the same columns as the + target table, and in the event of a conflict, it is populated with + the values that would have been inserted. This includes any values + that were supplied by defaults, as well as the effects of any per-row + <literal>BEFORE INSERT</literal> triggers, since those may have + contributed to the row being excluded from insertion. + </para> + <para> + The <varname>excluded</varname> table is accessible from the + <literal>SET</literal> and <literal>WHERE</literal> clauses of an + <literal>ON CONFLICT DO UPDATE</literal> action, the + <literal>WHERE</literal> clause of an <literal>ON CONFLICT DO + SELECT</literal> action, and the <literal>RETURNING</literal> list. + <literal>SELECT</literal> privilege is required on any columns in the + target table where the corresponding <varname>excluded</varname> + columns are read. + </para> + </note> </listitem> </varlistentry> @@ -468,15 +499,7 @@ INSERT INTO <replaceable class="parameter">table_name</replaceable> [ AS <replac <literal>DO SELECT</literal> and <literal>DO UPDATE</literal> have access to the existing row using the table's name (or an alias), and to the row proposed for insertion using the special - <varname>excluded</varname> table. <literal>SELECT</literal> - privilege is required on any column in the target table where - corresponding <varname>excluded</varname> columns are read. - </para> - <para> - Note that the effects of all per-row <literal>BEFORE - INSERT</literal> triggers are reflected in - <varname>excluded</varname> values, since those effects may - have contributed to the row being excluded from insertion. + <varname>excluded</varname> table (see note above). </para> </listitem> </varlistentry> diff --git a/src/backend/executor/execExpr.c b/src/backend/executor/execExpr.c index cfea7e160c2..ff6ac96c23b 100644 --- a/src/backend/executor/execExpr.c +++ b/src/backend/executor/execExpr.c @@ -455,6 +455,7 @@ ExecBuildProjectionInfo(List *targetList, /* * Get the tuple from the relation being scanned, or the * old/new tuple slot, if old/new values were requested. + * Should not see EXCLUDED here (should be INNER_VAR). */ switch (variable->varreturningtype) { @@ -469,6 +470,10 @@ ExecBuildProjectionInfo(List *targetList, scratch.opcode = EEOP_ASSIGN_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -972,6 +977,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_SYSVAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -1007,6 +1016,10 @@ ExecInitExprRec(Expr *node, ExprState *state, scratch.opcode = EEOP_NEW_VAR; state->flags |= EEO_FLAG_HAS_NEW; break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -2631,10 +2644,23 @@ ExecInitExprRec(Expr *node, ExprState *state, ReturningExpr *rexpr = (ReturningExpr *) node; int retstep; - /* Skip expression evaluation if OLD/NEW row doesn't exist */ + /* + * Skip expression evaluation if OLD/NEW/EXCLUDED row doesn't + * exist. + */ scratch.opcode = EEOP_RETURNINGEXPR; - scratch.d.returningexpr.nullflag = rexpr->retold ? - EEO_FLAG_OLD_IS_NULL : EEO_FLAG_NEW_IS_NULL; + switch (rexpr->retkind) + { + case RETURNING_OLD_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_OLD_IS_NULL; + break; + case RETURNING_NEW_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_NEW_IS_NULL; + break; + case RETURNING_EXCLUDED_EXPR: + scratch.d.returningexpr.nullflag = EEO_FLAG_INNER_IS_NULL; + break; + } scratch.d.returningexpr.jumpdone = -1; /* set below */ ExprEvalPushStep(state, &scratch); retstep = state->steps_len - 1; @@ -2642,14 +2668,15 @@ ExecInitExprRec(Expr *node, ExprState *state, /* Steps to evaluate expression to return */ ExecInitExprRec(rexpr->retexpr, state, resv, resnull); - /* Jump target used if OLD/NEW row doesn't exist */ + /* Jump target used if OLD/NEW/EXCLUDED row doesn't exist */ state->steps[retstep].d.returningexpr.jumpdone = state->steps_len; /* Update ExprState flags */ - if (rexpr->retold) + if (rexpr->retkind == RETURNING_OLD_EXPR) state->flags |= EEO_FLAG_HAS_OLD; - else + else if (rexpr->retkind == RETURNING_NEW_EXPR) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ break; } @@ -3008,6 +3035,10 @@ expr_setup_walker(Node *node, ExprSetupInfo *info) case VAR_RETURNING_NEW: info->last_new = Max(info->last_new, attnum); break; + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } @@ -3173,6 +3204,7 @@ ExecInitWholeRowVar(ExprEvalStep *scratch, Var *variable, ExprState *state) state->flags |= EEO_FLAG_HAS_OLD; else if (variable->varreturningtype == VAR_RETURNING_NEW) state->flags |= EEO_FLAG_HAS_NEW; + /* we don't bother recording references to EXCLUDED */ /* * If the input tuple came from a subquery, it might contain "resjunk" diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c index 0634af964a9..1c79bbb4e26 100644 --- a/src/backend/executor/execExprInterp.c +++ b/src/backend/executor/execExprInterp.c @@ -5413,7 +5413,21 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) switch (variable->varno) { case INNER_VAR: - /* get the tuple from the inner node */ + + /* + * Get the tuple from the inner node. + * + * In a RETURNING expression, this is used for EXCLUDED values in + * an INSERT ... ON CONFLICT DO SELECT/UPDATE. If the + * non-conflicting branch is taken, the EXCLUDED row is NULL, and + * we return NULL rather than an all-NULL record. + */ + if (state->flags & EEO_FLAG_INNER_IS_NULL) + { + *op->resvalue = (Datum) 0; + *op->resnull = true; + return; + } slot = econtext->ecxt_innertuple; break; @@ -5458,6 +5472,11 @@ ExecEvalWholeRowVar(ExprState *state, ExprEvalStep *op, ExprContext *econtext) } slot = econtext->ecxt_newtuple; break; + + case VAR_RETURNING_EXCLUDED: + elog(ERROR, "wrong varno %d (expected %d) for variable returning excluded", + variable->varno, INNER_VAR); + break; } break; } diff --git a/src/backend/executor/execPartition.c b/src/backend/executor/execPartition.c index d96d4f9947b..771fe9c31a2 100644 --- a/src/backend/executor/execPartition.c +++ b/src/backend/executor/execPartition.c @@ -709,12 +709,27 @@ ExecInitPartitionInfo(ModifyTableState *mtstate, EState *estate, /* * Convert Vars in it to contain this partition's attribute numbers. + * If we're doing an INSERT ... ON CONFLICT DO SELECT/UPDATE, the + * RETURNING list might contain references to the EXCLUDED + * pseudo-relation (INNER_VAR), so we must map their attribute numbers + * too. */ if (part_attmap == NULL) part_attmap = build_attrmap_by_name(RelationGetDescr(partrel), RelationGetDescr(firstResultRel), false); + + if (node->onConflictAction != ONCONFLICT_NONE) + { + returningList = (List *) + map_variable_attnos((Node *) returningList, + INNER_VAR, 0, + part_attmap, + RelationGetForm(partrel)->reltype, + &found_whole_row); + /* We ignore the value of found_whole_row. */ + } returningList = (List *) map_variable_attnos((Node *) returningList, firstVarno, 0, diff --git a/src/backend/executor/nodeModifyTable.c b/src/backend/executor/nodeModifyTable.c index 33a6735f08d..db2b041e22d 100644 --- a/src/backend/executor/nodeModifyTable.c +++ b/src/backend/executor/nodeModifyTable.c @@ -304,6 +304,7 @@ ExecCheckPlanOutput(Relation resultRel, List *targetList) * oldSlot: slot holding old tuple deleted or updated * newSlot: slot holding new tuple inserted or updated * planSlot: slot holding tuple returned by top subplan node + * exclSlot: slot holding EXCLUDED tuple (for INSERT ... ON CONFLICT ...) * * Note: If oldSlot and newSlot are NULL, the FDW should have already provided * econtext's scan tuple and its old & new tuples are not needed (FDW direct- @@ -320,8 +321,11 @@ ExecProcessReturning(ModifyTableContext *context, bool isDelete, TupleTableSlot *oldSlot, TupleTableSlot *newSlot, - TupleTableSlot *planSlot) + TupleTableSlot *planSlot, + TupleTableSlot *exclSlot) { + ModifyTableState *mtstate = context->mtstate; + ModifyTable *node = (ModifyTable *) mtstate->ps.plan; EState *estate = context->estate; ProjectionInfo *projectReturning = resultRelInfo->ri_projectReturning; ExprContext *econtext = projectReturning->pi_exprContext; @@ -356,10 +360,18 @@ ExecProcessReturning(ModifyTableContext *context, else econtext->ecxt_newtuple = NULL; /* No references to NEW columns */ + /* Make EXCLUDED tuple available to ExecProject, if required */ + if (exclSlot) + econtext->ecxt_innertuple = exclSlot; + else if (node->onConflictAction != ONCONFLICT_NONE) + econtext->ecxt_innertuple = ExecGetAllNullSlot(estate, resultRelInfo); + else + econtext->ecxt_innertuple = NULL; + /* - * Tell ExecProject whether or not the OLD/NEW rows actually exist. This - * information is required to evaluate ReturningExpr nodes and also in - * ExecEvalSysVar() and ExecEvalWholeRowVar(). + * Tell ExecProject whether or not the OLD/NEW/EXCLUDED rows actually + * exist. This information is required to evaluate ReturningExpr nodes + * and also in ExecEvalSysVar() and ExecEvalWholeRowVar(). */ if (oldSlot == NULL) projectReturning->pi_state.flags |= EEO_FLAG_OLD_IS_NULL; @@ -371,6 +383,11 @@ ExecProcessReturning(ModifyTableContext *context, else projectReturning->pi_state.flags &= ~EEO_FLAG_NEW_IS_NULL; + if (exclSlot == NULL) + projectReturning->pi_state.flags |= EEO_FLAG_INNER_IS_NULL; + else + projectReturning->pi_state.flags &= ~EEO_FLAG_INNER_IS_NULL; + /* Compute the RETURNING expressions */ return ExecProject(projectReturning); } @@ -1371,7 +1388,7 @@ ExecInsert(ModifyTableContext *context, } result = ExecProcessReturning(context, resultRelInfo, false, - oldSlot, slot, planSlot); + oldSlot, slot, planSlot, NULL); /* * For a cross-partition UPDATE, release the old tuple, first making @@ -2166,7 +2183,7 @@ ldelete: } rslot = ExecProcessReturning(context, resultRelInfo, true, - slot, NULL, context->planSlot); + slot, NULL, context->planSlot, NULL); /* * Before releasing the target tuple again, make sure rslot has a @@ -2739,6 +2756,8 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, * planSlot is the output of the ModifyTable's subplan; we use it * to access values from other input tables (for RETURNING), * row-ID junk columns, etc. + * exclSlot contains the EXCLUDED tuple if this is the auxiliary + * UPDATE of an INSERT ... ON CONFLICT DO SELECT/UPDATE. * * Returns RETURNING result if any, otherwise NULL. On exit, if tupleid * had identified the tuple to update, it will identify the tuple @@ -2748,7 +2767,7 @@ ExecCrossPartitionUpdateForeignKey(ModifyTableContext *context, static TupleTableSlot * ExecUpdate(ModifyTableContext *context, ResultRelInfo *resultRelInfo, ItemPointer tupleid, HeapTuple oldtuple, TupleTableSlot *oldSlot, - TupleTableSlot *slot, bool canSetTag) + TupleTableSlot *slot, TupleTableSlot *exclSlot, bool canSetTag) { EState *estate = context->estate; Relation resultRelationDesc = resultRelInfo->ri_RelationDesc; @@ -2981,7 +3000,8 @@ redo_act: /* Process RETURNING if present */ if (resultRelInfo->ri_projectReturning) return ExecProcessReturning(context, resultRelInfo, false, - oldSlot, slot, context->planSlot); + oldSlot, slot, context->planSlot, + exclSlot); return NULL; } @@ -3221,6 +3241,7 @@ ExecOnConflictUpdate(ModifyTableContext *context, *returning = ExecUpdate(context, resultRelInfo, conflictTid, NULL, existing, resultRelInfo->ri_onConflict->oc_ProjSlot, + excludedSlot, canSetTag); /* @@ -3353,7 +3374,8 @@ ExecOnConflictSelect(ModifyTableContext *context, Assert(resultRelInfo->ri_projectReturning); *returning = ExecProcessReturning(context, resultRelInfo, false, - existing, existing, context->planSlot); + existing, existing, context->planSlot, + excludedSlot); if (canSetTag) context->estate->es_processed++; @@ -4007,7 +4029,8 @@ lmerge_matched: false, resultRelInfo->ri_oldTupleSlot, newslot, - context->planSlot); + context->planSlot, + NULL); break; case CMD_DELETE: @@ -4016,7 +4039,8 @@ lmerge_matched: true, resultRelInfo->ri_oldTupleSlot, NULL, - context->planSlot); + context->planSlot, + NULL); break; case CMD_NOTHING: @@ -4790,13 +4814,17 @@ ExecModifyTable(PlanState *pstate) * provide it here. The individual old and new slots are not * needed, since direct-modify is disabled if the RETURNING list * refers to OLD/NEW values. + * + * Currently, foreign tables do not support UNIQUE constraints, + * and therefore they do not support INSERT ... ON CONFLICT DO + * SELECT/UPDATE, and so the EXCLUDED slot is also not needed. */ Assert((resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_OLD) == 0 && (resultRelInfo->ri_projectReturning->pi_state.flags & EEO_FLAG_HAS_NEW) == 0); slot = ExecProcessReturning(&context, resultRelInfo, operation == CMD_DELETE, - NULL, NULL, context.planSlot); + NULL, NULL, context.planSlot, NULL); return slot; } @@ -4990,7 +5018,7 @@ ExecModifyTable(PlanState *pstate) /* Now apply the update. */ slot = ExecUpdate(&context, resultRelInfo, tupleid, oldtuple, - oldSlot, slot, node->canSetTag); + oldSlot, slot, NULL, node->canSetTag); if (tuplock) UnlockTuple(resultRelInfo->ri_RelationDesc, tupleid, InplaceUpdateTupleLock); diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index c134594a21a..78a344a3d3e 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -4563,8 +4563,7 @@ subquery_push_qual(Query *subquery, RangeTblEntry *rte, Index rti, Node *qual) * each component query gets its own copy of the qual. */ qual = ReplaceVarsFromTargetList(qual, rti, 0, rte, - subquery->targetList, - subquery->resultRelation, + subquery->targetList, 0, REPLACEVARS_REPORT_ERROR, 0, &subquery->hasSubLinks); diff --git a/src/backend/optimizer/plan/setrefs.c b/src/backend/optimizer/plan/setrefs.c index ff0e875f2a2..1cd12046e3c 100644 --- a/src/backend/optimizer/plan/setrefs.c +++ b/src/backend/optimizer/plan/setrefs.c @@ -206,6 +206,8 @@ static List *set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset); static List *set_windowagg_runcondition_references(PlannerInfo *root, List *runcondition, @@ -1109,10 +1111,15 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) { ModifyTable *splan = (ModifyTable *) plan; Plan *subplan = outerPlan(splan); + indexed_tlist *excl_itlist = NULL; Assert(splan->plan.targetlist == NIL); Assert(splan->plan.qual == NIL); + if (splan->onConflictAction == ONCONFLICT_UPDATE || + splan->onConflictAction == ONCONFLICT_SELECT) + excl_itlist = build_tlist_index(splan->exclRelTlist); + splan->withCheckOptionLists = fix_scan_list(root, splan->withCheckOptionLists, rtoffset, 1); @@ -1138,6 +1145,8 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) rlist, subplan, resultrel, + splan->exclRelRTI, + excl_itlist, rtoffset); newRL = lappend(newRL, rlist); } @@ -1166,23 +1175,19 @@ set_plan_refs(PlannerInfo *root, Plan *plan, int rtoffset) if (splan->onConflictAction == ONCONFLICT_UPDATE || splan->onConflictAction == ONCONFLICT_SELECT) { - indexed_tlist *itlist; - - itlist = build_tlist_index(splan->exclRelTlist); - splan->onConflictSet = fix_join_expr(root, splan->onConflictSet, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); splan->onConflictWhere = (Node *) fix_join_expr(root, (List *) splan->onConflictWhere, - NULL, itlist, + NULL, excl_itlist, linitial_int(splan->resultRelations), rtoffset, NRM_EQUAL, NUM_EXEC_QUAL(plan)); - pfree(itlist); + pfree(excl_itlist); splan->exclRelTlist = fix_scan_list(root, splan->exclRelTlist, rtoffset, 1); @@ -2880,12 +2885,12 @@ build_tlist_index(List *tlist) * build_tlist_index_other_vars --- build a restricted tlist index * * This is like build_tlist_index, but we only index tlist entries that - * are Vars belonging to some rel other than the one specified. We will set + * are Vars belonging to some rel other than the ones specified. We will set * has_ph_vars (allowing PlaceHolderVars to be matched), but not has_non_vars * (so nothing other than Vars and PlaceHolderVars can be matched). */ static indexed_tlist * -build_tlist_index_other_vars(List *tlist, int ignore_rel) +build_tlist_index_other_vars(List *tlist, int ignore_rel1, int ignore_rel2) { indexed_tlist *itlist; tlist_vinfo *vinfo; @@ -2910,7 +2915,7 @@ build_tlist_index_other_vars(List *tlist, int ignore_rel) { Var *var = (Var *) tle->expr; - if (var->varno != ignore_rel) + if (var->varno != ignore_rel1 && var->varno != ignore_rel2) { vinfo->varno = var->varno; vinfo->varattno = var->varattno; @@ -3149,10 +3154,14 @@ search_indexed_tlist_for_sortgroupref(Expr *node, * acceptable_rel should be zero so that any failure to match a Var will be * reported as an error. * 2) RETURNING clauses, which may contain both Vars of the target relation - * and Vars of other relations. In this case we want to replace the - * other-relation Vars by OUTER_VAR references, while leaving target Vars - * alone. Thus inner_itlist = NULL and acceptable_rel = the ID of the - * target relation should be passed. + * and Vars of other relations, including the EXCLUDED pseudo-relation in + * an INSERT ... ON CONFLICT DO SELECT/UPDATE command. In this case, we + * want to replace references to EXCLUDED with INNER_VAR references, and + * other-relation Vars with OUTER_VAR references, while leaving target Vars + * alone. Thus inner_itlist is to be EXCLUDED elements, if this is an + * INSERT with an ON CONFLICT DO SELECT/UPDATE clause, outer_itlist is any + * other non-target relation elements, and acceptable_rel = the ID of the + * target relation. * 3) ON CONFLICT SET and WHERE clauses. Here references to EXCLUDED are * to be replaced with INNER_VAR references, while leaving target Vars (the * to-be-updated relation) alone. Correspondingly inner_itlist is to be @@ -3213,15 +3222,16 @@ fix_join_expr_mutator(Node *node, fix_join_expr_context *context) /* * Verify that Vars with non-default varreturningtype only appear in - * the RETURNING list, and refer to the target relation. + * the RETURNING list, and that OLD/NEW Vars refer to the target + * relation. */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { - if (context->inner_itlist != NULL || - context->outer_itlist == NULL || + if (context->outer_itlist == NULL || context->acceptable_rel == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); - if (var->varno != context->acceptable_rel) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list"); + if (var->varreturningtype != VAR_RETURNING_EXCLUDED && + var->varno != context->acceptable_rel) elog(ERROR, "wrong varno %d (expected %d) for variable returning old/new", var->varno, context->acceptable_rel); } @@ -3451,11 +3461,14 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * * If the query involves more than just the result table, we have to * adjust any Vars that refer to other tables to reference junk tlist - * entries in the top subplan's targetlist. Vars referencing the result - * table should be left alone, however (the executor will evaluate them - * using the actual heap tuple, after firing triggers if any). In the - * adjusted RETURNING list, result-table Vars will have their original - * varno (plus rtoffset), but Vars for other rels will have varno OUTER_VAR. + * entries in the top subplan's targetlist. Vars referencing the EXCLUDED + * pseudo-relation of an INSERT ... ON CONFLICT DO SELECT/UPDATE command + * should be adjusted to reference INNER_VAR, and Vars referencing the result + * table should be left alone (the executor will evaluate them using the + * actual heap tuple, after firing triggers if any). In the adjusted RETURNING + * list, result-table Vars will have their original varno (plus rtoffset), but + * Vars for the EXCLUDED pseudo-relation and other rels will have varno + * INNER_VAR and OUTER_VAR espectively. * * We also must perform opcode lookup and add regclass OIDs to * root->glob->relationOids. @@ -3464,6 +3477,8 @@ fix_upper_expr_mutator(Node *node, fix_upper_expr_context *context) * 'topplan': the top subplan node that will be just below the ModifyTable * node (note it's not yet passed through set_plan_refs) * 'resultRelation': RT index of the associated result relation + * 'exclRelRTI': RT index of EXCLUDED pseudo-relation + * 'excl_itlist': EXCLUDED pseudo-relation elements (or NULL) * 'rtoffset': how much to increment varnos by * * Note: the given 'root' is for the parent query level, not the 'topplan'. @@ -3478,6 +3493,8 @@ set_returning_clause_references(PlannerInfo *root, List *rlist, Plan *topplan, Index resultRelation, + Index exclRelRTI, + indexed_tlist *excl_itlist, int rtoffset) { indexed_tlist *itlist; @@ -3485,9 +3502,11 @@ set_returning_clause_references(PlannerInfo *root, /* * We can perform the desired Var fixup by abusing the fix_join_expr * machinery that formerly handled inner indexscan fixup. We search the - * top plan's targetlist for Vars of non-result relations, and use - * fix_join_expr to convert RETURNING Vars into references to those tlist - * entries, while leaving result-rel Vars as-is. + * top plan's targetlist for Vars of non-result relations (other than + * EXCLUDED), and use fix_join_expr to convert RETURNING Vars into + * references to those tlist entries, and convert RETURNING EXCLUDED Vars + * into references to excl_itlist entries, while leaving result-rel Vars + * as-is. * * PlaceHolderVars will also be sought in the targetlist, but no * more-complex expressions will be. Note that it is not possible for a @@ -3496,12 +3515,13 @@ set_returning_clause_references(PlannerInfo *root, * prepared to pick apart the PlaceHolderVar and evaluate its contained * expression instead. */ - itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation); + itlist = build_tlist_index_other_vars(topplan->targetlist, resultRelation, + exclRelRTI); rlist = fix_join_expr(root, rlist, itlist, - NULL, + excl_itlist, resultRelation, rtoffset, NRM_EQUAL, diff --git a/src/backend/optimizer/prep/prepjointree.c b/src/backend/optimizer/prep/prepjointree.c index 4424fdbe906..3e56d09f792 100644 --- a/src/backend/optimizer/prep/prepjointree.c +++ b/src/backend/optimizer/prep/prepjointree.c @@ -72,8 +72,7 @@ typedef struct pullup_replace_vars_context PlannerInfo *root; List *targetlist; /* tlist of subquery being pulled up */ RangeTblEntry *target_rte; /* RTE of subquery */ - int result_relation; /* the index of the result relation in the - * rewritten query */ + int new_target_varno; /* see ReplaceVarFromTargetList() */ Relids relids; /* relids within subquery, as numbered after * pullup (set only if target_rte->lateral) */ nullingrel_info *nullinfo; /* per-RTE nullingrel info (set only if @@ -542,11 +541,20 @@ expand_virtual_generated_columns(PlannerInfo *root, Query *parse, * insert into the query, except that we may need to wrap them in * PlaceHolderVars. Set up required context data for * pullup_replace_vars. + * + * In order to handle any Vars with non-default varreturningtype, + * new_target_varno should equal rt_index if it is the result relation + * or the EXCLUDED pseudo-relation. Otherwise, it should be 0. See + * comments in ReplaceVarFromTargetList(). */ rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = parse->resultRelation; + if (rt_index == parse->resultRelation || + (parse->onConflict && rt_index == parse->onConflict->exclRelIndex)) + rvcontext.new_target_varno = rt_index; + else + rvcontext.new_target_varno = 0; /* won't need these values */ rvcontext.relids = NULL; rvcontext.nullinfo = NULL; @@ -1579,7 +1587,7 @@ pull_up_simple_subquery(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte, rvcontext.root = root; rvcontext.targetlist = subquery->targetList; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; if (rte->lateral) { rvcontext.relids = get_relids_in_jointree((Node *) subquery->jointree, @@ -2134,7 +2142,7 @@ pull_up_simple_values(PlannerInfo *root, Node *jtnode, RangeTblEntry *rte) rvcontext.root = root; rvcontext.targetlist = tlist; rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; rvcontext.relids = NULL; /* can't be any lateral references here */ rvcontext.nullinfo = NULL; rvcontext.outer_hasSubLinks = &parse->hasSubLinks; @@ -2294,7 +2302,7 @@ pull_up_constant_function(PlannerInfo *root, Node *jtnode, NULL, /* resname */ false)); /* resjunk */ rvcontext.target_rte = rte; - rvcontext.result_relation = 0; + rvcontext.new_target_varno = 0; /* * Since this function was reduced to a Const, it doesn't contain any @@ -2832,7 +2840,7 @@ pullup_replace_vars_callback(const Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, REPLACEVARS_REPORT_ERROR, 0); diff --git a/src/backend/optimizer/prep/preptlist.c b/src/backend/optimizer/prep/preptlist.c index 1647066a13d..3d70b9d01b9 100644 --- a/src/backend/optimizer/prep/preptlist.c +++ b/src/backend/optimizer/prep/preptlist.c @@ -293,7 +293,10 @@ preprocess_targetlist(PlannerInfo *root) * used in RETURNING that belong to other relations. We need to do this * to make these Vars available for the RETURNING calculation. Vars that * belong to the result rel don't need to be added, because they will be - * made to refer to the actual heap tuple. + * made to refer to the actual heap tuple. Vars that refer to the + * EXCLUDED pseudo-relation of an INSERT ... ON CONFLICT DO SELECT/UPDATE + * command are also not needed, because they are handled specially in the + * executor. */ if (parse->returningList && list_length(parse->rtable) > 1) { @@ -310,7 +313,9 @@ preprocess_targetlist(PlannerInfo *root) TargetEntry *tle; if (IsA(var, Var) && - var->varno == result_relation) + (var->varno == result_relation || + (parse->onConflict && + var->varno == parse->onConflict->exclRelIndex))) continue; /* don't need it */ if (tlist_member((Expr *) var, tlist)) diff --git a/src/backend/optimizer/util/appendinfo.c b/src/backend/optimizer/util/appendinfo.c index 778e4662f6e..ddf99a1a32d 100644 --- a/src/backend/optimizer/util/appendinfo.c +++ b/src/backend/optimizer/util/appendinfo.c @@ -260,8 +260,8 @@ adjust_appendrel_attrs_mutator(Node *node, * also needs to be copied to the translated Var. That too would fail * if the translation wasn't a Var, but that should never happen since * a non-default var->varreturningtype is only used for Vars referring - * to the result relation, which should never be a flattened UNION ALL - * subquery. + * to the result relation or the EXCLUDED pseudo-relation, which can + * never be a flattened UNION ALL subquery. */ for (cnt = 0; cnt < nappinfos; cnt++) diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 01997e22266..46bf08affc4 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -3770,7 +3770,7 @@ eval_const_expressions_mutator(Node *node, fselect->resulttypmod, fselect->resultcollid, ((Var *) arg)->varlevelsup); - /* New Var has same OLD/NEW returning as old one */ + /* New Var has same returningtype as old one */ newvar->varreturningtype = ((Var *) arg)->varreturningtype; /* New Var is nullable by same rels as the old one */ newvar->varnullingrels = ((Var *) arg)->varnullingrels; diff --git a/src/backend/optimizer/util/var.c b/src/backend/optimizer/util/var.c index 907a255c36f..86fa4414a45 100644 --- a/src/backend/optimizer/util/var.c +++ b/src/backend/optimizer/util/var.c @@ -501,8 +501,8 @@ contain_vars_of_level_walker(Node *node, int *sublevels_up) * * Returns true if any found. * - * Any ReturningExprs are also detected --- if an OLD/NEW Var was rewritten, - * we still regard this as a clause that returns OLD/NEW values. + * Any ReturningExprs are also checked --- if an OLD/NEW Var was rewritten, we + * still regard this as a clause that returns OLD/NEW values. * * Does not examine subqueries, therefore must only be used after reduction * of sublinks to subplans! @@ -521,13 +521,16 @@ contain_vars_returning_old_or_new_walker(Node *node, void *context) if (IsA(node, Var)) { if (((Var *) node)->varlevelsup == 0 && - ((Var *) node)->varreturningtype != VAR_RETURNING_DEFAULT) + (((Var *) node)->varreturningtype == VAR_RETURNING_OLD || + ((Var *) node)->varreturningtype == VAR_RETURNING_NEW)) return true; /* abort the tree traversal and return true */ return false; } if (IsA(node, ReturningExpr)) { - if (((ReturningExpr *) node)->retlevelsup == 0) + if (((ReturningExpr *) node)->retlevelsup == 0 && + (((ReturningExpr *) node)->retkind == RETURNING_OLD_EXPR || + ((ReturningExpr *) node)->retkind == RETURNING_NEW_EXPR)) return true; /* abort the tree traversal and return true */ return false; } diff --git a/src/backend/parser/analyze.c b/src/backend/parser/analyze.c index 93fa66ae57c..e0d8c1c6d41 100644 --- a/src/backend/parser/analyze.c +++ b/src/backend/parser/analyze.c @@ -1279,12 +1279,21 @@ transformOnConflictClause(ParseState *pstate, EXPR_KIND_WHERE, "WHERE"); /* - * Remove the EXCLUDED pseudo relation from the query namespace, since - * it's not supposed to be available in RETURNING. (Maybe someday we - * could allow that, and drop this step.) + * Leave the EXCLUDED pseudo relation in the query namespace so that + * it is available in RETURNING expressions, but change it to be a + * table-only item so that its columns are only accessible using + * qualified names. This ensures that columns from the target + * relation can be accessed using unqualified names without ambiguity. + * + * Also, set its returning_type so that any RETURNING list Vars + * referencing it are marked correctly. */ Assert((ParseNamespaceItem *) llast(pstate->p_namespace) == exclNSItem); - pstate->p_namespace = list_delete_last(pstate->p_namespace); + exclNSItem->p_cols_visible = false; + + exclNSItem->p_returning_type = VAR_RETURNING_EXCLUDED; + for (int i = 0; i < list_length(exclNSItem->p_names->colnames); i++) + exclNSItem->p_nscolumns[i].p_varreturningtype = VAR_RETURNING_EXCLUDED; } /* Finally, build ON CONFLICT DO [NOTHING | SELECT | UPDATE] expression */ diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c index 9adc9d4c0f6..8276fbba935 100644 --- a/src/backend/parser/parse_expr.c +++ b/src/backend/parser/parse_expr.c @@ -2685,7 +2685,7 @@ transformWholeRowRef(ParseState *pstate, ParseNamespaceItem *nsitem, result = makeWholeRowVar(nsitem->p_rte, nsitem->p_rtindex, sublevels_up, true); - /* mark Var for RETURNING OLD/NEW, as necessary */ + /* mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ result->varreturningtype = nsitem->p_returning_type; /* location is not filled in by makeWholeRowVar */ diff --git a/src/backend/parser/parse_relation.c b/src/backend/parser/parse_relation.c index ced210cd206..0a5766d0588 100644 --- a/src/backend/parser/parse_relation.c +++ b/src/backend/parser/parse_relation.c @@ -254,7 +254,7 @@ scanNameSpaceForRelid(ParseState *pstate, Oid relid, int location) /* If not inside LATERAL, ignore lateral-only items */ if (nsitem->p_lateral_only && !pstate->p_lateral_active) continue; - /* Ignore OLD/NEW namespace items that can appear in RETURNING */ + /* Ignore OLD/NEW/EXCLUDED namespace items in RETURNING */ if (nsitem->p_returning_type != VAR_RETURNING_DEFAULT) continue; @@ -803,7 +803,7 @@ scanNSItemForColumn(ParseState *pstate, ParseNamespaceItem *nsitem, } var->location = location; - /* Mark Var for RETURNING OLD/NEW, as necessary */ + /* Mark Var for RETURNING OLD/NEW/EXCLUDED, as necessary */ var->varreturningtype = nsitem->p_returning_type; /* Mark Var if it's nulled by any outer joins */ diff --git a/src/backend/rewrite/rewriteHandler.c b/src/backend/rewrite/rewriteHandler.c index e7ae9cce65f..028a05638f4 100644 --- a/src/backend/rewrite/rewriteHandler.c +++ b/src/backend/rewrite/rewriteHandler.c @@ -664,7 +664,7 @@ rewriteRuleAction(Query *parsetree, 0, new_rte, parsetree->targetList, - sub_action->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -681,7 +681,7 @@ rewriteRuleAction(Query *parsetree, 0, new_rte, list_concat(gen_cols, parsetree->targetList), - sub_action->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -2425,7 +2425,7 @@ CopyAndAddInvertedQual(Query *parsetree, 0, rte, parsetree->targetList, - parsetree->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -2438,7 +2438,7 @@ CopyAndAddInvertedQual(Query *parsetree, rte, list_concat(gen_cols, parsetree->targetList), - parsetree->resultRelation, + 0, (event == CMD_UPDATE) ? REPLACEVARS_CHANGE_VARNO : REPLACEVARS_SUBSTITUTE_NULL, @@ -3845,12 +3845,12 @@ rewriteTargetView(Query *parsetree, Relation view) BuildOnConflictExcludedTargetlist(base_rel, new_exclRelIndex); /* - * Update all Vars in the ON CONFLICT clause that refer to the old - * EXCLUDED pseudo-relation. We want to use the column mappings - * defined in the view targetlist, but we need the outputs to refer to - * the new EXCLUDED pseudo-relation rather than the new target RTE. - * Also notice that "EXCLUDED.*" will be expanded using the view's - * rowtype, which seems correct. + * Update all Vars in the ON CONFLICT clause and RETURNING list that + * refer to the old EXCLUDED pseudo-relation. We want to use the + * column mappings defined in the view targetlist, but we need the + * outputs to refer to the new EXCLUDED pseudo-relation rather than + * the new target RTE. Also notice that "EXCLUDED.*" will be expanded + * using the view's rowtype, which seems correct. */ tmp_tlist = copyObject(view_targetlist); @@ -3863,7 +3863,18 @@ rewriteTargetView(Query *parsetree, Relation view) 0, view_rte, tmp_tlist, - new_rt_index, + 0, + REPLACEVARS_REPORT_ERROR, + 0, + &parsetree->hasSubLinks); + + parsetree->returningList = (List *) + ReplaceVarsFromTargetList((Node *) parsetree->returningList, + old_exclRelIndex, + 0, + view_rte, + tmp_tlist, + new_exclRelIndex, REPLACEVARS_REPORT_ERROR, 0, &parsetree->hasSubLinks); diff --git a/src/backend/rewrite/rewriteManip.c b/src/backend/rewrite/rewriteManip.c index 9aa7ef60475..ff100511610 100644 --- a/src/backend/rewrite/rewriteManip.c +++ b/src/backend/rewrite/rewriteManip.c @@ -930,7 +930,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, /* * SetVarReturningType - adjust Var nodes for a specified varreturningtype. * - * Find all Var nodes referring to the specified result relation in the given + * Find all Var nodes referring to the specified relation in the given * expression and set their varreturningtype to the specified value. * * NOTE: although this has the form of a walker, we cheat and modify the @@ -940,7 +940,7 @@ IncrementVarSublevelsUp_rtable(List *rtable, int delta_sublevels_up, typedef struct { - int result_relation; + int target_varno; int sublevels_up; VarReturningType returning_type; } SetVarReturningType_context; @@ -954,7 +954,7 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) { Var *var = (Var *) node; - if (var->varno == context->result_relation && + if (var->varno == context->target_varno && var->varlevelsup == context->sublevels_up) var->varreturningtype = context->returning_type; @@ -976,12 +976,12 @@ SetVarReturningType_walker(Node *node, SetVarReturningType_context *context) } static void -SetVarReturningType(Node *node, int result_relation, int sublevels_up, +SetVarReturningType(Node *node, int target_varno, int sublevels_up, VarReturningType returning_type) { SetVarReturningType_context context; - context.result_relation = result_relation; + context.target_varno = target_varno; context.sublevels_up = sublevels_up; context.returning_type = returning_type; @@ -1734,14 +1734,29 @@ map_variable_attnos(Node *node, * relation. This is needed to handle whole-row Vars referencing the target. * We expand such Vars into RowExpr constructs. * - * In addition, for INSERT/UPDATE/DELETE/MERGE queries, the caller must - * provide result_relation, the index of the result relation in the rewritten - * query. This is needed to handle OLD/NEW RETURNING list Vars referencing - * target_varno. When such Vars are expanded, their varreturningtype is - * copied onto any replacement Vars referencing result_relation. In addition, - * if the replacement expression from the targetlist is not simply a Var - * referencing result_relation, it is wrapped in a ReturningExpr node (causing - * the executor to return NULL if the OLD/NEW row doesn't exist). + * In addition, the caller should provide new_target_varno, which is needed to + * handle any OLD/NEW/EXCLUDED RETURNING list Vars (Vars with non-default + * varreturningtype) referencing target_varno. When such Vars are expanded, + * their varreturningtype is copied onto any Vars that reference + * new_target_varno in the replacement expression from the targetlist. In + * addition, if the replacement expression is not simply a Var referencing + * new_target_varno, it is wrapped in a ReturningExpr node (causing the + * executor to return NULL if the OLD/NEW/EXCLUDED row doesn't exist). The + * caller should set new_target_varno as follows: + * + * If the input node contains Vars from the RETURNING list of a query, and + * target_varno is the resultRelation of that query, then new_target_varno + * should be the (possibly new) resultRelation of the rewritten query. + * + * If the input node contains Vars from the RETURNING list of an INSERT ... + * ON CONFLICT DO SELECT/UPDATE query, and target_varno is the index of the + * EXCLUDED pseudo-relation, then new_target_varno should be the (possibly + * new) index of the EXCLUDED pseudo-relation in the rewritten query. + * + * Otherwise, new_target_varno should be set to 0 in order to detect any + * Vars with non-default varreturningtype outside the RETURNING list, or + * referencing a relation other than the result relation or the EXCLUDED + * pseudo-relation. * * Note that ReplaceVarFromTargetList always generates the replacement * expression with varlevelsup = 0. The caller is responsible for adjusting @@ -1755,7 +1770,7 @@ typedef struct { RangeTblEntry *target_rte; List *targetlist; - int result_relation; + int new_target_varno; ReplaceVarsNoMatchOption nomatch_option; int nomatch_varno; } ReplaceVarsFromTargetList_context; @@ -1770,7 +1785,7 @@ ReplaceVarsFromTargetList_callback(const Var *var, newnode = ReplaceVarFromTargetList(var, rcon->target_rte, rcon->targetlist, - rcon->result_relation, + rcon->new_target_varno, rcon->nomatch_option, rcon->nomatch_varno); @@ -1785,7 +1800,7 @@ Node * ReplaceVarFromTargetList(const Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno) { @@ -1834,7 +1849,7 @@ ReplaceVarFromTargetList(const Var *var, field = ReplaceVarFromTargetList((Var *) field, target_rte, targetlist, - result_relation, + new_target_varno, nomatch_option, nomatch_varno); rowexpr->args = lappend(rowexpr->args, field); @@ -1846,7 +1861,7 @@ ReplaceVarFromTargetList(const Var *var, ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = (Expr *) rowexpr; return (Node *) rexpr; @@ -1918,28 +1933,28 @@ ReplaceVarFromTargetList(const Var *var, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("NEW variables in ON UPDATE rules cannot reference columns that are part of a multiple assignment in the subject UPDATE command"))); - /* Handle any OLD/NEW RETURNING list Vars */ + /* Handle any OLD/NEW/EXCLUDED RETURNING list Vars */ if (var->varreturningtype != VAR_RETURNING_DEFAULT) { /* * Copy varreturningtype onto any Vars in the tlist item that - * refer to result_relation (which had better be non-zero). + * refer to new_target_varno (which had better be non-zero). */ - if (result_relation == 0) - elog(ERROR, "variable returning old/new found outside RETURNING list"); + if (new_target_varno == 0) + elog(ERROR, "variable returning old/new/excluded found outside RETURNING list, or referencing a relation other than the result relation or the EXCLUDED pseudo-relation"); - SetVarReturningType((Node *) newnode, result_relation, + SetVarReturningType((Node *) newnode, new_target_varno, 0, var->varreturningtype); /* Wrap it in a ReturningExpr, if needed, per comments above */ if (!IsA(newnode, Var) || - ((Var *) newnode)->varno != result_relation || + ((Var *) newnode)->varno != new_target_varno || ((Var *) newnode)->varlevelsup != 0) { ReturningExpr *rexpr = makeNode(ReturningExpr); rexpr->retlevelsup = 0; - rexpr->retold = (var->varreturningtype == VAR_RETURNING_OLD); + rexpr->retkind = (ReturningExprKind) var->varreturningtype; rexpr->retexpr = newnode; newnode = (Expr *) rexpr; @@ -1955,7 +1970,7 @@ ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks) @@ -1964,7 +1979,7 @@ ReplaceVarsFromTargetList(Node *node, context.target_rte = target_rte; context.targetlist = targetlist; - context.result_relation = result_relation; + context.new_target_varno = new_target_varno; context.nomatch_option = nomatch_option; context.nomatch_varno = nomatch_varno; diff --git a/src/include/executor/execExpr.h b/src/include/executor/execExpr.h index c61b3d624d5..e66d20c8113 100644 --- a/src/include/executor/execExpr.h +++ b/src/include/executor/execExpr.h @@ -26,9 +26,9 @@ struct JsonConstructorExprState; /* Bits in ExprState->flags (see also execnodes.h for public flag bits): */ /* expression's interpreter has been initialized */ -#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 5) +#define EEO_FLAG_INTERPRETER_INITIALIZED (1 << 6) /* jump-threading is in use */ -#define EEO_FLAG_DIRECT_THREADED (1 << 6) +#define EEO_FLAG_DIRECT_THREADED (1 << 7) /* Typical API for out-of-line evaluation subroutines */ typedef void (*ExecEvalSubroutine) (ExprState *state, @@ -338,7 +338,8 @@ typedef struct ExprEvalStep /* but it's just the normal (negative) attr number for SYSVAR */ int attnum; Oid vartype; /* type OID of variable */ - VarReturningType varreturningtype; /* return old/new/default */ + /* if not default, return old/new/excluded value */ + VarReturningType varreturningtype; } var; /* for EEOP_WHOLEROW */ diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h index 53c138310db..27dfc3456fc 100644 --- a/src/include/nodes/execnodes.h +++ b/src/include/nodes/execnodes.h @@ -94,6 +94,8 @@ typedef Datum (*ExprStateEvalFunc) (ExprState *expression, #define EEO_FLAG_OLD_IS_NULL (1 << 3) /* NEW table row is NULL in RETURNING list */ #define EEO_FLAG_NEW_IS_NULL (1 << 4) +/* INNER (EXCLUDED) table row is NULL in RETURNING list */ +#define EEO_FLAG_INNER_IS_NULL (1 << 5) typedef struct ExprState { diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h index bb05aeebee4..02e5f332751 100644 --- a/src/include/nodes/primnodes.h +++ b/src/include/nodes/primnodes.h @@ -228,7 +228,9 @@ typedef struct Expr * varreturningtype is used for Vars that refer to the target relation in the * RETURNING list of data-modifying queries. The default behavior is to * return old values for DELETE and new values for INSERT and UPDATE, but it - * is also possible to explicitly request old or new values. + * is also possible to explicitly request old or new values. For INSERT ... + * ON CONFLICT DO SELECT/UPDATE, varreturningtype is also used for Vars in the + * RETURNING list that refer to the EXCLUDED pseudo-relation. * * In the parser, varnosyn and varattnosyn are either identical to * varno/varattno, or they specify the column's position in an aliased JOIN @@ -257,6 +259,7 @@ typedef enum VarReturningType VAR_RETURNING_DEFAULT, /* return OLD for DELETE, else return NEW */ VAR_RETURNING_OLD, /* return OLD for DELETE/UPDATE, else NULL */ VAR_RETURNING_NEW, /* return NEW for INSERT/UPDATE, else NULL */ + VAR_RETURNING_EXCLUDED, /* return EXCLUDED on conflict, else NULL */ } VarReturningType; typedef struct Var @@ -2150,14 +2153,15 @@ typedef struct InferenceElem } InferenceElem; /* - * ReturningExpr - return OLD/NEW.(expression) in RETURNING list + * ReturningExpr - return OLD/NEW/EXCLUDED.(expression) in RETURNING list * * This is used when updating an auto-updatable view and returning a view * column that is not simply a Var referring to the base relation. In such - * cases, OLD/NEW.viewcol can expand to an arbitrary expression, but the - * result is required to be NULL if the OLD/NEW row doesn't exist. To handle - * this, the rewriter wraps the expanded expression in a ReturningExpr, which - * is equivalent to "CASE WHEN (OLD/NEW row exists) THEN (expr) ELSE NULL". + * cases, OLD/NEW/EXCLUDED.viewcol can expand to an arbitrary expression, but + * the result is required to be NULL if the OLD/NEW/EXCLUDED row doesn't + * exist. To handle this, the rewriter wraps the expanded expression in a + * ReturningExpr, which is equivalent to "CASE WHEN (OLD/NEW/EXCLUDED row + * exists) THEN (expr) ELSE NULL". * * A similar situation can arise when rewriting the RETURNING clause of a * rule, which may also contain arbitrary expressions. @@ -2165,11 +2169,19 @@ typedef struct InferenceElem * ReturningExpr nodes never appear in a parsed Query --- they are only ever * inserted by the rewriter and the planner. */ +typedef enum ReturningExprKind +{ + /* values here match non-default VarReturningType values */ + RETURNING_OLD_EXPR = VAR_RETURNING_OLD, + RETURNING_NEW_EXPR = VAR_RETURNING_NEW, + RETURNING_EXCLUDED_EXPR = VAR_RETURNING_EXCLUDED, +} ReturningExprKind; + typedef struct ReturningExpr { Expr xpr; int retlevelsup; /* > 0 if it belongs to outer query */ - bool retold; /* true for OLD, false for NEW */ + ReturningExprKind retkind; /* return OLD/NEW/EXCLUDED expression */ Expr *retexpr; /* expression to be returned */ } ReturningExpr; diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h index f7f4ba6c2a8..076632484a5 100644 --- a/src/include/parser/parse_node.h +++ b/src/include/parser/parse_node.h @@ -300,7 +300,8 @@ struct ParseState * forbid LATERAL references to an UPDATE/DELETE target table. * * While processing the RETURNING clause, special namespace items are added to - * refer to the OLD and NEW state of the result relation. These namespace + * refer to the OLD and NEW state of the result relation, and EXCLUDED pseudo- + * relation for INSERT ... ON CONFLICT DO SELECT/UPDATE. These namespace * items have p_returning_type set appropriately, for use when creating Vars. * For convenience, this information is duplicated on each namespace column. * @@ -321,7 +322,7 @@ struct ParseNamespaceItem bool p_cols_visible; /* Column names visible as unqualified refs? */ bool p_lateral_only; /* Is only visible to LATERAL expressions? */ bool p_lateral_ok; /* If so, does join type allow use? */ - VarReturningType p_returning_type; /* Is OLD/NEW for use in RETURNING? */ + VarReturningType p_returning_type; /* for RETURNING OLD/NEW/EXCLUDED */ }; /* @@ -352,7 +353,7 @@ struct ParseNamespaceColumn Oid p_vartype; /* pg_type OID */ int32 p_vartypmod; /* type modifier value */ Oid p_varcollid; /* OID of collation, or InvalidOid */ - VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW */ + VarReturningType p_varreturningtype; /* for RETURNING OLD/NEW/EXCLUDED */ Index p_varnosyn; /* rangetable index of syntactic referent */ AttrNumber p_varattnosyn; /* attribute number of syntactic referent */ bool p_dontexpand; /* not included in star expansion */ diff --git a/src/include/rewrite/rewriteManip.h b/src/include/rewrite/rewriteManip.h index 9d234cb8741..930438dbacc 100644 --- a/src/include/rewrite/rewriteManip.h +++ b/src/include/rewrite/rewriteManip.h @@ -107,14 +107,14 @@ extern Node *map_variable_attnos(Node *node, extern Node *ReplaceVarFromTargetList(const Var *var, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno); extern Node *ReplaceVarsFromTargetList(Node *node, int target_varno, int sublevels_up, RangeTblEntry *target_rte, List *targetlist, - int result_relation, + int new_target_varno, ReplaceVarsNoMatchOption nomatch_option, int nomatch_varno, bool *outer_hasSubLinks); diff --git a/src/test/regress/expected/arrays.out b/src/test/regress/expected/arrays.out index 66439d427a3..12b5a7be7af 100644 --- a/src/test/regress/expected/arrays.out +++ b/src/test/regress/expected/arrays.out @@ -1398,20 +1398,30 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+--------- - 1 | {3,2,5} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+---------+------------- + 1 | {3,2,5} | {3,4,5} (1 row) insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; - pk | f1 -----+------------ - 1 | {6,7,NULL} + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+------------+------------- + 1 | {6,7,NULL} | {6,7} +(1 row) + +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; + pk | f1 | excluded f1 +----+----------------+------------- + 1 | {NULL,10,NULL} | [2:2]={10} (1 row) -- note: if above selects don't produce the expected tuple order, diff --git a/src/test/regress/expected/generated_stored.out b/src/test/regress/expected/generated_stored.out index e17ba2f4881..fa8376ff0f1 100644 --- a/src/test/regress/expected/generated_stored.out +++ b/src/test/regress/expected/generated_stored.out @@ -114,32 +114,44 @@ INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error ERROR: cannot insert a non-DEFAULT value into column "b" DETAIL: Column "b" is a generated column. INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + a | b | a | b | a | b +---+---+-----+-----+---+--- + 4 | 8 | 104 | 208 | 4 | 8 + | | 5 | 10 | | +(2 rows) + SELECT * FROM gtest1 ORDER BY a; - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference - gtest1 --------- + gtest1 +----------- (1,2) (2,4) (3,6) - (4,8) -(4 rows) + (5,10) + (104,208) +(5 rows) SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) DELETE FROM gtest1 WHERE a >= 3; UPDATE gtest1 SET b = DEFAULT WHERE a = 1; diff --git a/src/test/regress/expected/generated_virtual.out b/src/test/regress/expected/generated_virtual.out index 01ee29fee10..25fb30d42bf 100644 --- a/src/test/regress/expected/generated_virtual.out +++ b/src/test/regress/expected/generated_virtual.out @@ -114,32 +114,44 @@ INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error ERROR: cannot insert a non-DEFAULT value into column "b" DETAIL: Column "b" is a generated column. INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + a | b | a | b | a | b +---+---+-----+-----+---+--- + 4 | 8 | 104 | 208 | 4 | 8 + | | 5 | 10 | | +(2 rows) + SELECT * FROM gtest1 ORDER BY a; - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference - gtest1 --------- + gtest1 +----------- (1,2) (2,4) (3,6) - (4,8) -(4 rows) + (5,10) + (104,208) +(5 rows) SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink - a | b ----+--- - 1 | 2 - 2 | 4 - 3 | 6 - 4 | 8 -(4 rows) + a | b +-----+----- + 1 | 2 + 2 | 4 + 3 | 6 + 5 | 10 + 104 | 208 +(5 rows) DELETE FROM gtest1 WHERE a >= 3; UPDATE gtest1 SET b = DEFAULT WHERE a = 1; diff --git a/src/test/regress/expected/inherit.out b/src/test/regress/expected/inherit.out index 3d8e8d8afd2..3cb0c713c7e 100644 --- a/src/test/regress/expected/inherit.out +++ b/src/test/regress/expected/inherit.out @@ -2219,7 +2219,14 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; + old | new | excluded +--------+---------+---------- + (3,3-) | (3,3-+) | (3,) + (7,7-) | (7,7-+) | (7,) +(2 rows) + select * from inhpar order by f1; -- tuple order might be unstable here f1 | f2 ----+----- diff --git a/src/test/regress/expected/insert_conflict.out b/src/test/regress/expected/insert_conflict.out index 34e2e7ee355..5976dee1e4d 100644 --- a/src/test/regress/expected/insert_conflict.out +++ b/src/test/regress/expected/insert_conflict.out @@ -281,13 +281,13 @@ insert into insertconflicttest values (2, 'Orange') on conflict (key, key, key) insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -ERROR: invalid reference to FROM-clause entry for table "excluded" -LINE 1: ...y) do update set fruit = excluded.fruit RETURNING excluded.f... - ^ -DETAIL: There is an entry for table "excluded", but it cannot be referenced from this part of the query. + fruit +------- + Apple +(1 row) + -- Only suggest <table>.* column when inference element misspelled: insert into insertconflicttest values (1, 'Apple') on conflict (keyy) do update set fruit = excluded.fruit; ERROR: column "keyy" does not exist @@ -482,33 +482,33 @@ drop index partial_key_index; create unique index plain on insertconflicttest(key); -- Succeeds, updates existing row: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; - key | fruit ------+----------- - 23 | Jackfruit + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-----------+----------+---------- + 23 | Jackfruit | f | t (1 row) -- No update this time, though: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; - key | fruit ------+------- + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-------+----------+---------- (0 rows) -- Predicate changed to require match rather than non-match, so updates once more: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* = excluded.* returning *; - key | fruit ------+----------- - 23 | Jackfruit + where i.* = excluded.* returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+-----------+----------+---------- + 23 | Jackfruit | t | t (1 row) -- Assign: insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text - returning *; - key | fruit ------+-------------- - 23 | (23,Avocado) + returning *, excluded.* = old.*, excluded.* = new.*; + key | fruit | ?column? | ?column? +-----+--------------+----------+---------- + 23 | (23,Avocado) | f | f (1 row) -- deparse whole row var in WHERE and SET clauses: @@ -546,6 +546,10 @@ insert into syscolconflicttest values (1) on conflict (key) do update set data = ERROR: column excluded.ctid does not exist LINE 1: ...values (1) on conflict (key) do update set data = excluded.c... ^ +insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.data returning excluded.ctid; +ERROR: column excluded.ctid does not exist +LINE 1: ...key) do update set data = excluded.data returning excluded.c... + ^ drop table syscolconflicttest; -- -- Previous tests all managed to not test any expressions requiring @@ -620,7 +624,13 @@ select * from capitals; -- Succeeds: insert into cities values ('Las Vegas', 2.583E+5, 2174) on conflict do nothing; -insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; + name | population | altitude | state | name | population | altitude | state | name | population | altitude | state +------------+------------+----------+-------+------------+------------+----------+-------+------------+------------+----------+------- + Sacramento | 369400 | 30 | CA | Sacramento | 466400000 | 30 | CA | Sacramento | 466400000 | 30 | CA +(1 row) + -- Wrong "Sacramento", so do nothing: insert into capitals values ('Sacramento', 50, 2267, 'NE') on conflict (name) do nothing; select * from capitals; @@ -630,7 +640,13 @@ select * from capitals; Sacramento | 466400000 | 30 | CA (2 rows) -insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old, new, excluded; + old | new | excluded +---------------------------+---------------------------+--------------------------- + ("Las Vegas",258300,2174) | ("Las Vegas",583000,2001) | ("Las Vegas",583000,2001) +(1 row) + select tableoid::regclass, * from cities; tableoid | name | population | altitude ----------+---------------+------------+---------- @@ -641,7 +657,13 @@ select tableoid::regclass, * from cities; capitals | Sacramento | 466400000 | 30 (5 rows) -insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population + returning old, new, excluded; + old | new | excluded +-----+------------------------------+---------- + | ("Las Vegas",583000,2222,NV) | +(1 row) + -- Capitals will contain new capital, Las Vegas: select * from capitals; name | population | altitude | state @@ -665,7 +687,13 @@ select tableoid::regclass, * from cities; (6 rows) -- This only affects "cities" version of "Las Vegas": -insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; + name | population | altitude | name | population | altitude | name | population | altitude +-----------+------------+----------+-----------+------------+----------+-----------+------------+---------- + Las Vegas | 583000 | 2001 | Las Vegas | 586000 | 2223 | Las Vegas | 586000 | 2223 +(1 row) + select tableoid::regclass, * from cities; tableoid | name | population | altitude ----------+---------------+------------+---------- @@ -702,11 +730,17 @@ insert into excluded AS target values(1, '2') on conflict (key) do update set da 1 | 2 (1 row) --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; - key | data ------+------ - 1 | 3 +ERROR: table reference "excluded" is ambiguous +LINE 1: ...n conflict (key) do update set data = 3 RETURNING excluded.*... + ^ +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; + key | data | key | data +-----+------+-----+------ + 1 | 3 | 1 | 2 (1 row) -- clean up @@ -925,10 +959,10 @@ insert into parted_conflict_test values (3, 'a') on conflict (a) do select where (3,b) (1 row) -insert into parted_conflict_test values (3, 'a') on conflict (a) do select where parted_conflict_test.b = 'b' returning b; - b ---- - b +insert into parted_conflict_test values (3, 'a') on conflict (a) do select where parted_conflict_test.b = 'b' returning b, excluded; + b | excluded +---+---------- + b | (3,a) (1 row) -- should see (3, 'b') @@ -944,10 +978,10 @@ create table parted_conflict_test_3 partition of parted_conflict_test for values truncate parted_conflict_test; insert into parted_conflict_test (a, b) values (4, 'a') on conflict (a) do update set b = excluded.b; insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do update set b = excluded.b where parted_conflict_test.b = 'a'; -insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do select returning b; - b ---- - b +insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do select returning b, excluded; + b | excluded +---+---------- + b | (4,b) (1 row) -- should see (4, 'b') diff --git a/src/test/regress/expected/returning.out b/src/test/regress/expected/returning.out index ca83d9fcc09..d4ccc61c039 100644 --- a/src/test/regress/expected/returning.out +++ b/src/test/regress/expected/returning.out @@ -463,18 +463,19 @@ INSERT INTO foo VALUES (4) | | | | | | foo | (0,4) | 4 | | 42 | 99 | 4 | | 42 | 99 (1 row) --- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW +-- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW (and EXLCUDED) CREATE UNIQUE INDEX foo_f1_idx ON foo (f1); EXPLAIN (verbose, costs off) INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; - QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------------------------------------- + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; + QUERY PLAN +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Insert on pg_temp.foo - Output: (o.tableoid)::regclass, o.ctid, o.f1, o.f2, o.f3, o.f4, (n.tableoid)::regclass, n.ctid, n.f1, n.f2, n.f3, n.f4, foo.f1, foo.f2, foo.f3, foo.f4 + Output: (o.tableoid)::regclass, o.ctid, o.f1, o.f2, o.f3, o.f4, (n.tableoid)::regclass, n.ctid, n.f1, n.f2, n.f3, n.f4, foo.f1, foo.f2, foo.f3, foo.f4, excluded.f1, excluded.f2, excluded.f3, excluded.f4 Conflict Resolution: UPDATE Conflict Arbiter Indexes: foo_f1_idx -> Values Scan on "*VALUES*" @@ -485,11 +486,12 @@ INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; - tableoid | ctid | f1 | f2 | f3 | f4 | tableoid | ctid | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 -----------+-------+----+----+----+----+----------+-------+----+------------+----+----+----+------------+----+---- - foo | (0,4) | 4 | | 42 | 99 | foo | (0,5) | 4 | conflicted | -1 | 99 | 4 | conflicted | -1 | 99 - | | | | | | foo | (0,6) | 5 | ok | 42 | 99 | 5 | ok | 42 | 99 + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; + tableoid | ctid | f1 | f2 | f3 | f4 | tableoid | ctid | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 | f1 | f2 | f3 | f4 +----------+-------+----+----+----+----+----------+-------+----+------------+----+----+----+------------+----+----+----+----------+----+---- + foo | (0,4) | 4 | | 42 | 99 | foo | (0,5) | 4 | conflicted | -1 | 99 | 4 | conflicted | -1 | 99 | 4 | conflict | 42 | 99 + | | | | | | foo | (0,6) | 5 | ok | 42 | 99 | 5 | ok | 42 | 99 | | | | (2 rows) -- UPDATE has OLD and NEW diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index a65a5bf0c4f..be2c9e442d1 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -3705,6 +3705,67 @@ SELECT * FROM hat_data WHERE hat_name IN ('h8', 'h9', 'h7') ORDER BY hat_name; h9 | blue (3 rows) +DROP RULE hat_upsert ON hats; +-- DO UPDATE ... RETURNING excluded values +CREATE RULE hat_upsert AS ON INSERT TO hats + DO INSTEAD + INSERT INTO hat_data VALUES ( + NEW.hat_name, + NEW.hat_color) + ON CONFLICT (hat_name) + DO UPDATE + SET hat_name = hat_data.hat_name, hat_color = 'Excl: '||excluded.hat_color + WHERE excluded.hat_color <> 'forbidden' AND hat_data.* != excluded.* + RETURNING excluded.*; +SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename; + definition +--------------------------------------------------------------------------------------------------------------------------------------------------------------------- + CREATE RULE hat_upsert AS + + ON INSERT TO public.hats DO INSTEAD INSERT INTO hat_data (hat_name, hat_color) + + VALUES (new.hat_name, new.hat_color) ON CONFLICT(hat_name) DO UPDATE SET hat_name = hat_data.hat_name, hat_color = ('Excl: '::text || (excluded.hat_color)::text)+ + WHERE ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) + + RETURNING excluded.hat_name, + + excluded.hat_color; +(1 row) + +-- EXCLUDED not allowed in plain INSERT +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING excluded.*; +ERROR: missing FROM-clause entry for table "excluded" +LINE 2: RETURNING excluded.*; + ^ +-- OLD/NEW have no effect on EXCLUDED +EXPLAIN (verbose, costs off) +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; + QUERY PLAN +------------------------------------------------------------------------------------------------------------------------------- + Insert on public.hat_data + Output: excluded.hat_name, excluded.hat_color, excluded.hat_name, excluded.hat_color, excluded.hat_name, excluded.hat_color + Conflict Resolution: UPDATE + Conflict Arbiter Indexes: hat_data_unique_idx + Conflict Filter: ((excluded.hat_color <> 'forbidden'::bpchar) AND (hat_data.* <> excluded.*)) + -> Values Scan on "*VALUES*" + Output: "*VALUES*".column1, "*VALUES*".column2 +(7 rows) + +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; + hat_name | hat_color | hat_name | hat_color | hat_name | hat_color +------------+------------+------------+------------+------------+------------ + | | | | | + h8 | red | h8 | red | h8 | red +(2 rows) + +SELECT * FROM hat_data ORDER BY hat_name; + hat_name | hat_color +------------+------------ + h6 | black + h7 | black + h8 | Excl: red + h9 | blue +(4 rows) + DROP RULE hat_upsert ON hats; -- DO SELECT with a WHERE clause CREATE RULE hat_confsel AS ON INSERT TO hats diff --git a/src/test/regress/expected/triggers.out b/src/test/regress/expected/triggers.out index 8fcb33ac81a..40386431bdb 100644 --- a/src/test/regress/expected/triggers.out +++ b/src/test/regress/expected/triggers.out @@ -1708,49 +1708,89 @@ end; $$; create trigger upsert_after_trig after insert or update on upsert for each row execute procedure upsert_after_func(); -insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color; +insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (1,black) WARNING: after insert (new): (1,black) -insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+-------+-----+------- + | | 1 | black | | +(1 row) + +insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (2,red) WARNING: before insert (new, modified): (3,"red trig modified") WARNING: after insert (new): (3,"red trig modified") -insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+-------------------+-----+------- + | | 3 | red trig modified | | +(1 row) + +insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (3,orange) WARNING: before update (old): (3,"red trig modified") WARNING: before update (new): (3,"updated red trig modified") WARNING: after update (old): (3,"red trig modified") WARNING: after update (new): (3,"updated red trig modified") -insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------------------+-----+---------------------------+-----+-------- + 3 | red trig modified | 3 | updated red trig modified | 3 | orange +(1 row) + +insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (4,green) WARNING: before insert (new, modified): (5,"green trig modified") WARNING: after insert (new): (5,"green trig modified") -insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+---------------------+-----+------- + | | 5 | green trig modified | | +(1 row) + +insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (5,purple) WARNING: before update (old): (5,"green trig modified") WARNING: before update (new): (5,"updated green trig modified") WARNING: after update (old): (5,"green trig modified") WARNING: after update (new): (5,"updated green trig modified") -insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+---------------------+-----+-----------------------------+-----+-------- + 5 | green trig modified | 5 | updated green trig modified | 5 | purple +(1 row) + +insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (6,white) WARNING: before insert (new, modified): (7,"white trig modified") WARNING: after insert (new): (7,"white trig modified") -insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+-------+-----+---------------------+-----+------- + | | 7 | white trig modified | | +(1 row) + +insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (7,pink) WARNING: before update (old): (7,"white trig modified") WARNING: before update (new): (7,"updated white trig modified") WARNING: after update (old): (7,"white trig modified") WARNING: after update (new): (7,"updated white trig modified") -insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color; + key | color | key | color | key | color +-----+---------------------+-----+-----------------------------+-----+------- + 7 | white trig modified | 7 | updated white trig modified | 7 | pink +(1 row) + +insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; WARNING: before insert (new): (8,yellow) WARNING: before insert (new, modified): (9,"yellow trig modified") WARNING: after insert (new): (9,"yellow trig modified") -insert into upsert values(8, 'blue') on conflict (key) do select for update where upsert.color = 'yellow trig modified' returning old.*, new.*, upsert.*; + key | color | key | color | key | color +-----+-------+-----+----------------------+-----+------- + | | 9 | yellow trig modified | | +(1 row) + +insert into upsert values(8, 'blue') on conflict (key) do select for update where upsert.color = 'yellow trig modified' returning old.*, new.*, upsert.*, excluded.*; WARNING: before insert (new): (8,blue) WARNING: before insert (new, modified): (9,"blue trig modified") - key | color | key | color | key | color ------+----------------------+-----+----------------------+-----+---------------------- - 9 | yellow trig modified | 9 | yellow trig modified | 9 | yellow trig modified + key | color | key | color | key | color | key | color +-----+----------------------+-----+----------------------+-----+----------------------+-----+-------------------- + 9 | yellow trig modified | 9 | yellow trig modified | 9 | yellow trig modified | 9 | blue trig modified (1 row) select * from upsert; diff --git a/src/test/regress/expected/updatable_views.out b/src/test/regress/expected/updatable_views.out index 7b00c742776..21459415c3d 100644 --- a/src/test/regress/expected/updatable_views.out +++ b/src/test/regress/expected/updatable_views.out @@ -3668,7 +3668,13 @@ insert into uv_iocu_tab values ('xyxyxy', 0); create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- @@ -3676,7 +3682,13 @@ select * from uv_iocu_tab; (1 row) insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; + b | c | a | two | b | c | a | two | b | c | a | two +---+---+--------+-----+---+---+--------+-----+---+---+--------+----- + 0 | 1 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 | 1 | 2 | xyxyxy | 2.0 +(1 row) + select * from uv_iocu_tab; a | b --------+--- @@ -3778,7 +3790,8 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; QUERY PLAN --------------------------------------------------------------------------------------------------------- Insert on uv_iocu_tab @@ -3792,7 +3805,13 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; + ?column? | ?column? | ?column? +--------------------+------------------------------------------------------------------------------+------------------------- + Old: (x,1,"(1,x)") | New: ("Rejected: (y,1,""(1,y)"")",1,"(1,""Rejected: (y,1,""""(1,y)"""")"")") | Excluded: (y,1,"(1,y)") +(1 row) + select * from uv_iocu_view; bb | aa | cc -------------------------+----+--------------------------------- diff --git a/src/test/regress/sql/arrays.sql b/src/test/regress/sql/arrays.sql index 82837af7c4a..8a5f94ae6a4 100644 --- a/src/test/regress/sql/arrays.sql +++ b/src/test/regress/sql/arrays.sql @@ -426,12 +426,17 @@ create temp table arr_pk_tbl (pk int4 primary key, f1 int[]); insert into arr_pk_tbl values (1, '{1,2,3}'); insert into arr_pk_tbl values (1, '{3,4,5}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; insert into arr_pk_tbl(pk, f1[1:2]) values (1, '{6,7,8}') on conflict (pk) do update set f1[1] = excluded.f1[1], f1[2] = excluded.f1[2], f1[3] = excluded.f1[3] - returning pk, f1; + returning pk, f1, excluded.f1 as "excluded f1"; +insert into arr_pk_tbl(pk, f1[2]) values (1, 10) on conflict (pk) + do update set f1[1] = excluded.f1[1], + f1[2] = excluded.f1[2], + f1[3] = excluded.f1[3] + returning pk, f1, excluded.f1 as "excluded f1"; -- note: if above selects don't produce the expected tuple order, -- then you didn't get an indexscan plan, and something is busted. diff --git a/src/test/regress/sql/generated_stored.sql b/src/test/regress/sql/generated_stored.sql index 85b6212023d..cc8c335a919 100644 --- a/src/test/regress/sql/generated_stored.sql +++ b/src/test/regress/sql/generated_stored.sql @@ -58,6 +58,10 @@ INSERT INTO gtest1 VALUES (3, DEFAULT), (4, 44); -- error INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + SELECT * FROM gtest1 ORDER BY a; SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink diff --git a/src/test/regress/sql/generated_virtual.sql b/src/test/regress/sql/generated_virtual.sql index 0cb14eb0e36..d744e84f766 100644 --- a/src/test/regress/sql/generated_virtual.sql +++ b/src/test/regress/sql/generated_virtual.sql @@ -58,6 +58,10 @@ INSERT INTO gtest1 VALUES (3, DEFAULT), (4, 44); -- error INSERT INTO gtest1 VALUES (3, 33), (4, DEFAULT); -- error INSERT INTO gtest1 VALUES (3, DEFAULT), (4, DEFAULT); -- ok +INSERT INTO gtest1 VALUES (4, DEFAULT), (5, DEFAULT) + ON CONFLICT (a) DO UPDATE SET a = excluded.a + 100 + RETURNING old.*, new.*, excluded.*; + SELECT * FROM gtest1 ORDER BY a; SELECT gtest1 FROM gtest1 ORDER BY a; -- whole-row reference SELECT a, (SELECT gtest1.b) FROM gtest1 ORDER BY a; -- sublink diff --git a/src/test/regress/sql/inherit.sql b/src/test/regress/sql/inherit.sql index 8f986904389..3ba19cd163e 100644 --- a/src/test/regress/sql/inherit.sql +++ b/src/test/regress/sql/inherit.sql @@ -849,7 +849,8 @@ select * from inhpar; -- Also check ON CONFLICT insert into inhpar as i values (3), (7) on conflict (f1) - do update set (f1, f2) = (select i.f1, i.f2 || '+'); + do update set (f1, f2) = (select i.f1, i.f2 || '+') + returning old, new, excluded; select * from inhpar order by f1; -- tuple order might be unstable here drop table inhpar cascade; diff --git a/src/test/regress/sql/insert_conflict.sql b/src/test/regress/sql/insert_conflict.sql index a5a84d1d4b8..2bb71dfa510 100644 --- a/src/test/regress/sql/insert_conflict.sql +++ b/src/test/regress/sql/insert_conflict.sql @@ -109,8 +109,7 @@ insert into insertconflicttest values (1, 'Apple'), (2, 'Orange') on conflict (key) do update set (fruit, key) = (excluded.fruit, excluded.key); --- Give good diagnostic message when EXCLUDED.* spuriously referenced from --- RETURNING: +-- EXCLUDED.* referenced from RETURNING: insert into insertconflicttest values (1, 'Apple') on conflict (key) do update set fruit = excluded.fruit RETURNING excluded.fruit; -- Only suggest <table>.* column when inference element misspelled: @@ -258,16 +257,16 @@ create unique index plain on insertconflicttest(key); -- Succeeds, updates existing row: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- No update this time, though: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* != excluded.* returning *; + where i.* != excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- Predicate changed to require match rather than non-match, so updates once more: insert into insertconflicttest as i values (23, 'Jackfruit') on conflict (key) do update set fruit = excluded.fruit - where i.* = excluded.* returning *; + where i.* = excluded.* returning *, excluded.* = old.*, excluded.* = new.*; -- Assign: insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text - returning *; + returning *, excluded.* = old.*, excluded.* = new.*; -- deparse whole row var in WHERE and SET clauses: explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.fruit where excluded.* is null; explain (costs off) insert into insertconflicttest as i values (23, 'Avocado') on conflict (key) do update set fruit = excluded.*::text; @@ -287,6 +286,7 @@ drop table insertconflicttest; create table syscolconflicttest(key int4, data text); insert into syscolconflicttest values (1); insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.ctid::text; +insert into syscolconflicttest values (1) on conflict (key) do update set data = excluded.data returning excluded.ctid; drop table syscolconflicttest; -- @@ -364,20 +364,24 @@ select * from capitals; -- Succeeds: insert into cities values ('Las Vegas', 2.583E+5, 2174) on conflict do nothing; -insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Sacramento', 4664.E+5, 30, 'CA') on conflict (name) do update set population = excluded.population + returning old.*, new.*, excluded.*; -- Wrong "Sacramento", so do nothing: insert into capitals values ('Sacramento', 50, 2267, 'NE') on conflict (name) do nothing; select * from capitals; -insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.83E+5, 2001) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old, new, excluded; select tableoid::regclass, * from cities; -insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population; +insert into capitals values ('Las Vegas', 5.83E+5, 2222, 'NV') on conflict (name) do update set population = excluded.population + returning old, new, excluded; -- Capitals will contain new capital, Las Vegas: select * from capitals; -- Cities contains two instances of "Las Vegas", since unique constraints don't -- work across inheritance: select tableoid::regclass, * from cities; -- This only affects "cities" version of "Las Vegas": -insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude; +insert into cities values ('Las Vegas', 5.86E+5, 2223) on conflict (name) do update set population = excluded.population, altitude = excluded.altitude + returning old.*, new.*, excluded.*; select tableoid::regclass, * from cities; -- clean up @@ -394,8 +398,11 @@ insert into excluded values(1, '2') on conflict (key) do update set data = exclu insert into excluded AS target values(1, '2') on conflict (key) do update set data = excluded.data RETURNING *; -- ok, aliased insert into excluded AS target values(1, '2') on conflict (key) do update set data = target.data RETURNING *; --- make sure excluded isn't a problem in returning clause +-- error, ambiguous insert into excluded values(1, '2') on conflict (key) do update set data = 3 RETURNING excluded.*; +-- ok, aliased +insert into excluded AS target values(1, '2') on conflict (key) do update set data = 3 +RETURNING target.*, excluded.*; -- clean up drop table excluded; @@ -539,7 +546,7 @@ insert into parted_conflict_test values (3, 'a') on conflict (a) do update set b insert into parted_conflict_test values (3, 'b') on conflict (a) do update set b = excluded.b; insert into parted_conflict_test values (3, 'a') on conflict (a) do select returning b; insert into parted_conflict_test values (3, 'a') on conflict (a) do select where excluded.b = 'a' returning parted_conflict_test; -insert into parted_conflict_test values (3, 'a') on conflict (a) do select where parted_conflict_test.b = 'b' returning b; +insert into parted_conflict_test values (3, 'a') on conflict (a) do select where parted_conflict_test.b = 'b' returning b, excluded; -- should see (3, 'b') select * from parted_conflict_test order by a; @@ -550,7 +557,7 @@ create table parted_conflict_test_3 partition of parted_conflict_test for values truncate parted_conflict_test; insert into parted_conflict_test (a, b) values (4, 'a') on conflict (a) do update set b = excluded.b; insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do update set b = excluded.b where parted_conflict_test.b = 'a'; -insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do select returning b; +insert into parted_conflict_test (a, b) values (4, 'b') on conflict (a) do select returning b, excluded; -- should see (4, 'b') select * from parted_conflict_test order by a; diff --git a/src/test/regress/sql/returning.sql b/src/test/regress/sql/returning.sql index 27fa4a374ed..fc60e322435 100644 --- a/src/test/regress/sql/returning.sql +++ b/src/test/regress/sql/returning.sql @@ -209,19 +209,21 @@ INSERT INTO foo VALUES (4) RETURNING old.tableoid::regclass, old.ctid, old.*, new.tableoid::regclass, new.ctid, new.*, *; --- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW +-- INSERT ... ON CONFLICT ... UPDATE has OLD and NEW (and EXLCUDED) CREATE UNIQUE INDEX foo_f1_idx ON foo (f1); EXPLAIN (verbose, costs off) INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; INSERT INTO foo VALUES (4, 'conflict'), (5, 'ok') ON CONFLICT (f1) DO UPDATE SET f2 = excluded.f2||'ed', f3 = -1 RETURNING WITH (OLD AS o, NEW AS n) o.tableoid::regclass, o.ctid, o.*, - n.tableoid::regclass, n.ctid, n.*, *; + n.tableoid::regclass, n.ctid, n.*, *, + excluded.*; -- UPDATE has OLD and NEW EXPLAIN (verbose, costs off) diff --git a/src/test/regress/sql/rules.sql b/src/test/regress/sql/rules.sql index 40f5c16e540..952be1f9bfc 100644 --- a/src/test/regress/sql/rules.sql +++ b/src/test/regress/sql/rules.sql @@ -1205,6 +1205,33 @@ SELECT * FROM hat_data WHERE hat_name IN ('h8', 'h9', 'h7') ORDER BY hat_name; DROP RULE hat_upsert ON hats; +-- DO UPDATE ... RETURNING excluded values +CREATE RULE hat_upsert AS ON INSERT TO hats + DO INSTEAD + INSERT INTO hat_data VALUES ( + NEW.hat_name, + NEW.hat_color) + ON CONFLICT (hat_name) + DO UPDATE + SET hat_name = hat_data.hat_name, hat_color = 'Excl: '||excluded.hat_color + WHERE excluded.hat_color <> 'forbidden' AND hat_data.* != excluded.* + RETURNING excluded.*; +SELECT definition FROM pg_rules WHERE tablename = 'hats' ORDER BY rulename; + +-- EXCLUDED not allowed in plain INSERT +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING excluded.*; + +-- OLD/NEW have no effect on EXCLUDED +EXPLAIN (verbose, costs off) +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; +INSERT INTO hats VALUES ('h6', 'black'), ('h7', 'forbidden'), ('h8', 'red') + RETURNING old.*, new.*, *; +SELECT * FROM hat_data ORDER BY hat_name; + +DROP RULE hat_upsert ON hats; + -- DO SELECT with a WHERE clause CREATE RULE hat_confsel AS ON INSERT TO hats DO INSTEAD diff --git a/src/test/regress/sql/triggers.sql b/src/test/regress/sql/triggers.sql index 2285e90110e..a553836ebca 100644 --- a/src/test/regress/sql/triggers.sql +++ b/src/test/regress/sql/triggers.sql @@ -1189,15 +1189,15 @@ $$; create trigger upsert_after_trig after insert or update on upsert for each row execute procedure upsert_after_func(); -insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color; -insert into upsert values(8, 'blue') on conflict (key) do select for update where upsert.color = 'yellow trig modified' returning old.*, new.*, upsert.*; +insert into upsert values(1, 'black') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(2, 'red') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(3, 'orange') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(4, 'green') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(5, 'purple') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(6, 'white') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(7, 'pink') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(8, 'yellow') on conflict (key) do update set color = 'updated ' || upsert.color returning old.*, new.*, excluded.*; +insert into upsert values(8, 'blue') on conflict (key) do select for update where upsert.color = 'yellow trig modified' returning old.*, new.*, upsert.*, excluded.*; select * from upsert; diff --git a/src/test/regress/sql/updatable_views.sql b/src/test/regress/sql/updatable_views.sql index 4a60126ec90..127488b4f94 100644 --- a/src/test/regress/sql/updatable_views.sql +++ b/src/test/regress/sql/updatable_views.sql @@ -1864,10 +1864,12 @@ create view uv_iocu_view as select b, b+1 as c, a, '2.0'::text as two from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = uv_iocu_view.b; + on conflict (a) do update set b = uv_iocu_view.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) - on conflict (a) do update set b = excluded.b; + on conflict (a) do update set b = excluded.b + returning old.*, new.*, excluded.*; select * from uv_iocu_tab; insert into uv_iocu_view (a, b) values ('xyxyxy', 1) on conflict (a) do select where uv_iocu_view.c = 2 and excluded.c = 2 returning *; @@ -1925,12 +1927,14 @@ insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; insert into uv_iocu_view (aa,bb) values (1,'y') on conflict (aa) do update set bb = 'Rejected: '||excluded.* where excluded.aa > 0 and excluded.bb != '' - and excluded.cc is not null; + and excluded.cc is not null + returning 'Old: '||old.*, 'New: '||new.*, 'Excluded: '||excluded.*; select * from uv_iocu_view; explain (costs off) insert into uv_iocu_view (aa,bb) values (1,'Rejected: (y,1,"(1,y)")') diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list index c5db6ca6705..7abd820d988 100644 --- a/src/tools/pgindent/typedefs.list +++ b/src/tools/pgindent/typedefs.list @@ -2700,6 +2700,7 @@ ReturnSetInfo ReturnStmt ReturningClause ReturningExpr +ReturningExprKind ReturningOption ReturningOptionKind RevmapContents -- 2.51.0
^ permalink raw reply [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2026-07-02 06:11  solai v <solai.cdac@gmail.com>
  parent: Dean Rasheed <dean.a.rasheed@gmail.com>
  0 siblings, 1 reply; 17+ messages in thread

From: solai v @ 2026-07-02 06:11 UTC (permalink / raw)
  To: Dean Rasheed <dean.a.rasheed@gmail.com>; +Cc: Viktor Holmberg <v@viktorh.net>; Vik Fearing <vik@postgresfriends.org>; pgsql-hackers

Hi Dean,

I tested the latest v6 patch and it worked well for me.
I first reproduced the current behavior on an unpatched build. As
expected, using EXCLUDED in the RETURNING clause resulted in:
ERROR: invalid reference to FROM-clause entry for table "excluded"
DETAIL: There is an entry for table "excluded", but it cannot be
referenced from this part of the query.
After applying v6-0001-Allow-EXCLUDED-in-RETURNING-list-of-INSERT-ON-CON.patch,
rebuilding PostgreSQL, and rerunning the same test, the query
completed successfully and returned the expected EXCLUDED value.
I also tried a few additional scenarios:
  RETURNING age, EXCLUDED.age
  Returning multiple EXCLUDED columns
  Using EXCLUDED in expressions (e.g. EXCLUDED.age + 10)
  Using aliases in the RETURNING list
  Testing with different data types (NUMERIC and BOOLEAN)
  Verifying that existing RETURNING behavior is unchanged
  Verifying that EXCLUDED is NULL when no conflict occurs
  Confirming that ON CONFLICT DO NOTHING behavior is unchanged

All of these behaved as expected, and I didn't encounter any issues
during testing.
Overall, the patch looks good to me.
Thanks for working on this.

Best regards,
solai






^ permalink  raw  reply  [nested|flat] 17+ messages in thread

* Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values
@ 2026-09-01 18:49  Andrey Borodin <x4mmm@yandex-team.ru>
  parent: solai v <solai.cdac@gmail.com>
  0 siblings, 0 replies; 17+ messages in thread

From: Andrey Borodin @ 2026-09-01 18:49 UTC (permalink / raw)
  To: solai v <solai.cdac@gmail.com>; +Cc: Dean Rasheed <dean.a.rasheed@gmail.com>; Viktor Holmberg <v@viktorh.net>; Vik Fearing <vik@postgresfriends.org>; pgsql-hackers

I reviewed v6 too.  The parser, rewriter, planner and executor changes
look correct to me.  I also checked mixed conflict/non-conflict rows,
correlated subqueries, view-expression rewriting and column-level
privileges.

I agree that allowing unqualified column names in ON CONFLICT SET and
WHERE should be a separate change.  This patch does not depend on it.

There are two small typos: "espectively" in setrefs.c, and Viktor's
previously reported "EXLCUDED" in returning.sql and returning.out.
Neither needs another patch revision.

I think this[0] is ready for committer.  I'll flip the status.


Best regards, Andrey Borodin.

[0] https://commitfest.postgresql.org/patch/5854/







^ permalink  raw  reply  [nested|flat] 17+ messages in thread


end of thread, other threads:[~2026-09-01 18:49 UTC | newest]

Thread overview: 17+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2025-06-24 18:49 Allow ON CONFLICT DO UPDATE to return EXCLUDED values Dean Rasheed <dean.a.rasheed@gmail.com>
2025-06-30 17:18 ` Dean Rasheed <dean.a.rasheed@gmail.com>
2025-07-07 10:38   ` Jim Jones <jim.jones@uni-muenster.de>
2025-07-07 17:52     ` Dean Rasheed <dean.a.rasheed@gmail.com>
2025-07-07 18:09       ` Jim Jones <jim.jones@uni-muenster.de>
2025-07-09 12:13         ` Dean Rasheed <dean.a.rasheed@gmail.com>
2025-07-25 08:42           ` Dean Rasheed <dean.a.rasheed@gmail.com>
2025-10-08 08:51             ` v@viktorh.net <v@viktorh.net>
2025-10-07 13:55 Re: Allow ON CONFLICT DO UPDATE to return EXCLUDED values Viktor Holmberg <v@viktorh.net>
2025-10-07 21:52 ` Dean Rasheed <dean.a.rasheed@gmail.com>
2025-10-08 09:20   ` Vik Fearing <vik@postgresfriends.org>
2026-02-12 11:11     ` Dean Rasheed <dean.a.rasheed@gmail.com>
2026-02-12 12:23       ` Dean Rasheed <dean.a.rasheed@gmail.com>
2026-02-13 14:16         ` Viktor Holmberg <v@viktorh.net>
2026-06-22 10:13           ` Dean Rasheed <dean.a.rasheed@gmail.com>
2026-07-02 06:11             ` solai v <solai.cdac@gmail.com>
2026-09-01 18:49               ` Andrey Borodin <x4mmm@yandex-team.ru>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox