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