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