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