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