PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
analyze.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * analyze.c
4 * transform the raw parse tree into a query tree
5 *
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.
15 *
16 *
17 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
18 * Portions Copyright (c) 1994, Regents of the University of California
19 *
20 * src/backend/parser/analyze.c
21 *
22 *-------------------------------------------------------------------------
23 */
24
25#include "postgres.h"
26
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"
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"
48#include "parser/parse_target.h"
49#include "parser/parse_type.h"
50#include "parser/parsetree.h"
52#include "utils/builtins.h"
53#include "utils/guc.h"
54#include "utils/rel.h"
55#include "utils/syscache.h"
56
57
58/* Hook for plugins to get control at end of parse analysis */
60
61static Query *transformOptionalSelectInto(ParseState *pstate, Node *parseTree);
65 OnConflictClause *onConflictClause);
66static int count_rowexpr_columns(ParseState *pstate, Node *expr);
71 bool isTopLevel, List **targetlist);
72static void determineRecursiveColTypes(ParseState *pstate,
73 Node *larg, List *nrtargetlist);
84static Query *transformCallStmt(ParseState *pstate,
85 CallStmt *stmt);
86static void transformLockingClause(ParseState *pstate, Query *qry,
87 LockingClause *lc, bool pushedDown);
88#ifdef DEBUG_NODE_TESTS_ENABLED
89static bool test_raw_expression_coverage(Node *node, void *context);
90#endif
91
92
93/*
94 * parse_analyze_fixedparams
95 * Analyze a raw parse tree and transform it to Query form.
96 *
97 * Optionally, information about $n parameter types can be supplied.
98 * References to $n indexes not defined by paramTypes[] are disallowed.
99 *
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.
103 */
104Query *
105parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText,
106 const Oid *paramTypes, int numParams,
107 QueryEnvironment *queryEnv)
108{
109 ParseState *pstate = make_parsestate(NULL);
110 Query *query;
111 JumbleState *jstate = NULL;
112
113 Assert(sourceText != NULL); /* required as of 8.4 */
114
115 pstate->p_sourcetext = sourceText;
116
117 if (numParams > 0)
118 setup_parse_fixed_parameters(pstate, paramTypes, numParams);
119
120 pstate->p_queryEnv = queryEnv;
121
122 query = transformTopLevelStmt(pstate, parseTree);
123
124 if (IsQueryIdEnabled())
125 jstate = JumbleQuery(query);
126
128 (*post_parse_analyze_hook) (pstate, query, jstate);
129
130 free_parsestate(pstate);
131
132 pgstat_report_query_id(query->queryId, false);
133
134 return query;
135}
136
137/*
138 * parse_analyze_varparams
139 *
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).
143 */
144Query *
145parse_analyze_varparams(RawStmt *parseTree, const char *sourceText,
146 Oid **paramTypes, int *numParams,
147 QueryEnvironment *queryEnv)
148{
149 ParseState *pstate = make_parsestate(NULL);
150 Query *query;
151 JumbleState *jstate = NULL;
152
153 Assert(sourceText != NULL); /* required as of 8.4 */
154
155 pstate->p_sourcetext = sourceText;
156
157 setup_parse_variable_parameters(pstate, paramTypes, numParams);
158
159 pstate->p_queryEnv = queryEnv;
160
161 query = transformTopLevelStmt(pstate, parseTree);
162
163 /* make sure all is well with parameter types */
164 check_variable_parameters(pstate, query);
165
166 if (IsQueryIdEnabled())
167 jstate = JumbleQuery(query);
168
170 (*post_parse_analyze_hook) (pstate, query, jstate);
171
172 free_parsestate(pstate);
173
174 pgstat_report_query_id(query->queryId, false);
175
176 return query;
177}
178
179/*
180 * parse_analyze_withcb
181 *
182 * This variant is used when the caller supplies their own parser callback to
183 * resolve parameters and possibly other things.
184 */
185Query *
186parse_analyze_withcb(RawStmt *parseTree, const char *sourceText,
187 ParserSetupHook parserSetup,
188 void *parserSetupArg,
189 QueryEnvironment *queryEnv)
190{
191 ParseState *pstate = make_parsestate(NULL);
192 Query *query;
193 JumbleState *jstate = NULL;
194
195 Assert(sourceText != NULL); /* required as of 8.4 */
196
197 pstate->p_sourcetext = sourceText;
198 pstate->p_queryEnv = queryEnv;
199 (*parserSetup) (pstate, parserSetupArg);
200
201 query = transformTopLevelStmt(pstate, parseTree);
202
203 if (IsQueryIdEnabled())
204 jstate = JumbleQuery(query);
205
207 (*post_parse_analyze_hook) (pstate, query, jstate);
208
209 free_parsestate(pstate);
210
211 pgstat_report_query_id(query->queryId, false);
212
213 return query;
214}
215
216
217/*
218 * parse_sub_analyze
219 * Entry point for recursively analyzing a sub-statement.
220 */
221Query *
222parse_sub_analyze(Node *parseTree, ParseState *parentParseState,
223 CommonTableExpr *parentCTE,
224 bool locked_from_parent,
225 bool resolve_unknowns)
226{
227 ParseState *pstate = make_parsestate(parentParseState);
228 Query *query;
229
230 pstate->p_parent_cte = parentCTE;
231 pstate->p_locked_from_parent = locked_from_parent;
232 pstate->p_resolve_unknowns = resolve_unknowns;
233
234 query = transformStmt(pstate, parseTree);
235
236 free_parsestate(pstate);
237
238 return query;
239}
240
241/*
242 * setQueryLocationAndLength
243 * Set query's location and length from statement and ParseState
244 *
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.
251 *
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.
257 */
258static void
260{
261 ParseLoc stmt_len = 0;
262
263 /*
264 * If there is no information about the top RawStmt's length, leave it at
265 * 0 to use the whole string.
266 */
267 if (pstate->p_stmt_len == 0)
268 return;
269
270 switch (nodeTag(parseTree))
271 {
272 case T_InsertStmt:
273 qry->stmt_location = ((InsertStmt *) parseTree)->stmt_location;
274 stmt_len = ((InsertStmt *) parseTree)->stmt_len;
275 break;
276
277 case T_DeleteStmt:
278 qry->stmt_location = ((DeleteStmt *) parseTree)->stmt_location;
279 stmt_len = ((DeleteStmt *) parseTree)->stmt_len;
280 break;
281
282 case T_UpdateStmt:
283 qry->stmt_location = ((UpdateStmt *) parseTree)->stmt_location;
284 stmt_len = ((UpdateStmt *) parseTree)->stmt_len;
285 break;
286
287 case T_MergeStmt:
288 qry->stmt_location = ((MergeStmt *) parseTree)->stmt_location;
289 stmt_len = ((MergeStmt *) parseTree)->stmt_len;
290 break;
291
292 case T_SelectStmt:
293 qry->stmt_location = ((SelectStmt *) parseTree)->stmt_location;
294 stmt_len = ((SelectStmt *) parseTree)->stmt_len;
295 break;
296
297 case T_PLAssignStmt:
298 qry->stmt_location = ((PLAssignStmt *) parseTree)->location;
299 break;
300
301 default:
302 qry->stmt_location = pstate->p_stmt_location;
303 break;
304 }
305
306 if (stmt_len > 0)
307 {
308 /* Statement's length is known, use it */
309 qry->stmt_len = stmt_len;
310 }
311 else
312 {
313 /*
314 * Compute the statement's length from the statement's location and
315 * the RawStmt's length and location.
316 */
317 qry->stmt_len = pstate->p_stmt_len - (qry->stmt_location - pstate->p_stmt_location);
318 }
319
320 /* The calculated statement length should be calculated as positive. */
321 Assert(qry->stmt_len >= 0);
322}
323
324/*
325 * transformTopLevelStmt -
326 * transform a Parse tree into a Query tree.
327 *
328 * This function is just responsible for storing location data
329 * from the RawStmt into the ParseState.
330 */
331Query *
333{
334 Query *result;
335
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;
339
340 /* We're at top level, so allow SELECT INTO */
341 result = transformOptionalSelectInto(pstate, parseTree->stmt);
342
343 return result;
344}
345
346/*
347 * transformOptionalSelectInto -
348 * If SELECT has INTO, convert it to CREATE TABLE AS.
349 *
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.
355 */
356static Query *
358{
359 if (IsA(parseTree, SelectStmt))
360 {
361 SelectStmt *stmt = (SelectStmt *) parseTree;
362
363 /* If it's a set-operation tree, drill down to leftmost SelectStmt */
364 while (stmt && stmt->op != SETOP_NONE)
365 stmt = stmt->larg;
366 Assert(stmt && IsA(stmt, SelectStmt) && stmt->larg == NULL);
367
368 if (stmt->intoClause)
369 {
371
372 ctas->query = parseTree;
373 ctas->into = stmt->intoClause;
374 ctas->objtype = OBJECT_TABLE;
375 ctas->is_select_into = true;
376
377 /*
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).
381 */
382 stmt->intoClause = NULL;
383
384 parseTree = (Node *) ctas;
385 }
386 }
387
388 return transformStmt(pstate, parseTree);
389}
390
391/*
392 * transformStmt -
393 * recursively transform a Parse tree into a Query tree.
394 */
395Query *
396transformStmt(ParseState *pstate, Node *parseTree)
397{
398 Query *result;
399
400#ifdef DEBUG_NODE_TESTS_ENABLED
401
402 /*
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
406 * statements.
407 */
408 if (Debug_raw_expression_coverage_test)
409 {
410 switch (nodeTag(parseTree))
411 {
412 case T_SelectStmt:
413 case T_InsertStmt:
414 case T_UpdateStmt:
415 case T_DeleteStmt:
416 case T_MergeStmt:
417 (void) test_raw_expression_coverage(parseTree, NULL);
418 break;
419 default:
420 break;
421 }
422 }
423#endif /* DEBUG_NODE_TESTS_ENABLED */
424
425 /*
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().
429 */
430 switch (nodeTag(parseTree))
431 {
432 /*
433 * Optimizable statements
434 */
435 case T_InsertStmt:
436 result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
437 break;
438
439 case T_DeleteStmt:
440 result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
441 break;
442
443 case T_UpdateStmt:
444 result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
445 break;
446
447 case T_MergeStmt:
448 result = transformMergeStmt(pstate, (MergeStmt *) parseTree);
449 break;
450
451 case T_SelectStmt:
452 {
453 SelectStmt *n = (SelectStmt *) parseTree;
454
455 if (n->valuesLists)
456 result = transformValuesClause(pstate, n);
457 else if (n->op == SETOP_NONE)
458 result = transformSelectStmt(pstate, n);
459 else
460 result = transformSetOperationStmt(pstate, n);
461 }
462 break;
463
464 case T_ReturnStmt:
465 result = transformReturnStmt(pstate, (ReturnStmt *) parseTree);
466 break;
467
468 case T_PLAssignStmt:
469 result = transformPLAssignStmt(pstate,
470 (PLAssignStmt *) parseTree);
471 break;
472
473 /*
474 * Special cases
475 */
476 case T_DeclareCursorStmt:
477 result = transformDeclareCursorStmt(pstate,
478 (DeclareCursorStmt *) parseTree);
479 break;
480
481 case T_ExplainStmt:
482 result = transformExplainStmt(pstate,
483 (ExplainStmt *) parseTree);
484 break;
485
486 case T_CreateTableAsStmt:
487 result = transformCreateTableAsStmt(pstate,
488 (CreateTableAsStmt *) parseTree);
489 break;
490
491 case T_CallStmt:
492 result = transformCallStmt(pstate,
493 (CallStmt *) parseTree);
494 break;
495
496 default:
497
498 /*
499 * other statements don't require any transformation; just return
500 * the original parsetree with a Query node plastered on top.
501 */
502 result = makeNode(Query);
503 result->commandType = CMD_UTILITY;
504 result->utilityStmt = (Node *) parseTree;
505 break;
506 }
507
508 /* Mark as original query until we learn differently */
509 result->querySource = QSRC_ORIGINAL;
510 result->canSetTag = true;
511 setQueryLocationAndLength(pstate, result, parseTree);
512
513 return result;
514}
515
516/*
517 * stmt_requires_parse_analysis
518 * Returns true if parse analysis will do anything non-trivial
519 * with the given raw parse tree.
520 *
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.
525 *
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.
530 */
531bool
533{
534 bool result;
535
536 switch (nodeTag(parseTree->stmt))
537 {
538 /*
539 * Optimizable statements
540 */
541 case T_InsertStmt:
542 case T_DeleteStmt:
543 case T_UpdateStmt:
544 case T_MergeStmt:
545 case T_SelectStmt:
546 case T_ReturnStmt:
547 case T_PLAssignStmt:
548 result = true;
549 break;
550
551 /*
552 * Special cases
553 */
554 case T_DeclareCursorStmt:
555 case T_ExplainStmt:
556 case T_CreateTableAsStmt:
557 case T_CallStmt:
558 result = true;
559 break;
560
561 default:
562 /* all other statements just get wrapped in a CMD_UTILITY Query */
563 result = false;
564 break;
565 }
566
567 return result;
568}
569
570/*
571 * analyze_requires_snapshot
572 * Returns true if a snapshot must be set before doing parse analysis
573 * on the given raw parse tree.
574 */
575bool
577{
578 /*
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.
584 *
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
589 * comment.
590 */
591 return stmt_requires_parse_analysis(parseTree);
592}
593
594/*
595 * transformDeleteStmt -
596 * transforms a Delete Statement
597 */
598static Query *
600{
601 Query *qry = makeNode(Query);
602 ParseNamespaceItem *nsitem;
603 Node *qual;
604
605 qry->commandType = CMD_DELETE;
606
607 /* process the WITH clause independently of all else */
608 if (stmt->withClause)
609 {
610 qry->hasRecursive = stmt->withClause->recursive;
611 qry->cteList = transformWithClause(pstate, stmt->withClause);
612 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
613 }
614
615 /* set up range table with just the result rel */
616 qry->resultRelation = setTargetTable(pstate, stmt->relation,
617 stmt->relation->inh,
618 true,
619 ACL_DELETE);
620 nsitem = pstate->p_target_nsitem;
621
622 /* there's no DISTINCT in DELETE */
623 qry->distinctClause = NIL;
624
625 /* subqueries in USING cannot access the result relation */
626 nsitem->p_lateral_only = true;
627 nsitem->p_lateral_ok = false;
628
629 /*
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.
634 */
635 transformFromClause(pstate, stmt->usingClause);
636
637 /* remaining clauses can reference the result relation normally */
638 nsitem->p_lateral_only = false;
639 nsitem->p_lateral_ok = true;
640
641 qual = transformWhereClause(pstate, stmt->whereClause,
642 EXPR_KIND_WHERE, "WHERE");
643
644 qry->returningList = transformReturningList(pstate, stmt->returningList,
646
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);
651
652 qry->hasSubLinks = pstate->p_hasSubLinks;
653 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
654 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
655 qry->hasAggs = pstate->p_hasAggs;
656
657 assign_query_collations(pstate, qry);
658
659 /* this must be done after collations, for reliable comparison of exprs */
660 if (pstate->p_hasAggs)
661 parseCheckAggregates(pstate, qry);
662
663 return qry;
664}
665
666/*
667 * transformInsertStmt -
668 * transform an Insert Statement
669 */
670static Query *
672{
673 Query *qry = makeNode(Query);
674 SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
675 List *exprList = NIL;
676 bool isGeneralSelect;
677 List *sub_rtable;
678 List *sub_rteperminfos;
679 List *sub_namespace;
680 List *icolumns;
681 List *attrnos;
682 ParseNamespaceItem *nsitem;
683 RTEPermissionInfo *perminfo;
684 ListCell *icols;
685 ListCell *attnos;
686 ListCell *lc;
687 bool isOnConflictUpdate;
688 AclMode targetPerms;
689
690 /* There can't be any outer WITH to worry about */
691 Assert(pstate->p_ctenamespace == NIL);
692
693 qry->commandType = CMD_INSERT;
694 pstate->p_is_insert = true;
695
696 /* process the WITH clause independently of all else */
697 if (stmt->withClause)
698 {
699 qry->hasRecursive = stmt->withClause->recursive;
700 qry->cteList = transformWithClause(pstate, stmt->withClause);
701 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
702 }
703
704 qry->override = stmt->override;
705
706 isOnConflictUpdate = (stmt->onConflictClause &&
707 stmt->onConflictClause->action == ONCONFLICT_UPDATE);
708
709 /*
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.
713 *
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.
717 */
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));
724
725 /*
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.
733 */
734 if (isGeneralSelect)
735 {
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;
742 }
743 else
744 {
745 sub_rtable = NIL; /* not used, but keep compiler quiet */
746 sub_rteperminfos = NIL;
747 sub_namespace = NIL;
748 }
749
750 /*
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.
755 */
756 targetPerms = ACL_INSERT;
757 if (isOnConflictUpdate)
758 targetPerms |= ACL_UPDATE;
759 qry->resultRelation = setTargetTable(pstate, stmt->relation,
760 false, false, targetPerms);
761
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));
765
766 /*
767 * Determine which variant of INSERT we have.
768 */
769 if (selectStmt == NULL)
770 {
771 /*
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.
775 */
776 exprList = NIL;
777 }
778 else if (isGeneralSelect)
779 {
780 /*
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
785 * see.
786 */
787 ParseState *sub_pstate = make_parsestate(pstate);
788 Query *selectQuery;
789
790 /*
791 * Process the source SELECT.
792 *
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...)
797 *
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.
803 */
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;
810
811 selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
812
813 free_parsestate(sub_pstate);
814
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");
819
820 /*
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).
823 */
824 nsitem = addRangeTableEntryForSubquery(pstate,
825 selectQuery,
826 makeAlias("*SELECT*", NIL),
827 false,
828 false);
829 addNSItemToQuery(pstate, nsitem, true, false, false);
830
831 /*----------
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.)
836 *
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
843 *----------
844 */
845 exprList = NIL;
846 foreach(lc, selectQuery->targetList)
847 {
848 TargetEntry *tle = (TargetEntry *) lfirst(lc);
849 Expr *expr;
850
851 if (tle->resjunk)
852 continue;
853 if (tle->expr &&
854 (IsA(tle->expr, Const) || IsA(tle->expr, Param)) &&
855 exprType((Node *) tle->expr) == UNKNOWNOID)
856 expr = tle->expr;
857 else
858 {
859 Var *var = makeVarFromTargetEntry(nsitem->p_rtindex, tle);
860
861 var->location = exprLocation((Node *) tle->expr);
862 expr = (Expr *) var;
863 }
864 exprList = lappend(exprList, expr);
865 }
866
867 /* Prepare row for assignment to target table */
868 exprList = transformInsertRow(pstate, exprList,
869 stmt->cols,
870 icolumns, attrnos,
871 false);
872 }
873 else if (list_length(selectStmt->valuesLists) > 1)
874 {
875 /*
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
879 * RTE.
880 */
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;
887
888 Assert(selectStmt->intoClause == NULL);
889
890 foreach(lc, selectStmt->valuesLists)
891 {
892 List *sublist = (List *) lfirst(lc);
893
894 /*
895 * Do basic expression transformation (same as a ROW() expr, but
896 * allow SetToDefault at top level)
897 */
898 sublist = transformExpressionList(pstate, sublist,
899 EXPR_KIND_VALUES, true);
900
901 /*
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.
905 */
906 if (sublist_length < 0)
907 {
908 /* Remember post-transformation length of first sublist */
909 sublist_length = list_length(sublist);
910 }
911 else if (sublist_length != list_length(sublist))
912 {
914 (errcode(ERRCODE_SYNTAX_ERROR),
915 errmsg("VALUES lists must all be the same length"),
916 parser_errposition(pstate,
917 exprLocation((Node *) sublist))));
918 }
919
920 /*
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.)
929 */
930 sublist = transformInsertRow(pstate, sublist,
931 stmt->cols,
932 icolumns, attrnos,
933 true);
934
935 /*
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.)
946 */
947 assign_list_collations(pstate, sublist);
948
949 exprsLists = lappend(exprsLists, sublist);
950 }
951
952 /*
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.
958 */
959 foreach(lc, (List *) linitial(exprsLists))
960 {
961 Node *val = (Node *) lfirst(lc);
962
963 coltypes = lappend_oid(coltypes, exprType(val));
964 coltypmods = lappend_int(coltypmods, exprTypmod(val));
965 colcollations = lappend_oid(colcollations, InvalidOid);
966 }
967
968 /*
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.
973 */
974 if (list_length(pstate->p_rtable) != 1 &&
975 contain_vars_of_level((Node *) exprsLists, 0))
976 lateral = true;
977
978 /*
979 * Generate the VALUES RTE
980 */
981 nsitem = addRangeTableEntryForValues(pstate, exprsLists,
982 coltypes, coltypmods, colcollations,
983 NULL, lateral, true);
984 addNSItemToQuery(pstate, nsitem, true, false, false);
985
986 /*
987 * Generate list of Vars referencing the RTE
988 */
989 exprList = expandNSItemVars(pstate, nsitem, 0, -1, NULL);
990
991 /*
992 * Re-apply any indirection on the target column specs to the Vars
993 */
994 exprList = transformInsertRow(pstate, exprList,
995 stmt->cols,
996 icolumns, attrnos,
997 false);
998 }
999 else
1000 {
1001 /*
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.
1006 */
1007 List *valuesLists = selectStmt->valuesLists;
1008
1009 Assert(list_length(valuesLists) == 1);
1010 Assert(selectStmt->intoClause == NULL);
1011
1012 /*
1013 * Do basic expression transformation (same as a ROW() expr, but allow
1014 * SetToDefault at top level)
1015 */
1016 exprList = transformExpressionList(pstate,
1017 (List *) linitial(valuesLists),
1019 true);
1020
1021 /* Prepare row for assignment to target table */
1022 exprList = transformInsertRow(pstate, exprList,
1023 stmt->cols,
1024 icolumns, attrnos,
1025 false);
1026 }
1027
1028 /*
1029 * Generate query's target list using the computed list of expressions.
1030 * Also, mark all the target columns as needing insert permissions.
1031 */
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)
1036 {
1037 Expr *expr = (Expr *) lfirst(lc);
1038 ResTarget *col = lfirst_node(ResTarget, icols);
1039 AttrNumber attr_num = (AttrNumber) lfirst_int(attnos);
1040 TargetEntry *tle;
1041
1042 tle = makeTargetEntry(expr,
1043 attr_num,
1044 col->name,
1045 false);
1046 qry->targetList = lappend(qry->targetList, tle);
1047
1048 perminfo->insertedCols = bms_add_member(perminfo->insertedCols,
1050 }
1051
1052 /*
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.
1056 */
1057 if (stmt->onConflictClause || stmt->returningList)
1058 {
1059 pstate->p_namespace = NIL;
1060 addNSItemToQuery(pstate, pstate->p_target_nsitem,
1061 false, true, true);
1062 }
1063
1064 /* Process ON CONFLICT, if any. */
1065 if (stmt->onConflictClause)
1066 qry->onConflict = transformOnConflictClause(pstate,
1067 stmt->onConflictClause);
1068
1069 /* Process RETURNING, if any. */
1070 if (stmt->returningList)
1071 qry->returningList = transformReturningList(pstate,
1072 stmt->returningList,
1074
1075 /* done building the range table and jointree */
1076 qry->rtable = pstate->p_rtable;
1077 qry->rteperminfos = pstate->p_rteperminfos;
1078 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1079
1080 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
1081 qry->hasSubLinks = pstate->p_hasSubLinks;
1082
1083 assign_query_collations(pstate, qry);
1084
1085 return qry;
1086}
1087
1088/*
1089 * Prepare an INSERT row for assignment to the target table.
1090 *
1091 * exprlist: transformed expressions for source values; these might come from
1092 * a VALUES row, or be Vars referencing a sub-SELECT or VALUES RTE output.
1093 * stmtcols: original target-columns spec for INSERT (we just test for NIL)
1094 * icolumns: effective target-columns spec (list of ResTarget)
1095 * attrnos: integer column numbers (must be same length as icolumns)
1096 * strip_indirection: if true, remove any field/array assignment nodes
1097 */
1098List *
1100 List *stmtcols, List *icolumns, List *attrnos,
1101 bool strip_indirection)
1102{
1103 List *result;
1104 ListCell *lc;
1105 ListCell *icols;
1106 ListCell *attnos;
1107
1108 /*
1109 * Check length of expr list. It must not have more expressions than
1110 * there are target columns. We allow fewer, but only if no explicit
1111 * columns list was given (the remaining columns are implicitly
1112 * defaulted). Note we must check this *after* transformation because
1113 * that could expand '*' into multiple items.
1114 */
1115 if (list_length(exprlist) > list_length(icolumns))
1116 ereport(ERROR,
1117 (errcode(ERRCODE_SYNTAX_ERROR),
1118 errmsg("INSERT has more expressions than target columns"),
1119 parser_errposition(pstate,
1120 exprLocation(list_nth(exprlist,
1121 list_length(icolumns))))));
1122 if (stmtcols != NIL &&
1123 list_length(exprlist) < list_length(icolumns))
1124 {
1125 /*
1126 * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
1127 * where the user accidentally created a RowExpr instead of separate
1128 * columns. Add a suitable hint if that seems to be the problem,
1129 * because the main error message is quite misleading for this case.
1130 * (If there's no stmtcols, you'll get something about data type
1131 * mismatch, which is less misleading so we don't worry about giving a
1132 * hint in that case.)
1133 */
1134 ereport(ERROR,
1135 (errcode(ERRCODE_SYNTAX_ERROR),
1136 errmsg("INSERT has more target columns than expressions"),
1137 ((list_length(exprlist) == 1 &&
1138 count_rowexpr_columns(pstate, linitial(exprlist)) ==
1139 list_length(icolumns)) ?
1140 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),
1141 parser_errposition(pstate,
1142 exprLocation(list_nth(icolumns,
1143 list_length(exprlist))))));
1144 }
1145
1146 /*
1147 * Prepare columns for assignment to target table.
1148 */
1149 result = NIL;
1150 forthree(lc, exprlist, icols, icolumns, attnos, attrnos)
1151 {
1152 Expr *expr = (Expr *) lfirst(lc);
1153 ResTarget *col = lfirst_node(ResTarget, icols);
1154 int attno = lfirst_int(attnos);
1155
1156 expr = transformAssignedExpr(pstate, expr,
1158 col->name,
1159 attno,
1160 col->indirection,
1161 col->location);
1162
1163 if (strip_indirection)
1164 {
1165 /*
1166 * We need to remove top-level FieldStores and SubscriptingRefs,
1167 * as well as any CoerceToDomain appearing above one of those ---
1168 * but not a CoerceToDomain that isn't above one of those.
1169 */
1170 while (expr)
1171 {
1172 Expr *subexpr = expr;
1173
1174 while (IsA(subexpr, CoerceToDomain))
1175 {
1176 subexpr = ((CoerceToDomain *) subexpr)->arg;
1177 }
1178 if (IsA(subexpr, FieldStore))
1179 {
1180 FieldStore *fstore = (FieldStore *) subexpr;
1181
1182 expr = (Expr *) linitial(fstore->newvals);
1183 }
1184 else if (IsA(subexpr, SubscriptingRef))
1185 {
1186 SubscriptingRef *sbsref = (SubscriptingRef *) subexpr;
1187
1188 if (sbsref->refassgnexpr == NULL)
1189 break;
1190
1191 expr = sbsref->refassgnexpr;
1192 }
1193 else
1194 break;
1195 }
1196 }
1197
1198 result = lappend(result, expr);
1199 }
1200
1201 return result;
1202}
1203
1204/*
1205 * transformOnConflictClause -
1206 * transforms an OnConflictClause in an INSERT
1207 */
1208static OnConflictExpr *
1210 OnConflictClause *onConflictClause)
1211{
1212 ParseNamespaceItem *exclNSItem = NULL;
1213 List *arbiterElems;
1214 Node *arbiterWhere;
1215 Oid arbiterConstraint;
1216 List *onConflictSet = NIL;
1217 Node *onConflictWhere = NULL;
1218 int exclRelIndex = 0;
1219 List *exclRelTlist = NIL;
1220 OnConflictExpr *result;
1221
1222 /*
1223 * If this is ON CONFLICT ... UPDATE, first create the range table entry
1224 * for the EXCLUDED pseudo relation, so that that will be present while
1225 * processing arbiter expressions. (You can't actually reference it from
1226 * there, but this provides a useful error message if you try.)
1227 */
1228 if (onConflictClause->action == ONCONFLICT_UPDATE)
1229 {
1230 Relation targetrel = pstate->p_target_relation;
1231 RangeTblEntry *exclRte;
1232
1233 exclNSItem = addRangeTableEntryForRelation(pstate,
1234 targetrel,
1236 makeAlias("excluded", NIL),
1237 false, false);
1238 exclRte = exclNSItem->p_rte;
1239 exclRelIndex = exclNSItem->p_rtindex;
1240
1241 /*
1242 * relkind is set to composite to signal that we're not dealing with
1243 * an actual relation, and no permission checks are required on it.
1244 * (We'll check the actual target relation, instead.)
1245 */
1246 exclRte->relkind = RELKIND_COMPOSITE_TYPE;
1247
1248 /* Create EXCLUDED rel's targetlist for use by EXPLAIN */
1249 exclRelTlist = BuildOnConflictExcludedTargetlist(targetrel,
1250 exclRelIndex);
1251 }
1252
1253 /* Process the arbiter clause, ON CONFLICT ON (...) */
1254 transformOnConflictArbiter(pstate, onConflictClause, &arbiterElems,
1255 &arbiterWhere, &arbiterConstraint);
1256
1257 /* Process DO UPDATE */
1258 if (onConflictClause->action == ONCONFLICT_UPDATE)
1259 {
1260 /*
1261 * Expressions in the UPDATE targetlist need to be handled like UPDATE
1262 * not INSERT. We don't need to save/restore this because all INSERT
1263 * expressions have been parsed already.
1264 */
1265 pstate->p_is_insert = false;
1266
1267 /*
1268 * Add the EXCLUDED pseudo relation to the query namespace, making it
1269 * available in the UPDATE subexpressions.
1270 */
1271 addNSItemToQuery(pstate, exclNSItem, false, true, true);
1272
1273 /*
1274 * Now transform the UPDATE subexpressions.
1275 */
1276 onConflictSet =
1277 transformUpdateTargetList(pstate, onConflictClause->targetList);
1278
1279 onConflictWhere = transformWhereClause(pstate,
1280 onConflictClause->whereClause,
1281 EXPR_KIND_WHERE, "WHERE");
1282
1283 /*
1284 * Remove the EXCLUDED pseudo relation from the query namespace, since
1285 * it's not supposed to be available in RETURNING. (Maybe someday we
1286 * could allow that, and drop this step.)
1287 */
1288 Assert((ParseNamespaceItem *) llast(pstate->p_namespace) == exclNSItem);
1289 pstate->p_namespace = list_delete_last(pstate->p_namespace);
1290 }
1291
1292 /* Finally, build ON CONFLICT DO [NOTHING | UPDATE] expression */
1293 result = makeNode(OnConflictExpr);
1294
1295 result->action = onConflictClause->action;
1296 result->arbiterElems = arbiterElems;
1297 result->arbiterWhere = arbiterWhere;
1298 result->constraint = arbiterConstraint;
1299 result->onConflictSet = onConflictSet;
1300 result->onConflictWhere = onConflictWhere;
1301 result->exclRelIndex = exclRelIndex;
1302 result->exclRelTlist = exclRelTlist;
1303
1304 return result;
1305}
1306
1307
1308/*
1309 * BuildOnConflictExcludedTargetlist
1310 * Create target list for the EXCLUDED pseudo-relation of ON CONFLICT,
1311 * representing the columns of targetrel with varno exclRelIndex.
1312 *
1313 * Note: Exported for use in the rewriter.
1314 */
1315List *
1317 Index exclRelIndex)
1318{
1319 List *result = NIL;
1320 int attno;
1321 Var *var;
1322 TargetEntry *te;
1323
1324 /*
1325 * Note that resnos of the tlist must correspond to attnos of the
1326 * underlying relation, hence we need entries for dropped columns too.
1327 */
1328 for (attno = 0; attno < RelationGetNumberOfAttributes(targetrel); attno++)
1329 {
1330 Form_pg_attribute attr = TupleDescAttr(targetrel->rd_att, attno);
1331 char *name;
1332
1333 if (attr->attisdropped)
1334 {
1335 /*
1336 * can't use atttypid here, but it doesn't really matter what type
1337 * the Const claims to be.
1338 */
1339 var = (Var *) makeNullConst(INT4OID, -1, InvalidOid);
1340 name = NULL;
1341 }
1342 else
1343 {
1344 var = makeVar(exclRelIndex, attno + 1,
1345 attr->atttypid, attr->atttypmod,
1346 attr->attcollation,
1347 0);
1348 name = pstrdup(NameStr(attr->attname));
1349 }
1350
1351 te = makeTargetEntry((Expr *) var,
1352 attno + 1,
1353 name,
1354 false);
1355
1356 result = lappend(result, te);
1357 }
1358
1359 /*
1360 * Add a whole-row-Var entry to support references to "EXCLUDED.*". Like
1361 * the other entries in the EXCLUDED tlist, its resno must match the Var's
1362 * varattno, else the wrong things happen while resolving references in
1363 * setrefs.c. This is against normal conventions for targetlists, but
1364 * it's okay since we don't use this as a real tlist.
1365 */
1366 var = makeVar(exclRelIndex, InvalidAttrNumber,
1367 targetrel->rd_rel->reltype,
1368 -1, InvalidOid, 0);
1369 te = makeTargetEntry((Expr *) var, InvalidAttrNumber, NULL, true);
1370 result = lappend(result, te);
1371
1372 return result;
1373}
1374
1375
1376/*
1377 * count_rowexpr_columns -
1378 * get number of columns contained in a ROW() expression;
1379 * return -1 if expression isn't a RowExpr or a Var referencing one.
1380 *
1381 * This is currently used only for hint purposes, so we aren't terribly
1382 * tense about recognizing all possible cases. The Var case is interesting
1383 * because that's what we'll get in the INSERT ... SELECT (...) case.
1384 */
1385static int
1387{
1388 if (expr == NULL)
1389 return -1;
1390 if (IsA(expr, RowExpr))
1391 return list_length(((RowExpr *) expr)->args);
1392 if (IsA(expr, Var))
1393 {
1394 Var *var = (Var *) expr;
1395 AttrNumber attnum = var->varattno;
1396
1397 if (attnum > 0 && var->vartype == RECORDOID)
1398 {
1399 RangeTblEntry *rte;
1400
1401 rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
1402 if (rte->rtekind == RTE_SUBQUERY)
1403 {
1404 /* Subselect-in-FROM: examine sub-select's output expr */
1406 attnum);
1407
1408 if (ste == NULL || ste->resjunk)
1409 return -1;
1410 expr = (Node *) ste->expr;
1411 if (IsA(expr, RowExpr))
1412 return list_length(((RowExpr *) expr)->args);
1413 }
1414 }
1415 }
1416 return -1;
1417}
1418
1419
1420/*
1421 * transformSelectStmt -
1422 * transforms a Select Statement
1423 *
1424 * Note: this covers only cases with no set operations and no VALUES lists;
1425 * see below for the other cases.
1426 */
1427static Query *
1429{
1430 Query *qry = makeNode(Query);
1431 Node *qual;
1432 ListCell *l;
1433
1434 qry->commandType = CMD_SELECT;
1435
1436 /* process the WITH clause independently of all else */
1437 if (stmt->withClause)
1438 {
1439 qry->hasRecursive = stmt->withClause->recursive;
1440 qry->cteList = transformWithClause(pstate, stmt->withClause);
1441 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1442 }
1443
1444 /* Complain if we get called from someplace where INTO is not allowed */
1445 if (stmt->intoClause)
1446 ereport(ERROR,
1447 (errcode(ERRCODE_SYNTAX_ERROR),
1448 errmsg("SELECT ... INTO is not allowed here"),
1449 parser_errposition(pstate,
1450 exprLocation((Node *) stmt->intoClause))));
1451
1452 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
1453 pstate->p_locking_clause = stmt->lockingClause;
1454
1455 /* make WINDOW info available for window functions, too */
1456 pstate->p_windowdefs = stmt->windowClause;
1457
1458 /* process the FROM clause */
1459 transformFromClause(pstate, stmt->fromClause);
1460
1461 /* transform targetlist */
1462 qry->targetList = transformTargetList(pstate, stmt->targetList,
1464
1465 /* mark column origins */
1466 markTargetListOrigins(pstate, qry->targetList);
1467
1468 /* transform WHERE */
1469 qual = transformWhereClause(pstate, stmt->whereClause,
1470 EXPR_KIND_WHERE, "WHERE");
1471
1472 /* initial processing of HAVING clause is much like WHERE clause */
1473 qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
1474 EXPR_KIND_HAVING, "HAVING");
1475
1476 /*
1477 * Transform sorting/grouping stuff. Do ORDER BY first because both
1478 * transformGroupClause and transformDistinctClause need the results. Note
1479 * that these functions can also change the targetList, so it's passed to
1480 * them by reference.
1481 */
1482 qry->sortClause = transformSortClause(pstate,
1483 stmt->sortClause,
1484 &qry->targetList,
1486 false /* allow SQL92 rules */ );
1487
1488 qry->groupClause = transformGroupClause(pstate,
1489 stmt->groupClause,
1490 &qry->groupingSets,
1491 &qry->targetList,
1492 qry->sortClause,
1494 false /* allow SQL92 rules */ );
1495 qry->groupDistinct = stmt->groupDistinct;
1496
1497 if (stmt->distinctClause == NIL)
1498 {
1499 qry->distinctClause = NIL;
1500 qry->hasDistinctOn = false;
1501 }
1502 else if (linitial(stmt->distinctClause) == NULL)
1503 {
1504 /* We had SELECT DISTINCT */
1506 &qry->targetList,
1507 qry->sortClause,
1508 false);
1509 qry->hasDistinctOn = false;
1510 }
1511 else
1512 {
1513 /* We had SELECT DISTINCT ON */
1515 stmt->distinctClause,
1516 &qry->targetList,
1517 qry->sortClause);
1518 qry->hasDistinctOn = true;
1519 }
1520
1521 /* transform LIMIT */
1522 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1523 EXPR_KIND_OFFSET, "OFFSET",
1524 stmt->limitOption);
1525 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1526 EXPR_KIND_LIMIT, "LIMIT",
1527 stmt->limitOption);
1528 qry->limitOption = stmt->limitOption;
1529
1530 /* transform window clauses after we have seen all window functions */
1532 pstate->p_windowdefs,
1533 &qry->targetList);
1534
1535 /* resolve any still-unresolved output columns as being type text */
1536 if (pstate->p_resolve_unknowns)
1538
1539 qry->rtable = pstate->p_rtable;
1540 qry->rteperminfos = pstate->p_rteperminfos;
1541 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1542
1543 qry->hasSubLinks = pstate->p_hasSubLinks;
1544 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1545 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
1546 qry->hasAggs = pstate->p_hasAggs;
1547
1548 foreach(l, stmt->lockingClause)
1549 {
1550 transformLockingClause(pstate, qry,
1551 (LockingClause *) lfirst(l), false);
1552 }
1553
1554 assign_query_collations(pstate, qry);
1555
1556 /* this must be done after collations, for reliable comparison of exprs */
1557 if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
1558 parseCheckAggregates(pstate, qry);
1559
1560 return qry;
1561}
1562
1563/*
1564 * transformValuesClause -
1565 * transforms a VALUES clause that's being used as a standalone SELECT
1566 *
1567 * We build a Query containing a VALUES RTE, rather as if one had written
1568 * SELECT * FROM (VALUES ...) AS "*VALUES*"
1569 */
1570static Query *
1572{
1573 Query *qry = makeNode(Query);
1574 List *exprsLists = NIL;
1575 List *coltypes = NIL;
1576 List *coltypmods = NIL;
1577 List *colcollations = NIL;
1578 List **colexprs = NULL;
1579 int sublist_length = -1;
1580 bool lateral = false;
1581 ParseNamespaceItem *nsitem;
1582 ListCell *lc;
1583 ListCell *lc2;
1584 int i;
1585
1586 qry->commandType = CMD_SELECT;
1587
1588 /* Most SELECT stuff doesn't apply in a VALUES clause */
1589 Assert(stmt->distinctClause == NIL);
1590 Assert(stmt->intoClause == NULL);
1591 Assert(stmt->targetList == NIL);
1592 Assert(stmt->fromClause == NIL);
1593 Assert(stmt->whereClause == NULL);
1594 Assert(stmt->groupClause == NIL);
1595 Assert(stmt->havingClause == NULL);
1596 Assert(stmt->windowClause == NIL);
1597 Assert(stmt->op == SETOP_NONE);
1598
1599 /* process the WITH clause independently of all else */
1600 if (stmt->withClause)
1601 {
1602 qry->hasRecursive = stmt->withClause->recursive;
1603 qry->cteList = transformWithClause(pstate, stmt->withClause);
1604 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1605 }
1606
1607 /*
1608 * For each row of VALUES, transform the raw expressions.
1609 *
1610 * Note that the intermediate representation we build is column-organized
1611 * not row-organized. That simplifies the type and collation processing
1612 * below.
1613 */
1614 foreach(lc, stmt->valuesLists)
1615 {
1616 List *sublist = (List *) lfirst(lc);
1617
1618 /*
1619 * Do basic expression transformation (same as a ROW() expr, but here
1620 * we disallow SetToDefault)
1621 */
1622 sublist = transformExpressionList(pstate, sublist,
1623 EXPR_KIND_VALUES, false);
1624
1625 /*
1626 * All the sublists must be the same length, *after* transformation
1627 * (which might expand '*' into multiple items). The VALUES RTE can't
1628 * handle anything different.
1629 */
1630 if (sublist_length < 0)
1631 {
1632 /* Remember post-transformation length of first sublist */
1633 sublist_length = list_length(sublist);
1634 /* and allocate array for per-column lists */
1635 colexprs = (List **) palloc0(sublist_length * sizeof(List *));
1636 }
1637 else if (sublist_length != list_length(sublist))
1638 {
1639 ereport(ERROR,
1640 (errcode(ERRCODE_SYNTAX_ERROR),
1641 errmsg("VALUES lists must all be the same length"),
1642 parser_errposition(pstate,
1643 exprLocation((Node *) sublist))));
1644 }
1645
1646 /* Build per-column expression lists */
1647 i = 0;
1648 foreach(lc2, sublist)
1649 {
1650 Node *col = (Node *) lfirst(lc2);
1651
1652 colexprs[i] = lappend(colexprs[i], col);
1653 i++;
1654 }
1655
1656 /* Release sub-list's cells to save memory */
1657 list_free(sublist);
1658
1659 /* Prepare an exprsLists element for this row */
1660 exprsLists = lappend(exprsLists, NIL);
1661 }
1662
1663 /*
1664 * Now resolve the common types of the columns, and coerce everything to
1665 * those types. Then identify the common typmod and common collation, if
1666 * any, of each column.
1667 *
1668 * We must do collation processing now because (1) assign_query_collations
1669 * doesn't process rangetable entries, and (2) we need to label the VALUES
1670 * RTE with column collations for use in the outer query. We don't
1671 * consider conflict of implicit collations to be an error here; instead
1672 * the column will just show InvalidOid as its collation, and you'll get a
1673 * failure later if that results in failure to resolve a collation.
1674 *
1675 * Note we modify the per-column expression lists in-place.
1676 */
1677 for (i = 0; i < sublist_length; i++)
1678 {
1679 Oid coltype;
1680 int32 coltypmod;
1681 Oid colcoll;
1682
1683 coltype = select_common_type(pstate, colexprs[i], "VALUES", NULL);
1684
1685 foreach(lc, colexprs[i])
1686 {
1687 Node *col = (Node *) lfirst(lc);
1688
1689 col = coerce_to_common_type(pstate, col, coltype, "VALUES");
1690 lfirst(lc) = col;
1691 }
1692
1693 coltypmod = select_common_typmod(pstate, colexprs[i], coltype);
1694 colcoll = select_common_collation(pstate, colexprs[i], true);
1695
1696 coltypes = lappend_oid(coltypes, coltype);
1697 coltypmods = lappend_int(coltypmods, coltypmod);
1698 colcollations = lappend_oid(colcollations, colcoll);
1699 }
1700
1701 /*
1702 * Finally, rearrange the coerced expressions into row-organized lists.
1703 */
1704 for (i = 0; i < sublist_length; i++)
1705 {
1706 forboth(lc, colexprs[i], lc2, exprsLists)
1707 {
1708 Node *col = (Node *) lfirst(lc);
1709 List *sublist = lfirst(lc2);
1710
1711 sublist = lappend(sublist, col);
1712 lfirst(lc2) = sublist;
1713 }
1714 list_free(colexprs[i]);
1715 }
1716
1717 /*
1718 * Ordinarily there can't be any current-level Vars in the expression
1719 * lists, because the namespace was empty ... but if we're inside CREATE
1720 * RULE, then NEW/OLD references might appear. In that case we have to
1721 * mark the VALUES RTE as LATERAL.
1722 */
1723 if (pstate->p_rtable != NIL &&
1724 contain_vars_of_level((Node *) exprsLists, 0))
1725 lateral = true;
1726
1727 /*
1728 * Generate the VALUES RTE
1729 */
1730 nsitem = addRangeTableEntryForValues(pstate, exprsLists,
1731 coltypes, coltypmods, colcollations,
1732 NULL, lateral, true);
1733 addNSItemToQuery(pstate, nsitem, true, true, true);
1734
1735 /*
1736 * Generate a targetlist as though expanding "*"
1737 */
1738 Assert(pstate->p_next_resno == 1);
1739 qry->targetList = expandNSItemAttrs(pstate, nsitem, 0, true, -1);
1740
1741 /*
1742 * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
1743 * VALUES, so cope.
1744 */
1745 qry->sortClause = transformSortClause(pstate,
1746 stmt->sortClause,
1747 &qry->targetList,
1749 false /* allow SQL92 rules */ );
1750
1751 qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1752 EXPR_KIND_OFFSET, "OFFSET",
1753 stmt->limitOption);
1754 qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1755 EXPR_KIND_LIMIT, "LIMIT",
1756 stmt->limitOption);
1757 qry->limitOption = stmt->limitOption;
1758
1759 if (stmt->lockingClause)
1760 ereport(ERROR,
1761 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1762 /*------
1763 translator: %s is a SQL row locking clause such as FOR UPDATE */
1764 errmsg("%s cannot be applied to VALUES",
1766 linitial(stmt->lockingClause))->strength))));
1767
1768 qry->rtable = pstate->p_rtable;
1769 qry->rteperminfos = pstate->p_rteperminfos;
1770 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1771
1772 qry->hasSubLinks = pstate->p_hasSubLinks;
1773
1774 assign_query_collations(pstate, qry);
1775
1776 return qry;
1777}
1778
1779/*
1780 * transformSetOperationStmt -
1781 * transforms a set-operations tree
1782 *
1783 * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1784 * structure to it. We must transform each leaf SELECT and build up a top-
1785 * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1786 * The tree of set operations is converted into the setOperations field of
1787 * the top-level Query.
1788 */
1789static Query *
1791{
1792 Query *qry = makeNode(Query);
1793 SelectStmt *leftmostSelect;
1794 int leftmostRTI;
1795 Query *leftmostQuery;
1796 SetOperationStmt *sostmt;
1797 List *sortClause;
1798 Node *limitOffset;
1799 Node *limitCount;
1800 List *lockingClause;
1801 WithClause *withClause;
1802 Node *node;
1803 ListCell *left_tlist,
1804 *lct,
1805 *lcm,
1806 *lcc,
1807 *l;
1808 List *targetvars,
1809 *targetnames,
1810 *sv_namespace;
1811 int sv_rtable_length;
1812 ParseNamespaceItem *jnsitem;
1813 ParseNamespaceColumn *sortnscolumns;
1814 int sortcolindex;
1815 int tllen;
1816
1817 qry->commandType = CMD_SELECT;
1818
1819 /*
1820 * Find leftmost leaf SelectStmt. We currently only need to do this in
1821 * order to deliver a suitable error message if there's an INTO clause
1822 * there, implying the set-op tree is in a context that doesn't allow
1823 * INTO. (transformSetOperationTree would throw error anyway, but it
1824 * seems worth the trouble to throw a different error for non-leftmost
1825 * INTO, so we produce that error in transformSetOperationTree.)
1826 */
1827 leftmostSelect = stmt->larg;
1828 while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1829 leftmostSelect = leftmostSelect->larg;
1830 Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1831 leftmostSelect->larg == NULL);
1832 if (leftmostSelect->intoClause)
1833 ereport(ERROR,
1834 (errcode(ERRCODE_SYNTAX_ERROR),
1835 errmsg("SELECT ... INTO is not allowed here"),
1836 parser_errposition(pstate,
1837 exprLocation((Node *) leftmostSelect->intoClause))));
1838
1839 /*
1840 * We need to extract ORDER BY and other top-level clauses here and not
1841 * let transformSetOperationTree() see them --- else it'll just recurse
1842 * right back here!
1843 */
1844 sortClause = stmt->sortClause;
1845 limitOffset = stmt->limitOffset;
1846 limitCount = stmt->limitCount;
1847 lockingClause = stmt->lockingClause;
1848 withClause = stmt->withClause;
1849
1850 stmt->sortClause = NIL;
1851 stmt->limitOffset = NULL;
1852 stmt->limitCount = NULL;
1853 stmt->lockingClause = NIL;
1854 stmt->withClause = NULL;
1855
1856 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1857 if (lockingClause)
1858 ereport(ERROR,
1859 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1860 /*------
1861 translator: %s is a SQL row locking clause such as FOR UPDATE */
1862 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
1864 linitial(lockingClause))->strength))));
1865
1866 /* Process the WITH clause independently of all else */
1867 if (withClause)
1868 {
1869 qry->hasRecursive = withClause->recursive;
1870 qry->cteList = transformWithClause(pstate, withClause);
1871 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1872 }
1873
1874 /*
1875 * Recursively transform the components of the tree.
1876 */
1877 sostmt = castNode(SetOperationStmt,
1878 transformSetOperationTree(pstate, stmt, true, NULL));
1879 Assert(sostmt);
1880 qry->setOperations = (Node *) sostmt;
1881
1882 /*
1883 * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1884 */
1885 node = sostmt->larg;
1886 while (node && IsA(node, SetOperationStmt))
1887 node = ((SetOperationStmt *) node)->larg;
1888 Assert(node && IsA(node, RangeTblRef));
1889 leftmostRTI = ((RangeTblRef *) node)->rtindex;
1890 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1891 Assert(leftmostQuery != NULL);
1892
1893 /*
1894 * Generate dummy targetlist for outer query using column names of
1895 * leftmost select and common datatypes/collations of topmost set
1896 * operation. Also make lists of the dummy vars and their names for use
1897 * in parsing ORDER BY.
1898 *
1899 * Note: we use leftmostRTI as the varno of the dummy variables. It
1900 * shouldn't matter too much which RT index they have, as long as they
1901 * have one that corresponds to a real RT entry; else funny things may
1902 * happen when the tree is mashed by rule rewriting.
1903 */
1904 qry->targetList = NIL;
1905 targetvars = NIL;
1906 targetnames = NIL;
1907 sortnscolumns = (ParseNamespaceColumn *)
1908 palloc0(list_length(sostmt->colTypes) * sizeof(ParseNamespaceColumn));
1909 sortcolindex = 0;
1910
1911 forfour(lct, sostmt->colTypes,
1912 lcm, sostmt->colTypmods,
1913 lcc, sostmt->colCollations,
1914 left_tlist, leftmostQuery->targetList)
1915 {
1916 Oid colType = lfirst_oid(lct);
1917 int32 colTypmod = lfirst_int(lcm);
1918 Oid colCollation = lfirst_oid(lcc);
1919 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1920 char *colName;
1921 TargetEntry *tle;
1922 Var *var;
1923
1924 Assert(!lefttle->resjunk);
1925 colName = pstrdup(lefttle->resname);
1926 var = makeVar(leftmostRTI,
1927 lefttle->resno,
1928 colType,
1929 colTypmod,
1930 colCollation,
1931 0);
1932 var->location = exprLocation((Node *) lefttle->expr);
1933 tle = makeTargetEntry((Expr *) var,
1934 (AttrNumber) pstate->p_next_resno++,
1935 colName,
1936 false);
1937 qry->targetList = lappend(qry->targetList, tle);
1938 targetvars = lappend(targetvars, var);
1939 targetnames = lappend(targetnames, makeString(colName));
1940 sortnscolumns[sortcolindex].p_varno = leftmostRTI;
1941 sortnscolumns[sortcolindex].p_varattno = lefttle->resno;
1942 sortnscolumns[sortcolindex].p_vartype = colType;
1943 sortnscolumns[sortcolindex].p_vartypmod = colTypmod;
1944 sortnscolumns[sortcolindex].p_varcollid = colCollation;
1945 sortnscolumns[sortcolindex].p_varnosyn = leftmostRTI;
1946 sortnscolumns[sortcolindex].p_varattnosyn = lefttle->resno;
1947 sortcolindex++;
1948 }
1949
1950 /*
1951 * As a first step towards supporting sort clauses that are expressions
1952 * using the output columns, generate a namespace entry that makes the
1953 * output columns visible. A Join RTE node is handy for this, since we
1954 * can easily control the Vars generated upon matches.
1955 *
1956 * Note: we don't yet do anything useful with such cases, but at least
1957 * "ORDER BY upper(foo)" will draw the right error message rather than
1958 * "foo not found".
1959 */
1960 sv_rtable_length = list_length(pstate->p_rtable);
1961
1962 jnsitem = addRangeTableEntryForJoin(pstate,
1963 targetnames,
1964 sortnscolumns,
1965 JOIN_INNER,
1966 0,
1967 targetvars,
1968 NIL,
1969 NIL,
1970 NULL,
1971 NULL,
1972 false);
1973
1974 sv_namespace = pstate->p_namespace;
1975 pstate->p_namespace = NIL;
1976
1977 /* add jnsitem to column namespace only */
1978 addNSItemToQuery(pstate, jnsitem, false, false, true);
1979
1980 /*
1981 * For now, we don't support resjunk sort clauses on the output of a
1982 * setOperation tree --- you can only use the SQL92-spec options of
1983 * selecting an output column by name or number. Enforce by checking that
1984 * transformSortClause doesn't add any items to tlist. Note, if changing
1985 * this, add_setop_child_rel_equivalences() will need to be updated.
1986 */
1987 tllen = list_length(qry->targetList);
1988
1989 qry->sortClause = transformSortClause(pstate,
1990 sortClause,
1991 &qry->targetList,
1993 false /* allow SQL92 rules */ );
1994
1995 /* restore namespace, remove join RTE from rtable */
1996 pstate->p_namespace = sv_namespace;
1997 pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
1998
1999 if (tllen != list_length(qry->targetList))
2000 ereport(ERROR,
2001 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2002 errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
2003 errdetail("Only result column names can be used, not expressions or functions."),
2004 errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
2005 parser_errposition(pstate,
2006 exprLocation(list_nth(qry->targetList, tllen)))));
2007
2008 qry->limitOffset = transformLimitClause(pstate, limitOffset,
2009 EXPR_KIND_OFFSET, "OFFSET",
2010 stmt->limitOption);
2011 qry->limitCount = transformLimitClause(pstate, limitCount,
2012 EXPR_KIND_LIMIT, "LIMIT",
2013 stmt->limitOption);
2014 qry->limitOption = stmt->limitOption;
2015
2016 qry->rtable = pstate->p_rtable;
2017 qry->rteperminfos = pstate->p_rteperminfos;
2018 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2019
2020 qry->hasSubLinks = pstate->p_hasSubLinks;
2021 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2022 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2023 qry->hasAggs = pstate->p_hasAggs;
2024
2025 foreach(l, lockingClause)
2026 {
2027 transformLockingClause(pstate, qry,
2028 (LockingClause *) lfirst(l), false);
2029 }
2030
2031 assign_query_collations(pstate, qry);
2032
2033 /* this must be done after collations, for reliable comparison of exprs */
2034 if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
2035 parseCheckAggregates(pstate, qry);
2036
2037 return qry;
2038}
2039
2040/*
2041 * Make a SortGroupClause node for a SetOperationStmt's groupClauses
2042 *
2043 * If require_hash is true, the caller is indicating that they need hash
2044 * support or they will fail. So look extra hard for hash support.
2045 */
2047makeSortGroupClauseForSetOp(Oid rescoltype, bool require_hash)
2048{
2050 Oid sortop;
2051 Oid eqop;
2052 bool hashable;
2053
2054 /* determine the eqop and optional sortop */
2055 get_sort_group_operators(rescoltype,
2056 false, true, false,
2057 &sortop, &eqop, NULL,
2058 &hashable);
2059
2060 /*
2061 * The type cache doesn't believe that record is hashable (see
2062 * cache_record_field_properties()), but if the caller really needs hash
2063 * support, we can assume it does. Worst case, if any components of the
2064 * record don't support hashing, we will fail at execution.
2065 */
2066 if (require_hash && (rescoltype == RECORDOID || rescoltype == RECORDARRAYOID))
2067 hashable = true;
2068
2069 /* we don't have a tlist yet, so can't assign sortgrouprefs */
2070 grpcl->tleSortGroupRef = 0;
2071 grpcl->eqop = eqop;
2072 grpcl->sortop = sortop;
2073 grpcl->reverse_sort = false; /* Sort-op is "less than", or InvalidOid */
2074 grpcl->nulls_first = false; /* OK with or without sortop */
2075 grpcl->hashable = hashable;
2076
2077 return grpcl;
2078}
2079
2080/*
2081 * transformSetOperationTree
2082 * Recursively transform leaves and internal nodes of a set-op tree
2083 *
2084 * In addition to returning the transformed node, if targetlist isn't NULL
2085 * then we return a list of its non-resjunk TargetEntry nodes. For a leaf
2086 * set-op node these are the actual targetlist entries; otherwise they are
2087 * dummy entries created to carry the type, typmod, collation, and location
2088 * (for error messages) of each output column of the set-op node. This info
2089 * is needed only during the internal recursion of this function, so outside
2090 * callers pass NULL for targetlist. Note: the reason for passing the
2091 * actual targetlist entries of a leaf node is so that upper levels can
2092 * replace UNKNOWN Consts with properly-coerced constants.
2093 */
2094static Node *
2096 bool isTopLevel, List **targetlist)
2097{
2098 bool isLeaf;
2099
2101
2102 /* Guard against stack overflow due to overly complex set-expressions */
2104
2105 /*
2106 * Validity-check both leaf and internal SELECTs for disallowed ops.
2107 */
2108 if (stmt->intoClause)
2109 ereport(ERROR,
2110 (errcode(ERRCODE_SYNTAX_ERROR),
2111 errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
2112 parser_errposition(pstate,
2113 exprLocation((Node *) stmt->intoClause))));
2114
2115 /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2116 if (stmt->lockingClause)
2117 ereport(ERROR,
2118 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2119 /*------
2120 translator: %s is a SQL row locking clause such as FOR UPDATE */
2121 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
2123 linitial(stmt->lockingClause))->strength))));
2124
2125 /*
2126 * If an internal node of a set-op tree has ORDER BY, LIMIT, FOR UPDATE,
2127 * or WITH clauses attached, we need to treat it like a leaf node to
2128 * generate an independent sub-Query tree. Otherwise, it can be
2129 * represented by a SetOperationStmt node underneath the parent Query.
2130 */
2131 if (stmt->op == SETOP_NONE)
2132 {
2133 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2134 isLeaf = true;
2135 }
2136 else
2137 {
2138 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2139 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2140 stmt->lockingClause || stmt->withClause)
2141 isLeaf = true;
2142 else
2143 isLeaf = false;
2144 }
2145
2146 if (isLeaf)
2147 {
2148 /* Process leaf SELECT */
2149 Query *selectQuery;
2150 char selectName[32];
2151 ParseNamespaceItem *nsitem;
2152 RangeTblRef *rtr;
2153 ListCell *tl;
2154
2155 /*
2156 * Transform SelectStmt into a Query.
2157 *
2158 * This works the same as SELECT transformation normally would, except
2159 * that we prevent resolving unknown-type outputs as TEXT. This does
2160 * not change the subquery's semantics since if the column type
2161 * matters semantically, it would have been resolved to something else
2162 * anyway. Doing this lets us resolve such outputs using
2163 * select_common_type(), below.
2164 *
2165 * Note: previously transformed sub-queries don't affect the parsing
2166 * of this sub-query, because they are not in the toplevel pstate's
2167 * namespace list.
2168 */
2169 selectQuery = parse_sub_analyze((Node *) stmt, pstate,
2170 NULL, false, false);
2171
2172 /*
2173 * Check for bogus references to Vars on the current query level (but
2174 * upper-level references are okay). Normally this can't happen
2175 * because the namespace will be empty, but it could happen if we are
2176 * inside a rule.
2177 */
2178 if (pstate->p_namespace)
2179 {
2180 if (contain_vars_of_level((Node *) selectQuery, 1))
2181 ereport(ERROR,
2182 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2183 errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
2184 parser_errposition(pstate,
2185 locate_var_of_level((Node *) selectQuery, 1))));
2186 }
2187
2188 /*
2189 * Extract a list of the non-junk TLEs for upper-level processing.
2190 */
2191 if (targetlist)
2192 {
2193 *targetlist = NIL;
2194 foreach(tl, selectQuery->targetList)
2195 {
2196 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2197
2198 if (!tle->resjunk)
2199 *targetlist = lappend(*targetlist, tle);
2200 }
2201 }
2202
2203 /*
2204 * Make the leaf query be a subquery in the top-level rangetable.
2205 */
2206 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2207 list_length(pstate->p_rtable) + 1);
2208 nsitem = addRangeTableEntryForSubquery(pstate,
2209 selectQuery,
2210 makeAlias(selectName, NIL),
2211 false,
2212 false);
2213
2214 /*
2215 * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2216 */
2217 rtr = makeNode(RangeTblRef);
2218 rtr->rtindex = nsitem->p_rtindex;
2219 return (Node *) rtr;
2220 }
2221 else
2222 {
2223 /* Process an internal node (set operation node) */
2225 List *ltargetlist;
2226 List *rtargetlist;
2227 ListCell *ltl;
2228 ListCell *rtl;
2229 const char *context;
2230 bool recursive = (pstate->p_parent_cte &&
2231 pstate->p_parent_cte->cterecursive);
2232
2233 context = (stmt->op == SETOP_UNION ? "UNION" :
2234 (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2235 "EXCEPT"));
2236
2237 op->op = stmt->op;
2238 op->all = stmt->all;
2239
2240 /*
2241 * Recursively transform the left child node.
2242 */
2243 op->larg = transformSetOperationTree(pstate, stmt->larg,
2244 false,
2245 &ltargetlist);
2246
2247 /*
2248 * If we are processing a recursive union query, now is the time to
2249 * examine the non-recursive term's output columns and mark the
2250 * containing CTE as having those result columns. We should do this
2251 * only at the topmost setop of the CTE, of course.
2252 */
2253 if (isTopLevel && recursive)
2254 determineRecursiveColTypes(pstate, op->larg, ltargetlist);
2255
2256 /*
2257 * Recursively transform the right child node.
2258 */
2259 op->rarg = transformSetOperationTree(pstate, stmt->rarg,
2260 false,
2261 &rtargetlist);
2262
2263 /*
2264 * Verify that the two children have the same number of non-junk
2265 * columns, and determine the types of the merged output columns.
2266 */
2267 if (list_length(ltargetlist) != list_length(rtargetlist))
2268 ereport(ERROR,
2269 (errcode(ERRCODE_SYNTAX_ERROR),
2270 errmsg("each %s query must have the same number of columns",
2271 context),
2272 parser_errposition(pstate,
2273 exprLocation((Node *) rtargetlist))));
2274
2275 if (targetlist)
2276 *targetlist = NIL;
2277 op->colTypes = NIL;
2278 op->colTypmods = NIL;
2279 op->colCollations = NIL;
2280 op->groupClauses = NIL;
2281 forboth(ltl, ltargetlist, rtl, rtargetlist)
2282 {
2283 TargetEntry *ltle = (TargetEntry *) lfirst(ltl);
2284 TargetEntry *rtle = (TargetEntry *) lfirst(rtl);
2285 Node *lcolnode = (Node *) ltle->expr;
2286 Node *rcolnode = (Node *) rtle->expr;
2287 Oid lcoltype = exprType(lcolnode);
2288 Oid rcoltype = exprType(rcolnode);
2289 Node *bestexpr;
2290 int bestlocation;
2291 Oid rescoltype;
2292 int32 rescoltypmod;
2293 Oid rescolcoll;
2294
2295 /* select common type, same as CASE et al */
2296 rescoltype = select_common_type(pstate,
2297 list_make2(lcolnode, rcolnode),
2298 context,
2299 &bestexpr);
2300 bestlocation = exprLocation(bestexpr);
2301
2302 /*
2303 * Verify the coercions are actually possible. If not, we'd fail
2304 * later anyway, but we want to fail now while we have sufficient
2305 * context to produce an error cursor position.
2306 *
2307 * For all non-UNKNOWN-type cases, we verify coercibility but we
2308 * don't modify the child's expression, for fear of changing the
2309 * child query's semantics.
2310 *
2311 * If a child expression is an UNKNOWN-type Const or Param, we
2312 * want to replace it with the coerced expression. This can only
2313 * happen when the child is a leaf set-op node. It's safe to
2314 * replace the expression because if the child query's semantics
2315 * depended on the type of this output column, it'd have already
2316 * coerced the UNKNOWN to something else. We want to do this
2317 * because (a) we want to verify that a Const is valid for the
2318 * target type, or resolve the actual type of an UNKNOWN Param,
2319 * and (b) we want to avoid unnecessary discrepancies between the
2320 * output type of the child query and the resolved target type.
2321 * Such a discrepancy would disable optimization in the planner.
2322 *
2323 * If it's some other UNKNOWN-type node, eg a Var, we do nothing
2324 * (knowing that coerce_to_common_type would fail). The planner
2325 * is sometimes able to fold an UNKNOWN Var to a constant before
2326 * it has to coerce the type, so failing now would just break
2327 * cases that might work.
2328 */
2329 if (lcoltype != UNKNOWNOID)
2330 lcolnode = coerce_to_common_type(pstate, lcolnode,
2331 rescoltype, context);
2332 else if (IsA(lcolnode, Const) ||
2333 IsA(lcolnode, Param))
2334 {
2335 lcolnode = coerce_to_common_type(pstate, lcolnode,
2336 rescoltype, context);
2337 ltle->expr = (Expr *) lcolnode;
2338 }
2339
2340 if (rcoltype != UNKNOWNOID)
2341 rcolnode = coerce_to_common_type(pstate, rcolnode,
2342 rescoltype, context);
2343 else if (IsA(rcolnode, Const) ||
2344 IsA(rcolnode, Param))
2345 {
2346 rcolnode = coerce_to_common_type(pstate, rcolnode,
2347 rescoltype, context);
2348 rtle->expr = (Expr *) rcolnode;
2349 }
2350
2351 rescoltypmod = select_common_typmod(pstate,
2352 list_make2(lcolnode, rcolnode),
2353 rescoltype);
2354
2355 /*
2356 * Select common collation. A common collation is required for
2357 * all set operators except UNION ALL; see SQL:2008 7.13 <query
2358 * expression> Syntax Rule 15c. (If we fail to identify a common
2359 * collation for a UNION ALL column, the colCollations element
2360 * will be set to InvalidOid, which may result in a runtime error
2361 * if something at a higher query level wants to use the column's
2362 * collation.)
2363 */
2364 rescolcoll = select_common_collation(pstate,
2365 list_make2(lcolnode, rcolnode),
2366 (op->op == SETOP_UNION && op->all));
2367
2368 /* emit results */
2369 op->colTypes = lappend_oid(op->colTypes, rescoltype);
2370 op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
2371 op->colCollations = lappend_oid(op->colCollations, rescolcoll);
2372
2373 /*
2374 * For all cases except UNION ALL, identify the grouping operators
2375 * (and, if available, sorting operators) that will be used to
2376 * eliminate duplicates.
2377 */
2378 if (op->op != SETOP_UNION || !op->all)
2379 {
2380 ParseCallbackState pcbstate;
2381
2382 setup_parser_errposition_callback(&pcbstate, pstate,
2383 bestlocation);
2384
2385 /*
2386 * If it's a recursive union, we need to require hashing
2387 * support.
2388 */
2389 op->groupClauses = lappend(op->groupClauses,
2390 makeSortGroupClauseForSetOp(rescoltype, recursive));
2391
2393 }
2394
2395 /*
2396 * Construct a dummy tlist entry to return. We use a SetToDefault
2397 * node for the expression, since it carries exactly the fields
2398 * needed, but any other expression node type would do as well.
2399 */
2400 if (targetlist)
2401 {
2402 SetToDefault *rescolnode = makeNode(SetToDefault);
2403 TargetEntry *restle;
2404
2405 rescolnode->typeId = rescoltype;
2406 rescolnode->typeMod = rescoltypmod;
2407 rescolnode->collation = rescolcoll;
2408 rescolnode->location = bestlocation;
2409 restle = makeTargetEntry((Expr *) rescolnode,
2410 0, /* no need to set resno */
2411 NULL,
2412 false);
2413 *targetlist = lappend(*targetlist, restle);
2414 }
2415 }
2416
2417 return (Node *) op;
2418 }
2419}
2420
2421/*
2422 * Process the outputs of the non-recursive term of a recursive union
2423 * to set up the parent CTE's columns
2424 */
2425static void
2426determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
2427{
2428 Node *node;
2429 int leftmostRTI;
2430 Query *leftmostQuery;
2431 List *targetList;
2432 ListCell *left_tlist;
2433 ListCell *nrtl;
2434 int next_resno;
2435
2436 /*
2437 * Find leftmost leaf SELECT
2438 */
2439 node = larg;
2440 while (node && IsA(node, SetOperationStmt))
2441 node = ((SetOperationStmt *) node)->larg;
2442 Assert(node && IsA(node, RangeTblRef));
2443 leftmostRTI = ((RangeTblRef *) node)->rtindex;
2444 leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2445 Assert(leftmostQuery != NULL);
2446
2447 /*
2448 * Generate dummy targetlist using column names of leftmost select and
2449 * dummy result expressions of the non-recursive term.
2450 */
2451 targetList = NIL;
2452 next_resno = 1;
2453
2454 forboth(nrtl, nrtargetlist, left_tlist, leftmostQuery->targetList)
2455 {
2456 TargetEntry *nrtle = (TargetEntry *) lfirst(nrtl);
2457 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
2458 char *colName;
2459 TargetEntry *tle;
2460
2461 Assert(!lefttle->resjunk);
2462 colName = pstrdup(lefttle->resname);
2463 tle = makeTargetEntry(nrtle->expr,
2464 next_resno++,
2465 colName,
2466 false);
2467 targetList = lappend(targetList, tle);
2468 }
2469
2470 /* Now build CTE's output column info using dummy targetlist */
2471 analyzeCTETargetList(pstate, pstate->p_parent_cte, targetList);
2472}
2473
2474
2475/*
2476 * transformReturnStmt -
2477 * transforms a return statement
2478 */
2479static Query *
2481{
2482 Query *qry = makeNode(Query);
2483
2484 qry->commandType = CMD_SELECT;
2485 qry->isReturn = true;
2486
2488 1, NULL, false));
2489
2490 if (pstate->p_resolve_unknowns)
2492 qry->rtable = pstate->p_rtable;
2493 qry->rteperminfos = pstate->p_rteperminfos;
2494 qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2495 qry->hasSubLinks = pstate->p_hasSubLinks;
2496 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2497 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2498 qry->hasAggs = pstate->p_hasAggs;
2499
2500 assign_query_collations(pstate, qry);
2501
2502 return qry;
2503}
2504
2505
2506/*
2507 * transformUpdateStmt -
2508 * transforms an update statement
2509 */
2510static Query *
2512{
2513 Query *qry = makeNode(Query);
2514 ParseNamespaceItem *nsitem;
2515 Node *qual;
2516
2517 qry->commandType = CMD_UPDATE;
2518 pstate->p_is_insert = false;
2519
2520 /* process the WITH clause independently of all else */
2521 if (stmt->withClause)
2522 {
2523 qry->hasRecursive = stmt->withClause->recursive;
2524 qry->cteList = transformWithClause(pstate, stmt->withClause);
2525 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
2526 }
2527
2528 qry->resultRelation = setTargetTable(pstate, stmt->relation,
2529 stmt->relation->inh,
2530 true,
2531 ACL_UPDATE);
2532 nsitem = pstate->p_target_nsitem;
2533
2534 /* subqueries in FROM cannot access the result relation */
2535 nsitem->p_lateral_only = true;
2536 nsitem->p_lateral_ok = false;
2537
2538 /*
2539 * the FROM clause is non-standard SQL syntax. We used to be able to do
2540 * this with REPLACE in POSTQUEL so we keep the feature.
2541 */
2542 transformFromClause(pstate, stmt->fromClause);
2543
2544 /* remaining clauses can reference the result relation normally */
2545 nsitem->p_lateral_only = false;
2546 nsitem->p_lateral_ok = true;
2547
2548 qual = transformWhereClause(pstate, stmt->whereClause,
2549 EXPR_KIND_WHERE, "WHERE");
2550
2551 qry->returningList = transformReturningList(pstate, stmt->returningList,
2553
2554 /*
2555 * Now we are done with SELECT-like processing, and can get on with
2556 * transforming the target list to match the UPDATE target columns.
2557 */
2558 qry->targetList = transformUpdateTargetList(pstate, stmt->targetList);
2559
2560 qry->rtable = pstate->p_rtable;
2561 qry->rteperminfos = pstate->p_rteperminfos;
2562 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2563
2564 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2565 qry->hasSubLinks = pstate->p_hasSubLinks;
2566
2567 assign_query_collations(pstate, qry);
2568
2569 return qry;
2570}
2571
2572/*
2573 * transformUpdateTargetList -
2574 * handle SET clause in UPDATE/MERGE/INSERT ... ON CONFLICT UPDATE
2575 */
2576List *
2578{
2579 List *tlist = NIL;
2580 RTEPermissionInfo *target_perminfo;
2581 ListCell *orig_tl;
2582 ListCell *tl;
2583
2584 tlist = transformTargetList(pstate, origTlist,
2586
2587 /* Prepare to assign non-conflicting resnos to resjunk attributes */
2590
2591 /* Prepare non-junk columns for assignment to target table */
2592 target_perminfo = pstate->p_target_nsitem->p_perminfo;
2593 orig_tl = list_head(origTlist);
2594
2595 foreach(tl, tlist)
2596 {
2597 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2598 ResTarget *origTarget;
2599 int attrno;
2600
2601 if (tle->resjunk)
2602 {
2603 /*
2604 * Resjunk nodes need no additional processing, but be sure they
2605 * have resnos that do not match any target columns; else rewriter
2606 * or planner might get confused. They don't need a resname
2607 * either.
2608 */
2609 tle->resno = (AttrNumber) pstate->p_next_resno++;
2610 tle->resname = NULL;
2611 continue;
2612 }
2613 if (orig_tl == NULL)
2614 elog(ERROR, "UPDATE target count mismatch --- internal error");
2615 origTarget = lfirst_node(ResTarget, orig_tl);
2616
2617 attrno = attnameAttNum(pstate->p_target_relation,
2618 origTarget->name, true);
2619 if (attrno == InvalidAttrNumber)
2620 ereport(ERROR,
2621 (errcode(ERRCODE_UNDEFINED_COLUMN),
2622 errmsg("column \"%s\" of relation \"%s\" does not exist",
2623 origTarget->name,
2625 (origTarget->indirection != NIL &&
2626 strcmp(origTarget->name, pstate->p_target_nsitem->p_names->aliasname) == 0) ?
2627 errhint("SET target columns cannot be qualified with the relation name.") : 0,
2628 parser_errposition(pstate, origTarget->location)));
2629
2630 updateTargetListEntry(pstate, tle, origTarget->name,
2631 attrno,
2632 origTarget->indirection,
2633 origTarget->location);
2634
2635 /* Mark the target column as requiring update permissions */
2636 target_perminfo->updatedCols = bms_add_member(target_perminfo->updatedCols,
2638
2639 orig_tl = lnext(origTlist, orig_tl);
2640 }
2641 if (orig_tl != NULL)
2642 elog(ERROR, "UPDATE target count mismatch --- internal error");
2643
2644 return tlist;
2645}
2646
2647/*
2648 * transformReturningList -
2649 * handle a RETURNING clause in INSERT/UPDATE/DELETE/MERGE
2650 */
2651List *
2653 ParseExprKind exprKind)
2654{
2655 List *rlist;
2656 int save_next_resno;
2657
2658 if (returningList == NIL)
2659 return NIL; /* nothing to do */
2660
2661 /*
2662 * We need to assign resnos starting at one in the RETURNING list. Save
2663 * and restore the main tlist's value of p_next_resno, just in case
2664 * someone looks at it later (probably won't happen).
2665 */
2666 save_next_resno = pstate->p_next_resno;
2667 pstate->p_next_resno = 1;
2668
2669 /* transform RETURNING identically to a SELECT targetlist */
2670 rlist = transformTargetList(pstate, returningList, exprKind);
2671
2672 /*
2673 * Complain if the nonempty tlist expanded to nothing (which is possible
2674 * if it contains only a star-expansion of a zero-column table). If we
2675 * allow this, the parsed Query will look like it didn't have RETURNING,
2676 * with results that would probably surprise the user.
2677 */
2678 if (rlist == NIL)
2679 ereport(ERROR,
2680 (errcode(ERRCODE_SYNTAX_ERROR),
2681 errmsg("RETURNING must have at least one column"),
2682 parser_errposition(pstate,
2683 exprLocation(linitial(returningList)))));
2684
2685 /* mark column origins */
2686 markTargetListOrigins(pstate, rlist);
2687
2688 /* resolve any still-unresolved output columns as being type text */
2689 if (pstate->p_resolve_unknowns)
2690 resolveTargetListUnknowns(pstate, rlist);
2691
2692 /* restore state */
2693 pstate->p_next_resno = save_next_resno;
2694
2695 return rlist;
2696}
2697
2698
2699/*
2700 * transformPLAssignStmt -
2701 * transform a PL/pgSQL assignment statement
2702 *
2703 * If there is no opt_indirection, the transformed statement looks like
2704 * "SELECT a_expr ...", except the expression has been cast to the type of
2705 * the target. With indirection, it's still a SELECT, but the expression will
2706 * incorporate FieldStore and/or assignment SubscriptingRef nodes to compute a
2707 * new value for a container-type variable represented by the target. The
2708 * expression references the target as the container source.
2709 */
2710static Query *
2712{
2713 Query *qry = makeNode(Query);
2714 ColumnRef *cref = makeNode(ColumnRef);
2715 List *indirection = stmt->indirection;
2716 int nnames = stmt->nnames;
2717 SelectStmt *sstmt = stmt->val;
2718 Node *target;
2719 Oid targettype;
2720 int32 targettypmod;
2721 Oid targetcollation;
2722 List *tlist;
2723 TargetEntry *tle;
2724 Oid type_id;
2725 Node *qual;
2726 ListCell *l;
2727
2728 /*
2729 * First, construct a ColumnRef for the target variable. If the target
2730 * has more than one dotted name, we have to pull the extra names out of
2731 * the indirection list.
2732 */
2733 cref->fields = list_make1(makeString(stmt->name));
2734 cref->location = stmt->location;
2735 if (nnames > 1)
2736 {
2737 /* avoid munging the raw parsetree */
2738 indirection = list_copy(indirection);
2739 while (--nnames > 0 && indirection != NIL)
2740 {
2741 Node *ind = (Node *) linitial(indirection);
2742
2743 if (!IsA(ind, String))
2744 elog(ERROR, "invalid name count in PLAssignStmt");
2745 cref->fields = lappend(cref->fields, ind);
2746 indirection = list_delete_first(indirection);
2747 }
2748 }
2749
2750 /*
2751 * Transform the target reference. Typically we will get back a Param
2752 * node, but there's no reason to be too picky about its type.
2753 */
2754 target = transformExpr(pstate, (Node *) cref,
2756 targettype = exprType(target);
2757 targettypmod = exprTypmod(target);
2758 targetcollation = exprCollation(target);
2759
2760 /*
2761 * The rest mostly matches transformSelectStmt, except that we needn't
2762 * consider WITH or INTO, and we build a targetlist our own way.
2763 */
2764 qry->commandType = CMD_SELECT;
2765 pstate->p_is_insert = false;
2766
2767 /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
2768 pstate->p_locking_clause = sstmt->lockingClause;
2769
2770 /* make WINDOW info available for window functions, too */
2771 pstate->p_windowdefs = sstmt->windowClause;
2772
2773 /* process the FROM clause */
2774 transformFromClause(pstate, sstmt->fromClause);
2775
2776 /* initially transform the targetlist as if in SELECT */
2777 tlist = transformTargetList(pstate, sstmt->targetList,
2779
2780 /* we should have exactly one targetlist item */
2781 if (list_length(tlist) != 1)
2782 ereport(ERROR,
2783 (errcode(ERRCODE_SYNTAX_ERROR),
2784 errmsg_plural("assignment source returned %d column",
2785 "assignment source returned %d columns",
2786 list_length(tlist),
2787 list_length(tlist))));
2788
2789 tle = linitial_node(TargetEntry, tlist);
2790
2791 /*
2792 * This next bit is similar to transformAssignedExpr; the key difference
2793 * is we use COERCION_PLPGSQL not COERCION_ASSIGNMENT.
2794 */
2795 type_id = exprType((Node *) tle->expr);
2796
2798
2799 if (indirection)
2800 {
2801 tle->expr = (Expr *)
2803 target,
2804 stmt->name,
2805 false,
2806 targettype,
2807 targettypmod,
2808 targetcollation,
2809 indirection,
2810 list_head(indirection),
2811 (Node *) tle->expr,
2813 exprLocation(target));
2814 }
2815 else if (targettype != type_id &&
2816 (targettype == RECORDOID || ISCOMPLEX(targettype)) &&
2817 (type_id == RECORDOID || ISCOMPLEX(type_id)))
2818 {
2819 /*
2820 * Hack: do not let coerce_to_target_type() deal with inconsistent
2821 * composite types. Just pass the expression result through as-is,
2822 * and let the PL/pgSQL executor do the conversion its way. This is
2823 * rather bogus, but it's needed for backwards compatibility.
2824 */
2825 }
2826 else
2827 {
2828 /*
2829 * For normal non-qualified target column, do type checking and
2830 * coercion.
2831 */
2832 Node *orig_expr = (Node *) tle->expr;
2833
2834 tle->expr = (Expr *)
2835 coerce_to_target_type(pstate,
2836 orig_expr, type_id,
2837 targettype, targettypmod,
2840 -1);
2841 /* With COERCION_PLPGSQL, this error is probably unreachable */
2842 if (tle->expr == NULL)
2843 ereport(ERROR,
2844 (errcode(ERRCODE_DATATYPE_MISMATCH),
2845 errmsg("variable \"%s\" is of type %s"
2846 " but expression is of type %s",
2847 stmt->name,
2848 format_type_be(targettype),
2849 format_type_be(type_id)),
2850 errhint("You will need to rewrite or cast the expression."),
2851 parser_errposition(pstate, exprLocation(orig_expr))));
2852 }
2853
2854 pstate->p_expr_kind = EXPR_KIND_NONE;
2855
2856 qry->targetList = list_make1(tle);
2857
2858 /* transform WHERE */
2859 qual = transformWhereClause(pstate, sstmt->whereClause,
2860 EXPR_KIND_WHERE, "WHERE");
2861
2862 /* initial processing of HAVING clause is much like WHERE clause */
2863 qry->havingQual = transformWhereClause(pstate, sstmt->havingClause,
2864 EXPR_KIND_HAVING, "HAVING");
2865
2866 /*
2867 * Transform sorting/grouping stuff. Do ORDER BY first because both
2868 * transformGroupClause and transformDistinctClause need the results. Note
2869 * that these functions can also change the targetList, so it's passed to
2870 * them by reference.
2871 */
2872 qry->sortClause = transformSortClause(pstate,
2873 sstmt->sortClause,
2874 &qry->targetList,
2876 false /* allow SQL92 rules */ );
2877
2878 qry->groupClause = transformGroupClause(pstate,
2879 sstmt->groupClause,
2880 &qry->groupingSets,
2881 &qry->targetList,
2882 qry->sortClause,
2884 false /* allow SQL92 rules */ );
2885
2886 if (sstmt->distinctClause == NIL)
2887 {
2888 qry->distinctClause = NIL;
2889 qry->hasDistinctOn = false;
2890 }
2891 else if (linitial(sstmt->distinctClause) == NULL)
2892 {
2893 /* We had SELECT DISTINCT */
2895 &qry->targetList,
2896 qry->sortClause,
2897 false);
2898 qry->hasDistinctOn = false;
2899 }
2900 else
2901 {
2902 /* We had SELECT DISTINCT ON */
2904 sstmt->distinctClause,
2905 &qry->targetList,
2906 qry->sortClause);
2907 qry->hasDistinctOn = true;
2908 }
2909
2910 /* transform LIMIT */
2911 qry->limitOffset = transformLimitClause(pstate, sstmt->limitOffset,
2912 EXPR_KIND_OFFSET, "OFFSET",
2913 sstmt->limitOption);
2914 qry->limitCount = transformLimitClause(pstate, sstmt->limitCount,
2915 EXPR_KIND_LIMIT, "LIMIT",
2916 sstmt->limitOption);
2917 qry->limitOption = sstmt->limitOption;
2918
2919 /* transform window clauses after we have seen all window functions */
2921 pstate->p_windowdefs,
2922 &qry->targetList);
2923
2924 qry->rtable = pstate->p_rtable;
2925 qry->rteperminfos = pstate->p_rteperminfos;
2926 qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2927
2928 qry->hasSubLinks = pstate->p_hasSubLinks;
2929 qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
2930 qry->hasTargetSRFs = pstate->p_hasTargetSRFs;
2931 qry->hasAggs = pstate->p_hasAggs;
2932
2933 foreach(l, sstmt->lockingClause)
2934 {
2935 transformLockingClause(pstate, qry,
2936 (LockingClause *) lfirst(l), false);
2937 }
2938
2939 assign_query_collations(pstate, qry);
2940
2941 /* this must be done after collations, for reliable comparison of exprs */
2942 if (pstate->p_hasAggs || qry->groupClause || qry->groupingSets || qry->havingQual)
2943 parseCheckAggregates(pstate, qry);
2944
2945 return qry;
2946}
2947
2948
2949/*
2950 * transformDeclareCursorStmt -
2951 * transform a DECLARE CURSOR Statement
2952 *
2953 * DECLARE CURSOR is like other utility statements in that we emit it as a
2954 * CMD_UTILITY Query node; however, we must first transform the contained
2955 * query. We used to postpone that until execution, but it's really necessary
2956 * to do it during the normal parse analysis phase to ensure that side effects
2957 * of parser hooks happen at the expected time.
2958 */
2959static Query *
2961{
2962 Query *result;
2963 Query *query;
2964
2965 if ((stmt->options & CURSOR_OPT_SCROLL) &&
2966 (stmt->options & CURSOR_OPT_NO_SCROLL))
2967 ereport(ERROR,
2968 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2969 /* translator: %s is a SQL keyword */
2970 errmsg("cannot specify both %s and %s",
2971 "SCROLL", "NO SCROLL")));
2972
2973 if ((stmt->options & CURSOR_OPT_ASENSITIVE) &&
2974 (stmt->options & CURSOR_OPT_INSENSITIVE))
2975 ereport(ERROR,
2976 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2977 /* translator: %s is a SQL keyword */
2978 errmsg("cannot specify both %s and %s",
2979 "ASENSITIVE", "INSENSITIVE")));
2980
2981 /* Transform contained query, not allowing SELECT INTO */
2982 query = transformStmt(pstate, stmt->query);
2983 stmt->query = (Node *) query;
2984
2985 /* Grammar should not have allowed anything but SELECT */
2986 if (!IsA(query, Query) ||
2987 query->commandType != CMD_SELECT)
2988 elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
2989
2990 /*
2991 * We also disallow data-modifying WITH in a cursor. (This could be
2992 * allowed, but the semantics of when the updates occur might be
2993 * surprising.)
2994 */
2995 if (query->hasModifyingCTE)
2996 ereport(ERROR,
2997 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2998 errmsg("DECLARE CURSOR must not contain data-modifying statements in WITH")));
2999
3000 /* FOR UPDATE and WITH HOLD are not compatible */
3001 if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
3002 ereport(ERROR,
3003 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3004 /*------
3005 translator: %s is a SQL row locking clause such as FOR UPDATE */
3006 errmsg("DECLARE CURSOR WITH HOLD ... %s is not supported",
3008 linitial(query->rowMarks))->strength)),
3009 errdetail("Holdable cursors must be READ ONLY.")));
3010
3011 /* FOR UPDATE and SCROLL are not compatible */
3012 if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
3013 ereport(ERROR,
3014 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3015 /*------
3016 translator: %s is a SQL row locking clause such as FOR UPDATE */
3017 errmsg("DECLARE SCROLL CURSOR ... %s is not supported",
3019 linitial(query->rowMarks))->strength)),
3020 errdetail("Scrollable cursors must be READ ONLY.")));
3021
3022 /* FOR UPDATE and INSENSITIVE are not compatible */
3023 if (query->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
3024 ereport(ERROR,
3025 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3026 /*------
3027 translator: %s is a SQL row locking clause such as FOR UPDATE */
3028 errmsg("DECLARE INSENSITIVE CURSOR ... %s is not valid",
3030 linitial(query->rowMarks))->strength)),
3031 errdetail("Insensitive cursors must be READ ONLY.")));
3032
3033 /* represent the command as a utility Query */
3034 result = makeNode(Query);
3035 result->commandType = CMD_UTILITY;
3036 result->utilityStmt = (Node *) stmt;
3037
3038 return result;
3039}
3040
3041
3042/*
3043 * transformExplainStmt -
3044 * transform an EXPLAIN Statement
3045 *
3046 * EXPLAIN is like other utility statements in that we emit it as a
3047 * CMD_UTILITY Query node; however, we must first transform the contained
3048 * query. We used to postpone that until execution, but it's really necessary
3049 * to do it during the normal parse analysis phase to ensure that side effects
3050 * of parser hooks happen at the expected time.
3051 */
3052static Query *
3054{
3055 Query *result;
3056 bool generic_plan = false;
3057 Oid *paramTypes = NULL;
3058 int numParams = 0;
3059
3060 /*
3061 * If we have no external source of parameter definitions, and the
3062 * GENERIC_PLAN option is specified, then accept variable parameter
3063 * definitions (similarly to PREPARE, for example).
3064 */
3065 if (pstate->p_paramref_hook == NULL)
3066 {
3067 ListCell *lc;
3068
3069 foreach(lc, stmt->options)
3070 {
3071 DefElem *opt = (DefElem *) lfirst(lc);
3072
3073 if (strcmp(opt->defname, "generic_plan") == 0)
3074 generic_plan = defGetBoolean(opt);
3075 /* don't "break", as we want the last value */
3076 }
3077 if (generic_plan)
3078 setup_parse_variable_parameters(pstate, &paramTypes, &numParams);
3079 }
3080
3081 /* transform contained query, allowing SELECT INTO */
3082 stmt->query = (Node *) transformOptionalSelectInto(pstate, stmt->query);
3083
3084 /* make sure all is well with parameter types */
3085 if (generic_plan)
3086 check_variable_parameters(pstate, (Query *) stmt->query);
3087
3088 /* represent the command as a utility Query */
3089 result = makeNode(Query);
3090 result->commandType = CMD_UTILITY;
3091 result->utilityStmt = (Node *) stmt;
3092
3093 return result;
3094}
3095
3096
3097/*
3098 * transformCreateTableAsStmt -
3099 * transform a CREATE TABLE AS, SELECT ... INTO, or CREATE MATERIALIZED VIEW
3100 * Statement
3101 *
3102 * As with DECLARE CURSOR and EXPLAIN, transform the contained statement now.
3103 */
3104static Query *
3106{
3107 Query *result;
3108 Query *query;
3109
3110 /* transform contained query, not allowing SELECT INTO */
3111 query = transformStmt(pstate, stmt->query);
3112 stmt->query = (Node *) query;
3113
3114 /* additional work needed for CREATE MATERIALIZED VIEW */
3115 if (stmt->objtype == OBJECT_MATVIEW)
3116 {
3117 /*
3118 * Prohibit a data-modifying CTE in the query used to create a
3119 * materialized view. It's not sufficiently clear what the user would
3120 * want to happen if the MV is refreshed or incrementally maintained.
3121 */
3122 if (query->hasModifyingCTE)
3123 ereport(ERROR,
3124 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3125 errmsg("materialized views must not use data-modifying statements in WITH")));
3126
3127 /*
3128 * Check whether any temporary database objects are used in the
3129 * creation query. It would be hard to refresh data or incrementally
3130 * maintain it if a source disappeared.
3131 */
3132 if (isQueryUsingTempRelation(query))
3133 ereport(ERROR,
3134 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3135 errmsg("materialized views must not use temporary tables or views")));
3136
3137 /*
3138 * A materialized view would either need to save parameters for use in
3139 * maintaining/loading the data or prohibit them entirely. The latter
3140 * seems safer and more sane.
3141 */
3143 ereport(ERROR,
3144 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3145 errmsg("materialized views may not be defined using bound parameters")));
3146
3147 /*
3148 * For now, we disallow unlogged materialized views, because it seems
3149 * like a bad idea for them to just go to empty after a crash. (If we
3150 * could mark them as unpopulated, that would be better, but that
3151 * requires catalog changes which crash recovery can't presently
3152 * handle.)
3153 */
3154 if (stmt->into->rel->relpersistence == RELPERSISTENCE_UNLOGGED)
3155 ereport(ERROR,
3156 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3157 errmsg("materialized views cannot be unlogged")));
3158
3159 /*
3160 * At runtime, we'll need a copy of the parsed-but-not-rewritten Query
3161 * for purposes of creating the view's ON SELECT rule. We stash that
3162 * in the IntoClause because that's where intorel_startup() can
3163 * conveniently get it from.
3164 */
3165 stmt->into->viewQuery = copyObject(query);
3166 }
3167
3168 /* represent the command as a utility Query */
3169 result = makeNode(Query);
3170 result->commandType = CMD_UTILITY;
3171 result->utilityStmt = (Node *) stmt;
3172
3173 return result;
3174}
3175
3176/*
3177 * transform a CallStmt
3178 */
3179static Query *
3181{
3182 List *targs;
3183 ListCell *lc;
3184 Node *node;
3185 FuncExpr *fexpr;
3186 HeapTuple proctup;
3187 Datum proargmodes;
3188 bool isNull;
3189 List *outargs = NIL;
3190 Query *result;
3191
3192 /*
3193 * First, do standard parse analysis on the procedure call and its
3194 * arguments, allowing us to identify the called procedure.
3195 */
3196 targs = NIL;
3197 foreach(lc, stmt->funccall->args)
3198 {
3199 targs = lappend(targs, transformExpr(pstate,
3200 (Node *) lfirst(lc),
3202 }
3203
3204 node = ParseFuncOrColumn(pstate,
3205 stmt->funccall->funcname,
3206 targs,
3207 pstate->p_last_srf,
3208 stmt->funccall,
3209 true,
3210 stmt->funccall->location);
3211
3212 assign_expr_collations(pstate, node);
3213
3214 fexpr = castNode(FuncExpr, node);
3215
3216 proctup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fexpr->funcid));
3217 if (!HeapTupleIsValid(proctup))
3218 elog(ERROR, "cache lookup failed for function %u", fexpr->funcid);
3219
3220 /*
3221 * Expand the argument list to deal with named-argument notation and
3222 * default arguments. For ordinary FuncExprs this'd be done during
3223 * planning, but a CallStmt doesn't go through planning, and there seems
3224 * no good reason not to do it here.
3225 */
3226 fexpr->args = expand_function_arguments(fexpr->args,
3227 true,
3228 fexpr->funcresulttype,
3229 proctup);
3230
3231 /* Fetch proargmodes; if it's null, there are no output args */
3232 proargmodes = SysCacheGetAttr(PROCOID, proctup,
3233 Anum_pg_proc_proargmodes,
3234 &isNull);
3235 if (!isNull)
3236 {
3237 /*
3238 * Split the list into input arguments in fexpr->args and output
3239 * arguments in stmt->outargs. INOUT arguments appear in both lists.
3240 */
3241 ArrayType *arr;
3242 int numargs;
3243 char *argmodes;
3244 List *inargs;
3245 int i;
3246
3247 arr = DatumGetArrayTypeP(proargmodes); /* ensure not toasted */
3248 numargs = list_length(fexpr->args);
3249 if (ARR_NDIM(arr) != 1 ||
3250 ARR_DIMS(arr)[0] != numargs ||
3251 ARR_HASNULL(arr) ||
3252 ARR_ELEMTYPE(arr) != CHAROID)
3253 elog(ERROR, "proargmodes is not a 1-D char array of length %d or it contains nulls",
3254 numargs);
3255 argmodes = (char *) ARR_DATA_PTR(arr);
3256
3257 inargs = NIL;
3258 i = 0;
3259 foreach(lc, fexpr->args)
3260 {
3261 Node *n = lfirst(lc);
3262
3263 switch (argmodes[i])
3264 {
3265 case PROARGMODE_IN:
3266 case PROARGMODE_VARIADIC:
3267 inargs = lappend(inargs, n);
3268 break;
3269 case PROARGMODE_OUT:
3270 outargs = lappend(outargs, n);
3271 break;
3272 case PROARGMODE_INOUT:
3273 inargs = lappend(inargs, n);
3274 outargs = lappend(outargs, copyObject(n));
3275 break;
3276 default:
3277 /* note we don't support PROARGMODE_TABLE */
3278 elog(ERROR, "invalid argmode %c for procedure",
3279 argmodes[i]);
3280 break;
3281 }
3282 i++;
3283 }
3284 fexpr->args = inargs;
3285 }
3286
3287 stmt->funcexpr = fexpr;
3288 stmt->outargs = outargs;
3289
3290 ReleaseSysCache(proctup);
3291
3292 /* represent the command as a utility Query */
3293 result = makeNode(Query);
3294 result->commandType = CMD_UTILITY;
3295 result->utilityStmt = (Node *) stmt;
3296
3297 return result;
3298}
3299
3300/*
3301 * Produce a string representation of a LockClauseStrength value.
3302 * This should only be applied to valid values (not LCS_NONE).
3303 */
3304const char *
3306{
3307 switch (strength)
3308 {
3309 case LCS_NONE:
3310 Assert(false);
3311 break;
3312 case LCS_FORKEYSHARE:
3313 return "FOR KEY SHARE";
3314 case LCS_FORSHARE:
3315 return "FOR SHARE";
3316 case LCS_FORNOKEYUPDATE:
3317 return "FOR NO KEY UPDATE";
3318 case LCS_FORUPDATE:
3319 return "FOR UPDATE";
3320 }
3321 return "FOR some"; /* shouldn't happen */
3322}
3323
3324/*
3325 * Check for features that are not supported with FOR [KEY] UPDATE/SHARE.
3326 *
3327 * exported so planner can check again after rewriting, query pullup, etc
3328 */
3329void
3331{
3332 Assert(strength != LCS_NONE); /* else caller error */
3333
3334 if (qry->setOperations)
3335 ereport(ERROR,
3336 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3337 /*------
3338 translator: %s is a SQL row locking clause such as FOR UPDATE */
3339 errmsg("%s is not allowed with UNION/INTERSECT/EXCEPT",
3340 LCS_asString(strength))));
3341 if (qry->distinctClause != NIL)
3342 ereport(ERROR,
3343 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3344 /*------
3345 translator: %s is a SQL row locking clause such as FOR UPDATE */
3346 errmsg("%s is not allowed with DISTINCT clause",
3347 LCS_asString(strength))));
3348 if (qry->groupClause != NIL || qry->groupingSets != NIL)
3349 ereport(ERROR,
3350 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3351 /*------
3352 translator: %s is a SQL row locking clause such as FOR UPDATE */
3353 errmsg("%s is not allowed with GROUP BY clause",
3354 LCS_asString(strength))));
3355 if (qry->havingQual != NULL)
3356 ereport(ERROR,
3357 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3358 /*------
3359 translator: %s is a SQL row locking clause such as FOR UPDATE */
3360 errmsg("%s is not allowed with HAVING clause",
3361 LCS_asString(strength))));
3362 if (qry->hasAggs)
3363 ereport(ERROR,
3364 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3365 /*------
3366 translator: %s is a SQL row locking clause such as FOR UPDATE */
3367 errmsg("%s is not allowed with aggregate functions",
3368 LCS_asString(strength))));
3369 if (qry->hasWindowFuncs)
3370 ereport(ERROR,
3371 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3372 /*------
3373 translator: %s is a SQL row locking clause such as FOR UPDATE */
3374 errmsg("%s is not allowed with window functions",
3375 LCS_asString(strength))));
3376 if (qry->hasTargetSRFs)
3377 ereport(ERROR,
3378 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3379 /*------
3380 translator: %s is a SQL row locking clause such as FOR UPDATE */
3381 errmsg("%s is not allowed with set-returning functions in the target list",
3382 LCS_asString(strength))));
3383}
3384
3385/*
3386 * Transform a FOR [KEY] UPDATE/SHARE clause
3387 *
3388 * This basically involves replacing names by integer relids.
3389 *
3390 * NB: if you need to change this, see also markQueryForLocking()
3391 * in rewriteHandler.c, and isLockedRefname() in parse_relation.c.
3392 */
3393static void
3395 bool pushedDown)
3396{
3397 List *lockedRels = lc->lockedRels;
3398 ListCell *l;
3399 ListCell *rt;
3400 Index i;
3401 LockingClause *allrels;
3402
3403 CheckSelectLocking(qry, lc->strength);
3404
3405 /* make a clause we can pass down to subqueries to select all rels */
3406 allrels = makeNode(LockingClause);
3407 allrels->lockedRels = NIL; /* indicates all rels */
3408 allrels->strength = lc->strength;
3409 allrels->waitPolicy = lc->waitPolicy;
3410
3411 if (lockedRels == NIL)
3412 {
3413 /*
3414 * Lock all regular tables used in query and its subqueries. We
3415 * examine inFromCl to exclude auto-added RTEs, particularly NEW/OLD
3416 * in rules. This is a bit of an abuse of a mostly-obsolete flag, but
3417 * it's convenient. We can't rely on the namespace mechanism that has
3418 * largely replaced inFromCl, since for example we need to lock
3419 * base-relation RTEs even if they are masked by upper joins.
3420 */
3421 i = 0;
3422 foreach(rt, qry->rtable)
3423 {
3424 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3425
3426 ++i;
3427 if (!rte->inFromCl)
3428 continue;
3429 switch (rte->rtekind)
3430 {
3431 case RTE_RELATION:
3432 {
3433 RTEPermissionInfo *perminfo;
3434
3435 applyLockingClause(qry, i,
3436 lc->strength,
3437 lc->waitPolicy,
3438 pushedDown);
3439 perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
3441 }
3442 break;
3443 case RTE_SUBQUERY:
3444 applyLockingClause(qry, i, lc->strength, lc->waitPolicy,
3445 pushedDown);
3446
3447 /*
3448 * FOR UPDATE/SHARE of subquery is propagated to all of
3449 * subquery's rels, too. We could do this later (based on
3450 * the marking of the subquery RTE) but it is convenient
3451 * to have local knowledge in each query level about which
3452 * rels need to be opened with RowShareLock.
3453 */
3454 transformLockingClause(pstate, rte->subquery,
3455 allrels, true);
3456 break;
3457 default:
3458 /* ignore JOIN, SPECIAL, FUNCTION, VALUES, CTE RTEs */
3459 break;
3460 }
3461 }
3462 }
3463 else
3464 {
3465 /*
3466 * Lock just the named tables. As above, we allow locking any base
3467 * relation regardless of alias-visibility rules, so we need to
3468 * examine inFromCl to exclude OLD/NEW.
3469 */
3470 foreach(l, lockedRels)
3471 {
3472 RangeVar *thisrel = (RangeVar *) lfirst(l);
3473
3474 /* For simplicity we insist on unqualified alias names here */
3475 if (thisrel->catalogname || thisrel->schemaname)
3476 ereport(ERROR,
3477 (errcode(ERRCODE_SYNTAX_ERROR),
3478 /*------
3479 translator: %s is a SQL row locking clause such as FOR UPDATE */
3480 errmsg("%s must specify unqualified relation names",
3481 LCS_asString(lc->strength)),
3482 parser_errposition(pstate, thisrel->location)));
3483
3484 i = 0;
3485 foreach(rt, qry->rtable)
3486 {
3487 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3488 char *rtename = rte->eref->aliasname;
3489
3490 ++i;
3491 if (!rte->inFromCl)
3492 continue;
3493
3494 /*
3495 * A join RTE without an alias is not visible as a relation
3496 * name and needs to be skipped (otherwise it might hide a
3497 * base relation with the same name), except if it has a USING
3498 * alias, which *is* visible.
3499 *
3500 * Subquery and values RTEs without aliases are never visible
3501 * as relation names and must always be skipped.
3502 */
3503 if (rte->alias == NULL)
3504 {
3505 if (rte->rtekind == RTE_JOIN)
3506 {
3507 if (rte->join_using_alias == NULL)
3508 continue;
3509 rtename = rte->join_using_alias->aliasname;
3510 }
3511 else if (rte->rtekind == RTE_SUBQUERY ||
3512 rte->rtekind == RTE_VALUES)
3513 continue;
3514 }
3515
3516 if (strcmp(rtename, thisrel->relname) == 0)
3517 {
3518 switch (rte->rtekind)
3519 {
3520 case RTE_RELATION:
3521 {
3522 RTEPermissionInfo *perminfo;
3523
3524 applyLockingClause(qry, i,
3525 lc->strength,
3526 lc->waitPolicy,
3527 pushedDown);
3528 perminfo = getRTEPermissionInfo(qry->rteperminfos, rte);
3530 }
3531 break;
3532 case RTE_SUBQUERY:
3533 applyLockingClause(qry, i, lc->strength,
3534 lc->waitPolicy, pushedDown);
3535 /* see comment above */
3536 transformLockingClause(pstate, rte->subquery,
3537 allrels, true);
3538 break;
3539 case RTE_JOIN:
3540 ereport(ERROR,
3541 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3542 /*------
3543 translator: %s is a SQL row locking clause such as FOR UPDATE */
3544 errmsg("%s cannot be applied to a join",
3545 LCS_asString(lc->strength)),
3546 parser_errposition(pstate, thisrel->location)));
3547 break;
3548 case RTE_FUNCTION:
3549 ereport(ERROR,
3550 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3551 /*------
3552 translator: %s is a SQL row locking clause such as FOR UPDATE */
3553 errmsg("%s cannot be applied to a function",
3554 LCS_asString(lc->strength)),
3555 parser_errposition(pstate, thisrel->location)));
3556 break;
3557 case RTE_TABLEFUNC:
3558 ereport(ERROR,
3559 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3560 /*------
3561 translator: %s is a SQL row locking clause such as FOR UPDATE */
3562 errmsg("%s cannot be applied to a table function",
3563 LCS_asString(lc->strength)),
3564 parser_errposition(pstate, thisrel->location)));
3565 break;
3566 case RTE_VALUES:
3567 ereport(ERROR,
3568 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3569 /*------
3570 translator: %s is a SQL row locking clause such as FOR UPDATE */
3571 errmsg("%s cannot be applied to VALUES",
3572 LCS_asString(lc->strength)),
3573 parser_errposition(pstate, thisrel->location)));
3574 break;
3575 case RTE_CTE:
3576 ereport(ERROR,
3577 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3578 /*------
3579 translator: %s is a SQL row locking clause such as FOR UPDATE */
3580 errmsg("%s cannot be applied to a WITH query",
3581 LCS_asString(lc->strength)),
3582 parser_errposition(pstate, thisrel->location)));
3583 break;
3585 ereport(ERROR,
3586 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3587 /*------
3588 translator: %s is a SQL row locking clause such as FOR UPDATE */
3589 errmsg("%s cannot be applied to a named tuplestore",
3590 LCS_asString(lc->strength)),
3591 parser_errposition(pstate, thisrel->location)));
3592 break;
3593
3594 /* Shouldn't be possible to see RTE_RESULT here */
3595
3596 default:
3597 elog(ERROR, "unrecognized RTE type: %d",
3598 (int) rte->rtekind);
3599 break;
3600 }
3601 break; /* out of foreach loop */
3602 }
3603 }
3604 if (rt == NULL)
3605 ereport(ERROR,
3607 /*------
3608 translator: %s is a SQL row locking clause such as FOR UPDATE */
3609 errmsg("relation \"%s\" in %s clause not found in FROM clause",
3610 thisrel->relname,
3611 LCS_asString(lc->strength)),
3612 parser_errposition(pstate, thisrel->location)));
3613 }
3614 }
3615}
3616
3617/*
3618 * Record locking info for a single rangetable item
3619 */
3620void
3622 LockClauseStrength strength, LockWaitPolicy waitPolicy,
3623 bool pushedDown)
3624{
3625 RowMarkClause *rc;
3626
3627 Assert(strength != LCS_NONE); /* else caller error */
3628
3629 /* If it's an explicit clause, make sure hasForUpdate gets set */
3630 if (!pushedDown)
3631 qry->hasForUpdate = true;
3632
3633 /* Check for pre-existing entry for same rtindex */
3634 if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
3635 {
3636 /*
3637 * If the same RTE is specified with more than one locking strength,
3638 * use the strongest. (Reasonable, since you can't take both a shared
3639 * and exclusive lock at the same time; it'll end up being exclusive
3640 * anyway.)
3641 *
3642 * Similarly, if the same RTE is specified with more than one lock
3643 * wait policy, consider that NOWAIT wins over SKIP LOCKED, which in
3644 * turn wins over waiting for the lock (the default). This is a bit
3645 * more debatable but raising an error doesn't seem helpful. (Consider
3646 * for instance SELECT FOR UPDATE NOWAIT from a view that internally
3647 * contains a plain FOR UPDATE spec.) Having NOWAIT win over SKIP
3648 * LOCKED is reasonable since the former throws an error in case of
3649 * coming across a locked tuple, which may be undesirable in some
3650 * cases but it seems better than silently returning inconsistent
3651 * results.
3652 *
3653 * And of course pushedDown becomes false if any clause is explicit.
3654 */
3655 rc->strength = Max(rc->strength, strength);
3656 rc->waitPolicy = Max(rc->waitPolicy, waitPolicy);
3657 rc->pushedDown &= pushedDown;
3658 return;
3659 }
3660
3661 /* Make a new RowMarkClause */
3662 rc = makeNode(RowMarkClause);
3663 rc->rti = rtindex;
3664 rc->strength = strength;
3665 rc->waitPolicy = waitPolicy;
3666 rc->pushedDown = pushedDown;
3667 qry->rowMarks = lappend(qry->rowMarks, rc);
3668}
3669
3670#ifdef DEBUG_NODE_TESTS_ENABLED
3671/*
3672 * Coverage testing for raw_expression_tree_walker().
3673 *
3674 * When enabled, we run raw_expression_tree_walker() over every DML statement
3675 * submitted to parse analysis. Without this provision, that function is only
3676 * applied in limited cases involving CTEs, and we don't really want to have
3677 * to test everything inside as well as outside a CTE.
3678 */
3679static bool
3680test_raw_expression_coverage(Node *node, void *context)
3681{
3682 if (node == NULL)
3683 return false;
3684 return raw_expression_tree_walker(node,
3685 test_raw_expression_coverage,
3686 context);
3687}
3688#endif /* DEBUG_NODE_TESTS_ENABLED */
void(* post_parse_analyze_hook_type)(ParseState *pstate, Query *query, JumbleState *jstate)
Definition: analyze.h:22
#define ARR_NDIM(a)
Definition: array.h:290
#define ARR_DATA_PTR(a)
Definition: array.h:322
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_DIMS(a)
Definition: array.h:294
#define ARR_HASNULL(a)
Definition: array.h:291
int16 AttrNumber
Definition: attnum.h:21
#define InvalidAttrNumber
Definition: attnum.h:23
void pgstat_report_query_id(uint64 query_id, bool force)
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define NameStr(name)
Definition: c.h:700
#define Max(x, y)
Definition: c.h:952
#define Assert(condition)
Definition: c.h:812
int32_t int32
Definition: c.h:481
unsigned int Index
Definition: c.h:568
List * expand_function_arguments(List *args, bool include_out_arguments, Oid result_type, HeapTuple func_tuple)
Definition: clauses.c:4174
bool defGetBoolean(DefElem *def)
Definition: define.c:94
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1180
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define stmt
Definition: indent_codes.h:59
long val
Definition: informix.c:689
int i
Definition: isn.c:72
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:76
List * lappend(List *list, void *datum)
Definition: list.c:339
List * list_delete_first(List *list)
Definition: list.c:943
List * list_copy(const List *oldlist)
Definition: list.c:1573
List * lappend_int(List *list, int datum)
Definition: list.c:357
List * lappend_oid(List *list, Oid datum)
Definition: list.c:375
List * list_delete_last(List *list)
Definition: list.c:957
void list_free(List *list)
Definition: list.c:1546
List * list_truncate(List *list, int new_size)
Definition: list.c:631
#define RowExclusiveLock
Definition: lockdefs.h:38
LockWaitPolicy
Definition: lockoptions.h:37
LockClauseStrength
Definition: lockoptions.h:22
@ LCS_FORUPDATE
Definition: lockoptions.h:27
@ LCS_NONE
Definition: lockoptions.h:23
@ LCS_FORSHARE
Definition: lockoptions.h:25
@ LCS_FORKEYSHARE
Definition: lockoptions.h:24
@ LCS_FORNOKEYUPDATE
Definition: lockoptions.h:26
Alias * makeAlias(const char *aliasname, List *colnames)
Definition: makefuncs.c:389
Var * makeVarFromTargetEntry(int varno, TargetEntry *tle)
Definition: makefuncs.c:105
FromExpr * makeFromExpr(List *fromlist, Node *quals)
Definition: makefuncs.c:287
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition: makefuncs.c:66
Const * makeNullConst(Oid consttype, int32 consttypmod, Oid constcollid)
Definition: makefuncs.c:339
TargetEntry * makeTargetEntry(Expr *expr, AttrNumber resno, char *resname, bool resjunk)
Definition: makefuncs.c:240
char * pstrdup(const char *in)
Definition: mcxt.c:1696
void * palloc0(Size size)
Definition: mcxt.c:1347
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:298
Oid exprCollation(const Node *expr)
Definition: nodeFuncs.c:816
int exprLocation(const Node *expr)
Definition: nodeFuncs.c:1380
#define raw_expression_tree_walker(n, w, c)
Definition: nodeFuncs.h:176
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define copyObject(obj)
Definition: nodes.h:224
#define nodeTag(nodeptr)
Definition: nodes.h:133
@ ONCONFLICT_UPDATE
Definition: nodes.h:420
@ CMD_UTILITY
Definition: nodes.h:270
@ CMD_INSERT
Definition: nodes.h:267
@ CMD_DELETE
Definition: nodes.h:268
@ CMD_UPDATE
Definition: nodes.h:266
@ CMD_SELECT
Definition: nodes.h:265
#define makeNode(_type_)
Definition: nodes.h:155
int ParseLoc
Definition: nodes.h:240
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
@ JOIN_INNER
Definition: nodes.h:293
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
void parseCheckAggregates(ParseState *pstate, Query *qry)
Definition: parse_agg.c:1085
List * transformGroupClause(ParseState *pstate, List *grouplist, List **groupingSets, List **targetlist, List *sortClause, ParseExprKind exprKind, bool useSQL99)
Node * transformWhereClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName)
List * transformSortClause(ParseState *pstate, List *orderlist, List **targetlist, ParseExprKind exprKind, bool useSQL99)
List * transformDistinctOnClause(ParseState *pstate, List *distinctlist, List **targetlist, List *sortClause)
List * transformWindowDefinitions(ParseState *pstate, List *windowdefs, List **targetlist)
void transformFromClause(ParseState *pstate, List *frmList)
Definition: parse_clause.c:112
List * transformDistinctClause(ParseState *pstate, List **targetlist, List *sortClause, bool is_agg)
Node * transformLimitClause(ParseState *pstate, Node *clause, ParseExprKind exprKind, const char *constructName, LimitOption limitOption)
void transformOnConflictArbiter(ParseState *pstate, OnConflictClause *onConflictClause, List **arbiterExpr, Node **arbiterWhere, Oid *constraint)
int setTargetTable(ParseState *pstate, RangeVar *relation, bool inh, bool alsoSource, AclMode requiredPerms)
Definition: parse_clause.c:178
Node * coerce_to_common_type(ParseState *pstate, Node *node, Oid targetTypeId, const char *context)
int32 select_common_typmod(ParseState *pstate, List *exprs, Oid common_type)
Oid select_common_type(ParseState *pstate, List *exprs, const char *context, Node **which_expr)
Node * coerce_to_target_type(ParseState *pstate, Node *expr, Oid exprtype, Oid targettype, int32 targettypmod, CoercionContext ccontext, CoercionForm cformat, int location)
Definition: parse_coerce.c:78
void assign_list_collations(ParseState *pstate, List *exprs)
Oid select_common_collation(ParseState *pstate, List *exprs, bool none_ok)
void assign_query_collations(ParseState *pstate, Query *query)
void assign_expr_collations(ParseState *pstate, Node *expr)
void analyzeCTETargetList(ParseState *pstate, CommonTableExpr *cte, List *tlist)
Definition: parse_cte.c:570
List * transformWithClause(ParseState *pstate, WithClause *withClause)
Definition: parse_cte.c:109
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:118
Node * ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs, Node *last_srf, FuncCall *fn, bool proc_call, int location)
Definition: parse_func.c:90
Query * transformMergeStmt(ParseState *pstate, MergeStmt *stmt)
Definition: parse_merge.c:107
void cancel_parser_errposition_callback(ParseCallbackState *pcbstate)
Definition: parse_node.c:156
void free_parsestate(ParseState *pstate)
Definition: parse_node.c:72
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
void setup_parser_errposition_callback(ParseCallbackState *pcbstate, ParseState *pstate, int location)
Definition: parse_node.c:140
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:39
ParseExprKind
Definition: parse_node.h:39
@ EXPR_KIND_VALUES
Definition: parse_node.h:66
@ EXPR_KIND_ORDER_BY
Definition: parse_node.h:60
@ EXPR_KIND_OFFSET
Definition: parse_node.h:63
@ EXPR_KIND_HAVING
Definition: parse_node.h:47
@ EXPR_KIND_INSERT_TARGET
Definition: parse_node.h:55
@ EXPR_KIND_LIMIT
Definition: parse_node.h:62
@ EXPR_KIND_WHERE
Definition: parse_node.h:46
@ EXPR_KIND_UPDATE_TARGET
Definition: parse_node.h:57
@ EXPR_KIND_SELECT_TARGET
Definition: parse_node.h:54
@ EXPR_KIND_RETURNING
Definition: parse_node.h:64
@ EXPR_KIND_NONE
Definition: parse_node.h:40
@ EXPR_KIND_CALL_ARGUMENT
Definition: parse_node.h:81
@ EXPR_KIND_GROUP_BY
Definition: parse_node.h:59
@ EXPR_KIND_UPDATE_SOURCE
Definition: parse_node.h:56
@ EXPR_KIND_VALUES_SINGLE
Definition: parse_node.h:67
struct ParseNamespaceColumn ParseNamespaceColumn
Definition: parse_node.h:25
void get_sort_group_operators(Oid argtype, bool needLT, bool needEQ, bool needGT, Oid *ltOpr, Oid *eqOpr, Oid *gtOpr, bool *isHashable)
Definition: parse_oper.c:180
void check_variable_parameters(ParseState *pstate, Query *query)
Definition: parse_param.c:269
bool query_contains_extern_params(Query *query)
Definition: parse_param.c:331
void setup_parse_variable_parameters(ParseState *pstate, Oid **paramTypes, int *numParams)
Definition: parse_param.c:84
void setup_parse_fixed_parameters(ParseState *pstate, const Oid *paramTypes, int numParams)
Definition: parse_param.c:68
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
RTEPermissionInfo * getRTEPermissionInfo(List *rteperminfos, RangeTblEntry *rte)
RowMarkClause * get_parse_rowmark(Query *qry, Index rtindex)
TargetEntry * get_tle_by_resno(List *tlist, AttrNumber resno)
List * expandNSItemVars(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, int location, List **colnames)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
ParseNamespaceItem * addRangeTableEntryForSubquery(ParseState *pstate, Query *subquery, Alias *alias, bool lateral, bool inFromCl)
ParseNamespaceItem * addRangeTableEntryForJoin(ParseState *pstate, List *colnames, ParseNamespaceColumn *nscolumns, JoinType jointype, int nummergedcols, List *aliasvars, List *leftcols, List *rightcols, Alias *join_using_alias, Alias *alias, bool inFromCl)
List * expandNSItemAttrs(ParseState *pstate, ParseNamespaceItem *nsitem, int sublevels_up, bool require_col_privs, int location)
bool isQueryUsingTempRelation(Query *query)
RangeTblEntry * GetRTEByRangeTablePosn(ParseState *pstate, int varno, int sublevels_up)
int attnameAttNum(Relation rd, const char *attname, bool sysColOK)
ParseNamespaceItem * addRangeTableEntryForValues(ParseState *pstate, List *exprs, List *coltypes, List *coltypmods, List *colcollations, Alias *alias, bool lateral, bool inFromCl)
Expr * transformAssignedExpr(ParseState *pstate, Expr *expr, ParseExprKind exprKind, const char *colname, int attrno, List *indirection, int location)
Definition: parse_target.c:455
List * transformExpressionList(ParseState *pstate, List *exprlist, ParseExprKind exprKind, bool allowDefault)
Definition: parse_target.c:220
Node * transformAssignmentIndirection(ParseState *pstate, Node *basenode, const char *targetName, bool targetIsSubscripting, Oid targetTypeId, int32 targetTypMod, Oid targetCollation, List *indirection, ListCell *indirection_cell, Node *rhs, CoercionContext ccontext, int location)
Definition: parse_target.c:686
void updateTargetListEntry(ParseState *pstate, TargetEntry *tle, char *colname, int attrno, List *indirection, int location)
Definition: parse_target.c:622
List * transformTargetList(ParseState *pstate, List *targetlist, ParseExprKind exprKind)
Definition: parse_target.c:121
void resolveTargetListUnknowns(ParseState *pstate, List *targetlist)
Definition: parse_target.c:288
void markTargetListOrigins(ParseState *pstate, List *targetlist)
Definition: parse_target.c:318
List * checkInsertTargets(ParseState *pstate, List *cols, List **attrnos)
#define ISCOMPLEX(typeid)
Definition: parse_type.h:59
#define CURSOR_OPT_INSENSITIVE
Definition: parsenodes.h:3310
#define CURSOR_OPT_SCROLL
Definition: parsenodes.h:3308
#define ACL_DELETE
Definition: parsenodes.h:79
@ SETOP_INTERSECT
Definition: parsenodes.h:2120
@ SETOP_UNION
Definition: parsenodes.h:2119
@ SETOP_NONE
Definition: parsenodes.h:2118
uint64 AclMode
Definition: parsenodes.h:74
#define ACL_INSERT
Definition: parsenodes.h:76
#define ACL_UPDATE
Definition: parsenodes.h:78
@ QSRC_ORIGINAL
Definition: parsenodes.h:36
@ RTE_JOIN
Definition: parsenodes.h:1019
@ RTE_CTE
Definition: parsenodes.h:1023
@ RTE_NAMEDTUPLESTORE
Definition: parsenodes.h:1024
@ RTE_VALUES
Definition: parsenodes.h:1022
@ RTE_SUBQUERY
Definition: parsenodes.h:1018
@ RTE_FUNCTION
Definition: parsenodes.h:1020
@ RTE_TABLEFUNC
Definition: parsenodes.h:1021
@ RTE_RELATION
Definition: parsenodes.h:1017
@ OBJECT_MATVIEW
Definition: parsenodes.h:2291
@ OBJECT_TABLE
Definition: parsenodes.h:2309
#define CURSOR_OPT_HOLD
Definition: parsenodes.h:3312
#define ACL_SELECT_FOR_UPDATE
Definition: parsenodes.h:94
#define CURSOR_OPT_ASENSITIVE
Definition: parsenodes.h:3311
#define CURSOR_OPT_NO_SCROLL
Definition: parsenodes.h:3309
static OnConflictExpr * transformOnConflictClause(ParseState *pstate, OnConflictClause *onConflictClause)
Definition: analyze.c:1209
static Query * transformOptionalSelectInto(ParseState *pstate, Node *parseTree)
Definition: analyze.c:357
static void transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc, bool pushedDown)
Definition: analyze.c:3394
static void setQueryLocationAndLength(ParseState *pstate, Query *qry, Node *parseTree)
Definition: analyze.c:259
static Query * transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
Definition: analyze.c:599
void CheckSelectLocking(Query *qry, LockClauseStrength strength)
Definition: analyze.c:3330
SortGroupClause * makeSortGroupClauseForSetOp(Oid rescoltype, bool require_hash)
Definition: analyze.c:2047
static Node * transformSetOperationTree(ParseState *pstate, SelectStmt *stmt, bool isTopLevel, List **targetlist)
Definition: analyze.c:2095
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition: analyze.c:186
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition: analyze.c:576
List * transformInsertRow(ParseState *pstate, List *exprlist, List *stmtcols, List *icolumns, List *attrnos, bool strip_indirection)
Definition: analyze.c:1099
void applyLockingClause(Query *qry, Index rtindex, LockClauseStrength strength, LockWaitPolicy waitPolicy, bool pushedDown)
Definition: analyze.c:3621
static void determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
Definition: analyze.c:2426
static Query * transformReturnStmt(ParseState *pstate, ReturnStmt *stmt)
Definition: analyze.c:2480
static Query * transformPLAssignStmt(ParseState *pstate, PLAssignStmt *stmt)
Definition: analyze.c:2711
static Query * transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
Definition: analyze.c:3105
post_parse_analyze_hook_type post_parse_analyze_hook
Definition: analyze.c:59
static Query * transformCallStmt(ParseState *pstate, CallStmt *stmt)
Definition: analyze.c:3180
List * transformUpdateTargetList(ParseState *pstate, List *origTlist)
Definition: analyze.c:2577
static Query * transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1790
List * transformReturningList(ParseState *pstate, List *returningList, ParseExprKind exprKind)
Definition: analyze.c:2652
Query * transformTopLevelStmt(ParseState *pstate, RawStmt *parseTree)
Definition: analyze.c:332
const char * LCS_asString(LockClauseStrength strength)
Definition: analyze.c:3305
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:105
static Query * transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
Definition: analyze.c:2511
static Query * transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1428
Query * parse_sub_analyze(Node *parseTree, ParseState *parentParseState, CommonTableExpr *parentCTE, bool locked_from_parent, bool resolve_unknowns)
Definition: analyze.c:222
static Query * transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
Definition: analyze.c:3053
List * BuildOnConflictExcludedTargetlist(Relation targetrel, Index exclRelIndex)
Definition: analyze.c:1316
static int count_rowexpr_columns(ParseState *pstate, Node *expr)
Definition: analyze.c:1386
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition: analyze.c:145
bool stmt_requires_parse_analysis(RawStmt *parseTree)
Definition: analyze.c:532
static Query * transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
Definition: analyze.c:2960
static Query * transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
Definition: analyze.c:671
static Query * transformValuesClause(ParseState *pstate, SelectStmt *stmt)
Definition: analyze.c:1571
Query * transformStmt(ParseState *pstate, Node *parseTree)
Definition: analyze.c:396
#define rt_fetch(rangetable_index, rangetable)
Definition: parsetree.h:31
int16 attnum
Definition: pg_attribute.h:74
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define lfirst(lc)
Definition: pg_list.h:172
#define llast(l)
Definition: pg_list.h:198
#define lfirst_node(type, lc)
Definition: pg_list.h:176
static int list_length(const List *l)
Definition: pg_list.h:152
#define linitial_node(type, l)
Definition: pg_list.h:181
#define NIL
Definition: pg_list.h:68
#define forboth(cell1, list1, cell2, list2)
Definition: pg_list.h:518
#define lfirst_int(lc)
Definition: pg_list.h:173
#define list_make1(x1)
Definition: pg_list.h:212
#define forthree(cell1, list1, cell2, list2, cell3, list3)
Definition: pg_list.h:563
static void * list_nth(const List *list, int n)
Definition: pg_list.h:299
#define linitial(l)
Definition: pg_list.h:178
#define forfour(cell1, list1, cell2, list2, cell3, list3, cell4, list4)
Definition: pg_list.h:575
static ListCell * list_head(const List *l)
Definition: pg_list.h:128
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:343
#define lfirst_oid(lc)
Definition: pg_list.h:174
#define list_make2(x1, x2)
Definition: pg_list.h:214
#define ERRCODE_UNDEFINED_TABLE
Definition: pgbench.c:78
#define snprintf
Definition: port.h:238
uintptr_t Datum
Definition: postgres.h:64
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
@ COERCE_IMPLICIT_CAST
Definition: primnodes.h:736
@ COERCION_PLPGSQL
Definition: primnodes.h:716
static bool IsQueryIdEnabled(void)
Definition: queryjumble.h:77
JumbleState * JumbleQuery(Query *query)
tree context
Definition: radixtree.h:1837
#define RelationGetNumberOfAttributes(relation)
Definition: rel.h:511
#define RelationGetRelationName(relation)
Definition: rel.h:539
void check_stack_depth(void)
Definition: stack_depth.c:95
char * aliasname
Definition: primnodes.h:50
ParseLoc location
Definition: parsenodes.h:297
List * fields
Definition: parsenodes.h:296
IntoClause * into
Definition: parsenodes.h:3920
ObjectType objtype
Definition: parsenodes.h:3921
char * defname
Definition: parsenodes.h:817
List * newvals
Definition: primnodes.h:1160
Oid funcid
Definition: primnodes.h:750
List * args
Definition: primnodes.h:768
Definition: pg_list.h:54
List * lockedRels
Definition: parsenodes.h:836
LockClauseStrength strength
Definition: parsenodes.h:837
LockWaitPolicy waitPolicy
Definition: parsenodes.h:838
Definition: nodes.h:129
OnConflictAction action
Definition: parsenodes.h:1624
List * arbiterElems
Definition: primnodes.h:2327
OnConflictAction action
Definition: primnodes.h:2324
List * onConflictSet
Definition: primnodes.h:2333
List * exclRelTlist
Definition: primnodes.h:2336
Node * onConflictWhere
Definition: primnodes.h:2334
Node * arbiterWhere
Definition: primnodes.h:2329
AttrNumber p_varattno
Definition: parse_node.h:341
AttrNumber p_varattnosyn
Definition: parse_node.h:346
RangeTblEntry * p_rte
Definition: parse_node.h:306
RTEPermissionInfo * p_perminfo
Definition: parse_node.h:308
bool p_hasTargetSRFs
Definition: parse_node.h:244
ParseLoc p_stmt_location
Definition: parse_node.h:210
List * p_ctenamespace
Definition: parse_node.h:222
bool p_hasWindowFuncs
Definition: parse_node.h:243
ParseNamespaceItem * p_target_nsitem
Definition: parse_node.h:226
ParseExprKind p_expr_kind
Definition: parse_node.h:230
bool p_locked_from_parent
Definition: parse_node.h:234
ParseParamRefHook p_paramref_hook
Definition: parse_node.h:256
List * p_nullingrels
Definition: parse_node.h:216
ParseLoc p_stmt_len
Definition: parse_node.h:211
List * p_namespace
Definition: parse_node.h:219
bool p_is_insert
Definition: parse_node.h:228
QueryEnvironment * p_queryEnv
Definition: parse_node.h:239
const char * p_sourcetext
Definition: parse_node.h:209
List * p_windowdefs
Definition: parse_node.h:229
bool p_resolve_unknowns
Definition: parse_node.h:236
int p_next_resno
Definition: parse_node.h:231
bool p_hasModifyingCTE
Definition: parse_node.h:246
List * p_rteperminfos
Definition: parse_node.h:213
List * p_joinexprs
Definition: parse_node.h:215
Relation p_target_relation
Definition: parse_node.h:225
CommonTableExpr * p_parent_cte
Definition: parse_node.h:224
bool p_hasSubLinks
Definition: parse_node.h:245
Node * p_last_srf
Definition: parse_node.h:248
List * p_joinlist
Definition: parse_node.h:217
List * p_locking_clause
Definition: parse_node.h:233
List * p_rtable
Definition: parse_node.h:212
bool p_hasAggs
Definition: parse_node.h:242
List * rowMarks
Definition: parsenodes.h:219
bool groupDistinct
Definition: parsenodes.h:203
Node * limitCount
Definition: parsenodes.h:216
FromExpr * jointree
Definition: parsenodes.h:177
List * returningList
Definition: parsenodes.h:200
Node * setOperations
Definition: parsenodes.h:221
List * cteList
Definition: parsenodes.h:168
List * groupClause
Definition: parsenodes.h:202
Node * havingQual
Definition: parsenodes.h:207
List * rtable
Definition: parsenodes.h:170
Node * limitOffset
Definition: parsenodes.h:215
CmdType commandType
Definition: parsenodes.h:121
LimitOption limitOption
Definition: parsenodes.h:217
Node * utilityStmt
Definition: parsenodes.h:136
List * windowClause
Definition: parsenodes.h:209
List * targetList
Definition: parsenodes.h:193
List * groupingSets
Definition: parsenodes.h:205
List * distinctClause
Definition: parsenodes.h:211
List * sortClause
Definition: parsenodes.h:213
ParseLoc stmt_location
Definition: parsenodes.h:240
AclMode requiredPerms
Definition: parsenodes.h:1291
Bitmapset * updatedCols
Definition: parsenodes.h:1295
Query * subquery
Definition: parsenodes.h:1104
RTEKind rtekind
Definition: parsenodes.h:1047
char * relname
Definition: primnodes.h:82
char * catalogname
Definition: primnodes.h:76
ParseLoc location
Definition: primnodes.h:94
char * schemaname
Definition: primnodes.h:79
ParseLoc stmt_location
Definition: parsenodes.h:2023
ParseLoc stmt_len
Definition: parsenodes.h:2024
Node * stmt
Definition: parsenodes.h:2022
TupleDesc rd_att
Definition: rel.h:112
Form_pg_class rd_rel
Definition: rel.h:111
ParseLoc location
Definition: parsenodes.h:522
List * indirection
Definition: parsenodes.h:520
char * name
Definition: parsenodes.h:519
LockClauseStrength strength
Definition: parsenodes.h:1580
LockWaitPolicy waitPolicy
Definition: parsenodes.h:1581
LimitOption limitOption
Definition: parsenodes.h:2159
List * sortClause
Definition: parsenodes.h:2156
List * targetList
Definition: parsenodes.h:2134
IntoClause * intoClause
Definition: parsenodes.h:2133
Node * limitOffset
Definition: parsenodes.h:2157
List * fromClause
Definition: parsenodes.h:2135
List * groupClause
Definition: parsenodes.h:2137
Node * havingClause
Definition: parsenodes.h:2139
List * lockingClause
Definition: parsenodes.h:2160
Node * limitCount
Definition: parsenodes.h:2158
List * windowClause
Definition: parsenodes.h:2140
List * distinctClause
Definition: parsenodes.h:2131
List * valuesLists
Definition: parsenodes.h:2150
struct SelectStmt * larg
Definition: parsenodes.h:2168
Node * whereClause
Definition: parsenodes.h:2136
SetOperation op
Definition: parsenodes.h:2166
WithClause * withClause
Definition: parsenodes.h:2161
SetOperation op
Definition: parsenodes.h:2198
ParseLoc location
Definition: primnodes.h:2078
Index tleSortGroupRef
Definition: parsenodes.h:1438
Definition: value.h:64
Expr * refassgnexpr
Definition: primnodes.h:703
Expr * expr
Definition: primnodes.h:2190
AttrNumber resno
Definition: primnodes.h:2192
Definition: primnodes.h:248
ParseLoc location
Definition: primnodes.h:293
AttrNumber varattno
Definition: primnodes.h:260
int varno
Definition: primnodes.h:255
Index varlevelsup
Definition: primnodes.h:280
bool recursive
Definition: parsenodes.h:1596
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:269
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:221
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:600
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition: tupdesc.h:152
String * makeString(char *str)
Definition: value.c:63
bool contain_vars_of_level(Node *node, int levelsup)
Definition: var.c:443
int locate_var_of_level(Node *node, int levelsup)
Definition: var.c:511
const char * name