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