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