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