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