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