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