]> granicus.if.org Git - postgresql/blob - src/backend/parser/analyze.c
Reduce hash size for compute_array_stats, compute_tsvector_stats.
[postgresql] / src / backend / parser / analyze.c
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-2012, 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_type.h"
29 #include "nodes/makefuncs.h"
30 #include "nodes/nodeFuncs.h"
31 #include "optimizer/var.h"
32 #include "parser/analyze.h"
33 #include "parser/parse_agg.h"
34 #include "parser/parse_clause.h"
35 #include "parser/parse_coerce.h"
36 #include "parser/parse_collate.h"
37 #include "parser/parse_cte.h"
38 #include "parser/parse_oper.h"
39 #include "parser/parse_param.h"
40 #include "parser/parse_relation.h"
41 #include "parser/parse_target.h"
42 #include "parser/parsetree.h"
43 #include "rewrite/rewriteManip.h"
44 #include "utils/rel.h"
45
46
47 /* Hook for plugins to get control at end of parse analysis */
48 post_parse_analyze_hook_type post_parse_analyze_hook = NULL;
49
50 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
51 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt);
52 static List *transformInsertRow(ParseState *pstate, List *exprlist,
53                                    List *stmtcols, List *icolumns, List *attrnos);
54 static int      count_rowexpr_columns(ParseState *pstate, Node *expr);
55 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
56 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
57 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
58 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
59                                                   bool isTopLevel, List **targetlist);
60 static void determineRecursiveColTypes(ParseState *pstate,
61                                                    Node *larg, List *nrtargetlist);
62 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
63 static List *transformReturningList(ParseState *pstate, List *returningList);
64 static Query *transformDeclareCursorStmt(ParseState *pstate,
65                                                    DeclareCursorStmt *stmt);
66 static Query *transformExplainStmt(ParseState *pstate,
67                                          ExplainStmt *stmt);
68 static Query *transformCreateTableAsStmt(ParseState *pstate,
69                                                    CreateTableAsStmt *stmt);
70 static void transformLockingClause(ParseState *pstate, Query *qry,
71                                            LockingClause *lc, bool pushedDown);
72
73
74 /*
75  * parse_analyze
76  *              Analyze a raw parse tree and transform it to Query form.
77  *
78  * Optionally, information about $n parameter types can be supplied.
79  * References to $n indexes not defined by paramTypes[] are disallowed.
80  *
81  * The result is a Query node.  Optimizable statements require considerable
82  * transformation, while utility-type statements are simply hung off
83  * a dummy CMD_UTILITY Query node.
84  */
85 Query *
86 parse_analyze(Node *parseTree, const char *sourceText,
87                           Oid *paramTypes, int numParams)
88 {
89         ParseState *pstate = make_parsestate(NULL);
90         Query      *query;
91
92         Assert(sourceText != NULL); /* required as of 8.4 */
93
94         pstate->p_sourcetext = sourceText;
95
96         if (numParams > 0)
97                 parse_fixed_parameters(pstate, paramTypes, numParams);
98
99         query = transformTopLevelStmt(pstate, parseTree);
100
101         if (post_parse_analyze_hook)
102                 (*post_parse_analyze_hook) (pstate, query);
103
104         free_parsestate(pstate);
105
106         return query;
107 }
108
109 /*
110  * parse_analyze_varparams
111  *
112  * This variant is used when it's okay to deduce information about $n
113  * symbol datatypes from context.  The passed-in paramTypes[] array can
114  * be modified or enlarged (via repalloc).
115  */
116 Query *
117 parse_analyze_varparams(Node *parseTree, const char *sourceText,
118                                                 Oid **paramTypes, int *numParams)
119 {
120         ParseState *pstate = make_parsestate(NULL);
121         Query      *query;
122
123         Assert(sourceText != NULL); /* required as of 8.4 */
124
125         pstate->p_sourcetext = sourceText;
126
127         parse_variable_parameters(pstate, paramTypes, numParams);
128
129         query = transformTopLevelStmt(pstate, parseTree);
130
131         /* make sure all is well with parameter types */
132         check_variable_parameters(pstate, query);
133
134         if (post_parse_analyze_hook)
135                 (*post_parse_analyze_hook) (pstate, query);
136
137         free_parsestate(pstate);
138
139         return query;
140 }
141
142 /*
143  * parse_sub_analyze
144  *              Entry point for recursively analyzing a sub-statement.
145  */
146 Query *
147 parse_sub_analyze(Node *parseTree, ParseState *parentParseState,
148                                   CommonTableExpr *parentCTE,
149                                   bool locked_from_parent)
150 {
151         ParseState *pstate = make_parsestate(parentParseState);
152         Query      *query;
153
154         pstate->p_parent_cte = parentCTE;
155         pstate->p_locked_from_parent = locked_from_parent;
156
157         query = transformStmt(pstate, parseTree);
158
159         free_parsestate(pstate);
160
161         return query;
162 }
163
164 /*
165  * transformTopLevelStmt -
166  *        transform a Parse tree into a Query tree.
167  *
168  * The only thing we do here that we don't do in transformStmt() is to
169  * convert SELECT ... INTO into CREATE TABLE AS.  Since utility statements
170  * aren't allowed within larger statements, this is only allowed at the top
171  * of the parse tree, and so we only try it before entering the recursive
172  * transformStmt() processing.
173  */
174 Query *
175 transformTopLevelStmt(ParseState *pstate, Node *parseTree)
176 {
177         if (IsA(parseTree, SelectStmt))
178         {
179                 SelectStmt *stmt = (SelectStmt *) parseTree;
180
181                 /* If it's a set-operation tree, drill down to leftmost SelectStmt */
182                 while (stmt && stmt->op != SETOP_NONE)
183                         stmt = stmt->larg;
184                 Assert(stmt && IsA(stmt, SelectStmt) && stmt->larg == NULL);
185
186                 if (stmt->intoClause)
187                 {
188                         CreateTableAsStmt *ctas = makeNode(CreateTableAsStmt);
189
190                         ctas->query = parseTree;
191                         ctas->into = stmt->intoClause;
192                         ctas->is_select_into = true;
193
194                         /*
195                          * Remove the intoClause from the SelectStmt.  This makes it safe
196                          * for transformSelectStmt to complain if it finds intoClause set
197                          * (implying that the INTO appeared in a disallowed place).
198                          */
199                         stmt->intoClause = NULL;
200
201                         parseTree = (Node *) ctas;
202                 }
203         }
204
205         return transformStmt(pstate, parseTree);
206 }
207
208 /*
209  * transformStmt -
210  *        recursively transform a Parse tree into a Query tree.
211  */
212 Query *
213 transformStmt(ParseState *pstate, Node *parseTree)
214 {
215         Query      *result;
216
217         switch (nodeTag(parseTree))
218         {
219                         /*
220                          * Optimizable statements
221                          */
222                 case T_InsertStmt:
223                         result = transformInsertStmt(pstate, (InsertStmt *) parseTree);
224                         break;
225
226                 case T_DeleteStmt:
227                         result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
228                         break;
229
230                 case T_UpdateStmt:
231                         result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
232                         break;
233
234                 case T_SelectStmt:
235                         {
236                                 SelectStmt *n = (SelectStmt *) parseTree;
237
238                                 if (n->valuesLists)
239                                         result = transformValuesClause(pstate, n);
240                                 else if (n->op == SETOP_NONE)
241                                         result = transformSelectStmt(pstate, n);
242                                 else
243                                         result = transformSetOperationStmt(pstate, n);
244                         }
245                         break;
246
247                         /*
248                          * Special cases
249                          */
250                 case T_DeclareCursorStmt:
251                         result = transformDeclareCursorStmt(pstate,
252                                                                                         (DeclareCursorStmt *) parseTree);
253                         break;
254
255                 case T_ExplainStmt:
256                         result = transformExplainStmt(pstate,
257                                                                                   (ExplainStmt *) parseTree);
258                         break;
259
260                 case T_CreateTableAsStmt:
261                         result = transformCreateTableAsStmt(pstate,
262                                                                                         (CreateTableAsStmt *) parseTree);
263                         break;
264
265                 default:
266
267                         /*
268                          * other statements don't require any transformation; just return
269                          * the original parsetree with a Query node plastered on top.
270                          */
271                         result = makeNode(Query);
272                         result->commandType = CMD_UTILITY;
273                         result->utilityStmt = (Node *) parseTree;
274                         break;
275         }
276
277         /* Mark as original query until we learn differently */
278         result->querySource = QSRC_ORIGINAL;
279         result->canSetTag = true;
280
281         return result;
282 }
283
284 /*
285  * analyze_requires_snapshot
286  *              Returns true if a snapshot must be set before doing parse analysis
287  *              on the given raw parse tree.
288  *
289  * Classification here should match transformStmt(); but we also have to
290  * allow a NULL input (for Parse/Bind of an empty query string).
291  */
292 bool
293 analyze_requires_snapshot(Node *parseTree)
294 {
295         bool            result;
296
297         if (parseTree == NULL)
298                 return false;
299
300         switch (nodeTag(parseTree))
301         {
302                         /*
303                          * Optimizable statements
304                          */
305                 case T_InsertStmt:
306                 case T_DeleteStmt:
307                 case T_UpdateStmt:
308                 case T_SelectStmt:
309                         result = true;
310                         break;
311
312                         /*
313                          * Special cases
314                          */
315                 case T_DeclareCursorStmt:
316                         /* yes, because it's analyzed just like SELECT */
317                         result = true;
318                         break;
319
320                 case T_ExplainStmt:
321                 case T_CreateTableAsStmt:
322                         /* yes, because we must analyze the contained statement */
323                         result = true;
324                         break;
325
326                 default:
327                         /* other utility statements don't have any real parse analysis */
328                         result = false;
329                         break;
330         }
331
332         return result;
333 }
334
335 /*
336  * transformDeleteStmt -
337  *        transforms a Delete Statement
338  */
339 static Query *
340 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
341 {
342         Query      *qry = makeNode(Query);
343         Node       *qual;
344
345         qry->commandType = CMD_DELETE;
346
347         /* process the WITH clause independently of all else */
348         if (stmt->withClause)
349         {
350                 qry->hasRecursive = stmt->withClause->recursive;
351                 qry->cteList = transformWithClause(pstate, stmt->withClause);
352                 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
353         }
354
355         /* set up range table with just the result rel */
356         qry->resultRelation = setTargetTable(pstate, stmt->relation,
357                                                                   interpretInhOption(stmt->relation->inhOpt),
358                                                                                  true,
359                                                                                  ACL_DELETE);
360
361         qry->distinctClause = NIL;
362
363         /*
364          * The USING clause is non-standard SQL syntax, and is equivalent in
365          * functionality to the FROM list that can be specified for UPDATE. The
366          * USING keyword is used rather than FROM because FROM is already a
367          * keyword in the DELETE syntax.
368          */
369         transformFromClause(pstate, stmt->usingClause);
370
371         qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
372
373         qry->returningList = transformReturningList(pstate, stmt->returningList);
374
375         /* done building the range table and jointree */
376         qry->rtable = pstate->p_rtable;
377         qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
378
379         qry->hasSubLinks = pstate->p_hasSubLinks;
380         qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
381         if (pstate->p_hasWindowFuncs)
382                 parseCheckWindowFuncs(pstate, qry);
383         qry->hasAggs = pstate->p_hasAggs;
384         if (pstate->p_hasAggs)
385                 parseCheckAggregates(pstate, qry);
386
387         assign_query_collations(pstate, qry);
388
389         return qry;
390 }
391
392 /*
393  * transformInsertStmt -
394  *        transform an Insert Statement
395  */
396 static Query *
397 transformInsertStmt(ParseState *pstate, InsertStmt *stmt)
398 {
399         Query      *qry = makeNode(Query);
400         SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
401         List       *exprList = NIL;
402         bool            isGeneralSelect;
403         List       *sub_rtable;
404         List       *sub_relnamespace;
405         List       *sub_varnamespace;
406         List       *icolumns;
407         List       *attrnos;
408         RangeTblEntry *rte;
409         RangeTblRef *rtr;
410         ListCell   *icols;
411         ListCell   *attnos;
412         ListCell   *lc;
413
414         /* There can't be any outer WITH to worry about */
415         Assert(pstate->p_ctenamespace == NIL);
416
417         qry->commandType = CMD_INSERT;
418         pstate->p_is_insert = true;
419
420         /* process the WITH clause independently of all else */
421         if (stmt->withClause)
422         {
423                 qry->hasRecursive = stmt->withClause->recursive;
424                 qry->cteList = transformWithClause(pstate, stmt->withClause);
425                 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
426         }
427
428         /*
429          * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
430          * VALUES list, or general SELECT input.  We special-case VALUES, both for
431          * efficiency and so we can handle DEFAULT specifications.
432          *
433          * The grammar allows attaching ORDER BY, LIMIT, FOR UPDATE, or WITH to a
434          * VALUES clause.  If we have any of those, treat it as a general SELECT;
435          * so it will work, but you can't use DEFAULT items together with those.
436          */
437         isGeneralSelect = (selectStmt && (selectStmt->valuesLists == NIL ||
438                                                                           selectStmt->sortClause != NIL ||
439                                                                           selectStmt->limitOffset != NULL ||
440                                                                           selectStmt->limitCount != NULL ||
441                                                                           selectStmt->lockingClause != NIL ||
442                                                                           selectStmt->withClause != NULL));
443
444         /*
445          * If a non-nil rangetable/namespace was passed in, and we are doing
446          * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
447          * SELECT.      This can only happen if we are inside a CREATE RULE, and in
448          * that case we want the rule's OLD and NEW rtable entries to appear as
449          * part of the SELECT's rtable, not as outer references for it.  (Kluge!)
450          * The SELECT's joinlist is not affected however.  We must do this before
451          * adding the target table to the INSERT's rtable.
452          */
453         if (isGeneralSelect)
454         {
455                 sub_rtable = pstate->p_rtable;
456                 pstate->p_rtable = NIL;
457                 sub_relnamespace = pstate->p_relnamespace;
458                 pstate->p_relnamespace = NIL;
459                 sub_varnamespace = pstate->p_varnamespace;
460                 pstate->p_varnamespace = NIL;
461         }
462         else
463         {
464                 sub_rtable = NIL;               /* not used, but keep compiler quiet */
465                 sub_relnamespace = NIL;
466                 sub_varnamespace = NIL;
467         }
468
469         /*
470          * Must get write lock on INSERT target table before scanning SELECT, else
471          * we will grab the wrong kind of initial lock if the target table is also
472          * mentioned in the SELECT part.  Note that the target table is not added
473          * to the joinlist or namespace.
474          */
475         qry->resultRelation = setTargetTable(pstate, stmt->relation,
476                                                                                  false, false, ACL_INSERT);
477
478         /* Validate stmt->cols list, or build default list if no list given */
479         icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
480         Assert(list_length(icolumns) == list_length(attrnos));
481
482         /*
483          * Determine which variant of INSERT we have.
484          */
485         if (selectStmt == NULL)
486         {
487                 /*
488                  * We have INSERT ... DEFAULT VALUES.  We can handle this case by
489                  * emitting an empty targetlist --- all columns will be defaulted when
490                  * the planner expands the targetlist.
491                  */
492                 exprList = NIL;
493         }
494         else if (isGeneralSelect)
495         {
496                 /*
497                  * We make the sub-pstate a child of the outer pstate so that it can
498                  * see any Param definitions supplied from above.  Since the outer
499                  * pstate's rtable and namespace are presently empty, there are no
500                  * side-effects of exposing names the sub-SELECT shouldn't be able to
501                  * see.
502                  */
503                 ParseState *sub_pstate = make_parsestate(pstate);
504                 Query      *selectQuery;
505
506                 /*
507                  * Process the source SELECT.
508                  *
509                  * It is important that this be handled just like a standalone SELECT;
510                  * otherwise the behavior of SELECT within INSERT might be different
511                  * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
512                  * bugs of just that nature...)
513                  */
514                 sub_pstate->p_rtable = sub_rtable;
515                 sub_pstate->p_joinexprs = NIL;  /* sub_rtable has no joins */
516                 sub_pstate->p_relnamespace = sub_relnamespace;
517                 sub_pstate->p_varnamespace = sub_varnamespace;
518
519                 selectQuery = transformStmt(sub_pstate, stmt->selectStmt);
520
521                 free_parsestate(sub_pstate);
522
523                 /* The grammar should have produced a SELECT */
524                 if (!IsA(selectQuery, Query) ||
525                         selectQuery->commandType != CMD_SELECT ||
526                         selectQuery->utilityStmt != NULL)
527                         elog(ERROR, "unexpected non-SELECT command in INSERT ... SELECT");
528
529                 /*
530                  * Make the source be a subquery in the INSERT's rangetable, and add
531                  * it to the INSERT's joinlist.
532                  */
533                 rte = addRangeTableEntryForSubquery(pstate,
534                                                                                         selectQuery,
535                                                                                         makeAlias("*SELECT*", NIL),
536                                                                                         false);
537                 rtr = makeNode(RangeTblRef);
538                 /* assume new rte is at end */
539                 rtr->rtindex = list_length(pstate->p_rtable);
540                 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
541                 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
542
543                 /*----------
544                  * Generate an expression list for the INSERT that selects all the
545                  * non-resjunk columns from the subquery.  (INSERT's tlist must be
546                  * separate from the subquery's tlist because we may add columns,
547                  * insert datatype coercions, etc.)
548                  *
549                  * HACK: unknown-type constants and params in the SELECT's targetlist
550                  * are copied up as-is rather than being referenced as subquery
551                  * outputs.  This is to ensure that when we try to coerce them to
552                  * the target column's datatype, the right things happen (see
553                  * special cases in coerce_type).  Otherwise, this fails:
554                  *              INSERT INTO foo SELECT 'bar', ... FROM baz
555                  *----------
556                  */
557                 exprList = NIL;
558                 foreach(lc, selectQuery->targetList)
559                 {
560                         TargetEntry *tle = (TargetEntry *) lfirst(lc);
561                         Expr       *expr;
562
563                         if (tle->resjunk)
564                                 continue;
565                         if (tle->expr &&
566                                 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
567                                 exprType((Node *) tle->expr) == UNKNOWNOID)
568                                 expr = tle->expr;
569                         else
570                         {
571                                 Var                *var = makeVarFromTargetEntry(rtr->rtindex, tle);
572
573                                 var->location = exprLocation((Node *) tle->expr);
574                                 expr = (Expr *) var;
575                         }
576                         exprList = lappend(exprList, expr);
577                 }
578
579                 /* Prepare row for assignment to target table */
580                 exprList = transformInsertRow(pstate, exprList,
581                                                                           stmt->cols,
582                                                                           icolumns, attrnos);
583         }
584         else if (list_length(selectStmt->valuesLists) > 1)
585         {
586                 /*
587                  * Process INSERT ... VALUES with multiple VALUES sublists. We
588                  * generate a VALUES RTE holding the transformed expression lists, and
589                  * build up a targetlist containing Vars that reference the VALUES
590                  * RTE.
591                  */
592                 List       *exprsLists = NIL;
593                 List       *collations = NIL;
594                 int                     sublist_length = -1;
595                 int                     i;
596
597                 Assert(selectStmt->intoClause == NULL);
598
599                 foreach(lc, selectStmt->valuesLists)
600                 {
601                         List       *sublist = (List *) lfirst(lc);
602
603                         /* Do basic expression transformation (same as a ROW() expr) */
604                         sublist = transformExpressionList(pstate, sublist);
605
606                         /*
607                          * All the sublists must be the same length, *after*
608                          * transformation (which might expand '*' into multiple items).
609                          * The VALUES RTE can't handle anything different.
610                          */
611                         if (sublist_length < 0)
612                         {
613                                 /* Remember post-transformation length of first sublist */
614                                 sublist_length = list_length(sublist);
615                         }
616                         else if (sublist_length != list_length(sublist))
617                         {
618                                 ereport(ERROR,
619                                                 (errcode(ERRCODE_SYNTAX_ERROR),
620                                                  errmsg("VALUES lists must all be the same length"),
621                                                  parser_errposition(pstate,
622                                                                                         exprLocation((Node *) sublist))));
623                         }
624
625                         /* Prepare row for assignment to target table */
626                         sublist = transformInsertRow(pstate, sublist,
627                                                                                  stmt->cols,
628                                                                                  icolumns, attrnos);
629
630                         /*
631                          * We must assign collations now because assign_query_collations
632                          * doesn't process rangetable entries.  We just assign all the
633                          * collations independently in each row, and don't worry about
634                          * whether they are consistent vertically.      The outer INSERT query
635                          * isn't going to care about the collations of the VALUES columns,
636                          * so it's not worth the effort to identify a common collation for
637                          * each one here.  (But note this does have one user-visible
638                          * consequence: INSERT ... VALUES won't complain about conflicting
639                          * explicit COLLATEs in a column, whereas the same VALUES
640                          * construct in another context would complain.)
641                          */
642                         assign_list_collations(pstate, sublist);
643
644                         exprsLists = lappend(exprsLists, sublist);
645                 }
646
647                 /*
648                  * Although we don't really need collation info, let's just make sure
649                  * we provide a correctly-sized list in the VALUES RTE.
650                  */
651                 for (i = 0; i < sublist_length; i++)
652                         collations = lappend_oid(collations, InvalidOid);
653
654                 /*
655                  * There mustn't have been any table references in the expressions,
656                  * else strange things would happen, like Cartesian products of those
657                  * tables with the VALUES list ...
658                  */
659                 if (pstate->p_joinlist != NIL)
660                         ereport(ERROR,
661                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
662                                          errmsg("VALUES must not contain table references"),
663                                          parser_errposition(pstate,
664                                                           locate_var_of_level((Node *) exprsLists, 0))));
665
666                 /*
667                  * Another thing we can't currently support is NEW/OLD references in
668                  * rules --- seems we'd need something like SQL99's LATERAL construct
669                  * to ensure that the values would be available while evaluating the
670                  * VALUES RTE.  This is a shame.  FIXME
671                  */
672                 if (list_length(pstate->p_rtable) != 1 &&
673                         contain_vars_of_level((Node *) exprsLists, 0))
674                         ereport(ERROR,
675                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
676                                          errmsg("VALUES must not contain OLD or NEW references"),
677                                          errhint("Use SELECT ... UNION ALL ... instead."),
678                                          parser_errposition(pstate,
679                                                           locate_var_of_level((Node *) exprsLists, 0))));
680
681                 /*
682                  * Generate the VALUES RTE
683                  */
684                 rte = addRangeTableEntryForValues(pstate, exprsLists, collations,
685                                                                                   NULL, true);
686                 rtr = makeNode(RangeTblRef);
687                 /* assume new rte is at end */
688                 rtr->rtindex = list_length(pstate->p_rtable);
689                 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
690                 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
691
692                 /*
693                  * Generate list of Vars referencing the RTE
694                  */
695                 expandRTE(rte, rtr->rtindex, 0, -1, false, NULL, &exprList);
696         }
697         else
698         {
699                 /*----------
700                  * Process INSERT ... VALUES with a single VALUES sublist.
701                  * We treat this separately for efficiency and for historical
702                  * compatibility --- specifically, allowing table references,
703                  * such as
704                  *                      INSERT INTO foo VALUES(bar.*)
705                  *
706                  * The sublist is just computed directly as the Query's targetlist,
707                  * with no VALUES RTE.  So it works just like SELECT without FROM.
708                  *----------
709                  */
710                 List       *valuesLists = selectStmt->valuesLists;
711
712                 Assert(list_length(valuesLists) == 1);
713                 Assert(selectStmt->intoClause == NULL);
714
715                 /* Do basic expression transformation (same as a ROW() expr) */
716                 exprList = transformExpressionList(pstate,
717                                                                                    (List *) linitial(valuesLists));
718
719                 /* Prepare row for assignment to target table */
720                 exprList = transformInsertRow(pstate, exprList,
721                                                                           stmt->cols,
722                                                                           icolumns, attrnos);
723         }
724
725         /*
726          * Generate query's target list using the computed list of expressions.
727          * Also, mark all the target columns as needing insert permissions.
728          */
729         rte = pstate->p_target_rangetblentry;
730         qry->targetList = NIL;
731         icols = list_head(icolumns);
732         attnos = list_head(attrnos);
733         foreach(lc, exprList)
734         {
735                 Expr       *expr = (Expr *) lfirst(lc);
736                 ResTarget  *col;
737                 AttrNumber      attr_num;
738                 TargetEntry *tle;
739
740                 col = (ResTarget *) lfirst(icols);
741                 Assert(IsA(col, ResTarget));
742                 attr_num = (AttrNumber) lfirst_int(attnos);
743
744                 tle = makeTargetEntry(expr,
745                                                           attr_num,
746                                                           col->name,
747                                                           false);
748                 qry->targetList = lappend(qry->targetList, tle);
749
750                 rte->modifiedCols = bms_add_member(rte->modifiedCols,
751                                                           attr_num - FirstLowInvalidHeapAttributeNumber);
752
753                 icols = lnext(icols);
754                 attnos = lnext(attnos);
755         }
756
757         /*
758          * If we have a RETURNING clause, we need to add the target relation to
759          * the query namespace before processing it, so that Var references in
760          * RETURNING will work.  Also, remove any namespace entries added in a
761          * sub-SELECT or VALUES list.
762          */
763         if (stmt->returningList)
764         {
765                 pstate->p_relnamespace = NIL;
766                 pstate->p_varnamespace = NIL;
767                 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
768                                           false, true, true);
769                 qry->returningList = transformReturningList(pstate,
770                                                                                                         stmt->returningList);
771         }
772
773         /* done building the range table and jointree */
774         qry->rtable = pstate->p_rtable;
775         qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
776
777         qry->hasSubLinks = pstate->p_hasSubLinks;
778         /* aggregates not allowed (but subselects are okay) */
779         if (pstate->p_hasAggs)
780                 ereport(ERROR,
781                                 (errcode(ERRCODE_GROUPING_ERROR),
782                                  errmsg("cannot use aggregate function in VALUES"),
783                                  parser_errposition(pstate,
784                                                                         locate_agg_of_level((Node *) qry, 0))));
785         if (pstate->p_hasWindowFuncs)
786                 ereport(ERROR,
787                                 (errcode(ERRCODE_WINDOWING_ERROR),
788                                  errmsg("cannot use window function in VALUES"),
789                                  parser_errposition(pstate,
790                                                                         locate_windowfunc((Node *) qry))));
791
792         assign_query_collations(pstate, qry);
793
794         return qry;
795 }
796
797 /*
798  * Prepare an INSERT row for assignment to the target table.
799  *
800  * The row might be either a VALUES row, or variables referencing a
801  * sub-SELECT output.
802  */
803 static List *
804 transformInsertRow(ParseState *pstate, List *exprlist,
805                                    List *stmtcols, List *icolumns, List *attrnos)
806 {
807         List       *result;
808         ListCell   *lc;
809         ListCell   *icols;
810         ListCell   *attnos;
811
812         /*
813          * Check length of expr list.  It must not have more expressions than
814          * there are target columns.  We allow fewer, but only if no explicit
815          * columns list was given (the remaining columns are implicitly
816          * defaulted).  Note we must check this *after* transformation because
817          * that could expand '*' into multiple items.
818          */
819         if (list_length(exprlist) > list_length(icolumns))
820                 ereport(ERROR,
821                                 (errcode(ERRCODE_SYNTAX_ERROR),
822                                  errmsg("INSERT has more expressions than target columns"),
823                                  parser_errposition(pstate,
824                                                                         exprLocation(list_nth(exprlist,
825                                                                                                   list_length(icolumns))))));
826         if (stmtcols != NIL &&
827                 list_length(exprlist) < list_length(icolumns))
828         {
829                 /*
830                  * We can get here for cases like INSERT ... SELECT (a,b,c) FROM ...
831                  * where the user accidentally created a RowExpr instead of separate
832                  * columns.  Add a suitable hint if that seems to be the problem,
833                  * because the main error message is quite misleading for this case.
834                  * (If there's no stmtcols, you'll get something about data type
835                  * mismatch, which is less misleading so we don't worry about giving a
836                  * hint in that case.)
837                  */
838                 ereport(ERROR,
839                                 (errcode(ERRCODE_SYNTAX_ERROR),
840                                  errmsg("INSERT has more target columns than expressions"),
841                                  ((list_length(exprlist) == 1 &&
842                                    count_rowexpr_columns(pstate, linitial(exprlist)) ==
843                                    list_length(icolumns)) ?
844                                   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),
845                                  parser_errposition(pstate,
846                                                                         exprLocation(list_nth(icolumns,
847                                                                                                   list_length(exprlist))))));
848         }
849
850         /*
851          * Prepare columns for assignment to target table.
852          */
853         result = NIL;
854         icols = list_head(icolumns);
855         attnos = list_head(attrnos);
856         foreach(lc, exprlist)
857         {
858                 Expr       *expr = (Expr *) lfirst(lc);
859                 ResTarget  *col;
860
861                 col = (ResTarget *) lfirst(icols);
862                 Assert(IsA(col, ResTarget));
863
864                 expr = transformAssignedExpr(pstate, expr,
865                                                                          col->name,
866                                                                          lfirst_int(attnos),
867                                                                          col->indirection,
868                                                                          col->location);
869
870                 result = lappend(result, expr);
871
872                 icols = lnext(icols);
873                 attnos = lnext(attnos);
874         }
875
876         return result;
877 }
878
879 /*
880  * count_rowexpr_columns -
881  *        get number of columns contained in a ROW() expression;
882  *        return -1 if expression isn't a RowExpr or a Var referencing one.
883  *
884  * This is currently used only for hint purposes, so we aren't terribly
885  * tense about recognizing all possible cases.  The Var case is interesting
886  * because that's what we'll get in the INSERT ... SELECT (...) case.
887  */
888 static int
889 count_rowexpr_columns(ParseState *pstate, Node *expr)
890 {
891         if (expr == NULL)
892                 return -1;
893         if (IsA(expr, RowExpr))
894                 return list_length(((RowExpr *) expr)->args);
895         if (IsA(expr, Var))
896         {
897                 Var                *var = (Var *) expr;
898                 AttrNumber      attnum = var->varattno;
899
900                 if (attnum > 0 && var->vartype == RECORDOID)
901                 {
902                         RangeTblEntry *rte;
903
904                         rte = GetRTEByRangeTablePosn(pstate, var->varno, var->varlevelsup);
905                         if (rte->rtekind == RTE_SUBQUERY)
906                         {
907                                 /* Subselect-in-FROM: examine sub-select's output expr */
908                                 TargetEntry *ste = get_tle_by_resno(rte->subquery->targetList,
909                                                                                                         attnum);
910
911                                 if (ste == NULL || ste->resjunk)
912                                         return -1;
913                                 expr = (Node *) ste->expr;
914                                 if (IsA(expr, RowExpr))
915                                         return list_length(((RowExpr *) expr)->args);
916                         }
917                 }
918         }
919         return -1;
920 }
921
922
923 /*
924  * transformSelectStmt -
925  *        transforms a Select Statement
926  *
927  * Note: this covers only cases with no set operations and no VALUES lists;
928  * see below for the other cases.
929  */
930 static Query *
931 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
932 {
933         Query      *qry = makeNode(Query);
934         Node       *qual;
935         ListCell   *l;
936
937         qry->commandType = CMD_SELECT;
938
939         /* process the WITH clause independently of all else */
940         if (stmt->withClause)
941         {
942                 qry->hasRecursive = stmt->withClause->recursive;
943                 qry->cteList = transformWithClause(pstate, stmt->withClause);
944                 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
945         }
946
947         /* Complain if we get called from someplace where INTO is not allowed */
948         if (stmt->intoClause)
949                 ereport(ERROR,
950                                 (errcode(ERRCODE_SYNTAX_ERROR),
951                                  errmsg("SELECT ... INTO is not allowed here"),
952                                  parser_errposition(pstate,
953                                                                         exprLocation((Node *) stmt->intoClause))));
954
955         /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
956         pstate->p_locking_clause = stmt->lockingClause;
957
958         /* make WINDOW info available for window functions, too */
959         pstate->p_windowdefs = stmt->windowClause;
960
961         /* process the FROM clause */
962         transformFromClause(pstate, stmt->fromClause);
963
964         /* transform targetlist */
965         qry->targetList = transformTargetList(pstate, stmt->targetList);
966
967         /* mark column origins */
968         markTargetListOrigins(pstate, qry->targetList);
969
970         /* transform WHERE */
971         qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
972
973         /*
974          * Initial processing of HAVING clause is just like WHERE clause.
975          */
976         qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
977                                                                                    "HAVING");
978
979         /*
980          * Transform sorting/grouping stuff.  Do ORDER BY first because both
981          * transformGroupClause and transformDistinctClause need the results. Note
982          * that these functions can also change the targetList, so it's passed to
983          * them by reference.
984          */
985         qry->sortClause = transformSortClause(pstate,
986                                                                                   stmt->sortClause,
987                                                                                   &qry->targetList,
988                                                                                   true /* fix unknowns */ ,
989                                                                                   false /* allow SQL92 rules */ );
990
991         qry->groupClause = transformGroupClause(pstate,
992                                                                                         stmt->groupClause,
993                                                                                         &qry->targetList,
994                                                                                         qry->sortClause,
995                                                                                         false /* allow SQL92 rules */ );
996
997         if (stmt->distinctClause == NIL)
998         {
999                 qry->distinctClause = NIL;
1000                 qry->hasDistinctOn = false;
1001         }
1002         else if (linitial(stmt->distinctClause) == NULL)
1003         {
1004                 /* We had SELECT DISTINCT */
1005                 qry->distinctClause = transformDistinctClause(pstate,
1006                                                                                                           &qry->targetList,
1007                                                                                                           qry->sortClause,
1008                                                                                                           false);
1009                 qry->hasDistinctOn = false;
1010         }
1011         else
1012         {
1013                 /* We had SELECT DISTINCT ON */
1014                 qry->distinctClause = transformDistinctOnClause(pstate,
1015                                                                                                                 stmt->distinctClause,
1016                                                                                                                 &qry->targetList,
1017                                                                                                                 qry->sortClause);
1018                 qry->hasDistinctOn = true;
1019         }
1020
1021         /* transform LIMIT */
1022         qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1023                                                                                         "OFFSET");
1024         qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1025                                                                                    "LIMIT");
1026
1027         /* transform window clauses after we have seen all window functions */
1028         qry->windowClause = transformWindowDefinitions(pstate,
1029                                                                                                    pstate->p_windowdefs,
1030                                                                                                    &qry->targetList);
1031
1032         qry->rtable = pstate->p_rtable;
1033         qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1034
1035         qry->hasSubLinks = pstate->p_hasSubLinks;
1036         qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1037         if (pstate->p_hasWindowFuncs)
1038                 parseCheckWindowFuncs(pstate, qry);
1039         qry->hasAggs = pstate->p_hasAggs;
1040         if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1041                 parseCheckAggregates(pstate, qry);
1042
1043         foreach(l, stmt->lockingClause)
1044         {
1045                 transformLockingClause(pstate, qry,
1046                                                            (LockingClause *) lfirst(l), false);
1047         }
1048
1049         assign_query_collations(pstate, qry);
1050
1051         return qry;
1052 }
1053
1054 /*
1055  * transformValuesClause -
1056  *        transforms a VALUES clause that's being used as a standalone SELECT
1057  *
1058  * We build a Query containing a VALUES RTE, rather as if one had written
1059  *                      SELECT * FROM (VALUES ...) AS "*VALUES*"
1060  */
1061 static Query *
1062 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
1063 {
1064         Query      *qry = makeNode(Query);
1065         List       *exprsLists;
1066         List       *collations;
1067         List      **colexprs = NULL;
1068         int                     sublist_length = -1;
1069         RangeTblEntry *rte;
1070         RangeTblRef *rtr;
1071         ListCell   *lc;
1072         ListCell   *lc2;
1073         int                     i;
1074
1075         qry->commandType = CMD_SELECT;
1076
1077         /* Most SELECT stuff doesn't apply in a VALUES clause */
1078         Assert(stmt->distinctClause == NIL);
1079         Assert(stmt->intoClause == NULL);
1080         Assert(stmt->targetList == NIL);
1081         Assert(stmt->fromClause == NIL);
1082         Assert(stmt->whereClause == NULL);
1083         Assert(stmt->groupClause == NIL);
1084         Assert(stmt->havingClause == NULL);
1085         Assert(stmt->windowClause == NIL);
1086         Assert(stmt->op == SETOP_NONE);
1087
1088         /* process the WITH clause independently of all else */
1089         if (stmt->withClause)
1090         {
1091                 qry->hasRecursive = stmt->withClause->recursive;
1092                 qry->cteList = transformWithClause(pstate, stmt->withClause);
1093                 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1094         }
1095
1096         /*
1097          * For each row of VALUES, transform the raw expressions.  This is also a
1098          * handy place to reject DEFAULT nodes, which the grammar allows for
1099          * simplicity.
1100          *
1101          * Note that the intermediate representation we build is column-organized
1102          * not row-organized.  That simplifies the type and collation processing
1103          * below.
1104          */
1105         foreach(lc, stmt->valuesLists)
1106         {
1107                 List       *sublist = (List *) lfirst(lc);
1108
1109                 /* Do basic expression transformation (same as a ROW() expr) */
1110                 sublist = transformExpressionList(pstate, sublist);
1111
1112                 /*
1113                  * All the sublists must be the same length, *after* transformation
1114                  * (which might expand '*' into multiple items).  The VALUES RTE can't
1115                  * handle anything different.
1116                  */
1117                 if (sublist_length < 0)
1118                 {
1119                         /* Remember post-transformation length of first sublist */
1120                         sublist_length = list_length(sublist);
1121                         /* and allocate array for per-column lists */
1122                         colexprs = (List **) palloc0(sublist_length * sizeof(List *));
1123                 }
1124                 else if (sublist_length != list_length(sublist))
1125                 {
1126                         ereport(ERROR,
1127                                         (errcode(ERRCODE_SYNTAX_ERROR),
1128                                          errmsg("VALUES lists must all be the same length"),
1129                                          parser_errposition(pstate,
1130                                                                                 exprLocation((Node *) sublist))));
1131                 }
1132
1133                 /* Check for DEFAULT and build per-column expression lists */
1134                 i = 0;
1135                 foreach(lc2, sublist)
1136                 {
1137                         Node       *col = (Node *) lfirst(lc2);
1138
1139                         if (IsA(col, SetToDefault))
1140                                 ereport(ERROR,
1141                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1142                                                  errmsg("DEFAULT can only appear in a VALUES list within INSERT"),
1143                                                  parser_errposition(pstate, exprLocation(col))));
1144                         colexprs[i] = lappend(colexprs[i], col);
1145                         i++;
1146                 }
1147
1148                 /* Release sub-list's cells to save memory */
1149                 list_free(sublist);
1150         }
1151
1152         /*
1153          * Now resolve the common types of the columns, and coerce everything to
1154          * those types.  Then identify the common collation, if any, of each
1155          * column.
1156          *
1157          * We must do collation processing now because (1) assign_query_collations
1158          * doesn't process rangetable entries, and (2) we need to label the VALUES
1159          * RTE with column collations for use in the outer query.  We don't
1160          * consider conflict of implicit collations to be an error here; instead
1161          * the column will just show InvalidOid as its collation, and you'll get a
1162          * failure later if that results in failure to resolve a collation.
1163          *
1164          * Note we modify the per-column expression lists in-place.
1165          */
1166         collations = NIL;
1167         for (i = 0; i < sublist_length; i++)
1168         {
1169                 Oid                     coltype;
1170                 Oid                     colcoll;
1171
1172                 coltype = select_common_type(pstate, colexprs[i], "VALUES", NULL);
1173
1174                 foreach(lc, colexprs[i])
1175                 {
1176                         Node       *col = (Node *) lfirst(lc);
1177
1178                         col = coerce_to_common_type(pstate, col, coltype, "VALUES");
1179                         lfirst(lc) = (void *) col;
1180                 }
1181
1182                 colcoll = select_common_collation(pstate, colexprs[i], true);
1183
1184                 collations = lappend_oid(collations, colcoll);
1185         }
1186
1187         /*
1188          * Finally, rearrange the coerced expressions into row-organized lists.
1189          */
1190         exprsLists = NIL;
1191         foreach(lc, colexprs[0])
1192         {
1193                 Node       *col = (Node *) lfirst(lc);
1194                 List       *sublist;
1195
1196                 sublist = list_make1(col);
1197                 exprsLists = lappend(exprsLists, sublist);
1198         }
1199         list_free(colexprs[0]);
1200         for (i = 1; i < sublist_length; i++)
1201         {
1202                 forboth(lc, colexprs[i], lc2, exprsLists)
1203                 {
1204                         Node       *col = (Node *) lfirst(lc);
1205                         List       *sublist = lfirst(lc2);
1206
1207                         /* sublist pointer in exprsLists won't need adjustment */
1208                         (void) lappend(sublist, col);
1209                 }
1210                 list_free(colexprs[i]);
1211         }
1212
1213         /*
1214          * Generate the VALUES RTE
1215          */
1216         rte = addRangeTableEntryForValues(pstate, exprsLists, collations,
1217                                                                           NULL, true);
1218         rtr = makeNode(RangeTblRef);
1219         /* assume new rte is at end */
1220         rtr->rtindex = list_length(pstate->p_rtable);
1221         Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1222         pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
1223         pstate->p_relnamespace = lappend(pstate->p_relnamespace, rte);
1224         pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
1225
1226         /*
1227          * Generate a targetlist as though expanding "*"
1228          */
1229         Assert(pstate->p_next_resno == 1);
1230         qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0, -1);
1231
1232         /*
1233          * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
1234          * VALUES, so cope.
1235          */
1236         qry->sortClause = transformSortClause(pstate,
1237                                                                                   stmt->sortClause,
1238                                                                                   &qry->targetList,
1239                                                                                   true /* fix unknowns */ ,
1240                                                                                   false /* allow SQL92 rules */ );
1241
1242         qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
1243                                                                                         "OFFSET");
1244         qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
1245                                                                                    "LIMIT");
1246
1247         if (stmt->lockingClause)
1248                 ereport(ERROR,
1249                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1250                          errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
1251
1252         /*
1253          * There mustn't have been any table references in the expressions, else
1254          * strange things would happen, like Cartesian products of those tables
1255          * with the VALUES list.  We have to check this after parsing ORDER BY et
1256          * al since those could insert more junk.
1257          */
1258         if (list_length(pstate->p_joinlist) != 1)
1259                 ereport(ERROR,
1260                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1261                                  errmsg("VALUES must not contain table references"),
1262                                  parser_errposition(pstate,
1263                                                           locate_var_of_level((Node *) exprsLists, 0))));
1264
1265         /*
1266          * Another thing we can't currently support is NEW/OLD references in rules
1267          * --- seems we'd need something like SQL99's LATERAL construct to ensure
1268          * that the values would be available while evaluating the VALUES RTE.
1269          * This is a shame.  FIXME
1270          */
1271         if (list_length(pstate->p_rtable) != 1 &&
1272                 contain_vars_of_level((Node *) exprsLists, 0))
1273                 ereport(ERROR,
1274                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1275                                  errmsg("VALUES must not contain OLD or NEW references"),
1276                                  errhint("Use SELECT ... UNION ALL ... instead."),
1277                                  parser_errposition(pstate,
1278                                                           locate_var_of_level((Node *) exprsLists, 0))));
1279
1280         qry->rtable = pstate->p_rtable;
1281         qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1282
1283         qry->hasSubLinks = pstate->p_hasSubLinks;
1284         /* aggregates not allowed (but subselects are okay) */
1285         if (pstate->p_hasAggs)
1286                 ereport(ERROR,
1287                                 (errcode(ERRCODE_GROUPING_ERROR),
1288                                  errmsg("cannot use aggregate function in VALUES"),
1289                                  parser_errposition(pstate,
1290                                                           locate_agg_of_level((Node *) exprsLists, 0))));
1291         if (pstate->p_hasWindowFuncs)
1292                 ereport(ERROR,
1293                                 (errcode(ERRCODE_WINDOWING_ERROR),
1294                                  errmsg("cannot use window function in VALUES"),
1295                                  parser_errposition(pstate,
1296                                                                         locate_windowfunc((Node *) exprsLists))));
1297
1298         assign_query_collations(pstate, qry);
1299
1300         return qry;
1301 }
1302
1303 /*
1304  * transformSetOperationStmt -
1305  *        transforms a set-operations tree
1306  *
1307  * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1308  * structure to it.  We must transform each leaf SELECT and build up a top-
1309  * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1310  * The tree of set operations is converted into the setOperations field of
1311  * the top-level Query.
1312  */
1313 static Query *
1314 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1315 {
1316         Query      *qry = makeNode(Query);
1317         SelectStmt *leftmostSelect;
1318         int                     leftmostRTI;
1319         Query      *leftmostQuery;
1320         SetOperationStmt *sostmt;
1321         List       *sortClause;
1322         Node       *limitOffset;
1323         Node       *limitCount;
1324         List       *lockingClause;
1325         Node       *node;
1326         ListCell   *left_tlist,
1327                            *lct,
1328                            *lcm,
1329                            *lcc,
1330                            *l;
1331         List       *targetvars,
1332                            *targetnames,
1333                            *sv_relnamespace,
1334                            *sv_varnamespace;
1335         int                     sv_rtable_length;
1336         RangeTblEntry *jrte;
1337         int                     tllen;
1338
1339         qry->commandType = CMD_SELECT;
1340
1341         /* process the WITH clause independently of all else */
1342         if (stmt->withClause)
1343         {
1344                 qry->hasRecursive = stmt->withClause->recursive;
1345                 qry->cteList = transformWithClause(pstate, stmt->withClause);
1346                 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1347         }
1348
1349         /*
1350          * Find leftmost leaf SelectStmt.  We currently only need to do this in
1351          * order to deliver a suitable error message if there's an INTO clause
1352          * there, implying the set-op tree is in a context that doesn't allow
1353          * INTO.  (transformSetOperationTree would throw error anyway, but it
1354          * seems worth the trouble to throw a different error for non-leftmost
1355          * INTO, so we produce that error in transformSetOperationTree.)
1356          */
1357         leftmostSelect = stmt->larg;
1358         while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1359                 leftmostSelect = leftmostSelect->larg;
1360         Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1361                    leftmostSelect->larg == NULL);
1362         if (leftmostSelect->intoClause)
1363                 ereport(ERROR,
1364                                 (errcode(ERRCODE_SYNTAX_ERROR),
1365                                  errmsg("SELECT ... INTO is not allowed here"),
1366                                  parser_errposition(pstate,
1367                                                                         exprLocation((Node *) leftmostSelect->intoClause))));
1368
1369         /*
1370          * We need to extract ORDER BY and other top-level clauses here and
1371          * not let transformSetOperationTree() see them --- else it'll just
1372          * recurse right back here!
1373          */
1374         sortClause = stmt->sortClause;
1375         limitOffset = stmt->limitOffset;
1376         limitCount = stmt->limitCount;
1377         lockingClause = stmt->lockingClause;
1378
1379         stmt->sortClause = NIL;
1380         stmt->limitOffset = NULL;
1381         stmt->limitCount = NULL;
1382         stmt->lockingClause = NIL;
1383
1384         /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1385         if (lockingClause)
1386                 ereport(ERROR,
1387                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1388                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1389
1390         /*
1391          * Recursively transform the components of the tree.
1392          */
1393         sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt,
1394                                                                                                                         true,
1395                                                                                                                         NULL);
1396         Assert(sostmt && IsA(sostmt, SetOperationStmt));
1397         qry->setOperations = (Node *) sostmt;
1398
1399         /*
1400          * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1401          */
1402         node = sostmt->larg;
1403         while (node && IsA(node, SetOperationStmt))
1404                 node = ((SetOperationStmt *) node)->larg;
1405         Assert(node && IsA(node, RangeTblRef));
1406         leftmostRTI = ((RangeTblRef *) node)->rtindex;
1407         leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1408         Assert(leftmostQuery != NULL);
1409
1410         /*
1411          * Generate dummy targetlist for outer query using column names of
1412          * leftmost select and common datatypes/collations of topmost set
1413          * operation.  Also make lists of the dummy vars and their names for use
1414          * in parsing ORDER BY.
1415          *
1416          * Note: we use leftmostRTI as the varno of the dummy variables. It
1417          * shouldn't matter too much which RT index they have, as long as they
1418          * have one that corresponds to a real RT entry; else funny things may
1419          * happen when the tree is mashed by rule rewriting.
1420          */
1421         qry->targetList = NIL;
1422         targetvars = NIL;
1423         targetnames = NIL;
1424         left_tlist = list_head(leftmostQuery->targetList);
1425
1426         forthree(lct, sostmt->colTypes,
1427                          lcm, sostmt->colTypmods,
1428                          lcc, sostmt->colCollations)
1429         {
1430                 Oid                     colType = lfirst_oid(lct);
1431                 int32           colTypmod = lfirst_int(lcm);
1432                 Oid                     colCollation = lfirst_oid(lcc);
1433                 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1434                 char       *colName;
1435                 TargetEntry *tle;
1436                 Var                *var;
1437
1438                 Assert(!lefttle->resjunk);
1439                 colName = pstrdup(lefttle->resname);
1440                 var = makeVar(leftmostRTI,
1441                                           lefttle->resno,
1442                                           colType,
1443                                           colTypmod,
1444                                           colCollation,
1445                                           0);
1446                 var->location = exprLocation((Node *) lefttle->expr);
1447                 tle = makeTargetEntry((Expr *) var,
1448                                                           (AttrNumber) pstate->p_next_resno++,
1449                                                           colName,
1450                                                           false);
1451                 qry->targetList = lappend(qry->targetList, tle);
1452                 targetvars = lappend(targetvars, var);
1453                 targetnames = lappend(targetnames, makeString(colName));
1454                 left_tlist = lnext(left_tlist);
1455         }
1456
1457         /*
1458          * As a first step towards supporting sort clauses that are expressions
1459          * using the output columns, generate a varnamespace entry that makes the
1460          * output columns visible.      A Join RTE node is handy for this, since we
1461          * can easily control the Vars generated upon matches.
1462          *
1463          * Note: we don't yet do anything useful with such cases, but at least
1464          * "ORDER BY upper(foo)" will draw the right error message rather than
1465          * "foo not found".
1466          */
1467         sv_rtable_length = list_length(pstate->p_rtable);
1468
1469         jrte = addRangeTableEntryForJoin(pstate,
1470                                                                          targetnames,
1471                                                                          JOIN_INNER,
1472                                                                          targetvars,
1473                                                                          NULL,
1474                                                                          false);
1475
1476         sv_relnamespace = pstate->p_relnamespace;
1477         pstate->p_relnamespace = NIL;           /* no qualified names allowed */
1478
1479         sv_varnamespace = pstate->p_varnamespace;
1480         pstate->p_varnamespace = list_make1(jrte);
1481
1482         /*
1483          * For now, we don't support resjunk sort clauses on the output of a
1484          * setOperation tree --- you can only use the SQL92-spec options of
1485          * selecting an output column by name or number.  Enforce by checking that
1486          * transformSortClause doesn't add any items to tlist.
1487          */
1488         tllen = list_length(qry->targetList);
1489
1490         qry->sortClause = transformSortClause(pstate,
1491                                                                                   sortClause,
1492                                                                                   &qry->targetList,
1493                                                                                   false /* no unknowns expected */ ,
1494                                                                                   false /* allow SQL92 rules */ );
1495
1496         pstate->p_rtable = list_truncate(pstate->p_rtable, sv_rtable_length);
1497         pstate->p_relnamespace = sv_relnamespace;
1498         pstate->p_varnamespace = sv_varnamespace;
1499
1500         if (tllen != list_length(qry->targetList))
1501                 ereport(ERROR,
1502                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1503                                  errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
1504                                  errdetail("Only result column names can be used, not expressions or functions."),
1505                                  errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause."),
1506                                  parser_errposition(pstate,
1507                                                    exprLocation(list_nth(qry->targetList, tllen)))));
1508
1509         qry->limitOffset = transformLimitClause(pstate, limitOffset,
1510                                                                                         "OFFSET");
1511         qry->limitCount = transformLimitClause(pstate, limitCount,
1512                                                                                    "LIMIT");
1513
1514         qry->rtable = pstate->p_rtable;
1515         qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
1516
1517         qry->hasSubLinks = pstate->p_hasSubLinks;
1518         qry->hasWindowFuncs = pstate->p_hasWindowFuncs;
1519         if (pstate->p_hasWindowFuncs)
1520                 parseCheckWindowFuncs(pstate, qry);
1521         qry->hasAggs = pstate->p_hasAggs;
1522         if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
1523                 parseCheckAggregates(pstate, qry);
1524
1525         foreach(l, lockingClause)
1526         {
1527                 transformLockingClause(pstate, qry,
1528                                                            (LockingClause *) lfirst(l), false);
1529         }
1530
1531         assign_query_collations(pstate, qry);
1532
1533         return qry;
1534 }
1535
1536 /*
1537  * transformSetOperationTree
1538  *              Recursively transform leaves and internal nodes of a set-op tree
1539  *
1540  * In addition to returning the transformed node, if targetlist isn't NULL
1541  * then we return a list of its non-resjunk TargetEntry nodes.  For a leaf
1542  * set-op node these are the actual targetlist entries; otherwise they are
1543  * dummy entries created to carry the type, typmod, collation, and location
1544  * (for error messages) of each output column of the set-op node.  This info
1545  * is needed only during the internal recursion of this function, so outside
1546  * callers pass NULL for targetlist.  Note: the reason for passing the
1547  * actual targetlist entries of a leaf node is so that upper levels can
1548  * replace UNKNOWN Consts with properly-coerced constants.
1549  */
1550 static Node *
1551 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt,
1552                                                   bool isTopLevel, List **targetlist)
1553 {
1554         bool            isLeaf;
1555
1556         Assert(stmt && IsA(stmt, SelectStmt));
1557
1558         /*
1559          * Validity-check both leaf and internal SELECTs for disallowed ops.
1560          */
1561         if (stmt->intoClause)
1562                 ereport(ERROR,
1563                                 (errcode(ERRCODE_SYNTAX_ERROR),
1564                                  errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT"),
1565                                  parser_errposition(pstate,
1566                                                                   exprLocation((Node *) stmt->intoClause))));
1567
1568         /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
1569         if (stmt->lockingClause)
1570                 ereport(ERROR,
1571                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1572                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
1573
1574         /*
1575          * If an internal node of a set-op tree has ORDER BY, LIMIT, or FOR UPDATE
1576          * clauses attached, we need to treat it like a leaf node to generate an
1577          * independent sub-Query tree.  Otherwise, it can be represented by a
1578          * SetOperationStmt node underneath the parent Query.
1579          */
1580         if (stmt->op == SETOP_NONE)
1581         {
1582                 Assert(stmt->larg == NULL && stmt->rarg == NULL);
1583                 isLeaf = true;
1584         }
1585         else
1586         {
1587                 Assert(stmt->larg != NULL && stmt->rarg != NULL);
1588                 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
1589                         stmt->lockingClause)
1590                         isLeaf = true;
1591                 else
1592                         isLeaf = false;
1593         }
1594
1595         if (isLeaf)
1596         {
1597                 /* Process leaf SELECT */
1598                 Query      *selectQuery;
1599                 char            selectName[32];
1600                 RangeTblEntry *rte PG_USED_FOR_ASSERTS_ONLY;
1601                 RangeTblRef *rtr;
1602                 ListCell   *tl;
1603
1604                 /*
1605                  * Transform SelectStmt into a Query.
1606                  *
1607                  * Note: previously transformed sub-queries don't affect the parsing
1608                  * of this sub-query, because they are not in the toplevel pstate's
1609                  * namespace list.
1610                  */
1611                 selectQuery = parse_sub_analyze((Node *) stmt, pstate, NULL, false);
1612
1613                 /*
1614                  * Check for bogus references to Vars on the current query level (but
1615                  * upper-level references are okay). Normally this can't happen
1616                  * because the namespace will be empty, but it could happen if we are
1617                  * inside a rule.
1618                  */
1619                 if (pstate->p_relnamespace || pstate->p_varnamespace)
1620                 {
1621                         if (contain_vars_of_level((Node *) selectQuery, 1))
1622                                 ereport(ERROR,
1623                                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1624                                                  errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level"),
1625                                                  parser_errposition(pstate,
1626                                                          locate_var_of_level((Node *) selectQuery, 1))));
1627                 }
1628
1629                 /*
1630                  * Extract a list of the non-junk TLEs for upper-level processing.
1631                  */
1632                 if (targetlist)
1633                 {
1634                         *targetlist = NIL;
1635                         foreach(tl, selectQuery->targetList)
1636                         {
1637                                 TargetEntry *tle = (TargetEntry *) lfirst(tl);
1638
1639                                 if (!tle->resjunk)
1640                                         *targetlist = lappend(*targetlist, tle);
1641                         }
1642                 }
1643
1644                 /*
1645                  * Make the leaf query be a subquery in the top-level rangetable.
1646                  */
1647                 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
1648                                  list_length(pstate->p_rtable) + 1);
1649                 rte = addRangeTableEntryForSubquery(pstate,
1650                                                                                         selectQuery,
1651                                                                                         makeAlias(selectName, NIL),
1652                                                                                         false);
1653
1654                 /*
1655                  * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
1656                  */
1657                 rtr = makeNode(RangeTblRef);
1658                 /* assume new rte is at end */
1659                 rtr->rtindex = list_length(pstate->p_rtable);
1660                 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
1661                 return (Node *) rtr;
1662         }
1663         else
1664         {
1665                 /* Process an internal node (set operation node) */
1666                 SetOperationStmt *op = makeNode(SetOperationStmt);
1667                 List       *ltargetlist;
1668                 List       *rtargetlist;
1669                 ListCell   *ltl;
1670                 ListCell   *rtl;
1671                 const char *context;
1672
1673                 context = (stmt->op == SETOP_UNION ? "UNION" :
1674                                    (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
1675                                         "EXCEPT"));
1676
1677                 op->op = stmt->op;
1678                 op->all = stmt->all;
1679
1680                 /*
1681                  * Recursively transform the left child node.
1682                  */
1683                 op->larg = transformSetOperationTree(pstate, stmt->larg,
1684                                                                                          false,
1685                                                                                          &ltargetlist);
1686
1687                 /*
1688                  * If we are processing a recursive union query, now is the time to
1689                  * examine the non-recursive term's output columns and mark the
1690                  * containing CTE as having those result columns.  We should do this
1691                  * only at the topmost setop of the CTE, of course.
1692                  */
1693                 if (isTopLevel &&
1694                         pstate->p_parent_cte &&
1695                         pstate->p_parent_cte->cterecursive)
1696                         determineRecursiveColTypes(pstate, op->larg, ltargetlist);
1697
1698                 /*
1699                  * Recursively transform the right child node.
1700                  */
1701                 op->rarg = transformSetOperationTree(pstate, stmt->rarg,
1702                                                                                          false,
1703                                                                                          &rtargetlist);
1704
1705                 /*
1706                  * Verify that the two children have the same number of non-junk
1707                  * columns, and determine the types of the merged output columns.
1708                  */
1709                 if (list_length(ltargetlist) != list_length(rtargetlist))
1710                         ereport(ERROR,
1711                                         (errcode(ERRCODE_SYNTAX_ERROR),
1712                                  errmsg("each %s query must have the same number of columns",
1713                                                 context),
1714                                          parser_errposition(pstate,
1715                                                                                 exprLocation((Node *) rtargetlist))));
1716
1717                 if (targetlist)
1718                         *targetlist = NIL;
1719                 op->colTypes = NIL;
1720                 op->colTypmods = NIL;
1721                 op->colCollations = NIL;
1722                 op->groupClauses = NIL;
1723                 forboth(ltl, ltargetlist, rtl, rtargetlist)
1724                 {
1725                         TargetEntry *ltle = (TargetEntry *) lfirst(ltl);
1726                         TargetEntry *rtle = (TargetEntry *) lfirst(rtl);
1727                         Node       *lcolnode = (Node *) ltle->expr;
1728                         Node       *rcolnode = (Node *) rtle->expr;
1729                         Oid                     lcoltype = exprType(lcolnode);
1730                         Oid                     rcoltype = exprType(rcolnode);
1731                         int32           lcoltypmod = exprTypmod(lcolnode);
1732                         int32           rcoltypmod = exprTypmod(rcolnode);
1733                         Node       *bestexpr;
1734                         int                     bestlocation;
1735                         Oid                     rescoltype;
1736                         int32           rescoltypmod;
1737                         Oid                     rescolcoll;
1738
1739                         /* select common type, same as CASE et al */
1740                         rescoltype = select_common_type(pstate,
1741                                                                                         list_make2(lcolnode, rcolnode),
1742                                                                                         context,
1743                                                                                         &bestexpr);
1744                         bestlocation = exprLocation(bestexpr);
1745                         /* if same type and same typmod, use typmod; else default */
1746                         if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
1747                                 rescoltypmod = lcoltypmod;
1748                         else
1749                                 rescoltypmod = -1;
1750
1751                         /*
1752                          * Verify the coercions are actually possible.  If not, we'd fail
1753                          * later anyway, but we want to fail now while we have sufficient
1754                          * context to produce an error cursor position.
1755                          *
1756                          * For all non-UNKNOWN-type cases, we verify coercibility but we
1757                          * don't modify the child's expression, for fear of changing the
1758                          * child query's semantics.
1759                          *
1760                          * If a child expression is an UNKNOWN-type Const or Param, we
1761                          * want to replace it with the coerced expression.      This can only
1762                          * happen when the child is a leaf set-op node.  It's safe to
1763                          * replace the expression because if the child query's semantics
1764                          * depended on the type of this output column, it'd have already
1765                          * coerced the UNKNOWN to something else.  We want to do this
1766                          * because (a) we want to verify that a Const is valid for the
1767                          * target type, or resolve the actual type of an UNKNOWN Param,
1768                          * and (b) we want to avoid unnecessary discrepancies between the
1769                          * output type of the child query and the resolved target type.
1770                          * Such a discrepancy would disable optimization in the planner.
1771                          *
1772                          * If it's some other UNKNOWN-type node, eg a Var, we do nothing
1773                          * (knowing that coerce_to_common_type would fail).  The planner
1774                          * is sometimes able to fold an UNKNOWN Var to a constant before
1775                          * it has to coerce the type, so failing now would just break
1776                          * cases that might work.
1777                          */
1778                         if (lcoltype != UNKNOWNOID)
1779                                 lcolnode = coerce_to_common_type(pstate, lcolnode,
1780                                                                                                  rescoltype, context);
1781                         else if (IsA(lcolnode, Const) ||
1782                                          IsA(lcolnode, Param))
1783                         {
1784                                 lcolnode = coerce_to_common_type(pstate, lcolnode,
1785                                                                                                  rescoltype, context);
1786                                 ltle->expr = (Expr *) lcolnode;
1787                         }
1788
1789                         if (rcoltype != UNKNOWNOID)
1790                                 rcolnode = coerce_to_common_type(pstate, rcolnode,
1791                                                                                                  rescoltype, context);
1792                         else if (IsA(rcolnode, Const) ||
1793                                          IsA(rcolnode, Param))
1794                         {
1795                                 rcolnode = coerce_to_common_type(pstate, rcolnode,
1796                                                                                                  rescoltype, context);
1797                                 rtle->expr = (Expr *) rcolnode;
1798                         }
1799
1800                         /*
1801                          * Select common collation.  A common collation is required for
1802                          * all set operators except UNION ALL; see SQL:2008 7.13 <query
1803                          * expression> Syntax Rule 15c.  (If we fail to identify a common
1804                          * collation for a UNION ALL column, the curCollations element
1805                          * will be set to InvalidOid, which may result in a runtime error
1806                          * if something at a higher query level wants to use the column's
1807                          * collation.)
1808                          */
1809                         rescolcoll = select_common_collation(pstate,
1810                                                                                           list_make2(lcolnode, rcolnode),
1811                                                                                  (op->op == SETOP_UNION && op->all));
1812
1813                         /* emit results */
1814                         op->colTypes = lappend_oid(op->colTypes, rescoltype);
1815                         op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
1816                         op->colCollations = lappend_oid(op->colCollations, rescolcoll);
1817
1818                         /*
1819                          * For all cases except UNION ALL, identify the grouping operators
1820                          * (and, if available, sorting operators) that will be used to
1821                          * eliminate duplicates.
1822                          */
1823                         if (op->op != SETOP_UNION || !op->all)
1824                         {
1825                                 SortGroupClause *grpcl = makeNode(SortGroupClause);
1826                                 Oid                     sortop;
1827                                 Oid                     eqop;
1828                                 bool            hashable;
1829                                 ParseCallbackState pcbstate;
1830
1831                                 setup_parser_errposition_callback(&pcbstate, pstate,
1832                                                                                                   bestlocation);
1833
1834                                 /* determine the eqop and optional sortop */
1835                                 get_sort_group_operators(rescoltype,
1836                                                                                  false, true, false,
1837                                                                                  &sortop, &eqop, NULL,
1838                                                                                  &hashable);
1839
1840                                 cancel_parser_errposition_callback(&pcbstate);
1841
1842                                 /* we don't have a tlist yet, so can't assign sortgrouprefs */
1843                                 grpcl->tleSortGroupRef = 0;
1844                                 grpcl->eqop = eqop;
1845                                 grpcl->sortop = sortop;
1846                                 grpcl->nulls_first = false;             /* OK with or without sortop */
1847                                 grpcl->hashable = hashable;
1848
1849                                 op->groupClauses = lappend(op->groupClauses, grpcl);
1850                         }
1851
1852                         /*
1853                          * Construct a dummy tlist entry to return.  We use a SetToDefault
1854                          * node for the expression, since it carries exactly the fields
1855                          * needed, but any other expression node type would do as well.
1856                          */
1857                         if (targetlist)
1858                         {
1859                                 SetToDefault *rescolnode = makeNode(SetToDefault);
1860                                 TargetEntry *restle;
1861
1862                                 rescolnode->typeId = rescoltype;
1863                                 rescolnode->typeMod = rescoltypmod;
1864                                 rescolnode->collation = rescolcoll;
1865                                 rescolnode->location = bestlocation;
1866                                 restle = makeTargetEntry((Expr *) rescolnode,
1867                                                                                  0,             /* no need to set resno */
1868                                                                                  NULL,
1869                                                                                  false);
1870                                 *targetlist = lappend(*targetlist, restle);
1871                         }
1872                 }
1873
1874                 return (Node *) op;
1875         }
1876 }
1877
1878 /*
1879  * Process the outputs of the non-recursive term of a recursive union
1880  * to set up the parent CTE's columns
1881  */
1882 static void
1883 determineRecursiveColTypes(ParseState *pstate, Node *larg, List *nrtargetlist)
1884 {
1885         Node       *node;
1886         int                     leftmostRTI;
1887         Query      *leftmostQuery;
1888         List       *targetList;
1889         ListCell   *left_tlist;
1890         ListCell   *nrtl;
1891         int                     next_resno;
1892
1893         /*
1894          * Find leftmost leaf SELECT
1895          */
1896         node = larg;
1897         while (node && IsA(node, SetOperationStmt))
1898                 node = ((SetOperationStmt *) node)->larg;
1899         Assert(node && IsA(node, RangeTblRef));
1900         leftmostRTI = ((RangeTblRef *) node)->rtindex;
1901         leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1902         Assert(leftmostQuery != NULL);
1903
1904         /*
1905          * Generate dummy targetlist using column names of leftmost select and
1906          * dummy result expressions of the non-recursive term.
1907          */
1908         targetList = NIL;
1909         left_tlist = list_head(leftmostQuery->targetList);
1910         next_resno = 1;
1911
1912         foreach(nrtl, nrtargetlist)
1913         {
1914                 TargetEntry *nrtle = (TargetEntry *) lfirst(nrtl);
1915                 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
1916                 char       *colName;
1917                 TargetEntry *tle;
1918
1919                 Assert(!lefttle->resjunk);
1920                 colName = pstrdup(lefttle->resname);
1921                 tle = makeTargetEntry(nrtle->expr,
1922                                                           next_resno++,
1923                                                           colName,
1924                                                           false);
1925                 targetList = lappend(targetList, tle);
1926                 left_tlist = lnext(left_tlist);
1927         }
1928
1929         /* Now build CTE's output column info using dummy targetlist */
1930         analyzeCTETargetList(pstate, pstate->p_parent_cte, targetList);
1931 }
1932
1933
1934 /*
1935  * transformUpdateStmt -
1936  *        transforms an update statement
1937  */
1938 static Query *
1939 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
1940 {
1941         Query      *qry = makeNode(Query);
1942         RangeTblEntry *target_rte;
1943         Node       *qual;
1944         ListCell   *origTargetList;
1945         ListCell   *tl;
1946
1947         qry->commandType = CMD_UPDATE;
1948         pstate->p_is_update = true;
1949
1950         /* process the WITH clause independently of all else */
1951         if (stmt->withClause)
1952         {
1953                 qry->hasRecursive = stmt->withClause->recursive;
1954                 qry->cteList = transformWithClause(pstate, stmt->withClause);
1955                 qry->hasModifyingCTE = pstate->p_hasModifyingCTE;
1956         }
1957
1958         qry->resultRelation = setTargetTable(pstate, stmt->relation,
1959                                                                   interpretInhOption(stmt->relation->inhOpt),
1960                                                                                  true,
1961                                                                                  ACL_UPDATE);
1962
1963         /*
1964          * the FROM clause is non-standard SQL syntax. We used to be able to do
1965          * this with REPLACE in POSTQUEL so we keep the feature.
1966          */
1967         transformFromClause(pstate, stmt->fromClause);
1968
1969         qry->targetList = transformTargetList(pstate, stmt->targetList);
1970
1971         qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
1972
1973         qry->returningList = transformReturningList(pstate, stmt->returningList);
1974
1975         qry->rtable = pstate->p_rtable;
1976         qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1977
1978         qry->hasSubLinks = pstate->p_hasSubLinks;
1979
1980         /*
1981          * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
1982          * an implementation point of view, this is forced because the implicit
1983          * ctid reference would otherwise be an ungrouped variable.)
1984          */
1985         if (pstate->p_hasAggs)
1986                 ereport(ERROR,
1987                                 (errcode(ERRCODE_GROUPING_ERROR),
1988                                  errmsg("cannot use aggregate function in UPDATE"),
1989                                  parser_errposition(pstate,
1990                                                                         locate_agg_of_level((Node *) qry, 0))));
1991         if (pstate->p_hasWindowFuncs)
1992                 ereport(ERROR,
1993                                 (errcode(ERRCODE_WINDOWING_ERROR),
1994                                  errmsg("cannot use window function in UPDATE"),
1995                                  parser_errposition(pstate,
1996                                                                         locate_windowfunc((Node *) qry))));
1997
1998         /*
1999          * Now we are done with SELECT-like processing, and can get on with
2000          * transforming the target list to match the UPDATE target columns.
2001          */
2002
2003         /* Prepare to assign non-conflicting resnos to resjunk attributes */
2004         if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2005                 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2006
2007         /* Prepare non-junk columns for assignment to target table */
2008         target_rte = pstate->p_target_rangetblentry;
2009         origTargetList = list_head(stmt->targetList);
2010
2011         foreach(tl, qry->targetList)
2012         {
2013                 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2014                 ResTarget  *origTarget;
2015                 int                     attrno;
2016
2017                 if (tle->resjunk)
2018                 {
2019                         /*
2020                          * Resjunk nodes need no additional processing, but be sure they
2021                          * have resnos that do not match any target columns; else rewriter
2022                          * or planner might get confused.  They don't need a resname
2023                          * either.
2024                          */
2025                         tle->resno = (AttrNumber) pstate->p_next_resno++;
2026                         tle->resname = NULL;
2027                         continue;
2028                 }
2029                 if (origTargetList == NULL)
2030                         elog(ERROR, "UPDATE target count mismatch --- internal error");
2031                 origTarget = (ResTarget *) lfirst(origTargetList);
2032                 Assert(IsA(origTarget, ResTarget));
2033
2034                 attrno = attnameAttNum(pstate->p_target_relation,
2035                                                            origTarget->name, true);
2036                 if (attrno == InvalidAttrNumber)
2037                         ereport(ERROR,
2038                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
2039                                          errmsg("column \"%s\" of relation \"%s\" does not exist",
2040                                                         origTarget->name,
2041                                                  RelationGetRelationName(pstate->p_target_relation)),
2042                                          parser_errposition(pstate, origTarget->location)));
2043
2044                 updateTargetListEntry(pstate, tle, origTarget->name,
2045                                                           attrno,
2046                                                           origTarget->indirection,
2047                                                           origTarget->location);
2048
2049                 /* Mark the target column as requiring update permissions */
2050                 target_rte->modifiedCols = bms_add_member(target_rte->modifiedCols,
2051                                                                 attrno - FirstLowInvalidHeapAttributeNumber);
2052
2053                 origTargetList = lnext(origTargetList);
2054         }
2055         if (origTargetList != NULL)
2056                 elog(ERROR, "UPDATE target count mismatch --- internal error");
2057
2058         assign_query_collations(pstate, qry);
2059
2060         return qry;
2061 }
2062
2063 /*
2064  * transformReturningList -
2065  *      handle a RETURNING clause in INSERT/UPDATE/DELETE
2066  */
2067 static List *
2068 transformReturningList(ParseState *pstate, List *returningList)
2069 {
2070         List       *rlist;
2071         int                     save_next_resno;
2072         bool            save_hasAggs;
2073         bool            save_hasWindowFuncs;
2074         int                     length_rtable;
2075
2076         if (returningList == NIL)
2077                 return NIL;                             /* nothing to do */
2078
2079         /*
2080          * We need to assign resnos starting at one in the RETURNING list. Save
2081          * and restore the main tlist's value of p_next_resno, just in case
2082          * someone looks at it later (probably won't happen).
2083          */
2084         save_next_resno = pstate->p_next_resno;
2085         pstate->p_next_resno = 1;
2086
2087         /* save other state so that we can detect disallowed stuff */
2088         save_hasAggs = pstate->p_hasAggs;
2089         pstate->p_hasAggs = false;
2090         save_hasWindowFuncs = pstate->p_hasWindowFuncs;
2091         pstate->p_hasWindowFuncs = false;
2092         length_rtable = list_length(pstate->p_rtable);
2093
2094         /* transform RETURNING identically to a SELECT targetlist */
2095         rlist = transformTargetList(pstate, returningList);
2096
2097         /* check for disallowed stuff */
2098
2099         /* aggregates not allowed (but subselects are okay) */
2100         if (pstate->p_hasAggs)
2101                 ereport(ERROR,
2102                                 (errcode(ERRCODE_GROUPING_ERROR),
2103                                  errmsg("cannot use aggregate function in RETURNING"),
2104                                  parser_errposition(pstate,
2105                                                                         locate_agg_of_level((Node *) rlist, 0))));
2106         if (pstate->p_hasWindowFuncs)
2107                 ereport(ERROR,
2108                                 (errcode(ERRCODE_WINDOWING_ERROR),
2109                                  errmsg("cannot use window function in RETURNING"),
2110                                  parser_errposition(pstate,
2111                                                                         locate_windowfunc((Node *) rlist))));
2112
2113         /* no new relation references please */
2114         if (list_length(pstate->p_rtable) != length_rtable)
2115         {
2116                 int                     vlocation = -1;
2117                 int                     relid;
2118
2119                 /* try to locate such a reference to point to */
2120                 for (relid = length_rtable + 1; relid <= list_length(pstate->p_rtable); relid++)
2121                 {
2122                         vlocation = locate_var_of_relation((Node *) rlist, relid, 0);
2123                         if (vlocation >= 0)
2124                                 break;
2125                 }
2126                 ereport(ERROR,
2127                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2128                         errmsg("RETURNING cannot contain references to other relations"),
2129                                  parser_errposition(pstate, vlocation)));
2130         }
2131
2132         /* mark column origins */
2133         markTargetListOrigins(pstate, rlist);
2134
2135         /* restore state */
2136         pstate->p_next_resno = save_next_resno;
2137         pstate->p_hasAggs = save_hasAggs;
2138         pstate->p_hasWindowFuncs = save_hasWindowFuncs;
2139
2140         return rlist;
2141 }
2142
2143
2144 /*
2145  * transformDeclareCursorStmt -
2146  *      transform a DECLARE CURSOR Statement
2147  *
2148  * DECLARE CURSOR is a hybrid case: it's an optimizable statement (in fact not
2149  * significantly different from a SELECT) as far as parsing/rewriting/planning
2150  * are concerned, but it's not passed to the executor and so in that sense is
2151  * a utility statement.  We transform it into a Query exactly as if it were
2152  * a SELECT, then stick the original DeclareCursorStmt into the utilityStmt
2153  * field to carry the cursor name and options.
2154  */
2155 static Query *
2156 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2157 {
2158         Query      *result;
2159
2160         /*
2161          * Don't allow both SCROLL and NO SCROLL to be specified
2162          */
2163         if ((stmt->options & CURSOR_OPT_SCROLL) &&
2164                 (stmt->options & CURSOR_OPT_NO_SCROLL))
2165                 ereport(ERROR,
2166                                 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
2167                                  errmsg("cannot specify both SCROLL and NO SCROLL")));
2168
2169         result = transformStmt(pstate, stmt->query);
2170
2171         /* Grammar should not have allowed anything but SELECT */
2172         if (!IsA(result, Query) ||
2173                 result->commandType != CMD_SELECT ||
2174                 result->utilityStmt != NULL)
2175                 elog(ERROR, "unexpected non-SELECT command in DECLARE CURSOR");
2176
2177         /*
2178          * We also disallow data-modifying WITH in a cursor.  (This could be
2179          * allowed, but the semantics of when the updates occur might be
2180          * surprising.)
2181          */
2182         if (result->hasModifyingCTE)
2183                 ereport(ERROR,
2184                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2185                                  errmsg("DECLARE CURSOR must not contain data-modifying statements in WITH")));
2186
2187         /* FOR UPDATE and WITH HOLD are not compatible */
2188         if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_HOLD))
2189                 ereport(ERROR,
2190                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2191                                  errmsg("DECLARE CURSOR WITH HOLD ... FOR UPDATE/SHARE is not supported"),
2192                                  errdetail("Holdable cursors must be READ ONLY.")));
2193
2194         /* FOR UPDATE and SCROLL are not compatible */
2195         if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_SCROLL))
2196                 ereport(ERROR,
2197                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2198                 errmsg("DECLARE SCROLL CURSOR ... FOR UPDATE/SHARE is not supported"),
2199                                  errdetail("Scrollable cursors must be READ ONLY.")));
2200
2201         /* FOR UPDATE and INSENSITIVE are not compatible */
2202         if (result->rowMarks != NIL && (stmt->options & CURSOR_OPT_INSENSITIVE))
2203                 ereport(ERROR,
2204                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2205                                  errmsg("DECLARE INSENSITIVE CURSOR ... FOR UPDATE/SHARE is not supported"),
2206                                  errdetail("Insensitive cursors must be READ ONLY.")));
2207
2208         /* We won't need the raw querytree any more */
2209         stmt->query = NULL;
2210
2211         result->utilityStmt = (Node *) stmt;
2212
2213         return result;
2214 }
2215
2216
2217 /*
2218  * transformExplainStmt -
2219  *      transform an EXPLAIN Statement
2220  *
2221  * EXPLAIN is like other utility statements in that we emit it as a
2222  * CMD_UTILITY Query node; however, we must first transform the contained
2223  * query.  We used to postpone that until execution, but it's really necessary
2224  * to do it during the normal parse analysis phase to ensure that side effects
2225  * of parser hooks happen at the expected time.
2226  */
2227 static Query *
2228 transformExplainStmt(ParseState *pstate, ExplainStmt *stmt)
2229 {
2230         Query      *result;
2231
2232         /* transform contained query, allowing SELECT INTO */
2233         stmt->query = (Node *) transformTopLevelStmt(pstate, stmt->query);
2234
2235         /* represent the command as a utility Query */
2236         result = makeNode(Query);
2237         result->commandType = CMD_UTILITY;
2238         result->utilityStmt = (Node *) stmt;
2239
2240         return result;
2241 }
2242
2243
2244 /*
2245  * transformCreateTableAsStmt -
2246  *      transform a CREATE TABLE AS (or SELECT ... INTO) Statement
2247  *
2248  * As with EXPLAIN, transform the contained statement now.
2249  */
2250 static Query *
2251 transformCreateTableAsStmt(ParseState *pstate, CreateTableAsStmt *stmt)
2252 {
2253         Query      *result;
2254
2255         /* transform contained query */
2256         stmt->query = (Node *) transformStmt(pstate, stmt->query);
2257
2258         /* represent the command as a utility Query */
2259         result = makeNode(Query);
2260         result->commandType = CMD_UTILITY;
2261         result->utilityStmt = (Node *) stmt;
2262
2263         return result;
2264 }
2265
2266
2267 /*
2268  * Check for features that are not supported together with FOR UPDATE/SHARE.
2269  *
2270  * exported so planner can check again after rewriting, query pullup, etc
2271  */
2272 void
2273 CheckSelectLocking(Query *qry)
2274 {
2275         if (qry->setOperations)
2276                 ereport(ERROR,
2277                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2278                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2279         if (qry->distinctClause != NIL)
2280                 ereport(ERROR,
2281                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2282                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
2283         if (qry->groupClause != NIL)
2284                 ereport(ERROR,
2285                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2286                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
2287         if (qry->havingQual != NULL)
2288                 ereport(ERROR,
2289                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2290                 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
2291         if (qry->hasAggs)
2292                 ereport(ERROR,
2293                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2294                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
2295         if (qry->hasWindowFuncs)
2296                 ereport(ERROR,
2297                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2298                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with window functions")));
2299         if (expression_returns_set((Node *) qry->targetList))
2300                 ereport(ERROR,
2301                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2302                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with set-returning functions in the target list")));
2303 }
2304
2305 /*
2306  * Transform a FOR UPDATE/SHARE clause
2307  *
2308  * This basically involves replacing names by integer relids.
2309  *
2310  * NB: if you need to change this, see also markQueryForLocking()
2311  * in rewriteHandler.c, and isLockedRefname() in parse_relation.c.
2312  */
2313 static void
2314 transformLockingClause(ParseState *pstate, Query *qry, LockingClause *lc,
2315                                            bool pushedDown)
2316 {
2317         List       *lockedRels = lc->lockedRels;
2318         ListCell   *l;
2319         ListCell   *rt;
2320         Index           i;
2321         LockingClause *allrels;
2322
2323         CheckSelectLocking(qry);
2324
2325         /* make a clause we can pass down to subqueries to select all rels */
2326         allrels = makeNode(LockingClause);
2327         allrels->lockedRels = NIL;      /* indicates all rels */
2328         allrels->forUpdate = lc->forUpdate;
2329         allrels->noWait = lc->noWait;
2330
2331         if (lockedRels == NIL)
2332         {
2333                 /* all regular tables used in query */
2334                 i = 0;
2335                 foreach(rt, qry->rtable)
2336                 {
2337                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2338
2339                         ++i;
2340                         switch (rte->rtekind)
2341                         {
2342                                 case RTE_RELATION:
2343                                         /* ignore foreign tables */
2344                                         if (rte->relkind == RELKIND_FOREIGN_TABLE)
2345                                                 break;
2346                                         applyLockingClause(qry, i,
2347                                                                            lc->forUpdate, lc->noWait, pushedDown);
2348                                         rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2349                                         break;
2350                                 case RTE_SUBQUERY:
2351                                         applyLockingClause(qry, i,
2352                                                                            lc->forUpdate, lc->noWait, pushedDown);
2353
2354                                         /*
2355                                          * FOR UPDATE/SHARE of subquery is propagated to all of
2356                                          * subquery's rels, too.  We could do this later (based on
2357                                          * the marking of the subquery RTE) but it is convenient
2358                                          * to have local knowledge in each query level about which
2359                                          * rels need to be opened with RowShareLock.
2360                                          */
2361                                         transformLockingClause(pstate, rte->subquery,
2362                                                                                    allrels, true);
2363                                         break;
2364                                 default:
2365                                         /* ignore JOIN, SPECIAL, FUNCTION, VALUES, CTE RTEs */
2366                                         break;
2367                         }
2368                 }
2369         }
2370         else
2371         {
2372                 /* just the named tables */
2373                 foreach(l, lockedRels)
2374                 {
2375                         RangeVar   *thisrel = (RangeVar *) lfirst(l);
2376
2377                         /* For simplicity we insist on unqualified alias names here */
2378                         if (thisrel->catalogname || thisrel->schemaname)
2379                                 ereport(ERROR,
2380                                                 (errcode(ERRCODE_SYNTAX_ERROR),
2381                                                  errmsg("SELECT FOR UPDATE/SHARE must specify unqualified relation names"),
2382                                                  parser_errposition(pstate, thisrel->location)));
2383
2384                         i = 0;
2385                         foreach(rt, qry->rtable)
2386                         {
2387                                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2388
2389                                 ++i;
2390                                 if (strcmp(rte->eref->aliasname, thisrel->relname) == 0)
2391                                 {
2392                                         switch (rte->rtekind)
2393                                         {
2394                                                 case RTE_RELATION:
2395                                                         if (rte->relkind == RELKIND_FOREIGN_TABLE)
2396                                                                 ereport(ERROR,
2397                                                                          (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2398                                                                           errmsg("SELECT FOR UPDATE/SHARE cannot be used with foreign table \"%s\"",
2399                                                                                          rte->eref->aliasname),
2400                                                                           parser_errposition(pstate, thisrel->location)));
2401                                                         applyLockingClause(qry, i,
2402                                                                                            lc->forUpdate, lc->noWait,
2403                                                                                            pushedDown);
2404                                                         rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
2405                                                         break;
2406                                                 case RTE_SUBQUERY:
2407                                                         applyLockingClause(qry, i,
2408                                                                                            lc->forUpdate, lc->noWait,
2409                                                                                            pushedDown);
2410                                                         /* see comment above */
2411                                                         transformLockingClause(pstate, rte->subquery,
2412                                                                                                    allrels, true);
2413                                                         break;
2414                                                 case RTE_JOIN:
2415                                                         ereport(ERROR,
2416                                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2417                                                                          errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join"),
2418                                                          parser_errposition(pstate, thisrel->location)));
2419                                                         break;
2420                                                 case RTE_FUNCTION:
2421                                                         ereport(ERROR,
2422                                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2423                                                                          errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function"),
2424                                                          parser_errposition(pstate, thisrel->location)));
2425                                                         break;
2426                                                 case RTE_VALUES:
2427                                                         ereport(ERROR,
2428                                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2429                                                                          errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES"),
2430                                                          parser_errposition(pstate, thisrel->location)));
2431                                                         break;
2432                                                 case RTE_CTE:
2433                                                         ereport(ERROR,
2434                                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2435                                                                          errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a WITH query"),
2436                                                          parser_errposition(pstate, thisrel->location)));
2437                                                         break;
2438                                                 default:
2439                                                         elog(ERROR, "unrecognized RTE type: %d",
2440                                                                  (int) rte->rtekind);
2441                                                         break;
2442                                         }
2443                                         break;          /* out of foreach loop */
2444                                 }
2445                         }
2446                         if (rt == NULL)
2447                                 ereport(ERROR,
2448                                                 (errcode(ERRCODE_UNDEFINED_TABLE),
2449                                                  errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
2450                                                                 thisrel->relname),
2451                                                  parser_errposition(pstate, thisrel->location)));
2452                 }
2453         }
2454 }
2455
2456 /*
2457  * Record locking info for a single rangetable item
2458  */
2459 void
2460 applyLockingClause(Query *qry, Index rtindex,
2461                                    bool forUpdate, bool noWait, bool pushedDown)
2462 {
2463         RowMarkClause *rc;
2464
2465         /* If it's an explicit clause, make sure hasForUpdate gets set */
2466         if (!pushedDown)
2467                 qry->hasForUpdate = true;
2468
2469         /* Check for pre-existing entry for same rtindex */
2470         if ((rc = get_parse_rowmark(qry, rtindex)) != NULL)
2471         {
2472                 /*
2473                  * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
2474                  * it as FOR UPDATE.  (Reasonable, since you can't take both a shared
2475                  * and exclusive lock at the same time; it'll end up being exclusive
2476                  * anyway.)
2477                  *
2478                  * We also consider that NOWAIT wins if it's specified both ways. This
2479                  * is a bit more debatable but raising an error doesn't seem helpful.
2480                  * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
2481                  * internally contains a plain FOR UPDATE spec.)
2482                  *
2483                  * And of course pushedDown becomes false if any clause is explicit.
2484                  */
2485                 rc->forUpdate |= forUpdate;
2486                 rc->noWait |= noWait;
2487                 rc->pushedDown &= pushedDown;
2488                 return;
2489         }
2490
2491         /* Make a new RowMarkClause */
2492         rc = makeNode(RowMarkClause);
2493         rc->rti = rtindex;
2494         rc->forUpdate = forUpdate;
2495         rc->noWait = noWait;
2496         rc->pushedDown = pushedDown;
2497         qry->rowMarks = lappend(qry->rowMarks, rc);
2498 }