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