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