1 /*-------------------------------------------------------------------------
4 * transform the raw parse tree into a query tree
6 * For optimizable statements, we are careful to obtain a suitable lock on
7 * each referenced table, and other modules of the backend preserve or
8 * re-obtain these locks before depending on the results. It is therefore
9 * okay to do significant semantic analysis of these statements. For
10 * utility commands, no locks are obtained here (and if they were, we could
11 * not be sure we'd still have them at execution). Hence the general rule
12 * for utility commands is to just dump them into a Query node untransformed.
13 * DECLARE CURSOR, EXPLAIN, and CREATE TABLE AS are exceptions because they
14 * contain optimizable statements, which we should transform.
17 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
18 * Portions Copyright (c) 1994, Regents of the University of California
20 * src/backend/parser/analyze.c
22 *-------------------------------------------------------------------------
27 #include "access/sysattr.h"
28 #include "catalog/pg_proc.h"
29 #include "catalog/pg_type.h"
30 #include "commands/defrem.h"
31 #include "miscadmin.h"
32 #include "nodes/makefuncs.h"
33 #include "nodes/nodeFuncs.h"
34 #include "nodes/queryjumble.h"
35 #include "optimizer/optimizer.h"
36 #include "parser/analyze.h"
37 #include "parser/parse_agg.h"
38 #include "parser/parse_clause.h"
39 #include "parser/parse_coerce.h"
40 #include "parser/parse_collate.h"
41 #include "parser/parse_cte.h"
42 #include "parser/parse_expr.h"
43 #include "parser/parse_func.h"
44 #include "parser/parse_merge.h"
45 #include "parser/parse_oper.h"
46 #include "parser/parse_param.h"
47 #include "parser/parse_relation.h"
48 #include "parser/parse_target.h"
49 #include "parser/parse_type.h"
50 #include "parser/parsetree.h"
51 #include "utils/backend_status.h"
52 #include "utils/builtins.h"
53 #include "utils/guc.h"
54 #include "utils/rel.h"
55 #include "utils/syscache.h"
58 /* Hook for plugins to get control at end of parse analysis */
59 post_parse_analyze_hook_type post_parse_analyze_hook
= NULL
;
61 static Query
*transformOptionalSelectInto(ParseState
*pstate
, Node
*parseTree
);
62 static Query
*transformDeleteStmt(ParseState
*pstate
, DeleteStmt
*stmt
);
63 static Query
*transformInsertStmt(ParseState
*pstate
, InsertStmt
*stmt
);
64 static OnConflictExpr
*transformOnConflictClause(ParseState
*pstate
,
65 OnConflictClause
*onConflictClause
);
66 static int count_rowexpr_columns(ParseState
*pstate
, Node
*expr
);
67 static Query
*transformSelectStmt(ParseState
*pstate
, SelectStmt
*stmt
);
68 static Query
*transformValuesClause(ParseState
*pstate
, SelectStmt
*stmt
);
69 static Query
*transformSetOperationStmt(ParseState
*pstate
, SelectStmt
*stmt
);
70 static Node
*transformSetOperationTree(ParseState
*pstate
, SelectStmt
*stmt
,
71 bool isTopLevel
, List
**targetlist
);
72 static void determineRecursiveColTypes(ParseState
*pstate
,
73 Node
*larg
, List
*nrtargetlist
);
74 static Query
*transformReturnStmt(ParseState
*pstate
, ReturnStmt
*stmt
);
75 static Query
*transformUpdateStmt(ParseState
*pstate
, UpdateStmt
*stmt
);
76 static Query
*transformPLAssignStmt(ParseState
*pstate
,
78 static Query
*transformDeclareCursorStmt(ParseState
*pstate
,
79 DeclareCursorStmt
*stmt
);
80 static Query
*transformExplainStmt(ParseState
*pstate
,
82 static Query
*transformCreateTableAsStmt(ParseState
*pstate
,
83 CreateTableAsStmt
*stmt
);
84 static Query
*transformCallStmt(ParseState
*pstate
,
86 static void transformLockingClause(ParseState
*pstate
, Query
*qry
,
87 LockingClause
*lc
, bool pushedDown
);
88 #ifdef DEBUG_NODE_TESTS_ENABLED
89 static bool test_raw_expression_coverage(Node
*node
, void *context
);
94 * parse_analyze_fixedparams
95 * Analyze a raw parse tree and transform it to Query form.
97 * Optionally, information about $n parameter types can be supplied.
98 * References to $n indexes not defined by paramTypes[] are disallowed.
100 * The result is a Query node. Optimizable statements require considerable
101 * transformation, while utility-type statements are simply hung off
102 * a dummy CMD_UTILITY Query node.
105 parse_analyze_fixedparams(RawStmt
*parseTree
, const char *sourceText
,
106 const Oid
*paramTypes
, int numParams
,
107 QueryEnvironment
*queryEnv
)
109 ParseState
*pstate
= make_parsestate(NULL
);
111 JumbleState
*jstate
= NULL
;
113 Assert(sourceText
!= NULL
); /* required as of 8.4 */
115 pstate
->p_sourcetext
= sourceText
;
118 setup_parse_fixed_parameters(pstate
, paramTypes
, numParams
);
120 pstate
->p_queryEnv
= queryEnv
;
122 query
= transformTopLevelStmt(pstate
, parseTree
);
124 if (IsQueryIdEnabled())
125 jstate
= JumbleQuery(query
);
127 if (post_parse_analyze_hook
)
128 (*post_parse_analyze_hook
) (pstate
, query
, jstate
);
130 free_parsestate(pstate
);
132 pgstat_report_query_id(query
->queryId
, false);
138 * parse_analyze_varparams
140 * This variant is used when it's okay to deduce information about $n
141 * symbol datatypes from context. The passed-in paramTypes[] array can
142 * be modified or enlarged (via repalloc).
145 parse_analyze_varparams(RawStmt
*parseTree
, const char *sourceText
,
146 Oid
**paramTypes
, int *numParams
,
147 QueryEnvironment
*queryEnv
)
149 ParseState
*pstate
= make_parsestate(NULL
);
151 JumbleState
*jstate
= NULL
;
153 Assert(sourceText
!= NULL
); /* required as of 8.4 */
155 pstate
->p_sourcetext
= sourceText
;
157 setup_parse_variable_parameters(pstate
, paramTypes
, numParams
);
159 pstate
->p_queryEnv
= queryEnv
;
161 query
= transformTopLevelStmt(pstate
, parseTree
);
163 /* make sure all is well with parameter types */
164 check_variable_parameters(pstate
, query
);
166 if (IsQueryIdEnabled())
167 jstate
= JumbleQuery(query
);
169 if (post_parse_analyze_hook
)
170 (*post_parse_analyze_hook
) (pstate
, query
, jstate
);
172 free_parsestate(pstate
);
174 pgstat_report_query_id(query
->queryId
, false);
180 * parse_analyze_withcb
182 * This variant is used when the caller supplies their own parser callback to
183 * resolve parameters and possibly other things.
186 parse_analyze_withcb(RawStmt
*parseTree
, const char *sourceText
,
187 ParserSetupHook parserSetup
,
188 void *parserSetupArg
,
189 QueryEnvironment
*queryEnv
)
191 ParseState
*pstate
= make_parsestate(NULL
);
193 JumbleState
*jstate
= NULL
;
195 Assert(sourceText
!= NULL
); /* required as of 8.4 */
197 pstate
->p_sourcetext
= sourceText
;
198 pstate
->p_queryEnv
= queryEnv
;
199 (*parserSetup
) (pstate
, parserSetupArg
);
201 query
= transformTopLevelStmt(pstate
, parseTree
);
203 if (IsQueryIdEnabled())
204 jstate
= JumbleQuery(query
);
206 if (post_parse_analyze_hook
)
207 (*post_parse_analyze_hook
) (pstate
, query
, jstate
);
209 free_parsestate(pstate
);
211 pgstat_report_query_id(query
->queryId
, false);
219 * Entry point for recursively analyzing a sub-statement.
222 parse_sub_analyze(Node
*parseTree
, ParseState
*parentParseState
,
223 CommonTableExpr
*parentCTE
,
224 bool locked_from_parent
,
225 bool resolve_unknowns
)
227 ParseState
*pstate
= make_parsestate(parentParseState
);
230 pstate
->p_parent_cte
= parentCTE
;
231 pstate
->p_locked_from_parent
= locked_from_parent
;
232 pstate
->p_resolve_unknowns
= resolve_unknowns
;
234 query
= transformStmt(pstate
, parseTree
);
236 free_parsestate(pstate
);
242 * setQueryLocationAndLength
243 * Set query's location and length from statement and ParseState
245 * Some statements, like PreparableStmt, can be located within parentheses.
246 * For example "(SELECT 1)" or "COPY (UPDATE ...) to x;". For those, we
247 * cannot use the whole string from the statement's location or the SQL
248 * string would yield incorrectly. The parser will set stmt_len, reflecting
249 * the size of the statement within the parentheses. Thus, when stmt_len is
250 * available, we need to use it for the Query's stmt_len.
252 * For other cases, the parser can't provide the length of individual
253 * statements. However, we have the statement's location plus the length
254 * (p_stmt_len) and location (p_stmt_location) of the top level RawStmt,
255 * stored in pstate. Thus, the statement's length is the RawStmt's length
256 * minus how much we've advanced in the RawStmt's string.
259 setQueryLocationAndLength(ParseState
*pstate
, Query
*qry
, Node
*parseTree
)
261 ParseLoc stmt_len
= 0;
264 * If there is no information about the top RawStmt's length, leave it at
265 * 0 to use the whole string.
267 if (pstate
->p_stmt_len
== 0)
270 switch (nodeTag(parseTree
))
273 qry
->stmt_location
= ((InsertStmt
*) parseTree
)->stmt_location
;
274 stmt_len
= ((InsertStmt
*) parseTree
)->stmt_len
;
278 qry
->stmt_location
= ((DeleteStmt
*) parseTree
)->stmt_location
;
279 stmt_len
= ((DeleteStmt
*) parseTree
)->stmt_len
;
283 qry
->stmt_location
= ((UpdateStmt
*) parseTree
)->stmt_location
;
284 stmt_len
= ((UpdateStmt
*) parseTree
)->stmt_len
;
288 qry
->stmt_location
= ((MergeStmt
*) parseTree
)->stmt_location
;
289 stmt_len
= ((MergeStmt
*) parseTree
)->stmt_len
;
293 qry
->stmt_location
= ((SelectStmt
*) parseTree
)->stmt_location
;
294 stmt_len
= ((SelectStmt
*) parseTree
)->stmt_len
;
298 qry
->stmt_location
= ((PLAssignStmt
*) parseTree
)->location
;
302 qry
->stmt_location
= pstate
->p_stmt_location
;
308 /* Statement's length is known, use it */
309 qry
->stmt_len
= stmt_len
;
314 * Compute the statement's length from the statement's location and
315 * the RawStmt's length and location.
317 qry
->stmt_len
= pstate
->p_stmt_len
- (qry
->stmt_location
- pstate
->p_stmt_location
);
320 /* The calculated statement length should be calculated as positive. */
321 Assert(qry
->stmt_len
>= 0);
325 * transformTopLevelStmt -
326 * transform a Parse tree into a Query tree.
328 * This function is just responsible for storing location data
329 * from the RawStmt into the ParseState.
332 transformTopLevelStmt(ParseState
*pstate
, RawStmt
*parseTree
)
336 /* Store RawStmt's length and location in pstate */
337 pstate
->p_stmt_len
= parseTree
->stmt_len
;
338 pstate
->p_stmt_location
= parseTree
->stmt_location
;
340 /* We're at top level, so allow SELECT INTO */
341 result
= transformOptionalSelectInto(pstate
, parseTree
->stmt
);
347 * transformOptionalSelectInto -
348 * If SELECT has INTO, convert it to CREATE TABLE AS.
350 * The only thing we do here that we don't do in transformStmt() is to
351 * convert SELECT ... INTO into CREATE TABLE AS. Since utility statements
352 * aren't allowed within larger statements, this is only allowed at the top
353 * of the parse tree, and so we only try it before entering the recursive
354 * transformStmt() processing.
357 transformOptionalSelectInto(ParseState
*pstate
, Node
*parseTree
)
359 if (IsA(parseTree
, SelectStmt
))
361 SelectStmt
*stmt
= (SelectStmt
*) parseTree
;
363 /* If it's a set-operation tree, drill down to leftmost SelectStmt */
364 while (stmt
&& stmt
->op
!= SETOP_NONE
)
366 Assert(stmt
&& IsA(stmt
, SelectStmt
) && stmt
->larg
== NULL
);
368 if (stmt
->intoClause
)
370 CreateTableAsStmt
*ctas
= makeNode(CreateTableAsStmt
);
372 ctas
->query
= parseTree
;
373 ctas
->into
= stmt
->intoClause
;
374 ctas
->objtype
= OBJECT_TABLE
;
375 ctas
->is_select_into
= true;
378 * Remove the intoClause from the SelectStmt. This makes it safe
379 * for transformSelectStmt to complain if it finds intoClause set
380 * (implying that the INTO appeared in a disallowed place).
382 stmt
->intoClause
= NULL
;
384 parseTree
= (Node
*) ctas
;
388 return transformStmt(pstate
, parseTree
);
393 * recursively transform a Parse tree into a Query tree.
396 transformStmt(ParseState
*pstate
, Node
*parseTree
)
400 #ifdef DEBUG_NODE_TESTS_ENABLED
403 * We apply debug_raw_expression_coverage_test testing to basic DML
404 * statements; we can't just run it on everything because
405 * raw_expression_tree_walker() doesn't claim to handle utility
408 if (Debug_raw_expression_coverage_test
)
410 switch (nodeTag(parseTree
))
417 (void) test_raw_expression_coverage(parseTree
, NULL
);
423 #endif /* DEBUG_NODE_TESTS_ENABLED */
426 * Caution: when changing the set of statement types that have non-default
427 * processing here, see also stmt_requires_parse_analysis() and
428 * analyze_requires_snapshot().
430 switch (nodeTag(parseTree
))
433 * Optimizable statements
436 result
= transformInsertStmt(pstate
, (InsertStmt
*) parseTree
);
440 result
= transformDeleteStmt(pstate
, (DeleteStmt
*) parseTree
);
444 result
= transformUpdateStmt(pstate
, (UpdateStmt
*) parseTree
);
448 result
= transformMergeStmt(pstate
, (MergeStmt
*) parseTree
);
453 SelectStmt
*n
= (SelectStmt
*) parseTree
;
456 result
= transformValuesClause(pstate
, n
);
457 else if (n
->op
== SETOP_NONE
)
458 result
= transformSelectStmt(pstate
, n
);
460 result
= transformSetOperationStmt(pstate
, n
);
465 result
= transformReturnStmt(pstate
, (ReturnStmt
*) parseTree
);
469 result
= transformPLAssignStmt(pstate
,
470 (PLAssignStmt
*) parseTree
);
476 case T_DeclareCursorStmt
:
477 result
= transformDeclareCursorStmt(pstate
,
478 (DeclareCursorStmt
*) parseTree
);
482 result
= transformExplainStmt(pstate
,
483 (ExplainStmt
*) parseTree
);
486 case T_CreateTableAsStmt
:
487 result
= transformCreateTableAsStmt(pstate
,
488 (CreateTableAsStmt
*) parseTree
);
492 result
= transformCallStmt(pstate
,
493 (CallStmt
*) parseTree
);
499 * other statements don't require any transformation; just return
500 * the original parsetree with a Query node plastered on top.
502 result
= makeNode(Query
);
503 result
->commandType
= CMD_UTILITY
;
504 result
->utilityStmt
= (Node
*) parseTree
;
508 /* Mark as original query until we learn differently */
509 result
->querySource
= QSRC_ORIGINAL
;
510 result
->canSetTag
= true;
511 setQueryLocationAndLength(pstate
, result
, parseTree
);
517 * stmt_requires_parse_analysis
518 * Returns true if parse analysis will do anything non-trivial
519 * with the given raw parse tree.
521 * Generally, this should return true for any statement type for which
522 * transformStmt() does more than wrap a CMD_UTILITY Query around it.
523 * When it returns false, the caller can assume that there is no situation
524 * in which parse analysis of the raw statement could need to be re-done.
526 * Currently, since the rewriter and planner do nothing for CMD_UTILITY
527 * Queries, a false result means that the entire parse analysis/rewrite/plan
528 * pipeline will never need to be re-done. If that ever changes, callers
529 * will likely need adjustment.
532 stmt_requires_parse_analysis(RawStmt
*parseTree
)
536 switch (nodeTag(parseTree
->stmt
))
539 * Optimizable statements
554 case T_DeclareCursorStmt
:
556 case T_CreateTableAsStmt
:
562 /* all other statements just get wrapped in a CMD_UTILITY Query */
571 * analyze_requires_snapshot
572 * Returns true if a snapshot must be set before doing parse analysis
573 * on the given raw parse tree.
576 analyze_requires_snapshot(RawStmt
*parseTree
)
579 * Currently, this should return true in exactly the same cases that
580 * stmt_requires_parse_analysis() does, so we just invoke that function
581 * rather than duplicating it. We keep the two entry points separate for
582 * clarity of callers, since from the callers' standpoint these are
583 * different conditions.
585 * While there may someday be a statement type for which transformStmt()
586 * does something nontrivial and yet no snapshot is needed for that
587 * processing, it seems likely that making such a choice would be fragile.
588 * If you want to install an exception, document the reasoning for it in a
591 return stmt_requires_parse_analysis(parseTree
);
595 * transformDeleteStmt -
596 * transforms a Delete Statement
599 transformDeleteStmt(ParseState
*pstate
, DeleteStmt
*stmt
)
601 Query
*qry
= makeNode(Query
);
602 ParseNamespaceItem
*nsitem
;
605 qry
->commandType
= CMD_DELETE
;
607 /* process the WITH clause independently of all else */
608 if (stmt
->withClause
)
610 qry
->hasRecursive
= stmt
->withClause
->recursive
;
611 qry
->cteList
= transformWithClause(pstate
, stmt
->withClause
);
612 qry
->hasModifyingCTE
= pstate
->p_hasModifyingCTE
;
615 /* set up range table with just the result rel */
616 qry
->resultRelation
= setTargetTable(pstate
, stmt
->relation
,
620 nsitem
= pstate
->p_target_nsitem
;
622 /* there's no DISTINCT in DELETE */
623 qry
->distinctClause
= NIL
;
625 /* subqueries in USING cannot access the result relation */
626 nsitem
->p_lateral_only
= true;
627 nsitem
->p_lateral_ok
= false;
630 * The USING clause is non-standard SQL syntax, and is equivalent in
631 * functionality to the FROM list that can be specified for UPDATE. The
632 * USING keyword is used rather than FROM because FROM is already a
633 * keyword in the DELETE syntax.
635 transformFromClause(pstate
, stmt
->usingClause
);
637 /* remaining clauses can reference the result relation normally */
638 nsitem
->p_lateral_only
= false;
639 nsitem
->p_lateral_ok
= true;
641 qual
= transformWhereClause(pstate
, stmt
->whereClause
,
642 EXPR_KIND_WHERE
, "WHERE");
644 transformReturningClause(pstate
, qry
, stmt
->returningClause
,
645 EXPR_KIND_RETURNING
);
647 /* done building the range table and jointree */
648 qry
->rtable
= pstate
->p_rtable
;
649 qry
->rteperminfos
= pstate
->p_rteperminfos
;
650 qry
->jointree
= makeFromExpr(pstate
->p_joinlist
, qual
);
652 qry
->hasSubLinks
= pstate
->p_hasSubLinks
;
653 qry
->hasWindowFuncs
= pstate
->p_hasWindowFuncs
;
654 qry
->hasTargetSRFs
= pstate
->p_hasTargetSRFs
;
655 qry
->hasAggs
= pstate
->p_hasAggs
;
657 assign_query_collations(pstate
, qry
);
659 /* this must be done after collations, for reliable comparison of exprs */
660 if (pstate
->p_hasAggs
)
661 parseCheckAggregates(pstate
, qry
);
667 * transformInsertStmt -
668 * transform an Insert Statement
671 transformInsertStmt(ParseState
*pstate
, InsertStmt
*stmt
)
673 Query
*qry
= makeNode(Query
);
674 SelectStmt
*selectStmt
= (SelectStmt
*) stmt
->selectStmt
;
675 List
*exprList
= NIL
;
676 bool isGeneralSelect
;
678 List
*sub_rteperminfos
;
682 ParseNamespaceItem
*nsitem
;
683 RTEPermissionInfo
*perminfo
;
687 bool isOnConflictUpdate
;
690 /* There can't be any outer WITH to worry about */
691 Assert(pstate
->p_ctenamespace
== NIL
);
693 qry
->commandType
= CMD_INSERT
;
694 pstate
->p_is_insert
= true;
696 /* process the WITH clause independently of all else */
697 if (stmt
->withClause
)
699 qry
->hasRecursive
= stmt
->withClause
->recursive
;
700 qry
->cteList
= transformWithClause(pstate
, stmt
->withClause
);
701 qry
->hasModifyingCTE
= pstate
->p_hasModifyingCTE
;
704 qry
->override
= stmt
->override
;
706 isOnConflictUpdate
= (stmt
->onConflictClause
&&
707 stmt
->onConflictClause
->action
== ONCONFLICT_UPDATE
);
710 * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
711 * VALUES list, or general SELECT input. We special-case VALUES, both for
712 * efficiency and so we can handle DEFAULT specifications.
714 * The grammar allows attaching ORDER BY, LIMIT, FOR UPDATE, or WITH to a
715 * VALUES clause. If we have any of those, treat it as a general SELECT;
716 * so it will work, but you can't use DEFAULT items together with those.
718 isGeneralSelect
= (selectStmt
&& (selectStmt
->valuesLists
== NIL
||
719 selectStmt
->sortClause
!= NIL
||
720 selectStmt
->limitOffset
!= NULL
||
721 selectStmt
->limitCount
!= NULL
||
722 selectStmt
->lockingClause
!= NIL
||
723 selectStmt
->withClause
!= NULL
));
726 * If a non-nil rangetable/namespace was passed in, and we are doing
727 * INSERT/SELECT, arrange to pass the rangetable/rteperminfos/namespace
728 * down to the SELECT. This can only happen if we are inside a CREATE
729 * RULE, and in that case we want the rule's OLD and NEW rtable entries to
730 * appear as part of the SELECT's rtable, not as outer references for it.
731 * (Kluge!) The SELECT's joinlist is not affected however. We must do
732 * this before adding the target table to the INSERT's rtable.
736 sub_rtable
= pstate
->p_rtable
;
737 pstate
->p_rtable
= NIL
;
738 sub_rteperminfos
= pstate
->p_rteperminfos
;
739 pstate
->p_rteperminfos
= NIL
;
740 sub_namespace
= pstate
->p_namespace
;
741 pstate
->p_namespace
= NIL
;
745 sub_rtable
= NIL
; /* not used, but keep compiler quiet */
746 sub_rteperminfos
= NIL
;
751 * Must get write lock on INSERT target table before scanning SELECT, else
752 * we will grab the wrong kind of initial lock if the target table is also
753 * mentioned in the SELECT part. Note that the target table is not added
754 * to the joinlist or namespace.
756 targetPerms
= ACL_INSERT
;
757 if (isOnConflictUpdate
)
758 targetPerms
|= ACL_UPDATE
;
759 qry
->resultRelation
= setTargetTable(pstate
, stmt
->relation
,
760 false, false, targetPerms
);
762 /* Validate stmt->cols list, or build default list if no list given */
763 icolumns
= checkInsertTargets(pstate
, stmt
->cols
, &attrnos
);
764 Assert(list_length(icolumns
) == list_length(attrnos
));
767 * Determine which variant of INSERT we have.
769 if (selectStmt
== NULL
)
772 * We have INSERT ... DEFAULT VALUES. We can handle this case by
773 * emitting an empty targetlist --- all columns will be defaulted when
774 * the planner expands the targetlist.
778 else if (isGeneralSelect
)
781 * We make the sub-pstate a child of the outer pstate so that it can
782 * see any Param definitions supplied from above. Since the outer
783 * pstate's rtable and namespace are presently empty, there are no
784 * side-effects of exposing names the sub-SELECT shouldn't be able to
787 ParseState
*sub_pstate
= make_parsestate(pstate
);
791 * Process the source SELECT.
793 * It is important that this be handled just like a standalone SELECT;
794 * otherwise the behavior of SELECT within INSERT might be different
795 * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
796 * bugs of just that nature...)
798 * The sole exception is that we prevent resolving unknown-type
799 * outputs as TEXT. This does not change the semantics since if the
800 * column type matters semantically, it would have been resolved to
801 * something else anyway. Doing this lets us resolve such outputs as
802 * the target column's type, which we handle below.
804 sub_pstate
->p_rtable
= sub_rtable
;
805 sub_pstate
->p_rteperminfos
= sub_rteperminfos
;
806 sub_pstate
->p_joinexprs
= NIL
; /* sub_rtable has no joins */
807 sub_pstate
->p_nullingrels
= NIL
;
808 sub_pstate
->p_namespace
= sub_namespace
;
809 sub_pstate
->p_resolve_unknowns
= false;
811 selectQuery
= transformStmt(sub_pstate
, stmt
->selectStmt
);
813 free_parsestate(sub_pstate
);
815 /* The grammar should have produced a SELECT */
816 if (!IsA(selectQuery
, Query
) ||
817 selectQuery
->commandType
!= CMD_SELECT
)
818 elog(ERROR
, "unexpected non-SELECT command in INSERT ... SELECT");
821 * Make the source be a subquery in the INSERT's rangetable, and add
822 * it to the INSERT's joinlist (but not the namespace).
824 nsitem
= addRangeTableEntryForSubquery(pstate
,
826 makeAlias("*SELECT*", NIL
),
829 addNSItemToQuery(pstate
, nsitem
, true, false, false);
832 * Generate an expression list for the INSERT that selects all the
833 * non-resjunk columns from the subquery. (INSERT's tlist must be
834 * separate from the subquery's tlist because we may add columns,
835 * insert datatype coercions, etc.)
837 * HACK: unknown-type constants and params in the SELECT's targetlist
838 * are copied up as-is rather than being referenced as subquery
839 * outputs. This is to ensure that when we try to coerce them to
840 * the target column's datatype, the right things happen (see
841 * special cases in coerce_type). Otherwise, this fails:
842 * INSERT INTO foo SELECT 'bar', ... FROM baz
846 foreach(lc
, selectQuery
->targetList
)
848 TargetEntry
*tle
= (TargetEntry
*) lfirst(lc
);
854 (IsA(tle
->expr
, Const
) || IsA(tle
->expr
, Param
)) &&
855 exprType((Node
*) tle
->expr
) == UNKNOWNOID
)
859 Var
*var
= makeVarFromTargetEntry(nsitem
->p_rtindex
, tle
);
861 var
->location
= exprLocation((Node
*) tle
->expr
);
864 exprList
= lappend(exprList
, expr
);
867 /* Prepare row for assignment to target table */
868 exprList
= transformInsertRow(pstate
, exprList
,
873 else if (list_length(selectStmt
->valuesLists
) > 1)
876 * Process INSERT ... VALUES with multiple VALUES sublists. We
877 * generate a VALUES RTE holding the transformed expression lists, and
878 * build up a targetlist containing Vars that reference the VALUES
881 List
*exprsLists
= NIL
;
882 List
*coltypes
= NIL
;
883 List
*coltypmods
= NIL
;
884 List
*colcollations
= NIL
;
885 int sublist_length
= -1;
886 bool lateral
= false;
888 Assert(selectStmt
->intoClause
== NULL
);
890 foreach(lc
, selectStmt
->valuesLists
)
892 List
*sublist
= (List
*) lfirst(lc
);
895 * Do basic expression transformation (same as a ROW() expr, but
896 * allow SetToDefault at top level)
898 sublist
= transformExpressionList(pstate
, sublist
,
899 EXPR_KIND_VALUES
, true);
902 * All the sublists must be the same length, *after*
903 * transformation (which might expand '*' into multiple items).
904 * The VALUES RTE can't handle anything different.
906 if (sublist_length
< 0)
908 /* Remember post-transformation length of first sublist */
909 sublist_length
= list_length(sublist
);
911 else if (sublist_length
!= list_length(sublist
))
914 (errcode(ERRCODE_SYNTAX_ERROR
),
915 errmsg("VALUES lists must all be the same length"),
916 parser_errposition(pstate
,
917 exprLocation((Node
*) sublist
))));
921 * Prepare row for assignment to target table. We process any
922 * indirection on the target column specs normally but then strip
923 * off the resulting field/array assignment nodes, since we don't
924 * want the parsed statement to contain copies of those in each
925 * VALUES row. (It's annoying to have to transform the
926 * indirection specs over and over like this, but avoiding it
927 * would take some really messy refactoring of
928 * transformAssignmentIndirection.)
930 sublist
= transformInsertRow(pstate
, sublist
,
936 * We must assign collations now because assign_query_collations
937 * doesn't process rangetable entries. We just assign all the
938 * collations independently in each row, and don't worry about
939 * whether they are consistent vertically. The outer INSERT query
940 * isn't going to care about the collations of the VALUES columns,
941 * so it's not worth the effort to identify a common collation for
942 * each one here. (But note this does have one user-visible
943 * consequence: INSERT ... VALUES won't complain about conflicting
944 * explicit COLLATEs in a column, whereas the same VALUES
945 * construct in another context would complain.)
947 assign_list_collations(pstate
, sublist
);
949 exprsLists
= lappend(exprsLists
, sublist
);
953 * Construct column type/typmod/collation lists for the VALUES RTE.
954 * Every expression in each column has been coerced to the type/typmod
955 * of the corresponding target column or subfield, so it's sufficient
956 * to look at the exprType/exprTypmod of the first row. We don't care
957 * about the collation labeling, so just fill in InvalidOid for that.
959 foreach(lc
, (List
*) linitial(exprsLists
))
961 Node
*val
= (Node
*) lfirst(lc
);
963 coltypes
= lappend_oid(coltypes
, exprType(val
));
964 coltypmods
= lappend_int(coltypmods
, exprTypmod(val
));
965 colcollations
= lappend_oid(colcollations
, InvalidOid
);
969 * Ordinarily there can't be any current-level Vars in the expression
970 * lists, because the namespace was empty ... but if we're inside
971 * CREATE RULE, then NEW/OLD references might appear. In that case we
972 * have to mark the VALUES RTE as LATERAL.
974 if (list_length(pstate
->p_rtable
) != 1 &&
975 contain_vars_of_level((Node
*) exprsLists
, 0))
979 * Generate the VALUES RTE
981 nsitem
= addRangeTableEntryForValues(pstate
, exprsLists
,
982 coltypes
, coltypmods
, colcollations
,
983 NULL
, lateral
, true);
984 addNSItemToQuery(pstate
, nsitem
, true, false, false);
987 * Generate list of Vars referencing the RTE
989 exprList
= expandNSItemVars(pstate
, nsitem
, 0, -1, NULL
);
992 * Re-apply any indirection on the target column specs to the Vars
994 exprList
= transformInsertRow(pstate
, exprList
,
1002 * Process INSERT ... VALUES with a single VALUES sublist. We treat
1003 * this case separately for efficiency. The sublist is just computed
1004 * directly as the Query's targetlist, with no VALUES RTE. So it
1005 * works just like a SELECT without any FROM.
1007 List
*valuesLists
= selectStmt
->valuesLists
;
1009 Assert(list_length(valuesLists
) == 1);
1010 Assert(selectStmt
->intoClause
== NULL
);
1013 * Do basic expression transformation (same as a ROW() expr, but allow
1014 * SetToDefault at top level)
1016 exprList
= transformExpressionList(pstate
,
1017 (List
*) linitial(valuesLists
),
1018 EXPR_KIND_VALUES_SINGLE
,
1021 /* Prepare row for assignment to target table */
1022 exprList
= transformInsertRow(pstate
, exprList
,
1029 * Generate query's target list using the computed list of expressions.
1030 * Also, mark all the target columns as needing insert permissions.
1032 perminfo
= pstate
->p_target_nsitem
->p_perminfo
;
1033 qry
->targetList
= NIL
;
1034 Assert(list_length(exprList
) <= list_length(icolumns
));
1035 forthree(lc
, exprList
, icols
, icolumns
, attnos
, attrnos
)
1037 Expr
*expr
= (Expr
*) lfirst(lc
);
1038 ResTarget
*col
= lfirst_node(ResTarget
, icols
);
1039 AttrNumber attr_num
= (AttrNumber
) lfirst_int(attnos
);
1042 tle
= makeTargetEntry(expr
,
1046 qry
->targetList
= lappend(qry
->targetList
, tle
);
1048 perminfo
->insertedCols
= bms_add_member(perminfo
->insertedCols
,
1049 attr_num
- FirstLowInvalidHeapAttributeNumber
);
1053 * If we have any clauses yet to process, set the query namespace to
1054 * contain only the target relation, removing any entries added in a
1055 * sub-SELECT or VALUES list.
1057 if (stmt
->onConflictClause
|| stmt
->returningClause
)
1059 pstate
->p_namespace
= NIL
;
1060 addNSItemToQuery(pstate
, pstate
->p_target_nsitem
,
1064 /* Process ON CONFLICT, if any. */
1065 if (stmt
->onConflictClause
)
1066 qry
->onConflict
= transformOnConflictClause(pstate
,
1067 stmt
->onConflictClause
);
1069 /* Process RETURNING, if any. */
1070 if (stmt
->returningClause
)
1071 transformReturningClause(pstate
, qry
, stmt
->returningClause
,
1072 EXPR_KIND_RETURNING
);
1074 /* done building the range table and jointree */
1075 qry
->rtable
= pstate
->p_rtable
;
1076 qry
->rteperminfos
= pstate
->p_rteperminfos
;
1077 qry
->jointree
= makeFromExpr(pstate
->p_joinlist
, NULL
);
1079 qry
->hasTargetSRFs
= pstate
->p_hasTargetSRFs
;
1080 qry
->hasSubLinks
= pstate
->p_hasSubLinks
;
1082 assign_query_collations(pstate
, qry
);
1088 * Prepare an INSERT row for assignment to the target table.
1090 * exprlist: transformed expressions for source values; these might come from
1091 * a VALUES row, or be Vars referencing a sub-SELECT or VALUES RTE output.
1092 * stmtcols: original target-columns spec for INSERT (we just test for NIL)
1093 * icolumns: effective target-columns spec (list of ResTarget)
1094 * attrnos: integer column numbers (must be same length as icolumns)
1095 * strip_indirection: if true, remove any field/array assignment nodes
1098 transformInsertRow(ParseState
*pstate
, List
*exprlist
,
1099 List
*stmtcols
, List
*icolumns
, List
*attrnos
,
1100 bool strip_indirection
)
1108 * Check length of expr list. It must not have more expressions than
1109 * there are target columns. We allow fewer, but only if no explicit
1110 * columns list was given (the remaining columns are implicitly
1111 * defaulted). Note we must check this *after* transformation because
1112 * that could expand '*' into multiple items.
1114 if (list_length(exprlist
) > list_length(icolumns
))
1116 (errcode(ERRCODE_SYNTAX_ERROR
),
1117 errmsg("INSERT has more expressions than target columns"),
1118 parser_errposition(pstate
,
1119 exprLocation(list_nth(exprlist
,
1120 list_length(icolumns
))))));
1121 if (stmtcols
!= NIL
&&
1122 list_length(exprlist
) < list_length(icolumns
))
1125 * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
1126 * where the user accidentally created a RowExpr instead of separate
1127 * columns. Add a suitable hint if that seems to be the problem,
1128 * because the main error message is quite misleading for this case.
1129 * (If there's no stmtcols, you'll get something about data type
1130 * mismatch, which is less misleading so we don't worry about giving a
1131 * hint in that case.)
1134 (errcode(ERRCODE_SYNTAX_ERROR
),
1135 errmsg("INSERT has more target columns than expressions"),
1136 ((list_length(exprlist
) == 1 &&
1137 count_rowexpr_columns(pstate
, linitial(exprlist
)) ==
1138 list_length(icolumns
)) ?
1139 errhint("The insertion source is a row expression containing the same number of columns expected by the INSERT. Did you accidentally use extra parentheses?") : 0),
1140 parser_errposition(pstate
,
1141 exprLocation(list_nth(icolumns
,
1142 list_length(exprlist
))))));
1146 * Prepare columns for assignment to target table.
1149 forthree(lc
, exprlist
, icols
, icolumns
, attnos
, attrnos
)
1151 Expr
*expr
= (Expr
*) lfirst(lc
);
1152 ResTarget
*col
= lfirst_node(ResTarget
, icols
);
1153 int attno
= lfirst_int(attnos
);
1155 expr
= transformAssignedExpr(pstate
, expr
,
1156 EXPR_KIND_INSERT_TARGET
,
1162 if (strip_indirection
)
1165 * We need to remove top-level FieldStores and SubscriptingRefs,
1166 * as well as any CoerceToDomain appearing above one of those ---
1167 * but not a CoerceToDomain that isn't above one of those.
1171 Expr
*subexpr
= expr
;
1173 while (IsA(subexpr
, CoerceToDomain
))
1175 subexpr
= ((CoerceToDomain
*) subexpr
)->arg
;
1177 if (IsA(subexpr
, FieldStore
))
1179 FieldStore
*fstore
= (FieldStore
*) subexpr
;
1181 expr
= (Expr
*) linitial(fstore
->newvals
);
1183 else if (IsA(subexpr
, SubscriptingRef
))
1185 SubscriptingRef
*sbsref
= (SubscriptingRef
*) subexpr
;
1187 if (sbsref
->refassgnexpr
== NULL
)
1190 expr
= sbsref
->refassgnexpr
;
1197 result
= lappend(result
, expr
);
1204 * transformOnConflictClause -
1205 * transforms an OnConflictClause in an INSERT
1207 static OnConflictExpr
*
1208 transformOnConflictClause(ParseState
*pstate
,
1209 OnConflictClause
*onConflictClause
)
1211 ParseNamespaceItem
*exclNSItem
= NULL
;
1214 Oid arbiterConstraint
;
1215 List
*onConflictSet
= NIL
;
1216 Node
*onConflictWhere
= NULL
;
1217 int exclRelIndex
= 0;
1218 List
*exclRelTlist
= NIL
;
1219 OnConflictExpr
*result
;
1222 * If this is ON CONFLICT ... UPDATE, first create the range table entry
1223 * for the EXCLUDED pseudo relation, so that that will be present while
1224 * processing arbiter expressions. (You can't actually reference it from
1225 * there, but this provides a useful error message if you try.)
1227 if (onConflictClause
->action
== ONCONFLICT_UPDATE
)
1229 Relation targetrel
= pstate
->p_target_relation
;
1230 RangeTblEntry
*exclRte
;
1232 exclNSItem
= addRangeTableEntryForRelation(pstate
,
1235 makeAlias("excluded", NIL
),
1237 exclRte
= exclNSItem
->p_rte
;
1238 exclRelIndex
= exclNSItem
->p_rtindex
;
1241 * relkind is set to composite to signal that we're not dealing with
1242 * an actual relation, and no permission checks are required on it.
1243 * (We'll check the actual target relation, instead.)
1245 exclRte
->relkind
= RELKIND_COMPOSITE_TYPE
;
1247 /* Create EXCLUDED rel's targetlist for use by EXPLAIN */
1248 exclRelTlist
= BuildOnConflictExcludedTargetlist(targetrel
,
1252 /* Process the arbiter clause, ON CONFLICT ON (...) */
1253 transformOnConflictArbiter(pstate
, onConflictClause
, &arbiterElems
,
1254 &arbiterWhere
, &arbiterConstraint
);
1256 /* Process DO UPDATE */
1257 if (onConflictClause
->action
== ONCONFLICT_UPDATE
)
1260 * Expressions in the UPDATE targetlist need to be handled like UPDATE
1261 * not INSERT. We don't need to save/restore this because all INSERT
1262 * expressions have been parsed already.
1264 pstate
->p_is_insert
= false;
1267 * Add the EXCLUDED pseudo relation to the query namespace, making it
1268 * available in the UPDATE subexpressions.
1270 addNSItemToQuery(pstate
, exclNSItem
, false, true, true);
1273 * Now transform the UPDATE subexpressions.
1276 transformUpdateTargetList(pstate
, onConflictClause
->targetList
);
1278 onConflictWhere
= transformWhereClause(pstate
,
1279 onConflictClause
->whereClause
,
1280 EXPR_KIND_WHERE
, "WHERE");
1283 * Remove the EXCLUDED pseudo relation from the query namespace, since
1284 * it's not supposed to be available in RETURNING. (Maybe someday we
1285 * could allow that, and drop this step.)
1287 Assert((ParseNamespaceItem
*) llast(pstate
->p_namespace
) == exclNSItem
);
1288 pstate
->p_namespace
= list_delete_last(pstate
->p_namespace
);
1291 /* Finally, build ON CONFLICT DO [NOTHING | UPDATE] expression */
1292 result
= makeNode(OnConflictExpr
);
1294 result
->action
= onConflictClause
->action
;
1295 result
->arbiterElems
= arbiterElems
;
1296 result
->arbiterWhere
= arbiterWhere
;
1297 result
->constraint
= arbiterConstraint
;
1298 result
->onConflictSet
= onConflictSet
;
1299 result
->onConflictWhere
= onConflictWhere
;
1300 result
->exclRelIndex
= exclRelIndex
;
1301 result
->exclRelTlist
= exclRelTlist
;
1308 * BuildOnConflictExcludedTargetlist
1309 * Create target list for the EXCLUDED pseudo-relation of ON CONFLICT,
1310 * representing the columns of targetrel with varno exclRelIndex.
1312 * Note: Exported for use in the rewriter.
1315 BuildOnConflictExcludedTargetlist(Relation targetrel
,
1324 * Note that resnos of the tlist must correspond to attnos of the
1325 * underlying relation, hence we need entries for dropped columns too.
1327 for (attno
= 0; attno
< RelationGetNumberOfAttributes(targetrel
); attno
++)
1329 Form_pg_attribute attr
= TupleDescAttr(targetrel
->rd_att
, attno
);
1332 if (attr
->attisdropped
)
1335 * can't use atttypid here, but it doesn't really matter what type
1336 * the Const claims to be.
1338 var
= (Var
*) makeNullConst(INT4OID
, -1, InvalidOid
);
1343 var
= makeVar(exclRelIndex
, attno
+ 1,
1344 attr
->atttypid
, attr
->atttypmod
,
1347 name
= pstrdup(NameStr(attr
->attname
));
1350 te
= makeTargetEntry((Expr
*) var
,
1355 result
= lappend(result
, te
);
1359 * Add a whole-row-Var entry to support references to "EXCLUDED.*". Like
1360 * the other entries in the EXCLUDED tlist, its resno must match the Var's
1361 * varattno, else the wrong things happen while resolving references in
1362 * setrefs.c. This is against normal conventions for targetlists, but
1363 * it's okay since we don't use this as a real tlist.
1365 var
= makeVar(exclRelIndex
, InvalidAttrNumber
,
1366 targetrel
->rd_rel
->reltype
,
1368 te
= makeTargetEntry((Expr
*) var
, InvalidAttrNumber
, NULL
, true);
1369 result
= lappend(result
, te
);
1376 * count_rowexpr_columns -
1377 * get number of columns contained in a ROW() expression;
1378 * return -1 if expression isn't a RowExpr or a Var referencing one.
1380 * This is currently used only for hint purposes, so we aren't terribly
1381 * tense about recognizing all possible cases. The Var case is interesting
1382 * because that's what we'll get in the INSERT ... SELECT (...) case.
1385 count_rowexpr_columns(ParseState
*pstate
, Node
*expr
)
1389 if (IsA(expr
, RowExpr
))
1390 return list_length(((RowExpr
*) expr
)->args
);
1393 Var
*var
= (Var
*) expr
;
1394 AttrNumber attnum
= var
->varattno
;
1396 if (attnum
> 0 && var
->vartype
== RECORDOID
)
1400 rte
= GetRTEByRangeTablePosn(pstate
, var
->varno
, var
->varlevelsup
);
1401 if (rte
->rtekind
== RTE_SUBQUERY
)
1403 /* Subselect-in-FROM: examine sub-select's output expr */
1404 TargetEntry
*ste
= get_tle_by_resno(rte
->subquery
->targetList
,
1407 if (ste
== NULL
|| ste
->resjunk
)
1409 expr
= (Node
*) ste
->expr
;
1410 if (IsA(expr
, RowExpr
))
1411 return list_length(((RowExpr
*) expr
)->args
);
1420 * transformSelectStmt -
1421 * transforms a Select Statement
1423 * Note: this covers only cases with no set operations and no VALUES lists;
1424 * see below for the other cases.
1427 transformSelectStmt(ParseState
*pstate
, SelectStmt
*stmt
)
1429 Query
*qry
= makeNode(Query
);
1433 qry
->commandType
= CMD_SELECT
;
1435 /* process the WITH clause independently of all else */
1436 if (stmt
->withClause
)
1438 qry
->hasRecursive
= stmt
->withClause
->recursive
;
1439 qry
->cteList
= transformWithClause(pstate
, stmt
->withClause
);
1440 qry
->hasModifyingCTE
= pstate
->p_hasModifyingCTE
;
1443 /* Complain if we get called from someplace where INTO is not allowed */
1444 if (stmt
->intoClause
)
1446 (errcode(ERRCODE_SYNTAX_ERROR
),
1447 errmsg("SELECT ... INTO is not allowed here"),
1448 parser_errposition(pstate
,
1449 exprLocation((Node
*) stmt
->intoClause
))));
1451 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
1452 pstate
->p_locking_clause
= stmt
->lockingClause
;
1454 /* make WINDOW info available for window functions, too */
1455 pstate
->p_windowdefs
= stmt
->windowClause
;
1457 /* process the FROM clause */
1458 transformFromClause(pstate
, stmt
->fromClause
);
1460 /* transform targetlist */
1461 qry
->targetList
= transformTargetList(pstate
, stmt
->targetList
,
1462 EXPR_KIND_SELECT_TARGET
);
1464 /* mark column origins */
1465 markTargetListOrigins(pstate
, qry
->targetList
);
1467 /* transform WHERE */
1468 qual
= transformWhereClause(pstate
, stmt
->whereClause
,
1469 EXPR_KIND_WHERE
, "WHERE");
1471 /* initial processing of HAVING clause is much like WHERE clause */
1472 qry
->havingQual
= transformWhereClause(pstate
, stmt
->havingClause
,
1473 EXPR_KIND_HAVING
, "HAVING");
1476 * Transform sorting/grouping stuff. Do ORDER BY first because both
1477 * transformGroupClause and transformDistinctClause need the results. Note
1478 * that these functions can also change the targetList, so it's passed to
1479 * them by reference.
1481 qry
->sortClause
= transformSortClause(pstate
,
1485 false /* allow SQL92 rules */ );
1487 qry
->groupClause
= transformGroupClause(pstate
,
1493 false /* allow SQL92 rules */ );
1494 qry
->groupDistinct
= stmt
->groupDistinct
;
1496 if (stmt
->distinctClause
== NIL
)
1498 qry
->distinctClause
= NIL
;
1499 qry
->hasDistinctOn
= false;
1501 else if (linitial(stmt
->distinctClause
) == NULL
)
1503 /* We had SELECT DISTINCT */
1504 qry
->distinctClause
= transformDistinctClause(pstate
,
1508 qry
->hasDistinctOn
= false;
1512 /* We had SELECT DISTINCT ON */
1513 qry
->distinctClause
= transformDistinctOnClause(pstate
,
1514 stmt
->distinctClause
,
1517 qry
->hasDistinctOn
= true;
1520 /* transform LIMIT */
1521 qry
->limitOffset
= transformLimitClause(pstate
, stmt
->limitOffset
,
1522 EXPR_KIND_OFFSET
, "OFFSET",
1524 qry
->limitCount
= transformLimitClause(pstate
, stmt
->limitCount
,
1525 EXPR_KIND_LIMIT
, "LIMIT",
1527 qry
->limitOption
= stmt
->limitOption
;
1529 /* transform window clauses after we have seen all window functions */
1530 qry
->windowClause
= transformWindowDefinitions(pstate
,
1531 pstate
->p_windowdefs
,
1534 /* resolve any still-unresolved output columns as being type text */
1535 if (pstate
->p_resolve_unknowns
)
1536 resolveTargetListUnknowns(pstate
, qry
->targetList
);
1538 qry
->rtable
= pstate
->p_rtable
;
1539 qry
->rteperminfos
= pstate
->p_rteperminfos
;
1540 qry
->jointree
= makeFromExpr(pstate
->p_joinlist
, qual
);
1542 qry
->hasSubLinks
= pstate
->p_hasSubLinks
;
1543 qry
->hasWindowFuncs
= pstate
->p_hasWindowFuncs
;
1544 qry
->hasTargetSRFs
= pstate
->p_hasTargetSRFs
;
1545 qry
->hasAggs
= pstate
->p_hasAggs
;
1547 foreach(l
, stmt
->lockingClause
)
1549 transformLockingClause(pstate
, qry
,
1550 (LockingClause
*) lfirst(l
), false);
1553 assign_query_collations(pstate
, qry
);
1555 /* this must be done after collations, for reliable comparison of exprs */
1556 if (pstate
->p_hasAggs
|| qry
->groupClause
|| qry
->groupingSets
|| qry
->havingQual
)
1557 parseCheckAggregates(pstate
, qry
);
1563 * transformValuesClause -
1564 * transforms a VALUES clause that's being used as a standalone SELECT
1566 * We build a Query containing a VALUES RTE, rather as if one had written
1567 * SELECT * FROM (VALUES ...) AS "*VALUES*"
1570 transformValuesClause(ParseState
*pstate
, SelectStmt
*stmt
)
1572 Query
*qry
= makeNode(Query
);
1573 List
*exprsLists
= NIL
;
1574 List
*coltypes
= NIL
;
1575 List
*coltypmods
= NIL
;
1576 List
*colcollations
= NIL
;
1577 List
**colexprs
= NULL
;
1578 int sublist_length
= -1;
1579 bool lateral
= false;
1580 ParseNamespaceItem
*nsitem
;
1585 qry
->commandType
= CMD_SELECT
;
1587 /* Most SELECT stuff doesn't apply in a VALUES clause */
1588 Assert(stmt
->distinctClause
== NIL
);
1589 Assert(stmt
->intoClause
== NULL
);
1590 Assert(stmt
->targetList
== NIL
);
1591 Assert(stmt
->fromClause
== NIL
);
1592 Assert(stmt
->whereClause
== NULL
);
1593 Assert(stmt
->groupClause
== NIL
);
1594 Assert(stmt
->havingClause
== NULL
);
1595 Assert(stmt
->windowClause
== NIL
);
1596 Assert(stmt
->op
== SETOP_NONE
);
1598 /* process the WITH clause independently of all else */
1599 if (stmt
->withClause
)
1601 qry
->hasRecursive
= stmt
->withClause
->recursive
;
1602 qry
->cteList
= transformWithClause(pstate
, stmt
->withClause
);
1603 qry
->hasModifyingCTE
= pstate
->p_hasModifyingCTE
;
1607 * For each row of VALUES, transform the raw expressions.
1609 * Note that the intermediate representation we build is column-organized
1610 * not row-organized. That simplifies the type and collation processing
1613 foreach(lc
, stmt
->valuesLists
)
1615 List
*sublist
= (List
*) lfirst(lc
);
1618 * Do basic expression transformation (same as a ROW() expr, but here
1619 * we disallow SetToDefault)
1621 sublist
= transformExpressionList(pstate
, sublist
,
1622 EXPR_KIND_VALUES
, false);
1625 * All the sublists must be the same length, *after* transformation
1626 * (which might expand '*' into multiple items). The VALUES RTE can't
1627 * handle anything different.
1629 if (sublist_length
< 0)
1631 /* Remember post-transformation length of first sublist */
1632 sublist_length
= list_length(sublist
);
1633 /* and allocate array for per-column lists */
1634 colexprs
= (List
**) palloc0(sublist_length
* sizeof(List
*));
1636 else if (sublist_length
!= list_length(sublist
))
1639 (errcode(ERRCODE_SYNTAX_ERROR
),
1640 errmsg("VALUES lists must all be the same length"),
1641 parser_errposition(pstate
,
1642 exprLocation((Node
*) sublist
))));
1645 /* Build per-column expression lists */
1647 foreach(lc2
, sublist
)
1649 Node
*col
= (Node
*) lfirst(lc2
);
1651 colexprs
[i
] = lappend(colexprs
[i
], col
);
1655 /* Release sub-list's cells to save memory */
1658 /* Prepare an exprsLists element for this row */
1659 exprsLists
= lappend(exprsLists
, NIL
);
1663 * Now resolve the common types of the columns, and coerce everything to
1664 * those types. Then identify the common typmod and common collation, if
1665 * any, of each column.
1667 * We must do collation processing now because (1) assign_query_collations
1668 * doesn't process rangetable entries, and (2) we need to label the VALUES
1669 * RTE with column collations for use in the outer query. We don't
1670 * consider conflict of implicit collations to be an error here; instead
1671 * the column will just show InvalidOid as its collation, and you'll get a
1672 * failure later if that results in failure to resolve a collation.
1674 * Note we modify the per-column expression lists in-place.
1676 for (i
= 0; i
< sublist_length
; i
++)
1682 coltype
= select_common_type(pstate
, colexprs
[i
], "VALUES", NULL
);
1684 foreach(lc
, colexprs
[i
])
1686 Node
*col
= (Node
*) lfirst(lc
);
1688 col
= coerce_to_common_type(pstate
, col
, coltype
, "VALUES");
1692 coltypmod
= select_common_typmod(pstate
, colexprs
[i
], coltype
);
1693 colcoll
= select_common_collation(pstate
, colexprs
[i
], true);
1695 coltypes
= lappend_oid(coltypes
, coltype
);
1696 coltypmods
= lappend_int(coltypmods
, coltypmod
);
1697 colcollations
= lappend_oid(colcollations
, colcoll
);
1701 * Finally, rearrange the coerced expressions into row-organized lists.
1703 for (i
= 0; i
< sublist_length
; i
++)
1705 forboth(lc
, colexprs
[i
], lc2
, exprsLists
)
1707 Node
*col
= (Node
*) lfirst(lc
);
1708 List
*sublist
= lfirst(lc2
);
1710 sublist
= lappend(sublist
, col
);
1711 lfirst(lc2
) = sublist
;
1713 list_free(colexprs
[i
]);
1717 * Ordinarily there can't be any current-level Vars in the expression
1718 * lists, because the namespace was empty ... but if we're inside CREATE
1719 * RULE, then NEW/OLD references might appear. In that case we have to
1720 * mark the VALUES RTE as LATERAL.
1722 if (pstate
->p_rtable
!= NIL
&&
1723 contain_vars_of_level((Node
*) exprsLists
, 0))
1727 * Generate the VALUES RTE
1729 nsitem
= addRangeTableEntryForValues(pstate
, exprsLists
,
1730 coltypes
, coltypmods
, colcollations
,
1731 NULL
, lateral
, true);
1732 addNSItemToQuery(pstate
, nsitem
, true, true, true);
1735 * Generate a targetlist as though expanding "*"
1737 Assert(pstate
->p_next_resno
== 1);
1738 qry
->targetList
= expandNSItemAttrs(pstate
, nsitem
, 0, true, -1);
1741 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
1744 qry
->sortClause
= transformSortClause(pstate
,
1748 false /* allow SQL92 rules */ );
1750 qry
->limitOffset
= transformLimitClause(pstate
, stmt
->limitOffset
,
1751 EXPR_KIND_OFFSET
, "OFFSET",
1753 qry
->limitCount
= transformLimitClause(pstate
, stmt
->limitCount
,
1754 EXPR_KIND_LIMIT
, "LIMIT",
1756 qry
->limitOption
= stmt
->limitOption
;
1758 if (stmt
->lockingClause
)
1760 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1762 translator: %s is a SQL row locking clause such as FOR UPDATE */
1763 errmsg("%s cannot be applied to VALUES",
1764 LCS_asString(((LockingClause
*)
1765 linitial(stmt
->lockingClause
))->strength
))));
1767 qry
->rtable
= pstate
->p_rtable
;
1768 qry
->rteperminfos
= pstate
->p_rteperminfos
;
1769 qry
->jointree
= makeFromExpr(pstate
->p_joinlist
, NULL
);
1771 qry
->hasSubLinks
= pstate
->p_hasSubLinks
;
1773 assign_query_collations(pstate
, qry
);
1779 * transformSetOperationStmt -
1780 * transforms a set-operations tree
1782 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1783 * structure to it. We must transform each leaf SELECT and build up a top-
1784 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1785 * The tree of set operations is converted into the setOperations field of
1786 * the top-level Query.
1789 transformSetOperationStmt(ParseState
*pstate
, SelectStmt
*stmt
)
1791 Query
*qry
= makeNode(Query
);
1792 SelectStmt
*leftmostSelect
;
1794 Query
*leftmostQuery
;
1795 SetOperationStmt
*sostmt
;
1799 List
*lockingClause
;
1800 WithClause
*withClause
;
1802 ListCell
*left_tlist
,
1810 int sv_rtable_length
;
1811 ParseNamespaceItem
*jnsitem
;
1812 ParseNamespaceColumn
*sortnscolumns
;
1816 qry
->commandType
= CMD_SELECT
;
1819 * Find leftmost leaf SelectStmt. We currently only need to do this in
1820 * order to deliver a suitable error message if there's an INTO clause
1821 * there, implying the set-op tree is in a context that doesn't allow
1822 * INTO. (transformSetOperationTree would throw error anyway, but it
1823 * seems worth the trouble to throw a different error for non-leftmost
1824 * INTO, so we produce that error in transformSetOperationTree.)
1826 leftmostSelect
= stmt
->larg
;
1827 while (leftmostSelect
&& leftmostSelect
->op
!= SETOP_NONE
)
1828 leftmostSelect
= leftmostSelect
->larg
;
1829 Assert(leftmostSelect
&& IsA(leftmostSelect
, SelectStmt
) &&
1830 leftmostSelect
->larg
== NULL
);
1831 if (leftmostSelect
->intoClause
)
1833 (errcode(ERRCODE_SYNTAX_ERROR
),
1834 errmsg("SELECT ... INTO is not allowed here"),
1835 parser_errposition(pstate
,
1836 exprLocation((Node
*) leftmostSelect
->intoClause
))));
1839 * We need to extract ORDER BY and other top-level clauses here and not
1840 * let transformSetOperationTree() see them --- else it'll just recurse
1843 sortClause
= stmt
->sortClause
;
1844 limitOffset
= stmt
->limitOffset
;
1845 limitCount
= stmt
->limitCount
;
1846 lockingClause
= stmt
->lockingClause
;
1847 withClause
= stmt
->withClause
;
1849 stmt
->sortClause
= NIL
;
1850 stmt
->limitOffset
= NULL
;
1851 stmt
->limitCount
= NULL
;
1852 stmt
->lockingClause
= NIL
;
1853 stmt
->withClause
= NULL
;
1855 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1858 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
1860 translator: %s is a SQL row locking clause such as FOR UPDATE */
1861 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1862 LCS_asString(((LockingClause
*)
1863 linitial(lockingClause
))->strength
))));
1865 /* Process the WITH clause independently of all else */
1868 qry
->hasRecursive
= withClause
->recursive
;
1869 qry
->cteList
= transformWithClause(pstate
, withClause
);
1870 qry
->hasModifyingCTE
= pstate
->p_hasModifyingCTE
;
1874 * Recursively transform the components of the tree.
1876 sostmt
= castNode(SetOperationStmt
,
1877 transformSetOperationTree(pstate
, stmt
, true, NULL
));
1879 qry
->setOperations
= (Node
*) sostmt
;
1882 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1884 node
= sostmt
->larg
;
1885 while (node
&& IsA(node
, SetOperationStmt
))
1886 node
= ((SetOperationStmt
*) node
)->larg
;
1887 Assert(node
&& IsA(node
, RangeTblRef
));
1888 leftmostRTI
= ((RangeTblRef
*) node
)->rtindex
;
1889 leftmostQuery
= rt_fetch(leftmostRTI
, pstate
->p_rtable
)->subquery
;
1890 Assert(leftmostQuery
!= NULL
);
1893 * Generate dummy targetlist for outer query using column names of
1894 * leftmost select and common datatypes/collations of topmost set
1895 * operation. Also make lists of the dummy vars and their names for use
1896 * in parsing ORDER BY.
1898 * Note: we use leftmostRTI as the varno of the dummy variables. It
1899 * shouldn't matter too much which RT index they have, as long as they
1900 * have one that corresponds to a real RT entry; else funny things may
1901 * happen when the tree is mashed by rule rewriting.
1903 qry
->targetList
= NIL
;
1906 sortnscolumns
= (ParseNamespaceColumn
*)
1907 palloc0(list_length(sostmt
->colTypes
) * sizeof(ParseNamespaceColumn
));
1910 forfour(lct
, sostmt
->colTypes
,
1911 lcm
, sostmt
->colTypmods
,
1912 lcc
, sostmt
->colCollations
,
1913 left_tlist
, leftmostQuery
->targetList
)
1915 Oid colType
= lfirst_oid(lct
);
1916 int32 colTypmod
= lfirst_int(lcm
);
1917 Oid colCollation
= lfirst_oid(lcc
);
1918 TargetEntry
*lefttle
= (TargetEntry
*) lfirst(left_tlist
);
1923 Assert(!lefttle
->resjunk
);
1924 colName
= pstrdup(lefttle
->resname
);
1925 var
= makeVar(leftmostRTI
,
1931 var
->location
= exprLocation((Node
*) lefttle
->expr
);
1932 tle
= makeTargetEntry((Expr
*) var
,
1933 (AttrNumber
) pstate
->p_next_resno
++,
1936 qry
->targetList
= lappend(qry
->targetList
, tle
);
1937 targetvars
= lappend(targetvars
, var
);
1938 targetnames
= lappend(targetnames
, makeString(colName
));
1939 sortnscolumns
[sortcolindex
].p_varno
= leftmostRTI
;
1940 sortnscolumns
[sortcolindex
].p_varattno
= lefttle
->resno
;
1941 sortnscolumns
[sortcolindex
].p_vartype
= colType
;
1942 sortnscolumns
[sortcolindex
].p_vartypmod
= colTypmod
;
1943 sortnscolumns
[sortcolindex
].p_varcollid
= colCollation
;
1944 sortnscolumns
[sortcolindex
].p_varnosyn
= leftmostRTI
;
1945 sortnscolumns
[sortcolindex
].p_varattnosyn
= lefttle
->resno
;
1950 * As a first step towards supporting sort clauses that are expressions
1951 * using the output columns, generate a namespace entry that makes the
1952 * output columns visible. A Join RTE node is handy for this, since we
1953 * can easily control the Vars generated upon matches.
1955 * Note: we don't yet do anything useful with such cases, but at least
1956 * "ORDER BY upper(foo)" will draw the right error message rather than
1959 sv_rtable_length
= list_length(pstate
->p_rtable
);
1961 jnsitem
= addRangeTableEntryForJoin(pstate
,
1973 sv_namespace
= pstate
->p_namespace
;
1974 pstate
->p_namespace
= NIL
;
1976 /* add jnsitem to column namespace only */
1977 addNSItemToQuery(pstate
, jnsitem
, false, false, true);
1980 * For now, we don't support resjunk sort clauses on the output of a
1981 * setOperation tree --- you can only use the SQL92-spec options of
1982 * selecting an output column by name or number. Enforce by checking that
1983 * transformSortClause doesn't add any items to tlist. Note, if changing
1984 * this, add_setop_child_rel_equivalences() will need to be updated.
1986 tllen
= list_length(qry
->targetList
);
1988 qry
->sortClause
= transformSortClause(pstate
,
1992 false /* allow SQL92 rules */ );
1994 /* restore namespace, remove join RTE from rtable */
1995 pstate
->p_namespace
= sv_namespace
;
1996 pstate
->p_rtable
= list_truncate(pstate
->p_rtable
, sv_rtable_length
);
1998 if (tllen
!= list_length(qry
->targetList
))
2000 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2001 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
2002 errdetail("Only result column names can be used, not expressions or functions."),
2003 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
2004 parser_errposition(pstate
,
2005 exprLocation(list_nth(qry
->targetList
, tllen
)))));
2007 qry
->limitOffset
= transformLimitClause(pstate
, limitOffset
,
2008 EXPR_KIND_OFFSET
, "OFFSET",
2010 qry
->limitCount
= transformLimitClause(pstate
, limitCount
,
2011 EXPR_KIND_LIMIT
, "LIMIT",
2013 qry
->limitOption
= stmt
->limitOption
;
2015 qry
->rtable
= pstate
->p_rtable
;
2016 qry
->rteperminfos
= pstate
->p_rteperminfos
;
2017 qry
->jointree
= makeFromExpr(pstate
->p_joinlist
, NULL
);
2019 qry
->hasSubLinks
= pstate
->p_hasSubLinks
;
2020 qry
->hasWindowFuncs
= pstate
->p_hasWindowFuncs
;
2021 qry
->hasTargetSRFs
= pstate
->p_hasTargetSRFs
;
2022 qry
->hasAggs
= pstate
->p_hasAggs
;
2024 foreach(l
, lockingClause
)
2026 transformLockingClause(pstate
, qry
,
2027 (LockingClause
*) lfirst(l
), false);
2030 assign_query_collations(pstate
, qry
);
2032 /* this must be done after collations, for reliable comparison of exprs */
2033 if (pstate
->p_hasAggs
|| qry
->groupClause
|| qry
->groupingSets
|| qry
->havingQual
)
2034 parseCheckAggregates(pstate
, qry
);
2040 * Make a SortGroupClause node for a SetOperationStmt's groupClauses
2042 * If require_hash is true, the caller is indicating that they need hash
2043 * support or they will fail. So look extra hard for hash support.
2046 makeSortGroupClauseForSetOp(Oid rescoltype
, bool require_hash
)
2048 SortGroupClause
*grpcl
= makeNode(SortGroupClause
);
2053 /* determine the eqop and optional sortop */
2054 get_sort_group_operators(rescoltype
,
2056 &sortop
, &eqop
, NULL
,
2060 * The type cache doesn't believe that record is hashable (see
2061 * cache_record_field_properties()), but if the caller really needs hash
2062 * support, we can assume it does. Worst case, if any components of the
2063 * record don't support hashing, we will fail at execution.
2065 if (require_hash
&& (rescoltype
== RECORDOID
|| rescoltype
== RECORDARRAYOID
))
2068 /* we don't have a tlist yet, so can't assign sortgrouprefs */
2069 grpcl
->tleSortGroupRef
= 0;
2071 grpcl
->sortop
= sortop
;
2072 grpcl
->reverse_sort
= false; /* Sort-op is "less than", or InvalidOid */
2073 grpcl
->nulls_first
= false; /* OK with or without sortop */
2074 grpcl
->hashable
= hashable
;
2080 * transformSetOperationTree
2081 * Recursively transform leaves and internal nodes of a set-op tree
2083 * In addition to returning the transformed node, if targetlist isn't NULL
2084 * then we return a list of its non-resjunk TargetEntry nodes. For a leaf
2085 * set-op node these are the actual targetlist entries; otherwise they are
2086 * dummy entries created to carry the type, typmod, collation, and location
2087 * (for error messages) of each output column of the set-op node. This info
2088 * is needed only during the internal recursion of this function, so outside
2089 * callers pass NULL for targetlist. Note: the reason for passing the
2090 * actual targetlist entries of a leaf node is so that upper levels can
2091 * replace UNKNOWN Consts with properly-coerced constants.
2094 transformSetOperationTree(ParseState
*pstate
, SelectStmt
*stmt
,
2095 bool isTopLevel
, List
**targetlist
)
2099 Assert(stmt
&& IsA(stmt
, SelectStmt
));
2101 /* Guard against stack overflow due to overly complex set-expressions */
2102 check_stack_depth();
2105 * Validity-check both leaf and internal SELECTs for disallowed ops.
2107 if (stmt
->intoClause
)
2109 (errcode(ERRCODE_SYNTAX_ERROR
),
2110 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
2111 parser_errposition(pstate
,
2112 exprLocation((Node
*) stmt
->intoClause
))));
2114 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2115 if (stmt
->lockingClause
)
2117 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
2119 translator: %s is a SQL row locking clause such as FOR UPDATE */
2120 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
2121 LCS_asString(((LockingClause
*)
2122 linitial(stmt
->lockingClause
))->strength
))));
2125 * If an internal node of a set-op tree has ORDER BY, LIMIT, FOR UPDATE,
2126 * or WITH clauses attached, we need to treat it like a leaf node to
2127 * generate an independent sub-Query tree. Otherwise, it can be
2128 * represented by a SetOperationStmt node underneath the parent Query.
2130 if (stmt
->op
== SETOP_NONE
)
2132 Assert(stmt
->larg
== NULL
&& stmt
->rarg
== NULL
);
2137 Assert(stmt
->larg
!= NULL
&& stmt
->rarg
!= NULL
);
2138 if (stmt
->sortClause
|| stmt
->limitOffset
|| stmt
->limitCount
||
2139 stmt
->lockingClause
|| stmt
->withClause
)
2147 /* Process leaf SELECT */
2149 char selectName
[32];
2150 ParseNamespaceItem
*nsitem
;
2155 * Transform SelectStmt into a Query.
2157 * This works the same as SELECT transformation normally would, except
2158 * that we prevent resolving unknown-type outputs as TEXT. This does
2159 * not change the subquery's semantics since if the column type
2160 * matters semantically, it would have been resolved to something else
2161 * anyway. Doing this lets us resolve such outputs using
2162 * select_common_type(), below.
2164 * Note: previously transformed sub-queries don't affect the parsing
2165 * of this sub-query, because they are not in the toplevel pstate's
2168 selectQuery
= parse_sub_analyze((Node
*) stmt
, pstate
,
2169 NULL
, false, false);
2172 * Check for bogus references to Vars on the current query level (but
2173 * upper-level references are okay). Normally this can't happen
2174 * because the namespace will be empty, but it could happen if we are
2177 if (pstate
->p_namespace
)
2179 if (contain_vars_of_level((Node
*) selectQuery
, 1))
2181 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE
),
2182 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
2183 parser_errposition(pstate
,
2184 locate_var_of_level((Node
*) selectQuery
, 1))));
2188 * Extract a list of the non-junk TLEs for upper-level processing.
2193 foreach(tl
, selectQuery
->targetList
)
2195 TargetEntry
*tle
= (TargetEntry
*) lfirst(tl
);
2198 *targetlist
= lappend(*targetlist
, tle
);
2203 * Make the leaf query be a subquery in the top-level rangetable.
2205 snprintf(selectName
, sizeof(selectName
), "*SELECT* %d",
2206 list_length(pstate
->p_rtable
) + 1);
2207 nsitem
= addRangeTableEntryForSubquery(pstate
,
2209 makeAlias(selectName
, NIL
),
2214 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2216 rtr
= makeNode(RangeTblRef
);
2217 rtr
->rtindex
= nsitem
->p_rtindex
;
2218 return (Node
*) rtr
;
2222 /* Process an internal node (set operation node) */
2223 SetOperationStmt
*op
= makeNode(SetOperationStmt
);
2228 const char *context
;
2229 bool recursive
= (pstate
->p_parent_cte
&&
2230 pstate
->p_parent_cte
->cterecursive
);
2232 context
= (stmt
->op
== SETOP_UNION
? "UNION" :
2233 (stmt
->op
== SETOP_INTERSECT
? "INTERSECT" :
2237 op
->all
= stmt
->all
;
2240 * Recursively transform the left child node.
2242 op
->larg
= transformSetOperationTree(pstate
, stmt
->larg
,
2247 * If we are processing a recursive union query, now is the time to
2248 * examine the non-recursive term's output columns and mark the
2249 * containing CTE as having those result columns. We should do this
2250 * only at the topmost setop of the CTE, of course.
2252 if (isTopLevel
&& recursive
)
2253 determineRecursiveColTypes(pstate
, op
->larg
, ltargetlist
);
2256 * Recursively transform the right child node.
2258 op
->rarg
= transformSetOperationTree(pstate
, stmt
->rarg
,
2263 * Verify that the two children have the same number of non-junk
2264 * columns, and determine the types of the merged output columns.
2266 if (list_length(ltargetlist
) != list_length(rtargetlist
))
2268 (errcode(ERRCODE_SYNTAX_ERROR
),
2269 errmsg("each %s query must have the same number of columns",
2271 parser_errposition(pstate
,
2272 exprLocation((Node
*) rtargetlist
))));
2277 op
->colTypmods
= NIL
;
2278 op
->colCollations
= NIL
;
2279 op
->groupClauses
= NIL
;
2280 forboth(ltl
, ltargetlist
, rtl
, rtargetlist
)
2282 TargetEntry
*ltle
= (TargetEntry
*) lfirst(ltl
);
2283 TargetEntry
*rtle
= (TargetEntry
*) lfirst(rtl
);
2284 Node
*lcolnode
= (Node
*) ltle
->expr
;
2285 Node
*rcolnode
= (Node
*) rtle
->expr
;
2286 Oid lcoltype
= exprType(lcolnode
);
2287 Oid rcoltype
= exprType(rcolnode
);
2294 /* select common type, same as CASE et al */
2295 rescoltype
= select_common_type(pstate
,
2296 list_make2(lcolnode
, rcolnode
),
2299 bestlocation
= exprLocation(bestexpr
);
2302 * Verify the coercions are actually possible. If not, we'd fail
2303 * later anyway, but we want to fail now while we have sufficient
2304 * context to produce an error cursor position.
2306 * For all non-UNKNOWN-type cases, we verify coercibility but we
2307 * don't modify the child's expression, for fear of changing the
2308 * child query's semantics.
2310 * If a child expression is an UNKNOWN-type Const or Param, we
2311 * want to replace it with the coerced expression. This can only
2312 * happen when the child is a leaf set-op node. It's safe to
2313 * replace the expression because if the child query's semantics
2314 * depended on the type of this output column, it'd have already
2315 * coerced the UNKNOWN to something else. We want to do this
2316 * because (a) we want to verify that a Const is valid for the
2317 * target type, or resolve the actual type of an UNKNOWN Param,
2318 * and (b) we want to avoid unnecessary discrepancies between the
2319 * output type of the child query and the resolved target type.
2320 * Such a discrepancy would disable optimization in the planner.
2322 * If it's some other UNKNOWN-type node, eg a Var, we do nothing
2323 * (knowing that coerce_to_common_type would fail). The planner
2324 * is sometimes able to fold an UNKNOWN Var to a constant before
2325 * it has to coerce the type, so failing now would just break
2326 * cases that might work.
2328 if (lcoltype
!= UNKNOWNOID
)
2329 lcolnode
= coerce_to_common_type(pstate
, lcolnode
,
2330 rescoltype
, context
);
2331 else if (IsA(lcolnode
, Const
) ||
2332 IsA(lcolnode
, Param
))
2334 lcolnode
= coerce_to_common_type(pstate
, lcolnode
,
2335 rescoltype
, context
);
2336 ltle
->expr
= (Expr
*) lcolnode
;
2339 if (rcoltype
!= UNKNOWNOID
)
2340 rcolnode
= coerce_to_common_type(pstate
, rcolnode
,
2341 rescoltype
, context
);
2342 else if (IsA(rcolnode
, Const
) ||
2343 IsA(rcolnode
, Param
))
2345 rcolnode
= coerce_to_common_type(pstate
, rcolnode
,
2346 rescoltype
, context
);
2347 rtle
->expr
= (Expr
*) rcolnode
;
2350 rescoltypmod
= select_common_typmod(pstate
,
2351 list_make2(lcolnode
, rcolnode
),
2355 * Select common collation. A common collation is required for
2356 * all set operators except UNION ALL; see SQL:2008 7.13 <query
2357 * expression> Syntax Rule 15c. (If we fail to identify a common
2358 * collation for a UNION ALL column, the colCollations element
2359 * will be set to InvalidOid, which may result in a runtime error
2360 * if something at a higher query level wants to use the column's
2363 rescolcoll
= select_common_collation(pstate
,
2364 list_make2(lcolnode
, rcolnode
),
2365 (op
->op
== SETOP_UNION
&& op
->all
));
2368 op
->colTypes
= lappend_oid(op
->colTypes
, rescoltype
);
2369 op
->colTypmods
= lappend_int(op
->colTypmods
, rescoltypmod
);
2370 op
->colCollations
= lappend_oid(op
->colCollations
, rescolcoll
);
2373 * For all cases except UNION ALL, identify the grouping operators
2374 * (and, if available, sorting operators) that will be used to
2375 * eliminate duplicates.
2377 if (op
->op
!= SETOP_UNION
|| !op
->all
)
2379 ParseCallbackState pcbstate
;
2381 setup_parser_errposition_callback(&pcbstate
, pstate
,
2385 * If it's a recursive union, we need to require hashing
2388 op
->groupClauses
= lappend(op
->groupClauses
,
2389 makeSortGroupClauseForSetOp(rescoltype
, recursive
));
2391 cancel_parser_errposition_callback(&pcbstate
);
2395 * Construct a dummy tlist entry to return. We use a SetToDefault
2396 * node for the expression, since it carries exactly the fields
2397 * needed, but any other expression node type would do as well.
2401 SetToDefault
*rescolnode
= makeNode(SetToDefault
);
2402 TargetEntry
*restle
;
2404 rescolnode
->typeId
= rescoltype
;
2405 rescolnode
->typeMod
= rescoltypmod
;
2406 rescolnode
->collation
= rescolcoll
;
2407 rescolnode
->location
= bestlocation
;
2408 restle
= makeTargetEntry((Expr
*) rescolnode
,
2409 0, /* no need to set resno */
2412 *targetlist
= lappend(*targetlist
, restle
);
2421 * Process the outputs of the non-recursive term of a recursive union
2422 * to set up the parent CTE's columns
2425 determineRecursiveColTypes(ParseState
*pstate
, Node
*larg
, List
*nrtargetlist
)
2429 Query
*leftmostQuery
;
2431 ListCell
*left_tlist
;
2436 * Find leftmost leaf SELECT
2439 while (node
&& IsA(node
, SetOperationStmt
))
2440 node
= ((SetOperationStmt
*) node
)->larg
;
2441 Assert(node
&& IsA(node
, RangeTblRef
));
2442 leftmostRTI
= ((RangeTblRef
*) node
)->rtindex
;
2443 leftmostQuery
= rt_fetch(leftmostRTI
, pstate
->p_rtable
)->subquery
;
2444 Assert(leftmostQuery
!= NULL
);
2447 * Generate dummy targetlist using column names of leftmost select and
2448 * dummy result expressions of the non-recursive term.
2453 forboth(nrtl
, nrtargetlist
, left_tlist
, leftmostQuery
->targetList
)
2455 TargetEntry
*nrtle
= (TargetEntry
*) lfirst(nrtl
);
2456 TargetEntry
*lefttle
= (TargetEntry
*) lfirst(left_tlist
);
2460 Assert(!lefttle
->resjunk
);
2461 colName
= pstrdup(lefttle
->resname
);
2462 tle
= makeTargetEntry(nrtle
->expr
,
2466 targetList
= lappend(targetList
, tle
);
2469 /* Now build CTE's output column info using dummy targetlist */
2470 analyzeCTETargetList(pstate
, pstate
->p_parent_cte
, targetList
);
2475 * transformReturnStmt -
2476 * transforms a return statement
2479 transformReturnStmt(ParseState
*pstate
, ReturnStmt
*stmt
)
2481 Query
*qry
= makeNode(Query
);
2483 qry
->commandType
= CMD_SELECT
;
2484 qry
->isReturn
= true;
2486 qry
->targetList
= list_make1(makeTargetEntry((Expr
*) transformExpr(pstate
, stmt
->returnval
, EXPR_KIND_SELECT_TARGET
),
2489 if (pstate
->p_resolve_unknowns
)
2490 resolveTargetListUnknowns(pstate
, qry
->targetList
);
2491 qry
->rtable
= pstate
->p_rtable
;
2492 qry
->rteperminfos
= pstate
->p_rteperminfos
;
2493 qry
->jointree
= makeFromExpr(pstate
->p_joinlist
, NULL
);
2494 qry
->hasSubLinks
= pstate
->p_hasSubLinks
;
2495 qry
->hasWindowFuncs
= pstate
->p_hasWindowFuncs
;
2496 qry
->hasTargetSRFs
= pstate
->p_hasTargetSRFs
;
2497 qry
->hasAggs
= pstate
->p_hasAggs
;
2499 assign_query_collations(pstate
, qry
);
2506 * transformUpdateStmt -
2507 * transforms an update statement
2510 transformUpdateStmt(ParseState
*pstate
, UpdateStmt
*stmt
)
2512 Query
*qry
= makeNode(Query
);
2513 ParseNamespaceItem
*nsitem
;
2516 qry
->commandType
= CMD_UPDATE
;
2517 pstate
->p_is_insert
= false;
2519 /* process the WITH clause independently of all else */
2520 if (stmt
->withClause
)
2522 qry
->hasRecursive
= stmt
->withClause
->recursive
;
2523 qry
->cteList
= transformWithClause(pstate
, stmt
->withClause
);
2524 qry
->hasModifyingCTE
= pstate
->p_hasModifyingCTE
;
2527 qry
->resultRelation
= setTargetTable(pstate
, stmt
->relation
,
2528 stmt
->relation
->inh
,
2531 nsitem
= pstate
->p_target_nsitem
;
2533 /* subqueries in FROM cannot access the result relation */
2534 nsitem
->p_lateral_only
= true;
2535 nsitem
->p_lateral_ok
= false;
2538 * the FROM clause is non-standard SQL syntax. We used to be able to do
2539 * this with REPLACE in POSTQUEL so we keep the feature.
2541 transformFromClause(pstate
, stmt
->fromClause
);
2543 /* remaining clauses can reference the result relation normally */
2544 nsitem
->p_lateral_only
= false;
2545 nsitem
->p_lateral_ok
= true;
2547 qual
= transformWhereClause(pstate
, stmt
->whereClause
,
2548 EXPR_KIND_WHERE
, "WHERE");
2550 transformReturningClause(pstate
, qry
, stmt
->returningClause
,
2551 EXPR_KIND_RETURNING
);
2554 * Now we are done with SELECT-like processing, and can get on with
2555 * transforming the target list to match the UPDATE target columns.
2557 qry
->targetList
= transformUpdateTargetList(pstate
, stmt
->targetList
);
2559 qry
->rtable
= pstate
->p_rtable
;
2560 qry
->rteperminfos
= pstate
->p_rteperminfos
;
2561 qry
->jointree
= makeFromExpr(pstate
->p_joinlist
, qual
);
2563 qry
->hasTargetSRFs
= pstate
->p_hasTargetSRFs
;
2564 qry
->hasSubLinks
= pstate
->p_hasSubLinks
;
2566 assign_query_collations(pstate
, qry
);
2572 * transformUpdateTargetList -
2573 * handle SET clause in UPDATE/MERGE/INSERT ... ON CONFLICT UPDATE
2576 transformUpdateTargetList(ParseState
*pstate
, List
*origTlist
)
2579 RTEPermissionInfo
*target_perminfo
;
2583 tlist
= transformTargetList(pstate
, origTlist
,
2584 EXPR_KIND_UPDATE_SOURCE
);
2586 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2587 if (pstate
->p_next_resno
<= RelationGetNumberOfAttributes(pstate
->p_target_relation
))
2588 pstate
->p_next_resno
= RelationGetNumberOfAttributes(pstate
->p_target_relation
) + 1;
2590 /* Prepare non-junk columns for assignment to target table */
2591 target_perminfo
= pstate
->p_target_nsitem
->p_perminfo
;
2592 orig_tl
= list_head(origTlist
);
2596 TargetEntry
*tle
= (TargetEntry
*) lfirst(tl
);
2597 ResTarget
*origTarget
;
2603 * Resjunk nodes need no additional processing, but be sure they
2604 * have resnos that do not match any target columns; else rewriter
2605 * or planner might get confused. They don't need a resname
2608 tle
->resno
= (AttrNumber
) pstate
->p_next_resno
++;
2609 tle
->resname
= NULL
;
2612 if (orig_tl
== NULL
)
2613 elog(ERROR
, "UPDATE target count mismatch --- internal error");
2614 origTarget
= lfirst_node(ResTarget
, orig_tl
);
2616 attrno
= attnameAttNum(pstate
->p_target_relation
,
2617 origTarget
->name
, true);
2618 if (attrno
== InvalidAttrNumber
)
2620 (errcode(ERRCODE_UNDEFINED_COLUMN
),
2621 errmsg("column \"%s\" of relation \"%s\" does not exist",
2623 RelationGetRelationName(pstate
->p_target_relation
)),
2624 (origTarget
->indirection
!= NIL
&&
2625 strcmp(origTarget
->name
, pstate
->p_target_nsitem
->p_names
->aliasname
) == 0) ?
2626 errhint("SET target columns cannot be qualified with the relation name.") : 0,
2627 parser_errposition(pstate
, origTarget
->location
)));
2629 updateTargetListEntry(pstate
, tle
, origTarget
->name
,
2631 origTarget
->indirection
,
2632 origTarget
->location
);
2634 /* Mark the target column as requiring update permissions */
2635 target_perminfo
->updatedCols
= bms_add_member(target_perminfo
->updatedCols
,
2636 attrno
- FirstLowInvalidHeapAttributeNumber
);
2638 orig_tl
= lnext(origTlist
, orig_tl
);
2640 if (orig_tl
!= NULL
)
2641 elog(ERROR
, "UPDATE target count mismatch --- internal error");
2647 * addNSItemForReturning -
2648 * add a ParseNamespaceItem for the OLD or NEW alias in RETURNING.
2651 addNSItemForReturning(ParseState
*pstate
, const char *aliasname
,
2652 VarReturningType returning_type
)
2656 ParseNamespaceColumn
*nscolumns
;
2657 ParseNamespaceItem
*nsitem
;
2659 /* copy per-column data from the target relation */
2660 colnames
= pstate
->p_target_nsitem
->p_rte
->eref
->colnames
;
2661 numattrs
= list_length(colnames
);
2663 nscolumns
= (ParseNamespaceColumn
*)
2664 palloc(numattrs
* sizeof(ParseNamespaceColumn
));
2666 memcpy(nscolumns
, pstate
->p_target_nsitem
->p_nscolumns
,
2667 numattrs
* sizeof(ParseNamespaceColumn
));
2669 /* mark all columns as returning OLD/NEW */
2670 for (int i
= 0; i
< numattrs
; i
++)
2671 nscolumns
[i
].p_varreturningtype
= returning_type
;
2673 /* build the nsitem, copying most fields from the target relation */
2674 nsitem
= (ParseNamespaceItem
*) palloc(sizeof(ParseNamespaceItem
));
2675 nsitem
->p_names
= makeAlias(aliasname
, colnames
);
2676 nsitem
->p_rte
= pstate
->p_target_nsitem
->p_rte
;
2677 nsitem
->p_rtindex
= pstate
->p_target_nsitem
->p_rtindex
;
2678 nsitem
->p_perminfo
= pstate
->p_target_nsitem
->p_perminfo
;
2679 nsitem
->p_nscolumns
= nscolumns
;
2680 nsitem
->p_returning_type
= returning_type
;
2682 /* add it to the query namespace as a table-only item */
2683 addNSItemToQuery(pstate
, nsitem
, false, true, false);
2687 * transformReturningClause -
2688 * handle a RETURNING clause in INSERT/UPDATE/DELETE/MERGE
2691 transformReturningClause(ParseState
*pstate
, Query
*qry
,
2692 ReturningClause
*returningClause
,
2693 ParseExprKind exprKind
)
2695 int save_nslen
= list_length(pstate
->p_namespace
);
2696 int save_next_resno
;
2698 if (returningClause
== NULL
)
2699 return; /* nothing to do */
2702 * Scan RETURNING WITH(...) options for OLD/NEW alias names. Complain if
2703 * there is any conflict with existing relations.
2705 foreach_node(ReturningOption
, option
, returningClause
->options
)
2707 switch (option
->option
)
2709 case RETURNING_OPTION_OLD
:
2710 if (qry
->returningOldAlias
!= NULL
)
2712 errcode(ERRCODE_SYNTAX_ERROR
),
2713 /* translator: %s is OLD or NEW */
2714 errmsg("%s cannot be specified multiple times", "OLD"),
2715 parser_errposition(pstate
, option
->location
));
2716 qry
->returningOldAlias
= option
->value
;
2719 case RETURNING_OPTION_NEW
:
2720 if (qry
->returningNewAlias
!= NULL
)
2722 errcode(ERRCODE_SYNTAX_ERROR
),
2723 /* translator: %s is OLD or NEW */
2724 errmsg("%s cannot be specified multiple times", "NEW"),
2725 parser_errposition(pstate
, option
->location
));
2726 qry
->returningNewAlias
= option
->value
;
2730 elog(ERROR
, "unrecognized returning option: %d", option
->option
);
2733 if (refnameNamespaceItem(pstate
, NULL
, option
->value
, -1, NULL
) != NULL
)
2735 errcode(ERRCODE_DUPLICATE_ALIAS
),
2736 errmsg("table name \"%s\" specified more than once",
2738 parser_errposition(pstate
, option
->location
));
2740 addNSItemForReturning(pstate
, option
->value
,
2741 option
->option
== RETURNING_OPTION_OLD
?
2742 VAR_RETURNING_OLD
: VAR_RETURNING_NEW
);
2746 * If OLD/NEW alias names weren't explicitly specified, use "old"/"new"
2747 * unless masked by existing relations.
2749 if (qry
->returningOldAlias
== NULL
&&
2750 refnameNamespaceItem(pstate
, NULL
, "old", -1, NULL
) == NULL
)
2752 qry
->returningOldAlias
= "old";
2753 addNSItemForReturning(pstate
, "old", VAR_RETURNING_OLD
);
2755 if (qry
->returningNewAlias
== NULL
&&
2756 refnameNamespaceItem(pstate
, NULL
, "new", -1, NULL
) == NULL
)
2758 qry
->returningNewAlias
= "new";
2759 addNSItemForReturning(pstate
, "new", VAR_RETURNING_NEW
);
2763 * We need to assign resnos starting at one in the RETURNING list. Save
2764 * and restore the main tlist's value of p_next_resno, just in case
2765 * someone looks at it later (probably won't happen).
2767 save_next_resno
= pstate
->p_next_resno
;
2768 pstate
->p_next_resno
= 1;
2770 /* transform RETURNING expressions identically to a SELECT targetlist */
2771 qry
->returningList
= transformTargetList(pstate
,
2772 returningClause
->exprs
,
2776 * Complain if the nonempty tlist expanded to nothing (which is possible
2777 * if it contains only a star-expansion of a zero-column table). If we
2778 * allow this, the parsed Query will look like it didn't have RETURNING,
2779 * with results that would probably surprise the user.
2781 if (qry
->returningList
== NIL
)
2783 (errcode(ERRCODE_SYNTAX_ERROR
),
2784 errmsg("RETURNING must have at least one column"),
2785 parser_errposition(pstate
,
2786 exprLocation(linitial(returningClause
->exprs
)))));
2788 /* mark column origins */
2789 markTargetListOrigins(pstate
, qry
->returningList
);
2791 /* resolve any still-unresolved output columns as being type text */
2792 if (pstate
->p_resolve_unknowns
)
2793 resolveTargetListUnknowns(pstate
, qry
->returningList
);
2796 pstate
->p_namespace
= list_truncate(pstate
->p_namespace
, save_nslen
);
2797 pstate
->p_next_resno
= save_next_resno
;
2802 * transformPLAssignStmt -
2803 * transform a PL/pgSQL assignment statement
2805 * If there is no opt_indirection, the transformed statement looks like
2806 * "SELECT a_expr ...", except the expression has been cast to the type of
2807 * the target. With indirection, it's still a SELECT, but the expression will
2808 * incorporate FieldStore and/or assignment SubscriptingRef nodes to compute a
2809 * new value for a container-type variable represented by the target. The
2810 * expression references the target as the container source.
2813 transformPLAssignStmt(ParseState
*pstate
, PLAssignStmt
*stmt
)
2815 Query
*qry
= makeNode(Query
);
2816 ColumnRef
*cref
= makeNode(ColumnRef
);
2817 List
*indirection
= stmt
->indirection
;
2818 int nnames
= stmt
->nnames
;
2819 SelectStmt
*sstmt
= stmt
->val
;
2823 Oid targetcollation
;
2831 * First, construct a ColumnRef for the target variable. If the target
2832 * has more than one dotted name, we have to pull the extra names out of
2833 * the indirection list.
2835 cref
->fields
= list_make1(makeString(stmt
->name
));
2836 cref
->location
= stmt
->location
;
2839 /* avoid munging the raw parsetree */
2840 indirection
= list_copy(indirection
);
2841 while (--nnames
> 0 && indirection
!= NIL
)
2843 Node
*ind
= (Node
*) linitial(indirection
);
2845 if (!IsA(ind
, String
))
2846 elog(ERROR
, "invalid name count in PLAssignStmt");
2847 cref
->fields
= lappend(cref
->fields
, ind
);
2848 indirection
= list_delete_first(indirection
);
2853 * Transform the target reference. Typically we will get back a Param
2854 * node, but there's no reason to be too picky about its type.
2856 target
= transformExpr(pstate
, (Node
*) cref
,
2857 EXPR_KIND_UPDATE_TARGET
);
2858 targettype
= exprType(target
);
2859 targettypmod
= exprTypmod(target
);
2860 targetcollation
= exprCollation(target
);
2863 * The rest mostly matches transformSelectStmt, except that we needn't
2864 * consider WITH or INTO, and we build a targetlist our own way.
2866 qry
->commandType
= CMD_SELECT
;
2867 pstate
->p_is_insert
= false;
2869 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
2870 pstate
->p_locking_clause
= sstmt
->lockingClause
;
2872 /* make WINDOW info available for window functions, too */
2873 pstate
->p_windowdefs
= sstmt
->windowClause
;
2875 /* process the FROM clause */
2876 transformFromClause(pstate
, sstmt
->fromClause
);
2878 /* initially transform the targetlist as if in SELECT */
2879 tlist
= transformTargetList(pstate
, sstmt
->targetList
,
2880 EXPR_KIND_SELECT_TARGET
);
2882 /* we should have exactly one targetlist item */
2883 if (list_length(tlist
) != 1)
2885 (errcode(ERRCODE_SYNTAX_ERROR
),
2886 errmsg_plural("assignment source returned %d column",
2887 "assignment source returned %d columns",
2889 list_length(tlist
))));
2891 tle
= linitial_node(TargetEntry
, tlist
);
2894 * This next bit is similar to transformAssignedExpr; the key difference
2895 * is we use COERCION_PLPGSQL not COERCION_ASSIGNMENT.
2897 type_id
= exprType((Node
*) tle
->expr
);
2899 pstate
->p_expr_kind
= EXPR_KIND_UPDATE_TARGET
;
2903 tle
->expr
= (Expr
*)
2904 transformAssignmentIndirection(pstate
,
2912 list_head(indirection
),
2915 exprLocation(target
));
2917 else if (targettype
!= type_id
&&
2918 (targettype
== RECORDOID
|| ISCOMPLEX(targettype
)) &&
2919 (type_id
== RECORDOID
|| ISCOMPLEX(type_id
)))
2922 * Hack: do not let coerce_to_target_type() deal with inconsistent
2923 * composite types. Just pass the expression result through as-is,
2924 * and let the PL/pgSQL executor do the conversion its way. This is
2925 * rather bogus, but it's needed for backwards compatibility.
2931 * For normal non-qualified target column, do type checking and
2934 Node
*orig_expr
= (Node
*) tle
->expr
;
2936 tle
->expr
= (Expr
*)
2937 coerce_to_target_type(pstate
,
2939 targettype
, targettypmod
,
2941 COERCE_IMPLICIT_CAST
,
2943 /* With COERCION_PLPGSQL, this error is probably unreachable */
2944 if (tle
->expr
== NULL
)
2946 (errcode(ERRCODE_DATATYPE_MISMATCH
),
2947 errmsg("variable \"%s\" is of type %s"
2948 " but expression is of type %s",
2950 format_type_be(targettype
),
2951 format_type_be(type_id
)),
2952 errhint("You will need to rewrite or cast the expression."),
2953 parser_errposition(pstate
, exprLocation(orig_expr
))));
2956 pstate
->p_expr_kind
= EXPR_KIND_NONE
;
2958 qry
->targetList
= list_make1(tle
);
2960 /* transform WHERE */
2961 qual
= transformWhereClause(pstate
, sstmt
->whereClause
,
2962 EXPR_KIND_WHERE
, "WHERE");
2964 /* initial processing of HAVING clause is much like WHERE clause */
2965 qry
->havingQual
= transformWhereClause(pstate
, sstmt
->havingClause
,
2966 EXPR_KIND_HAVING
, "HAVING");
2969 * Transform sorting/grouping stuff. Do ORDER BY first because both
2970 * transformGroupClause and transformDistinctClause need the results. Note
2971 * that these functions can also change the targetList, so it's passed to
2972 * them by reference.
2974 qry
->sortClause
= transformSortClause(pstate
,
2978 false /* allow SQL92 rules */ );
2980 qry
->groupClause
= transformGroupClause(pstate
,
2986 false /* allow SQL92 rules */ );
2988 if (sstmt
->distinctClause
== NIL
)
2990 qry
->distinctClause
= NIL
;
2991 qry
->hasDistinctOn
= false;
2993 else if (linitial(sstmt
->distinctClause
) == NULL
)
2995 /* We had SELECT DISTINCT */
2996 qry
->distinctClause
= transformDistinctClause(pstate
,
3000 qry
->hasDistinctOn
= false;
3004 /* We had SELECT DISTINCT ON */
3005 qry
->distinctClause
= transformDistinctOnClause(pstate
,
3006 sstmt
->distinctClause
,
3009 qry
->hasDistinctOn
= true;
3012 /* transform LIMIT */
3013 qry
->limitOffset
= transformLimitClause(pstate
, sstmt
->limitOffset
,
3014 EXPR_KIND_OFFSET
, "OFFSET",
3015 sstmt
->limitOption
);
3016 qry
->limitCount
= transformLimitClause(pstate
, sstmt
->limitCount
,
3017 EXPR_KIND_LIMIT
, "LIMIT",
3018 sstmt
->limitOption
);
3019 qry
->limitOption
= sstmt
->limitOption
;
3021 /* transform window clauses after we have seen all window functions */
3022 qry
->windowClause
= transformWindowDefinitions(pstate
,
3023 pstate
->p_windowdefs
,
3026 qry
->rtable
= pstate
->p_rtable
;
3027 qry
->rteperminfos
= pstate
->p_rteperminfos
;
3028 qry
->jointree
= makeFromExpr(pstate
->p_joinlist
, qual
);
3030 qry
->hasSubLinks
= pstate
->p_hasSubLinks
;
3031 qry
->hasWindowFuncs
= pstate
->p_hasWindowFuncs
;
3032 qry
->hasTargetSRFs
= pstate
->p_hasTargetSRFs
;
3033 qry
->hasAggs
= pstate
->p_hasAggs
;
3035 foreach(l
, sstmt
->lockingClause
)
3037 transformLockingClause(pstate
, qry
,
3038 (LockingClause
*) lfirst(l
), false);
3041 assign_query_collations(pstate
, qry
);
3043 /* this must be done after collations, for reliable comparison of exprs */
3044 if (pstate
->p_hasAggs
|| qry
->groupClause
|| qry
->groupingSets
|| qry
->havingQual
)
3045 parseCheckAggregates(pstate
, qry
);
3052 * transformDeclareCursorStmt -
3053 * transform a DECLARE CURSOR Statement
3055 * DECLARE CURSOR is like other utility statements in that we emit it as a
3056 * CMD_UTILITY Query node; however, we must first transform the contained
3057 * query. We used to postpone that until execution, but it's really necessary
3058 * to do it during the normal parse analysis phase to ensure that side effects
3059 * of parser hooks happen at the expected time.
3062 transformDeclareCursorStmt(ParseState
*pstate
, DeclareCursorStmt
*stmt
)
3067 if ((stmt
->options
& CURSOR_OPT_SCROLL
) &&
3068 (stmt
->options
& CURSOR_OPT_NO_SCROLL
))
3070 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION
),
3071 /* translator: %s is a SQL keyword */
3072 errmsg("cannot specify both %s and %s",
3073 "SCROLL", "NO SCROLL")));
3075 if ((stmt
->options
& CURSOR_OPT_ASENSITIVE
) &&
3076 (stmt
->options
& CURSOR_OPT_INSENSITIVE
))
3078 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION
),
3079 /* translator: %s is a SQL keyword */
3080 errmsg("cannot specify both %s and %s",
3081 "ASENSITIVE", "INSENSITIVE")));
3083 /* Transform contained query, not allowing SELECT INTO */
3084 query
= transformStmt(pstate
, stmt
->query
);
3085 stmt
->query
= (Node
*) query
;
3087 /* Grammar should not have allowed anything but SELECT */
3088 if (!IsA(query
, Query
) ||
3089 query
->commandType
!= CMD_SELECT
)
3090 elog(ERROR
, "unexpected non-SELECT command in DECLARE CURSOR");
3093 * We also disallow data-modifying WITH in a cursor. (This could be
3094 * allowed, but the semantics of when the updates occur might be
3097 if (query
->hasModifyingCTE
)
3099 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3100 errmsg("DECLARE CURSOR must not contain data-modifying statements in WITH")));
3102 /* FOR UPDATE and WITH HOLD are not compatible */
3103 if (query
->rowMarks
!= NIL
&& (stmt
->options
& CURSOR_OPT_HOLD
))
3105 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3107 translator: %s is a SQL row locking clause such as FOR UPDATE */
3108 errmsg("DECLARE CURSOR WITH HOLD ... %s is not supported",
3109 LCS_asString(((RowMarkClause
*)
3110 linitial(query
->rowMarks
))->strength
)),
3111 errdetail("Holdable cursors must be READ ONLY.")));
3113 /* FOR UPDATE and SCROLL are not compatible */
3114 if (query
->rowMarks
!= NIL
&& (stmt
->options
& CURSOR_OPT_SCROLL
))
3116 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3118 translator: %s is a SQL row locking clause such as FOR UPDATE */
3119 errmsg("DECLARE SCROLL CURSOR ... %s is not supported",
3120 LCS_asString(((RowMarkClause
*)
3121 linitial(query
->rowMarks
))->strength
)),
3122 errdetail("Scrollable cursors must be READ ONLY.")));
3124 /* FOR UPDATE and INSENSITIVE are not compatible */
3125 if (query
->rowMarks
!= NIL
&& (stmt
->options
& CURSOR_OPT_INSENSITIVE
))
3127 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION
),
3129 translator: %s is a SQL row locking clause such as FOR UPDATE */
3130 errmsg("DECLARE INSENSITIVE CURSOR ... %s is not valid",
3131 LCS_asString(((RowMarkClause
*)
3132 linitial(query
->rowMarks
))->strength
)),
3133 errdetail("Insensitive cursors must be READ ONLY.")));
3135 /* represent the command as a utility Query */
3136 result
= makeNode(Query
);
3137 result
->commandType
= CMD_UTILITY
;
3138 result
->utilityStmt
= (Node
*) stmt
;
3145 * transformExplainStmt -
3146 * transform an EXPLAIN Statement
3148 * EXPLAIN is like other utility statements in that we emit it as a
3149 * CMD_UTILITY Query node; however, we must first transform the contained
3150 * query. We used to postpone that until execution, but it's really necessary
3151 * to do it during the normal parse analysis phase to ensure that side effects
3152 * of parser hooks happen at the expected time.
3155 transformExplainStmt(ParseState
*pstate
, ExplainStmt
*stmt
)
3158 bool generic_plan
= false;
3159 Oid
*paramTypes
= NULL
;
3163 * If we have no external source of parameter definitions, and the
3164 * GENERIC_PLAN option is specified, then accept variable parameter
3165 * definitions (similarly to PREPARE, for example).
3167 if (pstate
->p_paramref_hook
== NULL
)
3171 foreach(lc
, stmt
->options
)
3173 DefElem
*opt
= (DefElem
*) lfirst(lc
);
3175 if (strcmp(opt
->defname
, "generic_plan") == 0)
3176 generic_plan
= defGetBoolean(opt
);
3177 /* don't "break", as we want the last value */
3180 setup_parse_variable_parameters(pstate
, ¶mTypes
, &numParams
);
3183 /* transform contained query, allowing SELECT INTO */
3184 stmt
->query
= (Node
*) transformOptionalSelectInto(pstate
, stmt
->query
);
3186 /* make sure all is well with parameter types */
3188 check_variable_parameters(pstate
, (Query
*) stmt
->query
);
3190 /* represent the command as a utility Query */
3191 result
= makeNode(Query
);
3192 result
->commandType
= CMD_UTILITY
;
3193 result
->utilityStmt
= (Node
*) stmt
;
3200 * transformCreateTableAsStmt -
3201 * transform a CREATE TABLE AS, SELECT ... INTO, or CREATE MATERIALIZED VIEW
3204 * As with DECLARE CURSOR and EXPLAIN, transform the contained statement now.
3207 transformCreateTableAsStmt(ParseState
*pstate
, CreateTableAsStmt
*stmt
)
3212 /* transform contained query, not allowing SELECT INTO */
3213 query
= transformStmt(pstate
, stmt
->query
);
3214 stmt
->query
= (Node
*) query
;
3216 /* additional work needed for CREATE MATERIALIZED VIEW */
3217 if (stmt
->objtype
== OBJECT_MATVIEW
)
3220 * Prohibit a data-modifying CTE in the query used to create a
3221 * materialized view. It's not sufficiently clear what the user would
3222 * want to happen if the MV is refreshed or incrementally maintained.
3224 if (query
->hasModifyingCTE
)
3226 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3227 errmsg("materialized views must not use data-modifying statements in WITH")));
3230 * Check whether any temporary database objects are used in the
3231 * creation query. It would be hard to refresh data or incrementally
3232 * maintain it if a source disappeared.
3234 if (isQueryUsingTempRelation(query
))
3236 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3237 errmsg("materialized views must not use temporary tables or views")));
3240 * A materialized view would either need to save parameters for use in
3241 * maintaining/loading the data or prohibit them entirely. The latter
3242 * seems safer and more sane.
3244 if (query_contains_extern_params(query
))
3246 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3247 errmsg("materialized views may not be defined using bound parameters")));
3250 * For now, we disallow unlogged materialized views, because it seems
3251 * like a bad idea for them to just go to empty after a crash. (If we
3252 * could mark them as unpopulated, that would be better, but that
3253 * requires catalog changes which crash recovery can't presently
3256 if (stmt
->into
->rel
->relpersistence
== RELPERSISTENCE_UNLOGGED
)
3258 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3259 errmsg("materialized views cannot be unlogged")));
3262 * At runtime, we'll need a copy of the parsed-but-not-rewritten Query
3263 * for purposes of creating the view's ON SELECT rule. We stash that
3264 * in the IntoClause because that's where intorel_startup() can
3265 * conveniently get it from.
3267 stmt
->into
->viewQuery
= copyObject(query
);
3270 /* represent the command as a utility Query */
3271 result
= makeNode(Query
);
3272 result
->commandType
= CMD_UTILITY
;
3273 result
->utilityStmt
= (Node
*) stmt
;
3279 * transform a CallStmt
3282 transformCallStmt(ParseState
*pstate
, CallStmt
*stmt
)
3291 List
*outargs
= NIL
;
3295 * First, do standard parse analysis on the procedure call and its
3296 * arguments, allowing us to identify the called procedure.
3299 foreach(lc
, stmt
->funccall
->args
)
3301 targs
= lappend(targs
, transformExpr(pstate
,
3302 (Node
*) lfirst(lc
),
3303 EXPR_KIND_CALL_ARGUMENT
));
3306 node
= ParseFuncOrColumn(pstate
,
3307 stmt
->funccall
->funcname
,
3312 stmt
->funccall
->location
);
3314 assign_expr_collations(pstate
, node
);
3316 fexpr
= castNode(FuncExpr
, node
);
3318 proctup
= SearchSysCache1(PROCOID
, ObjectIdGetDatum(fexpr
->funcid
));
3319 if (!HeapTupleIsValid(proctup
))
3320 elog(ERROR
, "cache lookup failed for function %u", fexpr
->funcid
);
3323 * Expand the argument list to deal with named-argument notation and
3324 * default arguments. For ordinary FuncExprs this'd be done during
3325 * planning, but a CallStmt doesn't go through planning, and there seems
3326 * no good reason not to do it here.
3328 fexpr
->args
= expand_function_arguments(fexpr
->args
,
3330 fexpr
->funcresulttype
,
3333 /* Fetch proargmodes; if it's null, there are no output args */
3334 proargmodes
= SysCacheGetAttr(PROCOID
, proctup
,
3335 Anum_pg_proc_proargmodes
,
3340 * Split the list into input arguments in fexpr->args and output
3341 * arguments in stmt->outargs. INOUT arguments appear in both lists.
3349 arr
= DatumGetArrayTypeP(proargmodes
); /* ensure not toasted */
3350 numargs
= list_length(fexpr
->args
);
3351 if (ARR_NDIM(arr
) != 1 ||
3352 ARR_DIMS(arr
)[0] != numargs
||
3354 ARR_ELEMTYPE(arr
) != CHAROID
)
3355 elog(ERROR
, "proargmodes is not a 1-D char array of length %d or it contains nulls",
3357 argmodes
= (char *) ARR_DATA_PTR(arr
);
3361 foreach(lc
, fexpr
->args
)
3363 Node
*n
= lfirst(lc
);
3365 switch (argmodes
[i
])
3368 case PROARGMODE_VARIADIC
:
3369 inargs
= lappend(inargs
, n
);
3371 case PROARGMODE_OUT
:
3372 outargs
= lappend(outargs
, n
);
3374 case PROARGMODE_INOUT
:
3375 inargs
= lappend(inargs
, n
);
3376 outargs
= lappend(outargs
, copyObject(n
));
3379 /* note we don't support PROARGMODE_TABLE */
3380 elog(ERROR
, "invalid argmode %c for procedure",
3386 fexpr
->args
= inargs
;
3389 stmt
->funcexpr
= fexpr
;
3390 stmt
->outargs
= outargs
;
3392 ReleaseSysCache(proctup
);
3394 /* represent the command as a utility Query */
3395 result
= makeNode(Query
);
3396 result
->commandType
= CMD_UTILITY
;
3397 result
->utilityStmt
= (Node
*) stmt
;
3403 * Produce a string representation of a LockClauseStrength value.
3404 * This should only be applied to valid values (not LCS_NONE).
3407 LCS_asString(LockClauseStrength strength
)
3414 case LCS_FORKEYSHARE
:
3415 return "FOR KEY SHARE";
3418 case LCS_FORNOKEYUPDATE
:
3419 return "FOR NO KEY UPDATE";
3421 return "FOR UPDATE";
3423 return "FOR some"; /* shouldn't happen */
3427 * Check for features that are not supported with FOR [KEY] UPDATE/SHARE.
3429 * exported so planner can check again after rewriting, query pullup, etc
3432 CheckSelectLocking(Query
*qry
, LockClauseStrength strength
)
3434 Assert(strength
!= LCS_NONE
); /* else caller error */
3436 if (qry
->setOperations
)
3438 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3440 translator: %s is a SQL row locking clause such as FOR UPDATE */
3441 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
3442 LCS_asString(strength
))));
3443 if (qry
->distinctClause
!= NIL
)
3445 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3447 translator: %s is a SQL row locking clause such as FOR UPDATE */
3448 errmsg("%s is not allowed with DISTINCT clause",
3449 LCS_asString(strength
))));
3450 if (qry
->groupClause
!= NIL
|| qry
->groupingSets
!= NIL
)
3452 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3454 translator: %s is a SQL row locking clause such as FOR UPDATE */
3455 errmsg("%s is not allowed with GROUP BY clause",
3456 LCS_asString(strength
))));
3457 if (qry
->havingQual
!= NULL
)
3459 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3461 translator: %s is a SQL row locking clause such as FOR UPDATE */
3462 errmsg("%s is not allowed with HAVING clause",
3463 LCS_asString(strength
))));
3466 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3468 translator: %s is a SQL row locking clause such as FOR UPDATE */
3469 errmsg("%s is not allowed with aggregate functions",
3470 LCS_asString(strength
))));
3471 if (qry
->hasWindowFuncs
)
3473 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3475 translator: %s is a SQL row locking clause such as FOR UPDATE */
3476 errmsg("%s is not allowed with window functions",
3477 LCS_asString(strength
))));
3478 if (qry
->hasTargetSRFs
)
3480 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3482 translator: %s is a SQL row locking clause such as FOR UPDATE */
3483 errmsg("%s is not allowed with set-returning functions in the target list",
3484 LCS_asString(strength
))));
3488 * Transform a FOR [KEY] UPDATE/SHARE clause
3490 * This basically involves replacing names by integer relids.
3492 * NB: if you need to change this, see also markQueryForLocking()
3493 * in rewriteHandler.c, and isLockedRefname() in parse_relation.c.
3496 transformLockingClause(ParseState
*pstate
, Query
*qry
, LockingClause
*lc
,
3499 List
*lockedRels
= lc
->lockedRels
;
3503 LockingClause
*allrels
;
3505 CheckSelectLocking(qry
, lc
->strength
);
3507 /* make a clause we can pass down to subqueries to select all rels */
3508 allrels
= makeNode(LockingClause
);
3509 allrels
->lockedRels
= NIL
; /* indicates all rels */
3510 allrels
->strength
= lc
->strength
;
3511 allrels
->waitPolicy
= lc
->waitPolicy
;
3513 if (lockedRels
== NIL
)
3516 * Lock all regular tables used in query and its subqueries. We
3517 * examine inFromCl to exclude auto-added RTEs, particularly NEW/OLD
3518 * in rules. This is a bit of an abuse of a mostly-obsolete flag, but
3519 * it's convenient. We can't rely on the namespace mechanism that has
3520 * largely replaced inFromCl, since for example we need to lock
3521 * base-relation RTEs even if they are masked by upper joins.
3524 foreach(rt
, qry
->rtable
)
3526 RangeTblEntry
*rte
= (RangeTblEntry
*) lfirst(rt
);
3531 switch (rte
->rtekind
)
3535 RTEPermissionInfo
*perminfo
;
3537 applyLockingClause(qry
, i
,
3541 perminfo
= getRTEPermissionInfo(qry
->rteperminfos
, rte
);
3542 perminfo
->requiredPerms
|= ACL_SELECT_FOR_UPDATE
;
3546 applyLockingClause(qry
, i
, lc
->strength
, lc
->waitPolicy
,
3550 * FOR UPDATE/SHARE of subquery is propagated to all of
3551 * subquery's rels, too. We could do this later (based on
3552 * the marking of the subquery RTE) but it is convenient
3553 * to have local knowledge in each query level about which
3554 * rels need to be opened with RowShareLock.
3556 transformLockingClause(pstate
, rte
->subquery
,
3560 /* ignore JOIN, SPECIAL, FUNCTION, VALUES, CTE RTEs */
3568 * Lock just the named tables. As above, we allow locking any base
3569 * relation regardless of alias-visibility rules, so we need to
3570 * examine inFromCl to exclude OLD/NEW.
3572 foreach(l
, lockedRels
)
3574 RangeVar
*thisrel
= (RangeVar
*) lfirst(l
);
3576 /* For simplicity we insist on unqualified alias names here */
3577 if (thisrel
->catalogname
|| thisrel
->schemaname
)
3579 (errcode(ERRCODE_SYNTAX_ERROR
),
3581 translator: %s is a SQL row locking clause such as FOR UPDATE */
3582 errmsg("%s must specify unqualified relation names",
3583 LCS_asString(lc
->strength
)),
3584 parser_errposition(pstate
, thisrel
->location
)));
3587 foreach(rt
, qry
->rtable
)
3589 RangeTblEntry
*rte
= (RangeTblEntry
*) lfirst(rt
);
3590 char *rtename
= rte
->eref
->aliasname
;
3597 * A join RTE without an alias is not visible as a relation
3598 * name and needs to be skipped (otherwise it might hide a
3599 * base relation with the same name), except if it has a USING
3600 * alias, which *is* visible.
3602 * Subquery and values RTEs without aliases are never visible
3603 * as relation names and must always be skipped.
3605 if (rte
->alias
== NULL
)
3607 if (rte
->rtekind
== RTE_JOIN
)
3609 if (rte
->join_using_alias
== NULL
)
3611 rtename
= rte
->join_using_alias
->aliasname
;
3613 else if (rte
->rtekind
== RTE_SUBQUERY
||
3614 rte
->rtekind
== RTE_VALUES
)
3618 if (strcmp(rtename
, thisrel
->relname
) == 0)
3620 switch (rte
->rtekind
)
3624 RTEPermissionInfo
*perminfo
;
3626 applyLockingClause(qry
, i
,
3630 perminfo
= getRTEPermissionInfo(qry
->rteperminfos
, rte
);
3631 perminfo
->requiredPerms
|= ACL_SELECT_FOR_UPDATE
;
3635 applyLockingClause(qry
, i
, lc
->strength
,
3636 lc
->waitPolicy
, pushedDown
);
3637 /* see comment above */
3638 transformLockingClause(pstate
, rte
->subquery
,
3643 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3645 translator: %s is a SQL row locking clause such as FOR UPDATE */
3646 errmsg("%s cannot be applied to a join",
3647 LCS_asString(lc
->strength
)),
3648 parser_errposition(pstate
, thisrel
->location
)));
3652 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3654 translator: %s is a SQL row locking clause such as FOR UPDATE */
3655 errmsg("%s cannot be applied to a function",
3656 LCS_asString(lc
->strength
)),
3657 parser_errposition(pstate
, thisrel
->location
)));
3661 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3663 translator: %s is a SQL row locking clause such as FOR UPDATE */
3664 errmsg("%s cannot be applied to a table function",
3665 LCS_asString(lc
->strength
)),
3666 parser_errposition(pstate
, thisrel
->location
)));
3670 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3672 translator: %s is a SQL row locking clause such as FOR UPDATE */
3673 errmsg("%s cannot be applied to VALUES",
3674 LCS_asString(lc
->strength
)),
3675 parser_errposition(pstate
, thisrel
->location
)));
3679 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3681 translator: %s is a SQL row locking clause such as FOR UPDATE */
3682 errmsg("%s cannot be applied to a WITH query",
3683 LCS_asString(lc
->strength
)),
3684 parser_errposition(pstate
, thisrel
->location
)));
3686 case RTE_NAMEDTUPLESTORE
:
3688 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED
),
3690 translator: %s is a SQL row locking clause such as FOR UPDATE */
3691 errmsg("%s cannot be applied to a named tuplestore",
3692 LCS_asString(lc
->strength
)),
3693 parser_errposition(pstate
, thisrel
->location
)));
3696 /* Shouldn't be possible to see RTE_RESULT here */
3699 elog(ERROR
, "unrecognized RTE type: %d",
3700 (int) rte
->rtekind
);
3703 break; /* out of foreach loop */
3708 (errcode(ERRCODE_UNDEFINED_TABLE
),
3710 translator: %s is a SQL row locking clause such as FOR UPDATE */
3711 errmsg("relation \"%s\" in %s clause not found in FROM clause",
3713 LCS_asString(lc
->strength
)),
3714 parser_errposition(pstate
, thisrel
->location
)));
3720 * Record locking info for a single rangetable item
3723 applyLockingClause(Query
*qry
, Index rtindex
,
3724 LockClauseStrength strength
, LockWaitPolicy waitPolicy
,
3729 Assert(strength
!= LCS_NONE
); /* else caller error */
3731 /* If it's an explicit clause, make sure hasForUpdate gets set */
3733 qry
->hasForUpdate
= true;
3735 /* Check for pre-existing entry for same rtindex */
3736 if ((rc
= get_parse_rowmark(qry
, rtindex
)) != NULL
)
3739 * If the same RTE is specified with more than one locking strength,
3740 * use the strongest. (Reasonable, since you can't take both a shared
3741 * and exclusive lock at the same time; it'll end up being exclusive
3744 * Similarly, if the same RTE is specified with more than one lock
3745 * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
3746 * turn wins over waiting for the lock (the default). This is a bit
3747 * more debatable but raising an error doesn't seem helpful. (Consider
3748 * for instance SELECT FOR UPDATE NOWAIT from a view that internally
3749 * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
3750 * LOCKED is reasonable since the former throws an error in case of
3751 * coming across a locked tuple, which may be undesirable in some
3752 * cases but it seems better than silently returning inconsistent
3755 * And of course pushedDown becomes false if any clause is explicit.
3757 rc
->strength
= Max(rc
->strength
, strength
);
3758 rc
->waitPolicy
= Max(rc
->waitPolicy
, waitPolicy
);
3759 rc
->pushedDown
&= pushedDown
;
3763 /* Make a new RowMarkClause */
3764 rc
= makeNode(RowMarkClause
);
3766 rc
->strength
= strength
;
3767 rc
->waitPolicy
= waitPolicy
;
3768 rc
->pushedDown
= pushedDown
;
3769 qry
->rowMarks
= lappend(qry
->rowMarks
, rc
);
3772 #ifdef DEBUG_NODE_TESTS_ENABLED
3774 * Coverage testing for raw_expression_tree_walker().
3776 * When enabled, we run raw_expression_tree_walker() over every DML statement
3777 * submitted to parse analysis. Without this provision, that function is only
3778 * applied in limited cases involving CTEs, and we don't really want to have
3779 * to test everything inside as well as outside a CTE.
3782 test_raw_expression_coverage(Node
*node
, void *context
)
3786 return raw_expression_tree_walker(node
,
3787 test_raw_expression_coverage
,
3790 #endif /* DEBUG_NODE_TESTS_ENABLED */