]> granicus.if.org Git - postgresql/blob - src/backend/parser/analyze.c
Wording cleanup for error messages. Also change can't -> cannot.
[postgresql] / src / backend / parser / analyze.c
1 /*-------------------------------------------------------------------------
2  *
3  * analyze.c
4  *        transform the parse tree into a query tree
5  *
6  * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *      $PostgreSQL: pgsql/src/backend/parser/analyze.c,v 1.360 2007/02/01 19:10:27 momjian Exp $
10  *
11  *-------------------------------------------------------------------------
12  */
13
14 #include "postgres.h"
15
16 #include "access/heapam.h"
17 #include "catalog/heap.h"
18 #include "catalog/index.h"
19 #include "catalog/namespace.h"
20 #include "catalog/pg_type.h"
21 #include "commands/defrem.h"
22 #include "commands/prepare.h"
23 #include "commands/tablecmds.h"
24 #include "miscadmin.h"
25 #include "nodes/makefuncs.h"
26 #include "optimizer/clauses.h"
27 #include "optimizer/var.h"
28 #include "parser/analyze.h"
29 #include "parser/gramparse.h"
30 #include "parser/parse_agg.h"
31 #include "parser/parse_clause.h"
32 #include "parser/parse_coerce.h"
33 #include "parser/parse_expr.h"
34 #include "parser/parse_expr.h"
35 #include "parser/parse_relation.h"
36 #include "parser/parse_target.h"
37 #include "parser/parse_type.h"
38 #include "parser/parsetree.h"
39 #include "rewrite/rewriteManip.h"
40 #include "utils/acl.h"
41 #include "utils/builtins.h"
42 #include "utils/lsyscache.h"
43 #include "utils/syscache.h"
44
45
46 /* State shared by transformCreateSchemaStmt and its subroutines */
47 typedef struct
48 {
49         const char *stmtType;           /* "CREATE SCHEMA" or "ALTER SCHEMA" */
50         char       *schemaname;         /* name of schema */
51         char       *authid;                     /* owner of schema */
52         List       *sequences;          /* CREATE SEQUENCE items */
53         List       *tables;                     /* CREATE TABLE items */
54         List       *views;                      /* CREATE VIEW items */
55         List       *indexes;            /* CREATE INDEX items */
56         List       *triggers;           /* CREATE TRIGGER items */
57         List       *grants;                     /* GRANT items */
58         List       *fwconstraints;      /* Forward referencing FOREIGN KEY constraints */
59         List       *alters;                     /* Generated ALTER items (from the above) */
60         List       *ixconstraints;      /* index-creating constraints */
61         List       *blist;                      /* "before list" of things to do before
62                                                                  * creating the schema */
63         List       *alist;                      /* "after list" of things to do after creating
64                                                                  * the schema */
65 } CreateSchemaStmtContext;
66
67 /* State shared by transformCreateStmt and its subroutines */
68 typedef struct
69 {
70         const char *stmtType;           /* "CREATE TABLE" or "ALTER TABLE" */
71         RangeVar   *relation;           /* relation to create */
72         List       *inhRelations;       /* relations to inherit from */
73         bool            hasoids;                /* does relation have an OID column? */
74         bool            isalter;                /* true if altering existing table */
75         List       *columns;            /* ColumnDef items */
76         List       *ckconstraints;      /* CHECK constraints */
77         List       *fkconstraints;      /* FOREIGN KEY constraints */
78         List       *ixconstraints;      /* index-creating constraints */
79         List       *blist;                      /* "before list" of things to do before
80                                                                  * creating the table */
81         List       *alist;                      /* "after list" of things to do after creating
82                                                                  * the table */
83         IndexStmt  *pkey;                       /* PRIMARY KEY index, if any */
84 } CreateStmtContext;
85
86 typedef struct
87 {
88         Oid                *paramTypes;
89         int                     numParams;
90 } check_parameter_resolution_context;
91
92
93 static List *do_parse_analyze(Node *parseTree, ParseState *pstate);
94 static Query *transformStmt(ParseState *pstate, Node *stmt,
95                           List **extras_before, List **extras_after);
96 static Query *transformViewStmt(ParseState *pstate, ViewStmt *stmt,
97                                   List **extras_before, List **extras_after);
98 static Query *transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt);
99 static Query *transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
100                                         List **extras_before, List **extras_after);
101 static List *transformInsertRow(ParseState *pstate, List *exprlist,
102                                    List *stmtcols, List *icolumns, List *attrnos);
103 static List *transformReturningList(ParseState *pstate, List *returningList);
104 static Query *transformIndexStmt(ParseState *pstate, IndexStmt *stmt);
105 static Query *transformRuleStmt(ParseState *query, RuleStmt *stmt,
106                                   List **extras_before, List **extras_after);
107 static Query *transformSelectStmt(ParseState *pstate, SelectStmt *stmt);
108 static Query *transformValuesClause(ParseState *pstate, SelectStmt *stmt);
109 static Query *transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt);
110 static Node *transformSetOperationTree(ParseState *pstate, SelectStmt *stmt);
111 static Query *transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt);
112 static Query *transformDeclareCursorStmt(ParseState *pstate,
113                                                    DeclareCursorStmt *stmt);
114 static Query *transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt);
115 static Query *transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt);
116 static Query *transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
117                                         List **extras_before, List **extras_after);
118 static Query *transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
119                                                 List **extras_before, List **extras_after);
120 static void transformColumnDefinition(ParseState *pstate,
121                                                   CreateStmtContext *cxt,
122                                                   ColumnDef *column);
123 static void transformTableConstraint(ParseState *pstate,
124                                                  CreateStmtContext *cxt,
125                                                  Constraint *constraint);
126 static void transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
127                                          InhRelation *inhrelation);
128 static void transformIndexConstraints(ParseState *pstate,
129                                                   CreateStmtContext *cxt);
130 static void transformFKConstraints(ParseState *pstate,
131                                            CreateStmtContext *cxt,
132                                            bool skipValidation,
133                                            bool isAddConstraint);
134 static void applyColumnNames(List *dst, List *src);
135 static void getSetColTypes(ParseState *pstate, Node *node,
136                            List **colTypes, List **colTypmods);
137 static void transformLockingClause(Query *qry, LockingClause *lc);
138 static void transformConstraintAttrs(List *constraintList);
139 static void transformColumnType(ParseState *pstate, ColumnDef *column);
140 static void release_pstate_resources(ParseState *pstate);
141 static FromExpr *makeFromExpr(List *fromlist, Node *quals);
142 static bool check_parameter_resolution_walker(Node *node,
143                                                                 check_parameter_resolution_context *context);
144
145
146 /*
147  * parse_analyze
148  *              Analyze a raw parse tree and transform it to Query form.
149  *
150  * If available, pass the source text from which the raw parse tree was
151  * generated; it's OK to pass NULL if this is not available.
152  *
153  * Optionally, information about $n parameter types can be supplied.
154  * References to $n indexes not defined by paramTypes[] are disallowed.
155  *
156  * The result is a List of Query nodes (we need a list since some commands
157  * produce multiple Queries).  Optimizable statements require considerable
158  * transformation, while many utility-type statements are simply hung off
159  * a dummy CMD_UTILITY Query node.
160  */
161 List *
162 parse_analyze(Node *parseTree, const char *sourceText,
163                           Oid *paramTypes, int numParams)
164 {
165         ParseState *pstate = make_parsestate(NULL);
166         List       *result;
167
168         pstate->p_sourcetext = sourceText;
169         pstate->p_paramtypes = paramTypes;
170         pstate->p_numparams = numParams;
171         pstate->p_variableparams = false;
172
173         result = do_parse_analyze(parseTree, pstate);
174
175         pfree(pstate);
176
177         return result;
178 }
179
180 /*
181  * parse_analyze_varparams
182  *
183  * This variant is used when it's okay to deduce information about $n
184  * symbol datatypes from context.  The passed-in paramTypes[] array can
185  * be modified or enlarged (via repalloc).
186  */
187 List *
188 parse_analyze_varparams(Node *parseTree, const char *sourceText,
189                                                 Oid **paramTypes, int *numParams)
190 {
191         ParseState *pstate = make_parsestate(NULL);
192         List       *result;
193
194         pstate->p_sourcetext = sourceText;
195         pstate->p_paramtypes = *paramTypes;
196         pstate->p_numparams = *numParams;
197         pstate->p_variableparams = true;
198
199         result = do_parse_analyze(parseTree, pstate);
200
201         *paramTypes = pstate->p_paramtypes;
202         *numParams = pstate->p_numparams;
203
204         pfree(pstate);
205
206         /* make sure all is well with parameter types */
207         if (*numParams > 0)
208         {
209                 check_parameter_resolution_context context;
210
211                 context.paramTypes = *paramTypes;
212                 context.numParams = *numParams;
213                 check_parameter_resolution_walker((Node *) result, &context);
214         }
215
216         return result;
217 }
218
219 /*
220  * parse_sub_analyze
221  *              Entry point for recursively analyzing a sub-statement.
222  */
223 List *
224 parse_sub_analyze(Node *parseTree, ParseState *parentParseState)
225 {
226         ParseState *pstate = make_parsestate(parentParseState);
227         List       *result;
228
229         result = do_parse_analyze(parseTree, pstate);
230
231         pfree(pstate);
232
233         return result;
234 }
235
236 /*
237  * do_parse_analyze
238  *              Workhorse code shared by the above variants of parse_analyze.
239  */
240 static List *
241 do_parse_analyze(Node *parseTree, ParseState *pstate)
242 {
243         List       *result = NIL;
244
245         /* Lists to return extra commands from transformation */
246         List       *extras_before = NIL;
247         List       *extras_after = NIL;
248         Query      *query;
249         ListCell   *l;
250
251         query = transformStmt(pstate, parseTree, &extras_before, &extras_after);
252
253         /* don't need to access result relation any more */
254         release_pstate_resources(pstate);
255
256         foreach(l, extras_before)
257                 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
258
259         result = lappend(result, query);
260
261         foreach(l, extras_after)
262                 result = list_concat(result, parse_sub_analyze(lfirst(l), pstate));
263
264         /*
265          * Make sure that only the original query is marked original. We have to
266          * do this explicitly since recursive calls of do_parse_analyze will have
267          * marked some of the added-on queries as "original".  Also mark only the
268          * original query as allowed to set the command-result tag.
269          */
270         foreach(l, result)
271         {
272                 Query      *q = lfirst(l);
273
274                 if (q == query)
275                 {
276                         q->querySource = QSRC_ORIGINAL;
277                         q->canSetTag = true;
278                 }
279                 else
280                 {
281                         q->querySource = QSRC_PARSER;
282                         q->canSetTag = false;
283                 }
284         }
285
286         return result;
287 }
288
289 static void
290 release_pstate_resources(ParseState *pstate)
291 {
292         if (pstate->p_target_relation != NULL)
293                 heap_close(pstate->p_target_relation, NoLock);
294         pstate->p_target_relation = NULL;
295         pstate->p_target_rangetblentry = NULL;
296 }
297
298 /*
299  * transformStmt -
300  *        transform a Parse tree into a Query tree.
301  */
302 static Query *
303 transformStmt(ParseState *pstate, Node *parseTree,
304                           List **extras_before, List **extras_after)
305 {
306         Query      *result = NULL;
307
308         switch (nodeTag(parseTree))
309         {
310                         /*
311                          * Non-optimizable statements
312                          */
313                 case T_CreateStmt:
314                         result = transformCreateStmt(pstate, (CreateStmt *) parseTree,
315                                                                                  extras_before, extras_after);
316                         break;
317
318                 case T_IndexStmt:
319                         result = transformIndexStmt(pstate, (IndexStmt *) parseTree);
320                         break;
321
322                 case T_RuleStmt:
323                         result = transformRuleStmt(pstate, (RuleStmt *) parseTree,
324                                                                            extras_before, extras_after);
325                         break;
326
327                 case T_ViewStmt:
328                         result = transformViewStmt(pstate, (ViewStmt *) parseTree,
329                                                                            extras_before, extras_after);
330                         break;
331
332                 case T_ExplainStmt:
333                         {
334                                 ExplainStmt *n = (ExplainStmt *) parseTree;
335
336                                 result = makeNode(Query);
337                                 result->commandType = CMD_UTILITY;
338                                 n->query = transformStmt(pstate, (Node *) n->query,
339                                                                                  extras_before, extras_after);
340                                 result->utilityStmt = (Node *) parseTree;
341                         }
342                         break;
343
344                 case T_CopyStmt:
345                         {
346                                 CopyStmt   *n = (CopyStmt *) parseTree;
347
348                                 result = makeNode(Query);
349                                 result->commandType = CMD_UTILITY;
350                                 if (n->query)
351                                         n->query = transformStmt(pstate, (Node *) n->query,
352                                                                                          extras_before, extras_after);
353                                 result->utilityStmt = (Node *) parseTree;
354                         }
355                         break;
356
357                 case T_AlterTableStmt:
358                         result = transformAlterTableStmt(pstate,
359                                                                                          (AlterTableStmt *) parseTree,
360                                                                                          extras_before, extras_after);
361                         break;
362
363                 case T_PrepareStmt:
364                         result = transformPrepareStmt(pstate, (PrepareStmt *) parseTree);
365                         break;
366
367                 case T_ExecuteStmt:
368                         result = transformExecuteStmt(pstate, (ExecuteStmt *) parseTree);
369                         break;
370
371                         /*
372                          * Optimizable statements
373                          */
374                 case T_InsertStmt:
375                         result = transformInsertStmt(pstate, (InsertStmt *) parseTree,
376                                                                                  extras_before, extras_after);
377                         break;
378
379                 case T_DeleteStmt:
380                         result = transformDeleteStmt(pstate, (DeleteStmt *) parseTree);
381                         break;
382
383                 case T_UpdateStmt:
384                         result = transformUpdateStmt(pstate, (UpdateStmt *) parseTree);
385                         break;
386
387                 case T_SelectStmt:
388                         {
389                                 SelectStmt *n = (SelectStmt *) parseTree;
390
391                                 if (n->valuesLists)
392                                         result = transformValuesClause(pstate, n);
393                                 else if (n->op == SETOP_NONE)
394                                         result = transformSelectStmt(pstate, n);
395                                 else
396                                         result = transformSetOperationStmt(pstate, n);
397                         }
398                         break;
399
400                 case T_DeclareCursorStmt:
401                         result = transformDeclareCursorStmt(pstate,
402                                                                                         (DeclareCursorStmt *) parseTree);
403                         break;
404
405                 default:
406
407                         /*
408                          * other statements don't require any transformation-- just return
409                          * the original parsetree, yea!
410                          */
411                         result = makeNode(Query);
412                         result->commandType = CMD_UTILITY;
413                         result->utilityStmt = (Node *) parseTree;
414                         break;
415         }
416
417         /* Mark as original query until we learn differently */
418         result->querySource = QSRC_ORIGINAL;
419         result->canSetTag = true;
420
421         /*
422          * Check that we did not produce too many resnos; at the very least we
423          * cannot allow more than 2^16, since that would exceed the range of a
424          * AttrNumber. It seems safest to use MaxTupleAttributeNumber.
425          */
426         if (pstate->p_next_resno - 1 > MaxTupleAttributeNumber)
427                 ereport(ERROR,
428                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
429                                  errmsg("target lists can have at most %d entries",
430                                                 MaxTupleAttributeNumber)));
431
432         return result;
433 }
434
435 static Query *
436 transformViewStmt(ParseState *pstate, ViewStmt *stmt,
437                                   List **extras_before, List **extras_after)
438 {
439         Query      *result = makeNode(Query);
440
441         result->commandType = CMD_UTILITY;
442         result->utilityStmt = (Node *) stmt;
443
444         stmt->query = transformStmt(pstate, (Node *) stmt->query,
445                                                                 extras_before, extras_after);
446
447         /*
448          * If a list of column names was given, run through and insert these into
449          * the actual query tree. - thomas 2000-03-08
450          *
451          * Outer loop is over targetlist to make it easier to skip junk targetlist
452          * entries.
453          */
454         if (stmt->aliases != NIL)
455         {
456                 ListCell   *alist_item = list_head(stmt->aliases);
457                 ListCell   *targetList;
458
459                 foreach(targetList, stmt->query->targetList)
460                 {
461                         TargetEntry *te = (TargetEntry *) lfirst(targetList);
462
463                         Assert(IsA(te, TargetEntry));
464                         /* junk columns don't get aliases */
465                         if (te->resjunk)
466                                 continue;
467                         te->resname = pstrdup(strVal(lfirst(alist_item)));
468                         alist_item = lnext(alist_item);
469                         if (alist_item == NULL)
470                                 break;                  /* done assigning aliases */
471                 }
472
473                 if (alist_item != NULL)
474                         ereport(ERROR,
475                                         (errcode(ERRCODE_SYNTAX_ERROR),
476                                          errmsg("CREATE VIEW specifies more column "
477                                                         "names than columns")));
478         }
479
480         return result;
481 }
482
483 /*
484  * transformDeleteStmt -
485  *        transforms a Delete Statement
486  */
487 static Query *
488 transformDeleteStmt(ParseState *pstate, DeleteStmt *stmt)
489 {
490         Query      *qry = makeNode(Query);
491         Node       *qual;
492
493         qry->commandType = CMD_DELETE;
494
495         /* set up range table with just the result rel */
496         qry->resultRelation = setTargetTable(pstate, stmt->relation,
497                                                                   interpretInhOption(stmt->relation->inhOpt),
498                                                                                  true,
499                                                                                  ACL_DELETE);
500
501         qry->distinctClause = NIL;
502
503         /*
504          * The USING clause is non-standard SQL syntax, and is equivalent in
505          * functionality to the FROM list that can be specified for UPDATE. The
506          * USING keyword is used rather than FROM because FROM is already a
507          * keyword in the DELETE syntax.
508          */
509         transformFromClause(pstate, stmt->usingClause);
510
511         qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
512
513         qry->returningList = transformReturningList(pstate, stmt->returningList);
514
515         /* done building the range table and jointree */
516         qry->rtable = pstate->p_rtable;
517         qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
518
519         qry->hasSubLinks = pstate->p_hasSubLinks;
520         qry->hasAggs = pstate->p_hasAggs;
521         if (pstate->p_hasAggs)
522                 parseCheckAggregates(pstate, qry);
523
524         return qry;
525 }
526
527 /*
528  * transformInsertStmt -
529  *        transform an Insert Statement
530  */
531 static Query *
532 transformInsertStmt(ParseState *pstate, InsertStmt *stmt,
533                                         List **extras_before, List **extras_after)
534 {
535         Query      *qry = makeNode(Query);
536         SelectStmt *selectStmt = (SelectStmt *) stmt->selectStmt;
537         List       *exprList = NIL;
538         bool            isGeneralSelect;
539         List       *sub_rtable;
540         List       *sub_relnamespace;
541         List       *sub_varnamespace;
542         List       *icolumns;
543         List       *attrnos;
544         RangeTblEntry *rte;
545         RangeTblRef *rtr;
546         ListCell   *icols;
547         ListCell   *attnos;
548         ListCell   *lc;
549
550         qry->commandType = CMD_INSERT;
551         pstate->p_is_insert = true;
552
553         /*
554          * We have three cases to deal with: DEFAULT VALUES (selectStmt == NULL),
555          * VALUES list, or general SELECT input.  We special-case VALUES, both for
556          * efficiency and so we can handle DEFAULT specifications.
557          */
558         isGeneralSelect = (selectStmt && selectStmt->valuesLists == NIL);
559
560         /*
561          * If a non-nil rangetable/namespace was passed in, and we are doing
562          * INSERT/SELECT, arrange to pass the rangetable/namespace down to the
563          * SELECT.      This can only happen if we are inside a CREATE RULE, and in
564          * that case we want the rule's OLD and NEW rtable entries to appear as
565          * part of the SELECT's rtable, not as outer references for it.  (Kluge!)
566          * The SELECT's joinlist is not affected however.  We must do this before
567          * adding the target table to the INSERT's rtable.
568          */
569         if (isGeneralSelect)
570         {
571                 sub_rtable = pstate->p_rtable;
572                 pstate->p_rtable = NIL;
573                 sub_relnamespace = pstate->p_relnamespace;
574                 pstate->p_relnamespace = NIL;
575                 sub_varnamespace = pstate->p_varnamespace;
576                 pstate->p_varnamespace = NIL;
577         }
578         else
579         {
580                 sub_rtable = NIL;               /* not used, but keep compiler quiet */
581                 sub_relnamespace = NIL;
582                 sub_varnamespace = NIL;
583         }
584
585         /*
586          * Must get write lock on INSERT target table before scanning SELECT, else
587          * we will grab the wrong kind of initial lock if the target table is also
588          * mentioned in the SELECT part.  Note that the target table is not added
589          * to the joinlist or namespace.
590          */
591         qry->resultRelation = setTargetTable(pstate, stmt->relation,
592                                                                                  false, false, ACL_INSERT);
593
594         /* Validate stmt->cols list, or build default list if no list given */
595         icolumns = checkInsertTargets(pstate, stmt->cols, &attrnos);
596         Assert(list_length(icolumns) == list_length(attrnos));
597
598         /*
599          * Determine which variant of INSERT we have.
600          */
601         if (selectStmt == NULL)
602         {
603                 /*
604                  * We have INSERT ... DEFAULT VALUES.  We can handle this case by
605                  * emitting an empty targetlist --- all columns will be defaulted when
606                  * the planner expands the targetlist.
607                  */
608                 exprList = NIL;
609         }
610         else if (isGeneralSelect)
611         {
612                 /*
613                  * We make the sub-pstate a child of the outer pstate so that it can
614                  * see any Param definitions supplied from above.  Since the outer
615                  * pstate's rtable and namespace are presently empty, there are no
616                  * side-effects of exposing names the sub-SELECT shouldn't be able to
617                  * see.
618                  */
619                 ParseState *sub_pstate = make_parsestate(pstate);
620                 Query      *selectQuery;
621
622                 /*
623                  * Process the source SELECT.
624                  *
625                  * It is important that this be handled just like a standalone SELECT;
626                  * otherwise the behavior of SELECT within INSERT might be different
627                  * from a stand-alone SELECT. (Indeed, Postgres up through 6.5 had
628                  * bugs of just that nature...)
629                  */
630                 sub_pstate->p_rtable = sub_rtable;
631                 sub_pstate->p_relnamespace = sub_relnamespace;
632                 sub_pstate->p_varnamespace = sub_varnamespace;
633
634                 /*
635                  * Note: we are not expecting that extras_before and extras_after are
636                  * going to be used by the transformation of the SELECT statement.
637                  */
638                 selectQuery = transformStmt(sub_pstate, stmt->selectStmt,
639                                                                         extras_before, extras_after);
640
641                 release_pstate_resources(sub_pstate);
642                 pfree(sub_pstate);
643
644                 Assert(IsA(selectQuery, Query));
645                 Assert(selectQuery->commandType == CMD_SELECT);
646                 if (selectQuery->into)
647                         ereport(ERROR,
648                                         (errcode(ERRCODE_SYNTAX_ERROR),
649                                          errmsg("INSERT ... SELECT cannot specify INTO")));
650
651                 /*
652                  * Make the source be a subquery in the INSERT's rangetable, and add
653                  * it to the INSERT's joinlist.
654                  */
655                 rte = addRangeTableEntryForSubquery(pstate,
656                                                                                         selectQuery,
657                                                                                         makeAlias("*SELECT*", NIL),
658                                                                                         false);
659                 rtr = makeNode(RangeTblRef);
660                 /* assume new rte is at end */
661                 rtr->rtindex = list_length(pstate->p_rtable);
662                 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
663                 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
664
665                 /*----------
666                  * Generate an expression list for the INSERT that selects all the
667                  * non-resjunk columns from the subquery.  (INSERT's tlist must be
668                  * separate from the subquery's tlist because we may add columns,
669                  * insert datatype coercions, etc.)
670                  *
671                  * HACK: unknown-type constants and params in the SELECT's targetlist
672                  * are copied up as-is rather than being referenced as subquery
673                  * outputs.  This is to ensure that when we try to coerce them to
674                  * the target column's datatype, the right things happen (see
675                  * special cases in coerce_type).  Otherwise, this fails:
676                  *              INSERT INTO foo SELECT 'bar', ... FROM baz
677                  *----------
678                  */
679                 exprList = NIL;
680                 foreach(lc, selectQuery->targetList)
681                 {
682                         TargetEntry *tle = (TargetEntry *) lfirst(lc);
683                         Expr       *expr;
684
685                         if (tle->resjunk)
686                                 continue;
687                         if (tle->expr &&
688                                 (IsA(tle->expr, Const) ||IsA(tle->expr, Param)) &&
689                                 exprType((Node *) tle->expr) == UNKNOWNOID)
690                                 expr = tle->expr;
691                         else
692                                 expr = (Expr *) makeVar(rtr->rtindex,
693                                                                                 tle->resno,
694                                                                                 exprType((Node *) tle->expr),
695                                                                                 exprTypmod((Node *) tle->expr),
696                                                                                 0);
697                         exprList = lappend(exprList, expr);
698                 }
699
700                 /* Prepare row for assignment to target table */
701                 exprList = transformInsertRow(pstate, exprList,
702                                                                           stmt->cols,
703                                                                           icolumns, attrnos);
704         }
705         else if (list_length(selectStmt->valuesLists) > 1)
706         {
707                 /*
708                  * Process INSERT ... VALUES with multiple VALUES sublists. We
709                  * generate a VALUES RTE holding the transformed expression lists, and
710                  * build up a targetlist containing Vars that reference the VALUES
711                  * RTE.
712                  */
713                 List       *exprsLists = NIL;
714                 int                     sublist_length = -1;
715
716                 foreach(lc, selectStmt->valuesLists)
717                 {
718                         List       *sublist = (List *) lfirst(lc);
719
720                         /* Do basic expression transformation (same as a ROW() expr) */
721                         sublist = transformExpressionList(pstate, sublist);
722
723                         /*
724                          * All the sublists must be the same length, *after*
725                          * transformation (which might expand '*' into multiple items).
726                          * The VALUES RTE can't handle anything different.
727                          */
728                         if (sublist_length < 0)
729                         {
730                                 /* Remember post-transformation length of first sublist */
731                                 sublist_length = list_length(sublist);
732                         }
733                         else if (sublist_length != list_length(sublist))
734                         {
735                                 ereport(ERROR,
736                                                 (errcode(ERRCODE_SYNTAX_ERROR),
737                                                  errmsg("VALUES lists must all be the same length")));
738                         }
739
740                         /* Prepare row for assignment to target table */
741                         sublist = transformInsertRow(pstate, sublist,
742                                                                                  stmt->cols,
743                                                                                  icolumns, attrnos);
744
745                         exprsLists = lappend(exprsLists, sublist);
746                 }
747
748                 /*
749                  * There mustn't have been any table references in the expressions,
750                  * else strange things would happen, like Cartesian products of those
751                  * tables with the VALUES list ...
752                  */
753                 if (pstate->p_joinlist != NIL)
754                         ereport(ERROR,
755                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
756                                          errmsg("VALUES must not contain table references")));
757
758                 /*
759                  * Another thing we can't currently support is NEW/OLD references in
760                  * rules --- seems we'd need something like SQL99's LATERAL construct
761                  * to ensure that the values would be available while evaluating the
762                  * VALUES RTE.  This is a shame.  FIXME
763                  */
764                 if (list_length(pstate->p_rtable) != 1 &&
765                         contain_vars_of_level((Node *) exprsLists, 0))
766                         ereport(ERROR,
767                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
768                                          errmsg("VALUES must not contain OLD or NEW references"),
769                                          errhint("Use SELECT ... UNION ALL ... instead.")));
770
771                 /*
772                  * Generate the VALUES RTE
773                  */
774                 rte = addRangeTableEntryForValues(pstate, exprsLists, NULL, true);
775                 rtr = makeNode(RangeTblRef);
776                 /* assume new rte is at end */
777                 rtr->rtindex = list_length(pstate->p_rtable);
778                 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
779                 pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
780
781                 /*
782                  * Generate list of Vars referencing the RTE
783                  */
784                 expandRTE(rte, rtr->rtindex, 0, false, NULL, &exprList);
785         }
786         else
787         {
788                 /*----------
789                  * Process INSERT ... VALUES with a single VALUES sublist.
790                  * We treat this separately for efficiency and for historical
791                  * compatibility --- specifically, allowing table references,
792                  * such as
793                  *                      INSERT INTO foo VALUES(bar.*)
794                  *
795                  * The sublist is just computed directly as the Query's targetlist,
796                  * with no VALUES RTE.  So it works just like SELECT without FROM.
797                  *----------
798                  */
799                 List       *valuesLists = selectStmt->valuesLists;
800
801                 Assert(list_length(valuesLists) == 1);
802
803                 /* Do basic expression transformation (same as a ROW() expr) */
804                 exprList = transformExpressionList(pstate,
805                                                                                    (List *) linitial(valuesLists));
806
807                 /* Prepare row for assignment to target table */
808                 exprList = transformInsertRow(pstate, exprList,
809                                                                           stmt->cols,
810                                                                           icolumns, attrnos);
811         }
812
813         /*
814          * Generate query's target list using the computed list of expressions.
815          */
816         qry->targetList = NIL;
817         icols = list_head(icolumns);
818         attnos = list_head(attrnos);
819         foreach(lc, exprList)
820         {
821                 Expr       *expr = (Expr *) lfirst(lc);
822                 ResTarget  *col;
823                 TargetEntry *tle;
824
825                 col = (ResTarget *) lfirst(icols);
826                 Assert(IsA(col, ResTarget));
827
828                 tle = makeTargetEntry(expr,
829                                                           (AttrNumber) lfirst_int(attnos),
830                                                           col->name,
831                                                           false);
832                 qry->targetList = lappend(qry->targetList, tle);
833
834                 icols = lnext(icols);
835                 attnos = lnext(attnos);
836         }
837
838         /*
839          * If we have a RETURNING clause, we need to add the target relation to
840          * the query namespace before processing it, so that Var references in
841          * RETURNING will work.  Also, remove any namespace entries added in a
842          * sub-SELECT or VALUES list.
843          */
844         if (stmt->returningList)
845         {
846                 pstate->p_relnamespace = NIL;
847                 pstate->p_varnamespace = NIL;
848                 addRTEtoQuery(pstate, pstate->p_target_rangetblentry,
849                                           false, true, true);
850                 qry->returningList = transformReturningList(pstate,
851                                                                                                         stmt->returningList);
852         }
853
854         /* done building the range table and jointree */
855         qry->rtable = pstate->p_rtable;
856         qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
857
858         qry->hasSubLinks = pstate->p_hasSubLinks;
859         /* aggregates not allowed (but subselects are okay) */
860         if (pstate->p_hasAggs)
861                 ereport(ERROR,
862                                 (errcode(ERRCODE_GROUPING_ERROR),
863                                  errmsg("cannot use aggregate function in VALUES")));
864
865         return qry;
866 }
867
868 /*
869  * Prepare an INSERT row for assignment to the target table.
870  *
871  * The row might be either a VALUES row, or variables referencing a
872  * sub-SELECT output.
873  */
874 static List *
875 transformInsertRow(ParseState *pstate, List *exprlist,
876                                    List *stmtcols, List *icolumns, List *attrnos)
877 {
878         List       *result;
879         ListCell   *lc;
880         ListCell   *icols;
881         ListCell   *attnos;
882
883         /*
884          * Check length of expr list.  It must not have more expressions than
885          * there are target columns.  We allow fewer, but only if no explicit
886          * columns list was given (the remaining columns are implicitly
887          * defaulted).  Note we must check this *after* transformation because
888          * that could expand '*' into multiple items.
889          */
890         if (list_length(exprlist) > list_length(icolumns))
891                 ereport(ERROR,
892                                 (errcode(ERRCODE_SYNTAX_ERROR),
893                                  errmsg("INSERT has more expressions than target columns")));
894         if (stmtcols != NIL &&
895                 list_length(exprlist) < list_length(icolumns))
896                 ereport(ERROR,
897                                 (errcode(ERRCODE_SYNTAX_ERROR),
898                                  errmsg("INSERT has more target columns than expressions")));
899
900         /*
901          * Prepare columns for assignment to target table.
902          */
903         result = NIL;
904         icols = list_head(icolumns);
905         attnos = list_head(attrnos);
906         foreach(lc, exprlist)
907         {
908                 Expr       *expr = (Expr *) lfirst(lc);
909                 ResTarget  *col;
910
911                 col = (ResTarget *) lfirst(icols);
912                 Assert(IsA(col, ResTarget));
913
914                 expr = transformAssignedExpr(pstate, expr,
915                                                                          col->name,
916                                                                          lfirst_int(attnos),
917                                                                          col->indirection,
918                                                                          col->location);
919
920                 result = lappend(result, expr);
921
922                 icols = lnext(icols);
923                 attnos = lnext(attnos);
924         }
925
926         return result;
927 }
928
929 /*
930  * transformCreateStmt -
931  *        transforms the "create table" statement
932  *        SQL92 allows constraints to be scattered all over, so thumb through
933  *         the columns and collect all constraints into one place.
934  *        If there are any implied indices (e.g. UNIQUE or PRIMARY KEY)
935  *         then expand those into multiple IndexStmt blocks.
936  *        - thomas 1997-12-02
937  */
938 static Query *
939 transformCreateStmt(ParseState *pstate, CreateStmt *stmt,
940                                         List **extras_before, List **extras_after)
941 {
942         CreateStmtContext cxt;
943         Query      *q;
944         ListCell   *elements;
945
946         cxt.stmtType = "CREATE TABLE";
947         cxt.relation = stmt->relation;
948         cxt.inhRelations = stmt->inhRelations;
949         cxt.isalter = false;
950         cxt.columns = NIL;
951         cxt.ckconstraints = NIL;
952         cxt.fkconstraints = NIL;
953         cxt.ixconstraints = NIL;
954         cxt.blist = NIL;
955         cxt.alist = NIL;
956         cxt.pkey = NULL;
957         cxt.hasoids = interpretOidsOption(stmt->options);
958
959         /*
960          * Run through each primary element in the table creation clause. Separate
961          * column defs from constraints, and do preliminary analysis.
962          */
963         foreach(elements, stmt->tableElts)
964         {
965                 Node       *element = lfirst(elements);
966
967                 switch (nodeTag(element))
968                 {
969                         case T_ColumnDef:
970                                 transformColumnDefinition(pstate, &cxt,
971                                                                                   (ColumnDef *) element);
972                                 break;
973
974                         case T_Constraint:
975                                 transformTableConstraint(pstate, &cxt,
976                                                                                  (Constraint *) element);
977                                 break;
978
979                         case T_FkConstraint:
980                                 /* No pre-transformation needed */
981                                 cxt.fkconstraints = lappend(cxt.fkconstraints, element);
982                                 break;
983
984                         case T_InhRelation:
985                                 transformInhRelation(pstate, &cxt,
986                                                                          (InhRelation *) element);
987                                 break;
988
989                         default:
990                                 elog(ERROR, "unrecognized node type: %d",
991                                          (int) nodeTag(element));
992                                 break;
993                 }
994         }
995
996         /*
997          * transformIndexConstraints wants cxt.alist to contain only index
998          * statements, so transfer anything we already have into extras_after
999          * immediately.
1000          */
1001         *extras_after = list_concat(cxt.alist, *extras_after);
1002         cxt.alist = NIL;
1003
1004         Assert(stmt->constraints == NIL);
1005
1006         /*
1007          * Postprocess constraints that give rise to index definitions.
1008          */
1009         transformIndexConstraints(pstate, &cxt);
1010
1011         /*
1012          * Postprocess foreign-key constraints.
1013          */
1014         transformFKConstraints(pstate, &cxt, true, false);
1015
1016         /*
1017          * Output results.
1018          */
1019         q = makeNode(Query);
1020         q->commandType = CMD_UTILITY;
1021         q->utilityStmt = (Node *) stmt;
1022         stmt->tableElts = cxt.columns;
1023         stmt->constraints = cxt.ckconstraints;
1024         *extras_before = list_concat(*extras_before, cxt.blist);
1025         *extras_after = list_concat(cxt.alist, *extras_after);
1026
1027         return q;
1028 }
1029
1030 static void
1031 transformColumnDefinition(ParseState *pstate, CreateStmtContext *cxt,
1032                                                   ColumnDef *column)
1033 {
1034         bool            is_serial;
1035         bool            saw_nullable;
1036         Constraint *constraint;
1037         ListCell   *clist;
1038
1039         cxt->columns = lappend(cxt->columns, column);
1040
1041         /* Check for SERIAL pseudo-types */
1042         is_serial = false;
1043         if (list_length(column->typename->names) == 1)
1044         {
1045                 char       *typname = strVal(linitial(column->typename->names));
1046
1047                 if (strcmp(typname, "serial") == 0 ||
1048                         strcmp(typname, "serial4") == 0)
1049                 {
1050                         is_serial = true;
1051                         column->typename->names = NIL;
1052                         column->typename->typeid = INT4OID;
1053                 }
1054                 else if (strcmp(typname, "bigserial") == 0 ||
1055                                  strcmp(typname, "serial8") == 0)
1056                 {
1057                         is_serial = true;
1058                         column->typename->names = NIL;
1059                         column->typename->typeid = INT8OID;
1060                 }
1061         }
1062
1063         /* Do necessary work on the column type declaration */
1064         transformColumnType(pstate, column);
1065
1066         /* Special actions for SERIAL pseudo-types */
1067         if (is_serial)
1068         {
1069                 Oid                     snamespaceid;
1070                 char       *snamespace;
1071                 char       *sname;
1072                 char       *qstring;
1073                 A_Const    *snamenode;
1074                 FuncCall   *funccallnode;
1075                 CreateSeqStmt *seqstmt;
1076                 AlterSeqStmt *altseqstmt;
1077                 List       *attnamelist;
1078
1079                 /*
1080                  * Determine namespace and name to use for the sequence.
1081                  *
1082                  * Although we use ChooseRelationName, it's not guaranteed that the
1083                  * selected sequence name won't conflict; given sufficiently long
1084                  * field names, two different serial columns in the same table could
1085                  * be assigned the same sequence name, and we'd not notice since we
1086                  * aren't creating the sequence quite yet.  In practice this seems
1087                  * quite unlikely to be a problem, especially since few people would
1088                  * need two serial columns in one table.
1089                  */
1090                 snamespaceid = RangeVarGetCreationNamespace(cxt->relation);
1091                 snamespace = get_namespace_name(snamespaceid);
1092                 sname = ChooseRelationName(cxt->relation->relname,
1093                                                                    column->colname,
1094                                                                    "seq",
1095                                                                    snamespaceid);
1096
1097                 ereport(NOTICE,
1098                                 (errmsg("%s will create implicit sequence \"%s\" for serial column \"%s.%s\"",
1099                                                 cxt->stmtType, sname,
1100                                                 cxt->relation->relname, column->colname)));
1101
1102                 /*
1103                  * Build a CREATE SEQUENCE command to create the sequence object, and
1104                  * add it to the list of things to be done before this CREATE/ALTER
1105                  * TABLE.
1106                  */
1107                 seqstmt = makeNode(CreateSeqStmt);
1108                 seqstmt->sequence = makeRangeVar(snamespace, sname);
1109                 seqstmt->options = NIL;
1110
1111                 cxt->blist = lappend(cxt->blist, seqstmt);
1112
1113                 /*
1114                  * Build an ALTER SEQUENCE ... OWNED BY command to mark the sequence
1115                  * as owned by this column, and add it to the list of things to be
1116                  * done after this CREATE/ALTER TABLE.
1117                  */
1118                 altseqstmt = makeNode(AlterSeqStmt);
1119                 altseqstmt->sequence = makeRangeVar(snamespace, sname);
1120                 attnamelist = list_make3(makeString(snamespace),
1121                                                                  makeString(cxt->relation->relname),
1122                                                                  makeString(column->colname));
1123                 altseqstmt->options = list_make1(makeDefElem("owned_by",
1124                                                                                                          (Node *) attnamelist));
1125
1126                 cxt->alist = lappend(cxt->alist, altseqstmt);
1127
1128                 /*
1129                  * Create appropriate constraints for SERIAL.  We do this in full,
1130                  * rather than shortcutting, so that we will detect any conflicting
1131                  * constraints the user wrote (like a different DEFAULT).
1132                  *
1133                  * Create an expression tree representing the function call
1134                  * nextval('sequencename').  We cannot reduce the raw tree to cooked
1135                  * form until after the sequence is created, but there's no need to do
1136                  * so.
1137                  */
1138                 qstring = quote_qualified_identifier(snamespace, sname);
1139                 snamenode = makeNode(A_Const);
1140                 snamenode->val.type = T_String;
1141                 snamenode->val.val.str = qstring;
1142                 snamenode->typename = SystemTypeName("regclass");
1143                 funccallnode = makeNode(FuncCall);
1144                 funccallnode->funcname = SystemFuncName("nextval");
1145                 funccallnode->args = list_make1(snamenode);
1146                 funccallnode->agg_star = false;
1147                 funccallnode->agg_distinct = false;
1148                 funccallnode->location = -1;
1149
1150                 constraint = makeNode(Constraint);
1151                 constraint->contype = CONSTR_DEFAULT;
1152                 constraint->raw_expr = (Node *) funccallnode;
1153                 constraint->cooked_expr = NULL;
1154                 constraint->keys = NIL;
1155                 column->constraints = lappend(column->constraints, constraint);
1156
1157                 constraint = makeNode(Constraint);
1158                 constraint->contype = CONSTR_NOTNULL;
1159                 column->constraints = lappend(column->constraints, constraint);
1160         }
1161
1162         /* Process column constraints, if any... */
1163         transformConstraintAttrs(column->constraints);
1164
1165         saw_nullable = false;
1166
1167         foreach(clist, column->constraints)
1168         {
1169                 constraint = lfirst(clist);
1170
1171                 /*
1172                  * If this column constraint is a FOREIGN KEY constraint, then we fill
1173                  * in the current attribute's name and throw it into the list of FK
1174                  * constraints to be processed later.
1175                  */
1176                 if (IsA(constraint, FkConstraint))
1177                 {
1178                         FkConstraint *fkconstraint = (FkConstraint *) constraint;
1179
1180                         fkconstraint->fk_attrs = list_make1(makeString(column->colname));
1181                         cxt->fkconstraints = lappend(cxt->fkconstraints, fkconstraint);
1182                         continue;
1183                 }
1184
1185                 Assert(IsA(constraint, Constraint));
1186
1187                 switch (constraint->contype)
1188                 {
1189                         case CONSTR_NULL:
1190                                 if (saw_nullable && column->is_not_null)
1191                                         ereport(ERROR,
1192                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1193                                                          errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
1194                                                                   column->colname, cxt->relation->relname)));
1195                                 column->is_not_null = FALSE;
1196                                 saw_nullable = true;
1197                                 break;
1198
1199                         case CONSTR_NOTNULL:
1200                                 if (saw_nullable && !column->is_not_null)
1201                                         ereport(ERROR,
1202                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1203                                                          errmsg("conflicting NULL/NOT NULL declarations for column \"%s\" of table \"%s\"",
1204                                                                   column->colname, cxt->relation->relname)));
1205                                 column->is_not_null = TRUE;
1206                                 saw_nullable = true;
1207                                 break;
1208
1209                         case CONSTR_DEFAULT:
1210                                 if (column->raw_default != NULL)
1211                                         ereport(ERROR,
1212                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1213                                                          errmsg("multiple default values specified for column \"%s\" of table \"%s\"",
1214                                                                   column->colname, cxt->relation->relname)));
1215                                 column->raw_default = constraint->raw_expr;
1216                                 Assert(constraint->cooked_expr == NULL);
1217                                 break;
1218
1219                         case CONSTR_PRIMARY:
1220                         case CONSTR_UNIQUE:
1221                                 if (constraint->keys == NIL)
1222                                         constraint->keys = list_make1(makeString(column->colname));
1223                                 cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1224                                 break;
1225
1226                         case CONSTR_CHECK:
1227                                 cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1228                                 break;
1229
1230                         case CONSTR_ATTR_DEFERRABLE:
1231                         case CONSTR_ATTR_NOT_DEFERRABLE:
1232                         case CONSTR_ATTR_DEFERRED:
1233                         case CONSTR_ATTR_IMMEDIATE:
1234                                 /* transformConstraintAttrs took care of these */
1235                                 break;
1236
1237                         default:
1238                                 elog(ERROR, "unrecognized constraint type: %d",
1239                                          constraint->contype);
1240                                 break;
1241                 }
1242         }
1243 }
1244
1245 static void
1246 transformTableConstraint(ParseState *pstate, CreateStmtContext *cxt,
1247                                                  Constraint *constraint)
1248 {
1249         switch (constraint->contype)
1250         {
1251                 case CONSTR_PRIMARY:
1252                 case CONSTR_UNIQUE:
1253                         cxt->ixconstraints = lappend(cxt->ixconstraints, constraint);
1254                         break;
1255
1256                 case CONSTR_CHECK:
1257                         cxt->ckconstraints = lappend(cxt->ckconstraints, constraint);
1258                         break;
1259
1260                 case CONSTR_NULL:
1261                 case CONSTR_NOTNULL:
1262                 case CONSTR_DEFAULT:
1263                 case CONSTR_ATTR_DEFERRABLE:
1264                 case CONSTR_ATTR_NOT_DEFERRABLE:
1265                 case CONSTR_ATTR_DEFERRED:
1266                 case CONSTR_ATTR_IMMEDIATE:
1267                         elog(ERROR, "invalid context for constraint type %d",
1268                                  constraint->contype);
1269                         break;
1270
1271                 default:
1272                         elog(ERROR, "unrecognized constraint type: %d",
1273                                  constraint->contype);
1274                         break;
1275         }
1276 }
1277
1278 /*
1279  * transformInhRelation
1280  *
1281  * Change the LIKE <subtable> portion of a CREATE TABLE statement into the
1282  * column definitions which recreate the user defined column portions of <subtable>.
1283  */
1284 static void
1285 transformInhRelation(ParseState *pstate, CreateStmtContext *cxt,
1286                                          InhRelation *inhRelation)
1287 {
1288         AttrNumber      parent_attno;
1289         Relation        relation;
1290         TupleDesc       tupleDesc;
1291         TupleConstr *constr;
1292         AclResult       aclresult;
1293         bool            including_defaults = false;
1294         bool            including_constraints = false;
1295         bool            including_indexes = false;
1296         ListCell   *elem;
1297
1298         relation = heap_openrv(inhRelation->relation, AccessShareLock);
1299
1300         if (relation->rd_rel->relkind != RELKIND_RELATION)
1301                 ereport(ERROR,
1302                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1303                                  errmsg("inherited relation \"%s\" is not a table",
1304                                                 inhRelation->relation->relname)));
1305
1306         /*
1307          * Check for SELECT privilages
1308          */
1309         aclresult = pg_class_aclcheck(RelationGetRelid(relation), GetUserId(),
1310                                                                   ACL_SELECT);
1311         if (aclresult != ACLCHECK_OK)
1312                 aclcheck_error(aclresult, ACL_KIND_CLASS,
1313                                            RelationGetRelationName(relation));
1314
1315         tupleDesc = RelationGetDescr(relation);
1316         constr = tupleDesc->constr;
1317
1318         foreach(elem, inhRelation->options)
1319         {
1320                 int                     option = lfirst_int(elem);
1321
1322                 switch (option)
1323                 {
1324                         case CREATE_TABLE_LIKE_INCLUDING_DEFAULTS:
1325                                 including_defaults = true;
1326                                 break;
1327                         case CREATE_TABLE_LIKE_EXCLUDING_DEFAULTS:
1328                                 including_defaults = false;
1329                                 break;
1330                         case CREATE_TABLE_LIKE_INCLUDING_CONSTRAINTS:
1331                                 including_constraints = true;
1332                                 break;
1333                         case CREATE_TABLE_LIKE_EXCLUDING_CONSTRAINTS:
1334                                 including_constraints = false;
1335                                 break;
1336                         case CREATE_TABLE_LIKE_INCLUDING_INDEXES:
1337                                 including_indexes = true;
1338                                 break;
1339                         case CREATE_TABLE_LIKE_EXCLUDING_INDEXES:
1340                                 including_indexes = false;
1341                                 break;
1342                         default:
1343                                 elog(ERROR, "unrecognized CREATE TABLE LIKE option: %d",
1344                                          option);
1345                 }
1346         }
1347
1348         if (including_indexes)
1349                 ereport(ERROR,
1350                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1351                                  errmsg("LIKE INCLUDING INDEXES is not implemented")));
1352
1353         /*
1354          * Insert the copied attributes into the cxt for the new table
1355          * definition.
1356          */
1357         for (parent_attno = 1; parent_attno <= tupleDesc->natts;
1358                  parent_attno++)
1359         {
1360                 Form_pg_attribute attribute = tupleDesc->attrs[parent_attno - 1];
1361                 char       *attributeName = NameStr(attribute->attname);
1362                 ColumnDef  *def;
1363
1364                 /*
1365                  * Ignore dropped columns in the parent.
1366                  */
1367                 if (attribute->attisdropped)
1368                         continue;
1369
1370                 /*
1371                  * Create a new column, which is marked as NOT inherited.
1372                  *
1373                  * For constraints, ONLY the NOT NULL constraint is inherited by the
1374                  * new column definition per SQL99.
1375                  */
1376                 def = makeNode(ColumnDef);
1377                 def->colname = pstrdup(attributeName);
1378                 def->typename = makeTypeNameFromOid(attribute->atttypid,
1379                                                                                         attribute->atttypmod);
1380                 def->inhcount = 0;
1381                 def->is_local = true;
1382                 def->is_not_null = attribute->attnotnull;
1383                 def->raw_default = NULL;
1384                 def->cooked_default = NULL;
1385                 def->constraints = NIL;
1386
1387                 /*
1388                  * Add to column list
1389                  */
1390                 cxt->columns = lappend(cxt->columns, def);
1391
1392                 /*
1393                  * Copy default, if present and the default has been requested
1394                  */
1395                 if (attribute->atthasdef && including_defaults)
1396                 {
1397                         char       *this_default = NULL;
1398                         AttrDefault *attrdef;
1399                         int                     i;
1400
1401                         /* Find default in constraint structure */
1402                         Assert(constr != NULL);
1403                         attrdef = constr->defval;
1404                         for (i = 0; i < constr->num_defval; i++)
1405                         {
1406                                 if (attrdef[i].adnum == parent_attno)
1407                                 {
1408                                         this_default = attrdef[i].adbin;
1409                                         break;
1410                                 }
1411                         }
1412                         Assert(this_default != NULL);
1413
1414                         /*
1415                          * If default expr could contain any vars, we'd need to fix 'em,
1416                          * but it can't; so default is ready to apply to child.
1417                          */
1418
1419                         def->cooked_default = pstrdup(this_default);
1420                 }
1421         }
1422
1423         /*
1424          * Copy CHECK constraints if requested, being careful to adjust
1425          * attribute numbers
1426          */
1427         if (including_constraints && tupleDesc->constr)
1428         {
1429                 AttrNumber *attmap = varattnos_map_schema(tupleDesc, cxt->columns);
1430                 int                     ccnum;
1431
1432                 for (ccnum = 0; ccnum < tupleDesc->constr->num_check; ccnum++)
1433                 {
1434                         char       *ccname = tupleDesc->constr->check[ccnum].ccname;
1435                         char       *ccbin = tupleDesc->constr->check[ccnum].ccbin;
1436                         Node       *ccbin_node = stringToNode(ccbin);
1437                         Constraint *n = makeNode(Constraint);
1438
1439                         change_varattnos_of_a_node(ccbin_node, attmap);
1440
1441                         n->contype = CONSTR_CHECK;
1442                         n->name = pstrdup(ccname);
1443                         n->raw_expr = NULL;
1444                         n->cooked_expr = nodeToString(ccbin_node);
1445                         n->indexspace = NULL;
1446                         cxt->ckconstraints = lappend(cxt->ckconstraints, (Node *) n);
1447                 }
1448         }
1449
1450         /*
1451          * Close the parent rel, but keep our AccessShareLock on it until xact
1452          * commit.      That will prevent someone else from deleting or ALTERing the
1453          * parent before the child is committed.
1454          */
1455         heap_close(relation, NoLock);
1456 }
1457
1458 static void
1459 transformIndexConstraints(ParseState *pstate, CreateStmtContext *cxt)
1460 {
1461         IndexStmt  *index;
1462         List       *indexlist = NIL;
1463         ListCell   *listptr;
1464         ListCell   *l;
1465
1466         /*
1467          * Run through the constraints that need to generate an index. For PRIMARY
1468          * KEY, mark each column as NOT NULL and create an index. For UNIQUE,
1469          * create an index as for PRIMARY KEY, but do not insist on NOT NULL.
1470          */
1471         foreach(listptr, cxt->ixconstraints)
1472         {
1473                 Constraint *constraint = lfirst(listptr);
1474                 ListCell   *keys;
1475                 IndexElem  *iparam;
1476
1477                 Assert(IsA(constraint, Constraint));
1478                 Assert((constraint->contype == CONSTR_PRIMARY)
1479                            || (constraint->contype == CONSTR_UNIQUE));
1480
1481                 index = makeNode(IndexStmt);
1482
1483                 index->unique = true;
1484                 index->primary = (constraint->contype == CONSTR_PRIMARY);
1485                 if (index->primary)
1486                 {
1487                         if (cxt->pkey != NULL)
1488                                 ereport(ERROR,
1489                                                 (errcode(ERRCODE_INVALID_TABLE_DEFINITION),
1490                                                  errmsg("multiple primary keys for table \"%s\" are not allowed",
1491                                                                 cxt->relation->relname)));
1492                         cxt->pkey = index;
1493
1494                         /*
1495                          * In ALTER TABLE case, a primary index might already exist, but
1496                          * DefineIndex will check for it.
1497                          */
1498                 }
1499                 index->isconstraint = true;
1500
1501                 if (constraint->name != NULL)
1502                         index->idxname = pstrdup(constraint->name);
1503                 else
1504                         index->idxname = NULL;          /* DefineIndex will choose name */
1505
1506                 index->relation = cxt->relation;
1507                 index->accessMethod = DEFAULT_INDEX_TYPE;
1508                 index->options = constraint->options;
1509                 index->tableSpace = constraint->indexspace;
1510                 index->indexParams = NIL;
1511                 index->whereClause = NULL;
1512                 index->concurrent = false;
1513
1514                 /*
1515                  * Make sure referenced keys exist.  If we are making a PRIMARY KEY
1516                  * index, also make sure they are NOT NULL, if possible. (Although we
1517                  * could leave it to DefineIndex to mark the columns NOT NULL, it's
1518                  * more efficient to get it right the first time.)
1519                  */
1520                 foreach(keys, constraint->keys)
1521                 {
1522                         char       *key = strVal(lfirst(keys));
1523                         bool            found = false;
1524                         ColumnDef  *column = NULL;
1525                         ListCell   *columns;
1526
1527                         foreach(columns, cxt->columns)
1528                         {
1529                                 column = (ColumnDef *) lfirst(columns);
1530                                 Assert(IsA(column, ColumnDef));
1531                                 if (strcmp(column->colname, key) == 0)
1532                                 {
1533                                         found = true;
1534                                         break;
1535                                 }
1536                         }
1537                         if (found)
1538                         {
1539                                 /* found column in the new table; force it to be NOT NULL */
1540                                 if (constraint->contype == CONSTR_PRIMARY)
1541                                         column->is_not_null = TRUE;
1542                         }
1543                         else if (SystemAttributeByName(key, cxt->hasoids) != NULL)
1544                         {
1545                                 /*
1546                                  * column will be a system column in the new table, so accept
1547                                  * it.  System columns can't ever be null, so no need to worry
1548                                  * about PRIMARY/NOT NULL constraint.
1549                                  */
1550                                 found = true;
1551                         }
1552                         else if (cxt->inhRelations)
1553                         {
1554                                 /* try inherited tables */
1555                                 ListCell   *inher;
1556
1557                                 foreach(inher, cxt->inhRelations)
1558                                 {
1559                                         RangeVar   *inh = (RangeVar *) lfirst(inher);
1560                                         Relation        rel;
1561                                         int                     count;
1562
1563                                         Assert(IsA(inh, RangeVar));
1564                                         rel = heap_openrv(inh, AccessShareLock);
1565                                         if (rel->rd_rel->relkind != RELKIND_RELATION)
1566                                                 ereport(ERROR,
1567                                                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1568                                                    errmsg("inherited relation \"%s\" is not a table",
1569                                                                   inh->relname)));
1570                                         for (count = 0; count < rel->rd_att->natts; count++)
1571                                         {
1572                                                 Form_pg_attribute inhattr = rel->rd_att->attrs[count];
1573                                                 char       *inhname = NameStr(inhattr->attname);
1574
1575                                                 if (inhattr->attisdropped)
1576                                                         continue;
1577                                                 if (strcmp(key, inhname) == 0)
1578                                                 {
1579                                                         found = true;
1580
1581                                                         /*
1582                                                          * We currently have no easy way to force an
1583                                                          * inherited column to be NOT NULL at creation, if
1584                                                          * its parent wasn't so already. We leave it to
1585                                                          * DefineIndex to fix things up in this case.
1586                                                          */
1587                                                         break;
1588                                                 }
1589                                         }
1590                                         heap_close(rel, NoLock);
1591                                         if (found)
1592                                                 break;
1593                                 }
1594                         }
1595
1596                         /*
1597                          * In the ALTER TABLE case, don't complain about index keys not
1598                          * created in the command; they may well exist already.
1599                          * DefineIndex will complain about them if not, and will also take
1600                          * care of marking them NOT NULL.
1601                          */
1602                         if (!found && !cxt->isalter)
1603                                 ereport(ERROR,
1604                                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
1605                                                  errmsg("column \"%s\" named in key does not exist",
1606                                                                 key)));
1607
1608                         /* Check for PRIMARY KEY(foo, foo) */
1609                         foreach(columns, index->indexParams)
1610                         {
1611                                 iparam = (IndexElem *) lfirst(columns);
1612                                 if (iparam->name && strcmp(key, iparam->name) == 0)
1613                                 {
1614                                         if (index->primary)
1615                                                 ereport(ERROR,
1616                                                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
1617                                                                  errmsg("column \"%s\" appears twice in primary key constraint",
1618                                                                                 key)));
1619                                         else
1620                                                 ereport(ERROR,
1621                                                                 (errcode(ERRCODE_DUPLICATE_COLUMN),
1622                                                                  errmsg("column \"%s\" appears twice in unique constraint",
1623                                                                                 key)));
1624                                 }
1625                         }
1626
1627                         /* OK, add it to the index definition */
1628                         iparam = makeNode(IndexElem);
1629                         iparam->name = pstrdup(key);
1630                         iparam->expr = NULL;
1631                         iparam->opclass = NIL;
1632                         iparam->ordering = SORTBY_DEFAULT;
1633                         iparam->nulls_ordering = SORTBY_NULLS_DEFAULT;
1634                         index->indexParams = lappend(index->indexParams, iparam);
1635                 }
1636
1637                 indexlist = lappend(indexlist, index);
1638         }
1639
1640         /*
1641          * Scan the index list and remove any redundant index specifications. This
1642          * can happen if, for instance, the user writes UNIQUE PRIMARY KEY. A
1643          * strict reading of SQL92 would suggest raising an error instead, but
1644          * that strikes me as too anal-retentive. - tgl 2001-02-14
1645          *
1646          * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1647          * pre-existing indexes, too.
1648          */
1649         Assert(cxt->alist == NIL);
1650         if (cxt->pkey != NULL)
1651         {
1652                 /* Make sure we keep the PKEY index in preference to others... */
1653                 cxt->alist = list_make1(cxt->pkey);
1654         }
1655
1656         foreach(l, indexlist)
1657         {
1658                 bool            keep = true;
1659                 ListCell   *k;
1660
1661                 index = lfirst(l);
1662
1663                 /* if it's pkey, it's already in cxt->alist */
1664                 if (index == cxt->pkey)
1665                         continue;
1666
1667                 foreach(k, cxt->alist)
1668                 {
1669                         IndexStmt  *priorindex = lfirst(k);
1670
1671                         if (equal(index->indexParams, priorindex->indexParams))
1672                         {
1673                                 /*
1674                                  * If the prior index is as yet unnamed, and this one is
1675                                  * named, then transfer the name to the prior index. This
1676                                  * ensures that if we have named and unnamed constraints,
1677                                  * we'll use (at least one of) the names for the index.
1678                                  */
1679                                 if (priorindex->idxname == NULL)
1680                                         priorindex->idxname = index->idxname;
1681                                 keep = false;
1682                                 break;
1683                         }
1684                 }
1685
1686                 if (keep)
1687                         cxt->alist = lappend(cxt->alist, index);
1688         }
1689 }
1690
1691 static void
1692 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1693                                            bool skipValidation, bool isAddConstraint)
1694 {
1695         ListCell   *fkclist;
1696
1697         if (cxt->fkconstraints == NIL)
1698                 return;
1699
1700         /*
1701          * If CREATE TABLE or adding a column with NULL default, we can safely
1702          * skip validation of the constraint.
1703          */
1704         if (skipValidation)
1705         {
1706                 foreach(fkclist, cxt->fkconstraints)
1707                 {
1708                         FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1709
1710                         fkconstraint->skip_validation = true;
1711                 }
1712         }
1713
1714         /*
1715          * For CREATE TABLE or ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD
1716          * CONSTRAINT command to execute after the basic command is complete. (If
1717          * called from ADD CONSTRAINT, that routine will add the FK constraints to
1718          * its own subcommand list.)
1719          *
1720          * Note: the ADD CONSTRAINT command must also execute after any index
1721          * creation commands.  Thus, this should run after
1722          * transformIndexConstraints, so that the CREATE INDEX commands are
1723          * already in cxt->alist.
1724          */
1725         if (!isAddConstraint)
1726         {
1727                 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1728
1729                 alterstmt->relation = cxt->relation;
1730                 alterstmt->cmds = NIL;
1731                 alterstmt->relkind = OBJECT_TABLE;
1732
1733                 foreach(fkclist, cxt->fkconstraints)
1734                 {
1735                         FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1736                         AlterTableCmd *altercmd = makeNode(AlterTableCmd);
1737
1738                         altercmd->subtype = AT_ProcessedConstraint;
1739                         altercmd->name = NULL;
1740                         altercmd->def = (Node *) fkconstraint;
1741                         alterstmt->cmds = lappend(alterstmt->cmds, altercmd);
1742                 }
1743
1744                 cxt->alist = lappend(cxt->alist, alterstmt);
1745         }
1746 }
1747
1748 /*
1749  * transformIndexStmt -
1750  *        transforms the qualification of the index statement
1751  */
1752 static Query *
1753 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
1754 {
1755         Query      *qry;
1756         RangeTblEntry *rte = NULL;
1757         ListCell   *l;
1758
1759         qry = makeNode(Query);
1760         qry->commandType = CMD_UTILITY;
1761
1762         /* take care of the where clause */
1763         if (stmt->whereClause)
1764         {
1765                 /*
1766                  * Put the parent table into the rtable so that the WHERE clause can
1767                  * refer to its fields without qualification.  Note that this only
1768                  * works if the parent table already exists --- so we can't easily
1769                  * support predicates on indexes created implicitly by CREATE TABLE.
1770                  * Fortunately, that's not necessary.
1771                  */
1772                 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1773
1774                 /* no to join list, yes to namespaces */
1775                 addRTEtoQuery(pstate, rte, false, true, true);
1776
1777                 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1778                                                                                                  "WHERE");
1779         }
1780
1781         /* take care of any index expressions */
1782         foreach(l, stmt->indexParams)
1783         {
1784                 IndexElem  *ielem = (IndexElem *) lfirst(l);
1785
1786                 if (ielem->expr)
1787                 {
1788                         /* Set up rtable as for predicate, see notes above */
1789                         if (rte == NULL)
1790                         {
1791                                 rte = addRangeTableEntry(pstate, stmt->relation, NULL,
1792                                                                                  false, true);
1793                                 /* no to join list, yes to namespaces */
1794                                 addRTEtoQuery(pstate, rte, false, true, true);
1795                         }
1796                         ielem->expr = transformExpr(pstate, ielem->expr);
1797
1798                         /*
1799                          * We check only that the result type is legitimate; this is for
1800                          * consistency with what transformWhereClause() checks for the
1801                          * predicate.  DefineIndex() will make more checks.
1802                          */
1803                         if (expression_returns_set(ielem->expr))
1804                                 ereport(ERROR,
1805                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
1806                                                  errmsg("index expression cannot return a set")));
1807                 }
1808         }
1809
1810         qry->hasSubLinks = pstate->p_hasSubLinks;
1811         stmt->rangetable = pstate->p_rtable;
1812
1813         qry->utilityStmt = (Node *) stmt;
1814
1815         return qry;
1816 }
1817
1818 /*
1819  * transformRuleStmt -
1820  *        transform a Create Rule Statement. The actions is a list of parse
1821  *        trees which is transformed into a list of query trees.
1822  */
1823 static Query *
1824 transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
1825                                   List **extras_before, List **extras_after)
1826 {
1827         Query      *qry;
1828         Relation        rel;
1829         RangeTblEntry *oldrte;
1830         RangeTblEntry *newrte;
1831
1832         qry = makeNode(Query);
1833         qry->commandType = CMD_UTILITY;
1834         qry->utilityStmt = (Node *) stmt;
1835
1836         /*
1837          * To avoid deadlock, make sure the first thing we do is grab
1838          * AccessExclusiveLock on the target relation.  This will be needed by
1839          * DefineQueryRewrite(), and we don't want to grab a lesser lock
1840          * beforehand.
1841          */
1842         rel = heap_openrv(stmt->relation, AccessExclusiveLock);
1843
1844         /*
1845          * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to 2.
1846          * Set up their RTEs in the main pstate for use in parsing the rule
1847          * qualification.
1848          */
1849         Assert(pstate->p_rtable == NIL);
1850         oldrte = addRangeTableEntryForRelation(pstate, rel,
1851                                                                                    makeAlias("*OLD*", NIL),
1852                                                                                    false, false);
1853         newrte = addRangeTableEntryForRelation(pstate, rel,
1854                                                                                    makeAlias("*NEW*", NIL),
1855                                                                                    false, false);
1856         /* Must override addRangeTableEntry's default access-check flags */
1857         oldrte->requiredPerms = 0;
1858         newrte->requiredPerms = 0;
1859
1860         /*
1861          * They must be in the namespace too for lookup purposes, but only add the
1862          * one(s) that are relevant for the current kind of rule.  In an UPDATE
1863          * rule, quals must refer to OLD.field or NEW.field to be unambiguous, but
1864          * there's no need to be so picky for INSERT & DELETE.  We do not add them
1865          * to the joinlist.
1866          */
1867         switch (stmt->event)
1868         {
1869                 case CMD_SELECT:
1870                         addRTEtoQuery(pstate, oldrte, false, true, true);
1871                         break;
1872                 case CMD_UPDATE:
1873                         addRTEtoQuery(pstate, oldrte, false, true, true);
1874                         addRTEtoQuery(pstate, newrte, false, true, true);
1875                         break;
1876                 case CMD_INSERT:
1877                         addRTEtoQuery(pstate, newrte, false, true, true);
1878                         break;
1879                 case CMD_DELETE:
1880                         addRTEtoQuery(pstate, oldrte, false, true, true);
1881                         break;
1882                 default:
1883                         elog(ERROR, "unrecognized event type: %d",
1884                                  (int) stmt->event);
1885                         break;
1886         }
1887
1888         /* take care of the where clause */
1889         stmt->whereClause = transformWhereClause(pstate, stmt->whereClause,
1890                                                                                          "WHERE");
1891
1892         if (list_length(pstate->p_rtable) != 2)         /* naughty, naughty... */
1893                 ereport(ERROR,
1894                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1895                                  errmsg("rule WHERE condition cannot contain references to other relations")));
1896
1897         /* aggregates not allowed (but subselects are okay) */
1898         if (pstate->p_hasAggs)
1899                 ereport(ERROR,
1900                                 (errcode(ERRCODE_GROUPING_ERROR),
1901                    errmsg("cannot use aggregate function in rule WHERE condition")));
1902
1903         /* save info about sublinks in where clause */
1904         qry->hasSubLinks = pstate->p_hasSubLinks;
1905
1906         /*
1907          * 'instead nothing' rules with a qualification need a query rangetable so
1908          * the rewrite handler can add the negated rule qualification to the
1909          * original query. We create a query with the new command type CMD_NOTHING
1910          * here that is treated specially by the rewrite system.
1911          */
1912         if (stmt->actions == NIL)
1913         {
1914                 Query      *nothing_qry = makeNode(Query);
1915
1916                 nothing_qry->commandType = CMD_NOTHING;
1917                 nothing_qry->rtable = pstate->p_rtable;
1918                 nothing_qry->jointree = makeFromExpr(NIL, NULL);                /* no join wanted */
1919
1920                 stmt->actions = list_make1(nothing_qry);
1921         }
1922         else
1923         {
1924                 ListCell   *l;
1925                 List       *newactions = NIL;
1926
1927                 /*
1928                  * transform each statement, like parse_sub_analyze()
1929                  */
1930                 foreach(l, stmt->actions)
1931                 {
1932                         Node       *action = (Node *) lfirst(l);
1933                         ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1934                         Query      *sub_qry,
1935                                            *top_subqry;
1936                         bool            has_old,
1937                                                 has_new;
1938
1939                         /*
1940                          * Set up OLD/NEW in the rtable for this statement.  The entries
1941                          * are added only to relnamespace, not varnamespace, because we
1942                          * don't want them to be referred to by unqualified field names
1943                          * nor "*" in the rule actions.  We decide later whether to put
1944                          * them in the joinlist.
1945                          */
1946                         oldrte = addRangeTableEntryForRelation(sub_pstate, rel,
1947                                                                                                    makeAlias("*OLD*", NIL),
1948                                                                                                    false, false);
1949                         newrte = addRangeTableEntryForRelation(sub_pstate, rel,
1950                                                                                                    makeAlias("*NEW*", NIL),
1951                                                                                                    false, false);
1952                         oldrte->requiredPerms = 0;
1953                         newrte->requiredPerms = 0;
1954                         addRTEtoQuery(sub_pstate, oldrte, false, true, false);
1955                         addRTEtoQuery(sub_pstate, newrte, false, true, false);
1956
1957                         /* Transform the rule action statement */
1958                         top_subqry = transformStmt(sub_pstate, action,
1959                                                                            extras_before, extras_after);
1960
1961                         /*
1962                          * We cannot support utility-statement actions (eg NOTIFY) with
1963                          * nonempty rule WHERE conditions, because there's no way to make
1964                          * the utility action execute conditionally.
1965                          */
1966                         if (top_subqry->commandType == CMD_UTILITY &&
1967                                 stmt->whereClause != NULL)
1968                                 ereport(ERROR,
1969                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1970                                                  errmsg("rules with WHERE conditions can only have SELECT, INSERT, UPDATE, or DELETE actions")));
1971
1972                         /*
1973                          * If the action is INSERT...SELECT, OLD/NEW have been pushed down
1974                          * into the SELECT, and that's what we need to look at. (Ugly
1975                          * kluge ... try to fix this when we redesign querytrees.)
1976                          */
1977                         sub_qry = getInsertSelectQuery(top_subqry, NULL);
1978
1979                         /*
1980                          * If the sub_qry is a setop, we cannot attach any qualifications
1981                          * to it, because the planner won't notice them.  This could
1982                          * perhaps be relaxed someday, but for now, we may as well reject
1983                          * such a rule immediately.
1984                          */
1985                         if (sub_qry->setOperations != NULL && stmt->whereClause != NULL)
1986                                 ereport(ERROR,
1987                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1988                                                  errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
1989
1990                         /*
1991                          * Validate action's use of OLD/NEW, qual too
1992                          */
1993                         has_old =
1994                                 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1995                                 rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
1996                         has_new =
1997                                 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1998                                 rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);
1999
2000                         switch (stmt->event)
2001                         {
2002                                 case CMD_SELECT:
2003                                         if (has_old)
2004                                                 ereport(ERROR,
2005                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2006                                                                  errmsg("ON SELECT rule cannot use OLD")));
2007                                         if (has_new)
2008                                                 ereport(ERROR,
2009                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2010                                                                  errmsg("ON SELECT rule cannot use NEW")));
2011                                         break;
2012                                 case CMD_UPDATE:
2013                                         /* both are OK */
2014                                         break;
2015                                 case CMD_INSERT:
2016                                         if (has_old)
2017                                                 ereport(ERROR,
2018                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2019                                                                  errmsg("ON INSERT rule cannot use OLD")));
2020                                         break;
2021                                 case CMD_DELETE:
2022                                         if (has_new)
2023                                                 ereport(ERROR,
2024                                                                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2025                                                                  errmsg("ON DELETE rule cannot use NEW")));
2026                                         break;
2027                                 default:
2028                                         elog(ERROR, "unrecognized event type: %d",
2029                                                  (int) stmt->event);
2030                                         break;
2031                         }
2032
2033                         /*
2034                          * For efficiency's sake, add OLD to the rule action's jointree
2035                          * only if it was actually referenced in the statement or qual.
2036                          *
2037                          * For INSERT, NEW is not really a relation (only a reference to
2038                          * the to-be-inserted tuple) and should never be added to the
2039                          * jointree.
2040                          *
2041                          * For UPDATE, we treat NEW as being another kind of reference to
2042                          * OLD, because it represents references to *transformed* tuples
2043                          * of the existing relation.  It would be wrong to enter NEW
2044                          * separately in the jointree, since that would cause a double
2045                          * join of the updated relation.  It's also wrong to fail to make
2046                          * a jointree entry if only NEW and not OLD is mentioned.
2047                          */
2048                         if (has_old || (has_new && stmt->event == CMD_UPDATE))
2049                         {
2050                                 /*
2051                                  * If sub_qry is a setop, manipulating its jointree will do no
2052                                  * good at all, because the jointree is dummy. (This should be
2053                                  * a can't-happen case because of prior tests.)
2054                                  */
2055                                 if (sub_qry->setOperations != NULL)
2056                                         ereport(ERROR,
2057                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2058                                                          errmsg("conditional UNION/INTERSECT/EXCEPT statements are not implemented")));
2059                                 /* hack so we can use addRTEtoQuery() */
2060                                 sub_pstate->p_rtable = sub_qry->rtable;
2061                                 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
2062                                 addRTEtoQuery(sub_pstate, oldrte, true, false, false);
2063                                 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
2064                         }
2065
2066                         newactions = lappend(newactions, top_subqry);
2067
2068                         release_pstate_resources(sub_pstate);
2069                         pfree(sub_pstate);
2070                 }
2071
2072                 stmt->actions = newactions;
2073         }
2074
2075         /* Close relation, but keep the exclusive lock */
2076         heap_close(rel, NoLock);
2077
2078         return qry;
2079 }
2080
2081
2082 /*
2083  * transformSelectStmt -
2084  *        transforms a Select Statement
2085  *
2086  * Note: this is also used for DECLARE CURSOR statements.
2087  */
2088 static Query *
2089 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
2090 {
2091         Query      *qry = makeNode(Query);
2092         Node       *qual;
2093         ListCell   *l;
2094
2095         qry->commandType = CMD_SELECT;
2096
2097         /* make FOR UPDATE/FOR SHARE info available to addRangeTableEntry */
2098         pstate->p_locking_clause = stmt->lockingClause;
2099
2100         /* process the FROM clause */
2101         transformFromClause(pstate, stmt->fromClause);
2102
2103         /* transform targetlist */
2104         qry->targetList = transformTargetList(pstate, stmt->targetList);
2105
2106         /* mark column origins */
2107         markTargetListOrigins(pstate, qry->targetList);
2108
2109         /* transform WHERE */
2110         qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2111
2112         /*
2113          * Initial processing of HAVING clause is just like WHERE clause.
2114          */
2115         qry->havingQual = transformWhereClause(pstate, stmt->havingClause,
2116                                                                                    "HAVING");
2117
2118         /*
2119          * Transform sorting/grouping stuff.  Do ORDER BY first because both
2120          * transformGroupClause and transformDistinctClause need the results.
2121          */
2122         qry->sortClause = transformSortClause(pstate,
2123                                                                                   stmt->sortClause,
2124                                                                                   &qry->targetList,
2125                                                                                   true /* fix unknowns */ );
2126
2127         qry->groupClause = transformGroupClause(pstate,
2128                                                                                         stmt->groupClause,
2129                                                                                         &qry->targetList,
2130                                                                                         qry->sortClause);
2131
2132         qry->distinctClause = transformDistinctClause(pstate,
2133                                                                                                   stmt->distinctClause,
2134                                                                                                   &qry->targetList,
2135                                                                                                   &qry->sortClause);
2136
2137         qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
2138                                                                                         "OFFSET");
2139         qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
2140                                                                                    "LIMIT");
2141
2142         /* handle any SELECT INTO/CREATE TABLE AS spec */
2143         if (stmt->into)
2144         {
2145                 qry->into = stmt->into;
2146                 if (stmt->intoColNames)
2147                         applyColumnNames(qry->targetList, stmt->intoColNames);
2148                 qry->intoOptions = copyObject(stmt->intoOptions);
2149                 qry->intoOnCommit = stmt->intoOnCommit;
2150                 qry->intoTableSpaceName = stmt->intoTableSpaceName;
2151         }
2152
2153         qry->rtable = pstate->p_rtable;
2154         qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2155
2156         qry->hasSubLinks = pstate->p_hasSubLinks;
2157         qry->hasAggs = pstate->p_hasAggs;
2158         if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2159                 parseCheckAggregates(pstate, qry);
2160
2161         foreach(l, stmt->lockingClause)
2162         {
2163                 transformLockingClause(qry, (LockingClause *) lfirst(l));
2164         }
2165
2166         return qry;
2167 }
2168
2169 /*
2170  * transformValuesClause -
2171  *        transforms a VALUES clause that's being used as a standalone SELECT
2172  *
2173  * We build a Query containing a VALUES RTE, rather as if one had written
2174  *                      SELECT * FROM (VALUES ...)
2175  */
2176 static Query *
2177 transformValuesClause(ParseState *pstate, SelectStmt *stmt)
2178 {
2179         Query      *qry = makeNode(Query);
2180         List       *exprsLists = NIL;
2181         List      **coltype_lists = NULL;
2182         Oid                *coltypes = NULL;
2183         int                     sublist_length = -1;
2184         List       *newExprsLists;
2185         RangeTblEntry *rte;
2186         RangeTblRef *rtr;
2187         ListCell   *lc;
2188         ListCell   *lc2;
2189         int                     i;
2190
2191         qry->commandType = CMD_SELECT;
2192
2193         /* Most SELECT stuff doesn't apply in a VALUES clause */
2194         Assert(stmt->distinctClause == NIL);
2195         Assert(stmt->targetList == NIL);
2196         Assert(stmt->fromClause == NIL);
2197         Assert(stmt->whereClause == NULL);
2198         Assert(stmt->groupClause == NIL);
2199         Assert(stmt->havingClause == NULL);
2200         Assert(stmt->op == SETOP_NONE);
2201
2202         /*
2203          * For each row of VALUES, transform the raw expressions and gather type
2204          * information.  This is also a handy place to reject DEFAULT nodes, which
2205          * the grammar allows for simplicity.
2206          */
2207         foreach(lc, stmt->valuesLists)
2208         {
2209                 List       *sublist = (List *) lfirst(lc);
2210
2211                 /* Do basic expression transformation (same as a ROW() expr) */
2212                 sublist = transformExpressionList(pstate, sublist);
2213
2214                 /*
2215                  * All the sublists must be the same length, *after* transformation
2216                  * (which might expand '*' into multiple items).  The VALUES RTE can't
2217                  * handle anything different.
2218                  */
2219                 if (sublist_length < 0)
2220                 {
2221                         /* Remember post-transformation length of first sublist */
2222                         sublist_length = list_length(sublist);
2223                         /* and allocate arrays for column-type info */
2224                         coltype_lists = (List **) palloc0(sublist_length * sizeof(List *));
2225                         coltypes = (Oid *) palloc0(sublist_length * sizeof(Oid));
2226                 }
2227                 else if (sublist_length != list_length(sublist))
2228                 {
2229                         ereport(ERROR,
2230                                         (errcode(ERRCODE_SYNTAX_ERROR),
2231                                          errmsg("VALUES lists must all be the same length")));
2232                 }
2233
2234                 exprsLists = lappend(exprsLists, sublist);
2235
2236                 i = 0;
2237                 foreach(lc2, sublist)
2238                 {
2239                         Node       *col = (Node *) lfirst(lc2);
2240
2241                         if (IsA(col, SetToDefault))
2242                                 ereport(ERROR,
2243                                                 (errcode(ERRCODE_SYNTAX_ERROR),
2244                                                  errmsg("DEFAULT can only appear in a VALUES list within INSERT")));
2245                         coltype_lists[i] = lappend_oid(coltype_lists[i], exprType(col));
2246                         i++;
2247                 }
2248         }
2249
2250         /*
2251          * Now resolve the common types of the columns, and coerce everything to
2252          * those types.
2253          */
2254         for (i = 0; i < sublist_length; i++)
2255         {
2256                 coltypes[i] = select_common_type(coltype_lists[i], "VALUES");
2257         }
2258
2259         newExprsLists = NIL;
2260         foreach(lc, exprsLists)
2261         {
2262                 List       *sublist = (List *) lfirst(lc);
2263                 List       *newsublist = NIL;
2264
2265                 i = 0;
2266                 foreach(lc2, sublist)
2267                 {
2268                         Node       *col = (Node *) lfirst(lc2);
2269
2270                         col = coerce_to_common_type(pstate, col, coltypes[i], "VALUES");
2271                         newsublist = lappend(newsublist, col);
2272                         i++;
2273                 }
2274
2275                 newExprsLists = lappend(newExprsLists, newsublist);
2276         }
2277
2278         /*
2279          * Generate the VALUES RTE
2280          */
2281         rte = addRangeTableEntryForValues(pstate, newExprsLists, NULL, true);
2282         rtr = makeNode(RangeTblRef);
2283         /* assume new rte is at end */
2284         rtr->rtindex = list_length(pstate->p_rtable);
2285         Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2286         pstate->p_joinlist = lappend(pstate->p_joinlist, rtr);
2287         pstate->p_varnamespace = lappend(pstate->p_varnamespace, rte);
2288
2289         /*
2290          * Generate a targetlist as though expanding "*"
2291          */
2292         Assert(pstate->p_next_resno == 1);
2293         qry->targetList = expandRelAttrs(pstate, rte, rtr->rtindex, 0);
2294
2295         /*
2296          * The grammar allows attaching ORDER BY, LIMIT, and FOR UPDATE to a
2297          * VALUES, so cope.
2298          */
2299         qry->sortClause = transformSortClause(pstate,
2300                                                                                   stmt->sortClause,
2301                                                                                   &qry->targetList,
2302                                                                                   true /* fix unknowns */ );
2303
2304         qry->limitOffset = transformLimitClause(pstate, stmt->limitOffset,
2305                                                                                         "OFFSET");
2306         qry->limitCount = transformLimitClause(pstate, stmt->limitCount,
2307                                                                                    "LIMIT");
2308
2309         if (stmt->lockingClause)
2310                 ereport(ERROR,
2311                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2312                          errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
2313
2314         /* handle any CREATE TABLE AS spec */
2315         if (stmt->into)
2316         {
2317                 qry->into = stmt->into;
2318                 if (stmt->intoColNames)
2319                         applyColumnNames(qry->targetList, stmt->intoColNames);
2320                 qry->intoOptions = copyObject(stmt->intoOptions);
2321                 qry->intoOnCommit = stmt->intoOnCommit;
2322                 qry->intoTableSpaceName = stmt->intoTableSpaceName;
2323         }
2324
2325         /*
2326          * There mustn't have been any table references in the expressions, else
2327          * strange things would happen, like Cartesian products of those tables
2328          * with the VALUES list.  We have to check this after parsing ORDER BY et
2329          * al since those could insert more junk.
2330          */
2331         if (list_length(pstate->p_joinlist) != 1)
2332                 ereport(ERROR,
2333                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2334                                  errmsg("VALUES must not contain table references")));
2335
2336         /*
2337          * Another thing we can't currently support is NEW/OLD references in rules
2338          * --- seems we'd need something like SQL99's LATERAL construct to ensure
2339          * that the values would be available while evaluating the VALUES RTE.
2340          * This is a shame.  FIXME
2341          */
2342         if (list_length(pstate->p_rtable) != 1 &&
2343                 contain_vars_of_level((Node *) newExprsLists, 0))
2344                 ereport(ERROR,
2345                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2346                                  errmsg("VALUES must not contain OLD or NEW references"),
2347                                  errhint("Use SELECT ... UNION ALL ... instead.")));
2348
2349         qry->rtable = pstate->p_rtable;
2350         qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2351
2352         qry->hasSubLinks = pstate->p_hasSubLinks;
2353         /* aggregates not allowed (but subselects are okay) */
2354         if (pstate->p_hasAggs)
2355                 ereport(ERROR,
2356                                 (errcode(ERRCODE_GROUPING_ERROR),
2357                                  errmsg("cannot use aggregate function in VALUES")));
2358
2359         return qry;
2360 }
2361
2362 /*
2363  * transformSetOperationsStmt -
2364  *        transforms a set-operations tree
2365  *
2366  * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
2367  * structure to it.  We must transform each leaf SELECT and build up a top-
2368  * level Query that contains the leaf SELECTs as subqueries in its rangetable.
2369  * The tree of set operations is converted into the setOperations field of
2370  * the top-level Query.
2371  */
2372 static Query *
2373 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
2374 {
2375         Query      *qry = makeNode(Query);
2376         SelectStmt *leftmostSelect;
2377         int                     leftmostRTI;
2378         Query      *leftmostQuery;
2379         SetOperationStmt *sostmt;
2380         List       *intoColNames = NIL;
2381         List       *sortClause;
2382         Node       *limitOffset;
2383         Node       *limitCount;
2384         List       *lockingClause;
2385         Node       *node;
2386         ListCell   *left_tlist,
2387                            *lct,
2388                            *lcm,
2389                            *l;
2390         List       *targetvars,
2391                            *targetnames,
2392                            *sv_relnamespace,
2393                            *sv_varnamespace,
2394                            *sv_rtable;
2395         RangeTblEntry *jrte;
2396         int                     tllen;
2397
2398         qry->commandType = CMD_SELECT;
2399
2400         /*
2401          * Find leftmost leaf SelectStmt; extract the one-time-only items from it
2402          * and from the top-level node.  (Most of the INTO options can be
2403          * transferred to the Query immediately, but intoColNames has to be saved
2404          * to apply below.)
2405          */
2406         leftmostSelect = stmt->larg;
2407         while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
2408                 leftmostSelect = leftmostSelect->larg;
2409         Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
2410                    leftmostSelect->larg == NULL);
2411         if (leftmostSelect->into)
2412         {
2413                 qry->into = leftmostSelect->into;
2414                 intoColNames = leftmostSelect->intoColNames;
2415                 qry->intoOptions = copyObject(leftmostSelect->intoOptions);
2416                 qry->intoOnCommit = leftmostSelect->intoOnCommit;
2417                 qry->intoTableSpaceName = leftmostSelect->intoTableSpaceName;
2418         }
2419
2420         /* clear this to prevent complaints in transformSetOperationTree() */
2421         leftmostSelect->into = NULL;
2422
2423         /*
2424          * These are not one-time, exactly, but we want to process them here and
2425          * not let transformSetOperationTree() see them --- else it'll just
2426          * recurse right back here!
2427          */
2428         sortClause = stmt->sortClause;
2429         limitOffset = stmt->limitOffset;
2430         limitCount = stmt->limitCount;
2431         lockingClause = stmt->lockingClause;
2432
2433         stmt->sortClause = NIL;
2434         stmt->limitOffset = NULL;
2435         stmt->limitCount = NULL;
2436         stmt->lockingClause = NIL;
2437
2438         /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2439         if (lockingClause)
2440                 ereport(ERROR,
2441                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2442                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2443
2444         /*
2445          * Recursively transform the components of the tree.
2446          */
2447         sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
2448         Assert(sostmt && IsA(sostmt, SetOperationStmt));
2449         qry->setOperations = (Node *) sostmt;
2450
2451         /*
2452          * Re-find leftmost SELECT (now it's a sub-query in rangetable)
2453          */
2454         node = sostmt->larg;
2455         while (node && IsA(node, SetOperationStmt))
2456                 node = ((SetOperationStmt *) node)->larg;
2457         Assert(node && IsA(node, RangeTblRef));
2458         leftmostRTI = ((RangeTblRef *) node)->rtindex;
2459         leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
2460         Assert(leftmostQuery != NULL);
2461
2462         /*
2463          * Generate dummy targetlist for outer query using column names of
2464          * leftmost select and common datatypes of topmost set operation. Also
2465          * make lists of the dummy vars and their names for use in parsing ORDER
2466          * BY.
2467          *
2468          * Note: we use leftmostRTI as the varno of the dummy variables. It
2469          * shouldn't matter too much which RT index they have, as long as they
2470          * have one that corresponds to a real RT entry; else funny things may
2471          * happen when the tree is mashed by rule rewriting.
2472          */
2473         qry->targetList = NIL;
2474         targetvars = NIL;
2475         targetnames = NIL;
2476         left_tlist = list_head(leftmostQuery->targetList);
2477
2478         forboth(lct, sostmt->colTypes, lcm, sostmt->colTypmods)
2479         {
2480                 Oid                     colType = lfirst_oid(lct);
2481                 int32           colTypmod = lfirst_int(lcm);
2482                 TargetEntry *lefttle = (TargetEntry *) lfirst(left_tlist);
2483                 char       *colName;
2484                 TargetEntry *tle;
2485                 Expr       *expr;
2486
2487                 Assert(!lefttle->resjunk);
2488                 colName = pstrdup(lefttle->resname);
2489                 expr = (Expr *) makeVar(leftmostRTI,
2490                                                                 lefttle->resno,
2491                                                                 colType,
2492                                                                 colTypmod,
2493                                                                 0);
2494                 tle = makeTargetEntry(expr,
2495                                                           (AttrNumber) pstate->p_next_resno++,
2496                                                           colName,
2497                                                           false);
2498                 qry->targetList = lappend(qry->targetList, tle);
2499                 targetvars = lappend(targetvars, expr);
2500                 targetnames = lappend(targetnames, makeString(colName));
2501                 left_tlist = lnext(left_tlist);
2502         }
2503
2504         /*
2505          * As a first step towards supporting sort clauses that are expressions
2506          * using the output columns, generate a varnamespace entry that makes the
2507          * output columns visible.      A Join RTE node is handy for this, since we
2508          * can easily control the Vars generated upon matches.
2509          *
2510          * Note: we don't yet do anything useful with such cases, but at least
2511          * "ORDER BY upper(foo)" will draw the right error message rather than
2512          * "foo not found".
2513          */
2514         jrte = addRangeTableEntryForJoin(NULL,
2515                                                                          targetnames,
2516                                                                          JOIN_INNER,
2517                                                                          targetvars,
2518                                                                          NULL,
2519                                                                          false);
2520
2521         sv_rtable = pstate->p_rtable;
2522         pstate->p_rtable = list_make1(jrte);
2523
2524         sv_relnamespace = pstate->p_relnamespace;
2525         pstate->p_relnamespace = NIL;           /* no qualified names allowed */
2526
2527         sv_varnamespace = pstate->p_varnamespace;
2528         pstate->p_varnamespace = list_make1(jrte);
2529
2530         /*
2531          * For now, we don't support resjunk sort clauses on the output of a
2532          * setOperation tree --- you can only use the SQL92-spec options of
2533          * selecting an output column by name or number.  Enforce by checking that
2534          * transformSortClause doesn't add any items to tlist.
2535          */
2536         tllen = list_length(qry->targetList);
2537
2538         qry->sortClause = transformSortClause(pstate,
2539                                                                                   sortClause,
2540                                                                                   &qry->targetList,
2541                                                                                   false /* no unknowns expected */ );
2542
2543         pstate->p_rtable = sv_rtable;
2544         pstate->p_relnamespace = sv_relnamespace;
2545         pstate->p_varnamespace = sv_varnamespace;
2546
2547         if (tllen != list_length(qry->targetList))
2548                 ereport(ERROR,
2549                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2550                                  errmsg("invalid UNION/INTERSECT/EXCEPT ORDER BY clause"),
2551                                  errdetail("Only result column names can be used, not expressions or functions."),
2552                                  errhint("Add the expression/function to every SELECT, or move the UNION into a FROM clause.")));
2553
2554         qry->limitOffset = transformLimitClause(pstate, limitOffset,
2555                                                                                         "OFFSET");
2556         qry->limitCount = transformLimitClause(pstate, limitCount,
2557                                                                                    "LIMIT");
2558
2559         /*
2560          * Handle SELECT INTO/CREATE TABLE AS.
2561          *
2562          * Any column names from CREATE TABLE AS need to be attached to both the
2563          * top level and the leftmost subquery.  We do not do this earlier because
2564          * we do *not* want sortClause processing to be affected.
2565          */
2566         if (intoColNames)
2567         {
2568                 applyColumnNames(qry->targetList, intoColNames);
2569                 applyColumnNames(leftmostQuery->targetList, intoColNames);
2570         }
2571
2572         qry->rtable = pstate->p_rtable;
2573         qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2574
2575         qry->hasSubLinks = pstate->p_hasSubLinks;
2576         qry->hasAggs = pstate->p_hasAggs;
2577         if (pstate->p_hasAggs || qry->groupClause || qry->havingQual)
2578                 parseCheckAggregates(pstate, qry);
2579
2580         foreach(l, lockingClause)
2581         {
2582                 transformLockingClause(qry, (LockingClause *) lfirst(l));
2583         }
2584
2585         return qry;
2586 }
2587
2588 /*
2589  * transformSetOperationTree
2590  *              Recursively transform leaves and internal nodes of a set-op tree
2591  */
2592 static Node *
2593 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2594 {
2595         bool            isLeaf;
2596
2597         Assert(stmt && IsA(stmt, SelectStmt));
2598
2599         /*
2600          * Validity-check both leaf and internal SELECTs for disallowed ops.
2601          */
2602         if (stmt->into)
2603                 ereport(ERROR,
2604                                 (errcode(ERRCODE_SYNTAX_ERROR),
2605                                  errmsg("INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT")));
2606         /* We don't support FOR UPDATE/SHARE with set ops at the moment. */
2607         if (stmt->lockingClause)
2608                 ereport(ERROR,
2609                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2610                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
2611
2612         /*
2613          * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2614          * clauses attached, we need to treat it like a leaf node to generate an
2615          * independent sub-Query tree.  Otherwise, it can be represented by a
2616          * SetOperationStmt node underneath the parent Query.
2617          */
2618         if (stmt->op == SETOP_NONE)
2619         {
2620                 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2621                 isLeaf = true;
2622         }
2623         else
2624         {
2625                 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2626                 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2627                         stmt->lockingClause)
2628                         isLeaf = true;
2629                 else
2630                         isLeaf = false;
2631         }
2632
2633         if (isLeaf)
2634         {
2635                 /* Process leaf SELECT */
2636                 List       *selectList;
2637                 Query      *selectQuery;
2638                 char            selectName[32];
2639                 RangeTblEntry *rte;
2640                 RangeTblRef *rtr;
2641
2642                 /*
2643                  * Transform SelectStmt into a Query.
2644                  *
2645                  * Note: previously transformed sub-queries don't affect the parsing
2646                  * of this sub-query, because they are not in the toplevel pstate's
2647                  * namespace list.
2648                  */
2649                 selectList = parse_sub_analyze((Node *) stmt, pstate);
2650
2651                 Assert(list_length(selectList) == 1);
2652                 selectQuery = (Query *) linitial(selectList);
2653                 Assert(IsA(selectQuery, Query));
2654
2655                 /*
2656                  * Check for bogus references to Vars on the current query level (but
2657                  * upper-level references are okay). Normally this can't happen
2658                  * because the namespace will be empty, but it could happen if we are
2659                  * inside a rule.
2660                  */
2661                 if (pstate->p_relnamespace || pstate->p_varnamespace)
2662                 {
2663                         if (contain_vars_of_level((Node *) selectQuery, 1))
2664                                 ereport(ERROR,
2665                                                 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
2666                                                  errmsg("UNION/INTERSECT/EXCEPT member statement cannot refer to other relations of same query level")));
2667                 }
2668
2669                 /*
2670                  * Make the leaf query be a subquery in the top-level rangetable.
2671                  */
2672                 snprintf(selectName, sizeof(selectName), "*SELECT* %d",
2673                                  list_length(pstate->p_rtable) + 1);
2674                 rte = addRangeTableEntryForSubquery(pstate,
2675                                                                                         selectQuery,
2676                                                                                         makeAlias(selectName, NIL),
2677                                                                                         false);
2678
2679                 /*
2680                  * Return a RangeTblRef to replace the SelectStmt in the set-op tree.
2681                  */
2682                 rtr = makeNode(RangeTblRef);
2683                 /* assume new rte is at end */
2684                 rtr->rtindex = list_length(pstate->p_rtable);
2685                 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2686                 return (Node *) rtr;
2687         }
2688         else
2689         {
2690                 /* Process an internal node (set operation node) */
2691                 SetOperationStmt *op = makeNode(SetOperationStmt);
2692                 List       *lcoltypes;
2693                 List       *rcoltypes;
2694                 List       *lcoltypmods;
2695                 List       *rcoltypmods;
2696                 ListCell   *lct;
2697                 ListCell   *rct;
2698                 ListCell   *lcm;
2699                 ListCell   *rcm;
2700                 const char *context;
2701
2702                 context = (stmt->op == SETOP_UNION ? "UNION" :
2703                                    (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2704                                         "EXCEPT"));
2705
2706                 op->op = stmt->op;
2707                 op->all = stmt->all;
2708
2709                 /*
2710                  * Recursively transform the child nodes.
2711                  */
2712                 op->larg = transformSetOperationTree(pstate, stmt->larg);
2713                 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2714
2715                 /*
2716                  * Verify that the two children have the same number of non-junk
2717                  * columns, and determine the types of the merged output columns.
2718                  */
2719                 getSetColTypes(pstate, op->larg, &lcoltypes, &lcoltypmods);
2720                 getSetColTypes(pstate, op->rarg, &rcoltypes, &rcoltypmods);
2721                 if (list_length(lcoltypes) != list_length(rcoltypes))
2722                         ereport(ERROR,
2723                                         (errcode(ERRCODE_SYNTAX_ERROR),
2724                                  errmsg("each %s query must have the same number of columns",
2725                                                 context)));
2726                 Assert(list_length(lcoltypes) == list_length(lcoltypmods));
2727                 Assert(list_length(rcoltypes) == list_length(rcoltypmods));
2728
2729                 op->colTypes = NIL;
2730                 op->colTypmods = NIL;
2731                 /* don't have a "foreach4", so chase two of the lists by hand */
2732                 lcm = list_head(lcoltypmods);
2733                 rcm = list_head(rcoltypmods);
2734                 forboth(lct, lcoltypes, rct, rcoltypes)
2735                 {
2736                         Oid                     lcoltype = lfirst_oid(lct);
2737                         Oid                     rcoltype = lfirst_oid(rct);
2738                         int32           lcoltypmod = lfirst_int(lcm);
2739                         int32           rcoltypmod = lfirst_int(rcm);
2740                         Oid                     rescoltype;
2741                         int32           rescoltypmod;
2742
2743                         /* select common type, same as CASE et al */
2744                         rescoltype = select_common_type(list_make2_oid(lcoltype, rcoltype),
2745                                                                                         context);
2746                         /* if same type and same typmod, use typmod; else default */
2747                         if (lcoltype == rcoltype && lcoltypmod == rcoltypmod)
2748                                 rescoltypmod = lcoltypmod;
2749                         else
2750                                 rescoltypmod = -1;
2751                         op->colTypes = lappend_oid(op->colTypes, rescoltype);
2752                         op->colTypmods = lappend_int(op->colTypmods, rescoltypmod);
2753
2754                         lcm = lnext(lcm);
2755                         rcm = lnext(rcm);
2756                 }
2757
2758                 return (Node *) op;
2759         }
2760 }
2761
2762 /*
2763  * getSetColTypes
2764  *        Get output column types/typmods of an (already transformed) set-op node
2765  */
2766 static void
2767 getSetColTypes(ParseState *pstate, Node *node,
2768                            List **colTypes, List **colTypmods)
2769 {
2770         *colTypes = NIL;
2771         *colTypmods = NIL;
2772         if (IsA(node, RangeTblRef))
2773         {
2774                 RangeTblRef *rtr = (RangeTblRef *) node;
2775                 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2776                 Query      *selectQuery = rte->subquery;
2777                 ListCell   *tl;
2778
2779                 Assert(selectQuery != NULL);
2780                 /* Get types of non-junk columns */
2781                 foreach(tl, selectQuery->targetList)
2782                 {
2783                         TargetEntry *tle = (TargetEntry *) lfirst(tl);
2784
2785                         if (tle->resjunk)
2786                                 continue;
2787                         *colTypes = lappend_oid(*colTypes,
2788                                                                         exprType((Node *) tle->expr));
2789                         *colTypmods = lappend_int(*colTypmods,
2790                                                                           exprTypmod((Node *) tle->expr));
2791                 }
2792         }
2793         else if (IsA(node, SetOperationStmt))
2794         {
2795                 SetOperationStmt *op = (SetOperationStmt *) node;
2796
2797                 /* Result already computed during transformation of node */
2798                 Assert(op->colTypes != NIL);
2799                 *colTypes = op->colTypes;
2800                 *colTypmods = op->colTypmods;
2801         }
2802         else
2803                 elog(ERROR, "unrecognized node type: %d", (int) nodeTag(node));
2804 }
2805
2806 /* Attach column names from a ColumnDef list to a TargetEntry list */
2807 static void
2808 applyColumnNames(List *dst, List *src)
2809 {
2810         ListCell   *dst_item;
2811         ListCell   *src_item;
2812
2813         src_item = list_head(src);
2814
2815         foreach(dst_item, dst)
2816         {
2817                 TargetEntry *d = (TargetEntry *) lfirst(dst_item);
2818                 ColumnDef  *s;
2819
2820                 /* junk targets don't count */
2821                 if (d->resjunk)
2822                         continue;
2823
2824                 /* fewer ColumnDefs than target entries is OK */
2825                 if (src_item == NULL)
2826                         break;
2827
2828                 s = (ColumnDef *) lfirst(src_item);
2829                 src_item = lnext(src_item);
2830
2831                 d->resname = pstrdup(s->colname);
2832         }
2833
2834         /* more ColumnDefs than target entries is not OK */
2835         if (src_item != NULL)
2836                 ereport(ERROR,
2837                                 (errcode(ERRCODE_SYNTAX_ERROR),
2838                                  errmsg("CREATE TABLE AS specifies too many column names")));
2839 }
2840
2841
2842 /*
2843  * transformUpdateStmt -
2844  *        transforms an update statement
2845  */
2846 static Query *
2847 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2848 {
2849         Query      *qry = makeNode(Query);
2850         Node       *qual;
2851         ListCell   *origTargetList;
2852         ListCell   *tl;
2853
2854         qry->commandType = CMD_UPDATE;
2855         pstate->p_is_update = true;
2856
2857         qry->resultRelation = setTargetTable(pstate, stmt->relation,
2858                                                                   interpretInhOption(stmt->relation->inhOpt),
2859                                                                                  true,
2860                                                                                  ACL_UPDATE);
2861
2862         /*
2863          * the FROM clause is non-standard SQL syntax. We used to be able to do
2864          * this with REPLACE in POSTQUEL so we keep the feature.
2865          */
2866         transformFromClause(pstate, stmt->fromClause);
2867
2868         qry->targetList = transformTargetList(pstate, stmt->targetList);
2869
2870         qual = transformWhereClause(pstate, stmt->whereClause, "WHERE");
2871
2872         qry->returningList = transformReturningList(pstate, stmt->returningList);
2873
2874         qry->rtable = pstate->p_rtable;
2875         qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2876
2877         qry->hasSubLinks = pstate->p_hasSubLinks;
2878
2879         /*
2880          * Top-level aggregates are simply disallowed in UPDATE, per spec. (From
2881          * an implementation point of view, this is forced because the implicit
2882          * ctid reference would otherwise be an ungrouped variable.)
2883          */
2884         if (pstate->p_hasAggs)
2885                 ereport(ERROR,
2886                                 (errcode(ERRCODE_GROUPING_ERROR),
2887                                  errmsg("cannot use aggregate function in UPDATE")));
2888
2889         /*
2890          * Now we are done with SELECT-like processing, and can get on with
2891          * transforming the target list to match the UPDATE target columns.
2892          */
2893
2894         /* Prepare to assign non-conflicting resnos to resjunk attributes */
2895         if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2896                 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2897
2898         /* Prepare non-junk columns for assignment to target table */
2899         origTargetList = list_head(stmt->targetList);
2900
2901         foreach(tl, qry->targetList)
2902         {
2903                 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2904                 ResTarget  *origTarget;
2905                 int                     attrno;
2906
2907                 if (tle->resjunk)
2908                 {
2909                         /*
2910                          * Resjunk nodes need no additional processing, but be sure they
2911                          * have resnos that do not match any target columns; else rewriter
2912                          * or planner might get confused.  They don't need a resname
2913                          * either.
2914                          */
2915                         tle->resno = (AttrNumber) pstate->p_next_resno++;
2916                         tle->resname = NULL;
2917                         continue;
2918                 }
2919                 if (origTargetList == NULL)
2920                         elog(ERROR, "UPDATE target count mismatch --- internal error");
2921                 origTarget = (ResTarget *) lfirst(origTargetList);
2922                 Assert(IsA(origTarget, ResTarget));
2923
2924                 attrno = attnameAttNum(pstate->p_target_relation,
2925                                                            origTarget->name, true);
2926                 if (attrno == InvalidAttrNumber)
2927                         ereport(ERROR,
2928                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
2929                                          errmsg("column \"%s\" of relation \"%s\" does not exist",
2930                                                         origTarget->name,
2931                                                  RelationGetRelationName(pstate->p_target_relation)),
2932                                          parser_errposition(pstate, origTarget->location)));
2933
2934                 updateTargetListEntry(pstate, tle, origTarget->name,
2935                                                           attrno,
2936                                                           origTarget->indirection,
2937                                                           origTarget->location);
2938
2939                 origTargetList = lnext(origTargetList);
2940         }
2941         if (origTargetList != NULL)
2942                 elog(ERROR, "UPDATE target count mismatch --- internal error");
2943
2944         return qry;
2945 }
2946
2947 /*
2948  * transformReturningList -
2949  *      handle a RETURNING clause in INSERT/UPDATE/DELETE
2950  */
2951 static List *
2952 transformReturningList(ParseState *pstate, List *returningList)
2953 {
2954         List       *rlist;
2955         int                     save_next_resno;
2956         bool            save_hasAggs;
2957         int                     length_rtable;
2958
2959         if (returningList == NIL)
2960                 return NIL;                             /* nothing to do */
2961
2962         /*
2963          * We need to assign resnos starting at one in the RETURNING list. Save
2964          * and restore the main tlist's value of p_next_resno, just in case
2965          * someone looks at it later (probably won't happen).
2966          */
2967         save_next_resno = pstate->p_next_resno;
2968         pstate->p_next_resno = 1;
2969
2970         /* save other state so that we can detect disallowed stuff */
2971         save_hasAggs = pstate->p_hasAggs;
2972         pstate->p_hasAggs = false;
2973         length_rtable = list_length(pstate->p_rtable);
2974
2975         /* transform RETURNING identically to a SELECT targetlist */
2976         rlist = transformTargetList(pstate, returningList);
2977
2978         /* check for disallowed stuff */
2979
2980         /* aggregates not allowed (but subselects are okay) */
2981         if (pstate->p_hasAggs)
2982                 ereport(ERROR,
2983                                 (errcode(ERRCODE_GROUPING_ERROR),
2984                                  errmsg("cannot use aggregate function in RETURNING")));
2985
2986         /* no new relation references please */
2987         if (list_length(pstate->p_rtable) != length_rtable)
2988                 ereport(ERROR,
2989                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2990                  errmsg("RETURNING cannot contain references to other relations")));
2991
2992         /* mark column origins */
2993         markTargetListOrigins(pstate, rlist);
2994
2995         /* restore state */
2996         pstate->p_next_resno = save_next_resno;
2997         pstate->p_hasAggs = save_hasAggs;
2998
2999         return rlist;
3000 }
3001
3002 /*
3003  * transformAlterTableStmt -
3004  *      transform an Alter Table Statement
3005  */
3006 static Query *
3007 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
3008                                                 List **extras_before, List **extras_after)
3009 {
3010         CreateStmtContext cxt;
3011         Query      *qry;
3012         ListCell   *lcmd,
3013                            *l;
3014         List       *newcmds = NIL;
3015         bool            skipValidation = true;
3016         AlterTableCmd *newcmd;
3017
3018         cxt.stmtType = "ALTER TABLE";
3019         cxt.relation = stmt->relation;
3020         cxt.inhRelations = NIL;
3021         cxt.isalter = true;
3022         cxt.hasoids = false;            /* need not be right */
3023         cxt.columns = NIL;
3024         cxt.ckconstraints = NIL;
3025         cxt.fkconstraints = NIL;
3026         cxt.ixconstraints = NIL;
3027         cxt.blist = NIL;
3028         cxt.alist = NIL;
3029         cxt.pkey = NULL;
3030
3031         /*
3032          * The only subtypes that currently require parse transformation handling
3033          * are ADD COLUMN and ADD CONSTRAINT.  These largely re-use code from
3034          * CREATE TABLE.
3035          */
3036         foreach(lcmd, stmt->cmds)
3037         {
3038                 AlterTableCmd *cmd = (AlterTableCmd *) lfirst(lcmd);
3039
3040                 switch (cmd->subtype)
3041                 {
3042                         case AT_AddColumn:
3043                                 {
3044                                         ColumnDef  *def = (ColumnDef *) cmd->def;
3045
3046                                         Assert(IsA(cmd->def, ColumnDef));
3047                                         transformColumnDefinition(pstate, &cxt,
3048                                                                                           (ColumnDef *) cmd->def);
3049
3050                                         /*
3051                                          * If the column has a non-null default, we can't skip
3052                                          * validation of foreign keys.
3053                                          */
3054                                         if (((ColumnDef *) cmd->def)->raw_default != NULL)
3055                                                 skipValidation = false;
3056
3057                                         newcmds = lappend(newcmds, cmd);
3058
3059                                         /*
3060                                          * Convert an ADD COLUMN ... NOT NULL constraint to a
3061                                          * separate command
3062                                          */
3063                                         if (def->is_not_null)
3064                                         {
3065                                                 /* Remove NOT NULL from AddColumn */
3066                                                 def->is_not_null = false;
3067
3068                                                 /* Add as a separate AlterTableCmd */
3069                                                 newcmd = makeNode(AlterTableCmd);
3070                                                 newcmd->subtype = AT_SetNotNull;
3071                                                 newcmd->name = pstrdup(def->colname);
3072                                                 newcmds = lappend(newcmds, newcmd);
3073                                         }
3074
3075                                         /*
3076                                          * All constraints are processed in other ways. Remove the
3077                                          * original list
3078                                          */
3079                                         def->constraints = NIL;
3080
3081                                         break;
3082                                 }
3083                         case AT_AddConstraint:
3084
3085                                 /*
3086                                  * The original AddConstraint cmd node doesn't go to newcmds
3087                                  */
3088
3089                                 if (IsA(cmd->def, Constraint))
3090                                         transformTableConstraint(pstate, &cxt,
3091                                                                                          (Constraint *) cmd->def);
3092                                 else if (IsA(cmd->def, FkConstraint))
3093                                 {
3094                                         cxt.fkconstraints = lappend(cxt.fkconstraints, cmd->def);
3095                                         skipValidation = false;
3096                                 }
3097                                 else
3098                                         elog(ERROR, "unrecognized node type: %d",
3099                                                  (int) nodeTag(cmd->def));
3100                                 break;
3101
3102                         case AT_ProcessedConstraint:
3103
3104                                 /*
3105                                  * Already-transformed ADD CONSTRAINT, so just make it look
3106                                  * like the standard case.
3107                                  */
3108                                 cmd->subtype = AT_AddConstraint;
3109                                 newcmds = lappend(newcmds, cmd);
3110                                 break;
3111
3112                         default:
3113                                 newcmds = lappend(newcmds, cmd);
3114                                 break;
3115                 }
3116         }
3117
3118         /*
3119          * transformIndexConstraints wants cxt.alist to contain only index
3120          * statements, so transfer anything we already have into extras_after
3121          * immediately.
3122          */
3123         *extras_after = list_concat(cxt.alist, *extras_after);
3124         cxt.alist = NIL;
3125
3126         /* Postprocess index and FK constraints */
3127         transformIndexConstraints(pstate, &cxt);
3128
3129         transformFKConstraints(pstate, &cxt, skipValidation, true);
3130
3131         /*
3132          * Push any index-creation commands into the ALTER, so that they can be
3133          * scheduled nicely by tablecmds.c.
3134          */
3135         foreach(l, cxt.alist)
3136         {
3137                 Node       *idxstmt = (Node *) lfirst(l);
3138
3139                 Assert(IsA(idxstmt, IndexStmt));
3140                 newcmd = makeNode(AlterTableCmd);
3141                 newcmd->subtype = AT_AddIndex;
3142                 newcmd->def = idxstmt;
3143                 newcmds = lappend(newcmds, newcmd);
3144         }
3145         cxt.alist = NIL;
3146
3147         /* Append any CHECK or FK constraints to the commands list */
3148         foreach(l, cxt.ckconstraints)
3149         {
3150                 newcmd = makeNode(AlterTableCmd);
3151                 newcmd->subtype = AT_AddConstraint;
3152                 newcmd->def = (Node *) lfirst(l);
3153                 newcmds = lappend(newcmds, newcmd);
3154         }
3155         foreach(l, cxt.fkconstraints)
3156         {
3157                 newcmd = makeNode(AlterTableCmd);
3158                 newcmd->subtype = AT_AddConstraint;
3159                 newcmd->def = (Node *) lfirst(l);
3160                 newcmds = lappend(newcmds, newcmd);
3161         }
3162
3163         /* Update statement's commands list */
3164         stmt->cmds = newcmds;
3165
3166         qry = makeNode(Query);
3167         qry->commandType = CMD_UTILITY;
3168         qry->utilityStmt = (Node *) stmt;
3169
3170         *extras_before = list_concat(*extras_before, cxt.blist);
3171         *extras_after = list_concat(cxt.alist, *extras_after);
3172
3173         return qry;
3174 }
3175
3176 static Query *
3177 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
3178 {
3179         Query      *result = makeNode(Query);
3180         List       *extras_before = NIL,
3181                            *extras_after = NIL;
3182
3183         result->commandType = CMD_UTILITY;
3184         result->utilityStmt = (Node *) stmt;
3185
3186         /*
3187          * Don't allow both SCROLL and NO SCROLL to be specified
3188          */
3189         if ((stmt->options & CURSOR_OPT_SCROLL) &&
3190                 (stmt->options & CURSOR_OPT_NO_SCROLL))
3191                 ereport(ERROR,
3192                                 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3193                                  errmsg("cannot specify both SCROLL and NO SCROLL")));
3194
3195         stmt->query = (Node *) transformStmt(pstate, stmt->query,
3196                                                                                  &extras_before, &extras_after);
3197
3198         /* Shouldn't get any extras, since grammar only allows SelectStmt */
3199         if (extras_before || extras_after)
3200                 elog(ERROR, "unexpected extra stuff in cursor statement");
3201         if (!IsA(stmt->query, Query) ||
3202                 ((Query *) stmt->query)->commandType != CMD_SELECT)
3203                 elog(ERROR, "unexpected non-SELECT command in cursor statement");
3204
3205         /* But we must explicitly disallow DECLARE CURSOR ... SELECT INTO */
3206         if (((Query *) stmt->query)->into)
3207                 ereport(ERROR,
3208                                 (errcode(ERRCODE_INVALID_CURSOR_DEFINITION),
3209                                  errmsg("DECLARE CURSOR cannot specify INTO")));
3210
3211         return result;
3212 }
3213
3214
3215 static Query *
3216 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
3217 {
3218         Query      *result = makeNode(Query);
3219         List       *argtype_oids;       /* argtype OIDs in a list */
3220         Oid                *argtoids = NULL;    /* and as an array */
3221         int                     nargs;
3222         List       *queries;
3223         int                     i;
3224
3225         result->commandType = CMD_UTILITY;
3226         result->utilityStmt = (Node *) stmt;
3227
3228         /* Transform list of TypeNames to list (and array) of type OIDs */
3229         nargs = list_length(stmt->argtypes);
3230
3231         if (nargs)
3232         {
3233                 ListCell   *l;
3234
3235                 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
3236                 i = 0;
3237
3238                 foreach(l, stmt->argtypes)
3239                 {
3240                         TypeName   *tn = lfirst(l);
3241                         Oid                     toid = typenameTypeId(pstate, tn);
3242
3243                         argtoids[i++] = toid;
3244                 }
3245         }
3246
3247         /*
3248          * Analyze the statement using these parameter types (any parameters
3249          * passed in from above us will not be visible to it), allowing
3250          * information about unknown parameters to be deduced from context.
3251          */
3252         queries = parse_analyze_varparams((Node *) stmt->query,
3253                                                                           pstate->p_sourcetext,
3254                                                                           &argtoids, &nargs);
3255
3256         /*
3257          * Shouldn't get any extra statements, since grammar only allows
3258          * OptimizableStmt
3259          */
3260         if (list_length(queries) != 1)
3261                 elog(ERROR, "unexpected extra stuff in prepared statement");
3262
3263         /*
3264          * Check that all parameter types were determined, and convert the array
3265          * of OIDs into a list for storage.
3266          */
3267         argtype_oids = NIL;
3268         for (i = 0; i < nargs; i++)
3269         {
3270                 Oid                     argtype = argtoids[i];
3271
3272                 if (argtype == InvalidOid || argtype == UNKNOWNOID)
3273                         ereport(ERROR,
3274                                         (errcode(ERRCODE_INDETERMINATE_DATATYPE),
3275                                          errmsg("could not determine data type of parameter $%d",
3276                                                         i + 1)));
3277
3278                 argtype_oids = lappend_oid(argtype_oids, argtype);
3279         }
3280
3281         stmt->argtype_oids = argtype_oids;
3282         stmt->query = linitial(queries);
3283         return result;
3284 }
3285
3286 static Query *
3287 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
3288 {
3289         Query      *result = makeNode(Query);
3290         List       *paramtypes;
3291
3292         result->commandType = CMD_UTILITY;
3293         result->utilityStmt = (Node *) stmt;
3294
3295         paramtypes = FetchPreparedStatementParams(stmt->name);
3296
3297         if (stmt->params || paramtypes)
3298         {
3299                 int                     nparams = list_length(stmt->params);
3300                 int                     nexpected = list_length(paramtypes);
3301                 ListCell   *l,
3302                                    *l2;
3303                 int                     i = 1;
3304
3305                 if (nparams != nexpected)
3306                         ereport(ERROR,
3307                                         (errcode(ERRCODE_SYNTAX_ERROR),
3308                         errmsg("wrong number of parameters for prepared statement \"%s\"",
3309                                    stmt->name),
3310                                          errdetail("Expected %d parameters but got %d.",
3311                                                            nexpected, nparams)));
3312
3313                 forboth(l, stmt->params, l2, paramtypes)
3314                 {
3315                         Node       *expr = lfirst(l);
3316                         Oid                     expected_type_id = lfirst_oid(l2);
3317                         Oid                     given_type_id;
3318
3319                         expr = transformExpr(pstate, expr);
3320
3321                         /* Cannot contain subselects or aggregates */
3322                         if (pstate->p_hasSubLinks)
3323                                 ereport(ERROR,
3324                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3325                                                  errmsg("cannot use subquery in EXECUTE parameter")));
3326                         if (pstate->p_hasAggs)
3327                                 ereport(ERROR,
3328                                                 (errcode(ERRCODE_GROUPING_ERROR),
3329                                                  errmsg("cannot use aggregate function in EXECUTE parameter")));
3330
3331                         given_type_id = exprType(expr);
3332
3333                         expr = coerce_to_target_type(pstate, expr, given_type_id,
3334                                                                                  expected_type_id, -1,
3335                                                                                  COERCION_ASSIGNMENT,
3336                                                                                  COERCE_IMPLICIT_CAST);
3337
3338                         if (expr == NULL)
3339                                 ereport(ERROR,
3340                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3341                                                  errmsg("parameter $%d of type %s cannot be coerced to the expected type %s",
3342                                                                 i,
3343                                                                 format_type_be(given_type_id),
3344                                                                 format_type_be(expected_type_id)),
3345                                 errhint("You will need to rewrite or cast the expression.")));
3346
3347                         lfirst(l) = expr;
3348                         i++;
3349                 }
3350         }
3351
3352         return result;
3353 }
3354
3355 /* exported so planner can check again after rewriting, query pullup, etc */
3356 void
3357 CheckSelectLocking(Query *qry)
3358 {
3359         if (qry->setOperations)
3360                 ereport(ERROR,
3361                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3362                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with UNION/INTERSECT/EXCEPT")));
3363         if (qry->distinctClause != NIL)
3364                 ereport(ERROR,
3365                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3366                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with DISTINCT clause")));
3367         if (qry->groupClause != NIL)
3368                 ereport(ERROR,
3369                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3370                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with GROUP BY clause")));
3371         if (qry->havingQual != NULL)
3372                 ereport(ERROR,
3373                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3374                 errmsg("SELECT FOR UPDATE/SHARE is not allowed with HAVING clause")));
3375         if (qry->hasAggs)
3376                 ereport(ERROR,
3377                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3378                                  errmsg("SELECT FOR UPDATE/SHARE is not allowed with aggregate functions")));
3379 }
3380
3381 /*
3382  * Transform a FOR UPDATE/SHARE clause
3383  *
3384  * This basically involves replacing names by integer relids.
3385  *
3386  * NB: if you need to change this, see also markQueryForLocking()
3387  * in rewriteHandler.c.
3388  */
3389 static void
3390 transformLockingClause(Query *qry, LockingClause *lc)
3391 {
3392         List       *lockedRels = lc->lockedRels;
3393         ListCell   *l;
3394         ListCell   *rt;
3395         Index           i;
3396         LockingClause *allrels;
3397
3398         CheckSelectLocking(qry);
3399
3400         /* make a clause we can pass down to subqueries to select all rels */
3401         allrels = makeNode(LockingClause);
3402         allrels->lockedRels = NIL;      /* indicates all rels */
3403         allrels->forUpdate = lc->forUpdate;
3404         allrels->noWait = lc->noWait;
3405
3406         if (lockedRels == NIL)
3407         {
3408                 /* all regular tables used in query */
3409                 i = 0;
3410                 foreach(rt, qry->rtable)
3411                 {
3412                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3413
3414                         ++i;
3415                         switch (rte->rtekind)
3416                         {
3417                                 case RTE_RELATION:
3418                                         applyLockingClause(qry, i, lc->forUpdate, lc->noWait);
3419                                         rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3420                                         break;
3421                                 case RTE_SUBQUERY:
3422
3423                                         /*
3424                                          * FOR UPDATE/SHARE of subquery is propagated to all of
3425                                          * subquery's rels
3426                                          */
3427                                         transformLockingClause(rte->subquery, allrels);
3428                                         break;
3429                                 default:
3430                                         /* ignore JOIN, SPECIAL, FUNCTION RTEs */
3431                                         break;
3432                         }
3433                 }
3434         }
3435         else
3436         {
3437                 /* just the named tables */
3438                 foreach(l, lockedRels)
3439                 {
3440                         char       *relname = strVal(lfirst(l));
3441
3442                         i = 0;
3443                         foreach(rt, qry->rtable)
3444                         {
3445                                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
3446
3447                                 ++i;
3448                                 if (strcmp(rte->eref->aliasname, relname) == 0)
3449                                 {
3450                                         switch (rte->rtekind)
3451                                         {
3452                                                 case RTE_RELATION:
3453                                                         applyLockingClause(qry, i,
3454                                                                                            lc->forUpdate, lc->noWait);
3455                                                         rte->requiredPerms |= ACL_SELECT_FOR_UPDATE;
3456                                                         break;
3457                                                 case RTE_SUBQUERY:
3458
3459                                                         /*
3460                                                          * FOR UPDATE/SHARE of subquery is propagated to
3461                                                          * all of subquery's rels
3462                                                          */
3463                                                         transformLockingClause(rte->subquery, allrels);
3464                                                         break;
3465                                                 case RTE_JOIN:
3466                                                         ereport(ERROR,
3467                                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3468                                                                          errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a join")));
3469                                                         break;
3470                                                 case RTE_SPECIAL:
3471                                                         ereport(ERROR,
3472                                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3473                                                                          errmsg("SELECT FOR UPDATE/SHARE cannot be applied to NEW or OLD")));
3474                                                         break;
3475                                                 case RTE_FUNCTION:
3476                                                         ereport(ERROR,
3477                                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3478                                                                          errmsg("SELECT FOR UPDATE/SHARE cannot be applied to a function")));
3479                                                         break;
3480                                                 case RTE_VALUES:
3481                                                         ereport(ERROR,
3482                                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3483                                                                          errmsg("SELECT FOR UPDATE/SHARE cannot be applied to VALUES")));
3484                                                         break;
3485                                                 default:
3486                                                         elog(ERROR, "unrecognized RTE type: %d",
3487                                                                  (int) rte->rtekind);
3488                                                         break;
3489                                         }
3490                                         break;          /* out of foreach loop */
3491                                 }
3492                         }
3493                         if (rt == NULL)
3494                                 ereport(ERROR,
3495                                                 (errcode(ERRCODE_UNDEFINED_TABLE),
3496                                                  errmsg("relation \"%s\" in FOR UPDATE/SHARE clause not found in FROM clause",
3497                                                                 relname)));
3498                 }
3499         }
3500 }
3501
3502 /*
3503  * Record locking info for a single rangetable item
3504  */
3505 void
3506 applyLockingClause(Query *qry, Index rtindex, bool forUpdate, bool noWait)
3507 {
3508         RowMarkClause *rc;
3509
3510         /* Check for pre-existing entry for same rtindex */
3511         if ((rc = get_rowmark(qry, rtindex)) != NULL)
3512         {
3513                 /*
3514                  * If the same RTE is specified both FOR UPDATE and FOR SHARE, treat
3515                  * it as FOR UPDATE.  (Reasonable, since you can't take both a shared
3516                  * and exclusive lock at the same time; it'll end up being exclusive
3517                  * anyway.)
3518                  *
3519                  * We also consider that NOWAIT wins if it's specified both ways. This
3520                  * is a bit more debatable but raising an error doesn't seem helpful.
3521                  * (Consider for instance SELECT FOR UPDATE NOWAIT from a view that
3522                  * internally contains a plain FOR UPDATE spec.)
3523                  */
3524                 rc->forUpdate |= forUpdate;
3525                 rc->noWait |= noWait;
3526                 return;
3527         }
3528
3529         /* Make a new RowMarkClause */
3530         rc = makeNode(RowMarkClause);
3531         rc->rti = rtindex;
3532         rc->forUpdate = forUpdate;
3533         rc->noWait = noWait;
3534         qry->rowMarks = lappend(qry->rowMarks, rc);
3535 }
3536
3537
3538 /*
3539  * Preprocess a list of column constraint clauses
3540  * to attach constraint attributes to their primary constraint nodes
3541  * and detect inconsistent/misplaced constraint attributes.
3542  *
3543  * NOTE: currently, attributes are only supported for FOREIGN KEY primary
3544  * constraints, but someday they ought to be supported for other constraints.
3545  */
3546 static void
3547 transformConstraintAttrs(List *constraintList)
3548 {
3549         Node       *lastprimarynode = NULL;
3550         bool            saw_deferrability = false;
3551         bool            saw_initially = false;
3552         ListCell   *clist;
3553
3554         foreach(clist, constraintList)
3555         {
3556                 Node       *node = lfirst(clist);
3557
3558                 if (!IsA(node, Constraint))
3559                 {
3560                         lastprimarynode = node;
3561                         /* reset flags for new primary node */
3562                         saw_deferrability = false;
3563                         saw_initially = false;
3564                 }
3565                 else
3566                 {
3567                         Constraint *con = (Constraint *) node;
3568
3569                         switch (con->contype)
3570                         {
3571                                 case CONSTR_ATTR_DEFERRABLE:
3572                                         if (lastprimarynode == NULL ||
3573                                                 !IsA(lastprimarynode, FkConstraint))
3574                                                 ereport(ERROR,
3575                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3576                                                                  errmsg("misplaced DEFERRABLE clause")));
3577                                         if (saw_deferrability)
3578                                                 ereport(ERROR,
3579                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3580                                                                  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
3581                                         saw_deferrability = true;
3582                                         ((FkConstraint *) lastprimarynode)->deferrable = true;
3583                                         break;
3584                                 case CONSTR_ATTR_NOT_DEFERRABLE:
3585                                         if (lastprimarynode == NULL ||
3586                                                 !IsA(lastprimarynode, FkConstraint))
3587                                                 ereport(ERROR,
3588                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3589                                                                  errmsg("misplaced NOT DEFERRABLE clause")));
3590                                         if (saw_deferrability)
3591                                                 ereport(ERROR,
3592                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3593                                                                  errmsg("multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed")));
3594                                         saw_deferrability = true;
3595                                         ((FkConstraint *) lastprimarynode)->deferrable = false;
3596                                         if (saw_initially &&
3597                                                 ((FkConstraint *) lastprimarynode)->initdeferred)
3598                                                 ereport(ERROR,
3599                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3600                                                                  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
3601                                         break;
3602                                 case CONSTR_ATTR_DEFERRED:
3603                                         if (lastprimarynode == NULL ||
3604                                                 !IsA(lastprimarynode, FkConstraint))
3605                                                 ereport(ERROR,
3606                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3607                                                          errmsg("misplaced INITIALLY DEFERRED clause")));
3608                                         if (saw_initially)
3609                                                 ereport(ERROR,
3610                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3611                                                                  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
3612                                         saw_initially = true;
3613                                         ((FkConstraint *) lastprimarynode)->initdeferred = true;
3614
3615                                         /*
3616                                          * If only INITIALLY DEFERRED appears, assume DEFERRABLE
3617                                          */
3618                                         if (!saw_deferrability)
3619                                                 ((FkConstraint *) lastprimarynode)->deferrable = true;
3620                                         else if (!((FkConstraint *) lastprimarynode)->deferrable)
3621                                                 ereport(ERROR,
3622                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3623                                                                  errmsg("constraint declared INITIALLY DEFERRED must be DEFERRABLE")));
3624                                         break;
3625                                 case CONSTR_ATTR_IMMEDIATE:
3626                                         if (lastprimarynode == NULL ||
3627                                                 !IsA(lastprimarynode, FkConstraint))
3628                                                 ereport(ERROR,
3629                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3630                                                         errmsg("misplaced INITIALLY IMMEDIATE clause")));
3631                                         if (saw_initially)
3632                                                 ereport(ERROR,
3633                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3634                                                                  errmsg("multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed")));
3635                                         saw_initially = true;
3636                                         ((FkConstraint *) lastprimarynode)->initdeferred = false;
3637                                         break;
3638                                 default:
3639                                         /* Otherwise it's not an attribute */
3640                                         lastprimarynode = node;
3641                                         /* reset flags for new primary node */
3642                                         saw_deferrability = false;
3643                                         saw_initially = false;
3644                                         break;
3645                         }
3646                 }
3647         }
3648 }
3649
3650 /* Build a FromExpr node */
3651 static FromExpr *
3652 makeFromExpr(List *fromlist, Node *quals)
3653 {
3654         FromExpr   *f = makeNode(FromExpr);
3655
3656         f->fromlist = fromlist;
3657         f->quals = quals;
3658         return f;
3659 }
3660
3661 /*
3662  * Special handling of type definition for a column
3663  */
3664 static void
3665 transformColumnType(ParseState *pstate, ColumnDef *column)
3666 {
3667         /*
3668          * All we really need to do here is verify that the type is valid.
3669          */
3670         Type            ctype = typenameType(pstate, column->typename);
3671
3672         ReleaseSysCache(ctype);
3673 }
3674
3675 static void
3676 setSchemaName(char *context_schema, char **stmt_schema_name)
3677 {
3678         if (*stmt_schema_name == NULL)
3679                 *stmt_schema_name = context_schema;
3680         else if (strcmp(context_schema, *stmt_schema_name) != 0)
3681                 ereport(ERROR,
3682                                 (errcode(ERRCODE_INVALID_SCHEMA_DEFINITION),
3683                                  errmsg("CREATE specifies a schema (%s) "
3684                                                 "different from the one being created (%s)",
3685                                                 *stmt_schema_name, context_schema)));
3686 }
3687
3688 /*
3689  * analyzeCreateSchemaStmt -
3690  *        analyzes the "create schema" statement
3691  *
3692  * Split the schema element list into individual commands and place
3693  * them in the result list in an order such that there are no forward
3694  * references (e.g. GRANT to a table created later in the list). Note
3695  * that the logic we use for determining forward references is
3696  * presently quite incomplete.
3697  *
3698  * SQL92 also allows constraints to make forward references, so thumb through
3699  * the table columns and move forward references to a posterior alter-table
3700  * command.
3701  *
3702  * The result is a list of parse nodes that still need to be analyzed ---
3703  * but we can't analyze the later commands until we've executed the earlier
3704  * ones, because of possible inter-object references.
3705  *
3706  * Note: Called from commands/schemacmds.c
3707  */
3708 List *
3709 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
3710 {
3711         CreateSchemaStmtContext cxt;
3712         List       *result;
3713         ListCell   *elements;
3714
3715         cxt.stmtType = "CREATE SCHEMA";
3716         cxt.schemaname = stmt->schemaname;
3717         cxt.authid = stmt->authid;
3718         cxt.sequences = NIL;
3719         cxt.tables = NIL;
3720         cxt.views = NIL;
3721         cxt.indexes = NIL;
3722         cxt.grants = NIL;
3723         cxt.triggers = NIL;
3724         cxt.fwconstraints = NIL;
3725         cxt.alters = NIL;
3726         cxt.blist = NIL;
3727         cxt.alist = NIL;
3728
3729         /*
3730          * Run through each schema element in the schema element list. Separate
3731          * statements by type, and do preliminary analysis.
3732          */
3733         foreach(elements, stmt->schemaElts)
3734         {
3735                 Node       *element = lfirst(elements);
3736
3737                 switch (nodeTag(element))
3738                 {
3739                         case T_CreateSeqStmt:
3740                                 {
3741                                         CreateSeqStmt *elp = (CreateSeqStmt *) element;
3742
3743                                         setSchemaName(cxt.schemaname, &elp->sequence->schemaname);
3744                                         cxt.sequences = lappend(cxt.sequences, element);
3745                                 }
3746                                 break;
3747
3748                         case T_CreateStmt:
3749                                 {
3750                                         CreateStmt *elp = (CreateStmt *) element;
3751
3752                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3753
3754                                         /*
3755                                          * XXX todo: deal with constraints
3756                                          */
3757                                         cxt.tables = lappend(cxt.tables, element);
3758                                 }
3759                                 break;
3760
3761                         case T_ViewStmt:
3762                                 {
3763                                         ViewStmt   *elp = (ViewStmt *) element;
3764
3765                                         setSchemaName(cxt.schemaname, &elp->view->schemaname);
3766
3767                                         /*
3768                                          * XXX todo: deal with references between views
3769                                          */
3770                                         cxt.views = lappend(cxt.views, element);
3771                                 }
3772                                 break;
3773
3774                         case T_IndexStmt:
3775                                 {
3776                                         IndexStmt  *elp = (IndexStmt *) element;
3777
3778                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3779                                         cxt.indexes = lappend(cxt.indexes, element);
3780                                 }
3781                                 break;
3782
3783                         case T_CreateTrigStmt:
3784                                 {
3785                                         CreateTrigStmt *elp = (CreateTrigStmt *) element;
3786
3787                                         setSchemaName(cxt.schemaname, &elp->relation->schemaname);
3788                                         cxt.triggers = lappend(cxt.triggers, element);
3789                                 }
3790                                 break;
3791
3792                         case T_GrantStmt:
3793                                 cxt.grants = lappend(cxt.grants, element);
3794                                 break;
3795
3796                         default:
3797                                 elog(ERROR, "unrecognized node type: %d",
3798                                          (int) nodeTag(element));
3799                 }
3800         }
3801
3802         result = NIL;
3803         result = list_concat(result, cxt.sequences);
3804         result = list_concat(result, cxt.tables);
3805         result = list_concat(result, cxt.views);
3806         result = list_concat(result, cxt.indexes);
3807         result = list_concat(result, cxt.triggers);
3808         result = list_concat(result, cxt.grants);
3809
3810         return result;
3811 }
3812
3813 /*
3814  * Traverse a fully-analyzed tree to verify that parameter symbols
3815  * match their types.  We need this because some Params might still
3816  * be UNKNOWN, if there wasn't anything to force their coercion,
3817  * and yet other instances seen later might have gotten coerced.
3818  */
3819 static bool
3820 check_parameter_resolution_walker(Node *node,
3821                                                                   check_parameter_resolution_context *context)
3822 {
3823         if (node == NULL)
3824                 return false;
3825         if (IsA(node, Param))
3826         {
3827                 Param      *param = (Param *) node;
3828
3829                 if (param->paramkind == PARAM_EXTERN)
3830                 {
3831                         int                     paramno = param->paramid;
3832
3833                         if (paramno <= 0 || /* shouldn't happen, but... */
3834                                 paramno > context->numParams)
3835                                 ereport(ERROR,
3836                                                 (errcode(ERRCODE_UNDEFINED_PARAMETER),
3837                                                  errmsg("there is no parameter $%d", paramno)));
3838
3839                         if (param->paramtype != context->paramTypes[paramno - 1])
3840                                 ereport(ERROR,
3841                                                 (errcode(ERRCODE_AMBIGUOUS_PARAMETER),
3842                                          errmsg("could not determine data type of parameter $%d",
3843                                                         paramno)));
3844                 }
3845                 return false;
3846         }
3847         if (IsA(node, Query))
3848         {
3849                 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
3850                 return query_tree_walker((Query *) node,
3851                                                                  check_parameter_resolution_walker,
3852                                                                  (void *) context, 0);
3853         }
3854         return expression_tree_walker(node, check_parameter_resolution_walker,
3855                                                                   (void *) context);
3856 }