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