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