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