]> granicus.if.org Git - postgresql/blob - src/backend/parser/analyze.c
Allow GROUP BY, ORDER BY, DISTINCT targets to be unknown literals,
[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.275 2003/06/16 02:03:37 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->expr = NULL;
1315                         iparam->opclass = NIL;
1316                         index->indexParams = lappend(index->indexParams, iparam);
1317                 }
1318
1319                 indexlist = lappend(indexlist, index);
1320         }
1321
1322         /*
1323          * Scan the index list and remove any redundant index specifications.
1324          * This can happen if, for instance, the user writes UNIQUE PRIMARY
1325          * KEY. A strict reading of SQL92 would suggest raising an error
1326          * instead, but that strikes me as too anal-retentive. - tgl
1327          * 2001-02-14
1328          *
1329          * XXX in ALTER TABLE case, it'd be nice to look for duplicate
1330          * pre-existing indexes, too.
1331          */
1332         cxt->alist = NIL;
1333         if (cxt->pkey != NULL)
1334         {
1335                 /* Make sure we keep the PKEY index in preference to others... */
1336                 cxt->alist = makeList1(cxt->pkey);
1337         }
1338         while (indexlist != NIL)
1339         {
1340                 index = lfirst(indexlist);
1341
1342                 /* if it's pkey, it's already in cxt->alist */
1343                 if (index != cxt->pkey)
1344                 {
1345                         bool            keep = true;
1346                         List       *priorlist;
1347
1348                         foreach(priorlist, cxt->alist)
1349                         {
1350                                 IndexStmt  *priorindex = lfirst(priorlist);
1351
1352                                 if (equal(index->indexParams, priorindex->indexParams))
1353                                 {
1354                                         /*
1355                                          * If the prior index is as yet unnamed, and this one
1356                                          * is named, then transfer the name to the prior
1357                                          * index. This ensures that if we have named and
1358                                          * unnamed constraints, we'll use (at least one of)
1359                                          * the names for the index.
1360                                          */
1361                                         if (priorindex->idxname == NULL)
1362                                                 priorindex->idxname = index->idxname;
1363                                         keep = false;
1364                                         break;
1365                                 }
1366                         }
1367
1368                         if (keep)
1369                                 cxt->alist = lappend(cxt->alist, index);
1370                 }
1371
1372                 indexlist = lnext(indexlist);
1373         }
1374
1375         /*
1376          * Finally, select unique names for all not-previously-named indices,
1377          * and display NOTICE messages.
1378          *
1379          * XXX in ALTER TABLE case, we fail to consider name collisions against
1380          * pre-existing indexes.
1381          */
1382         foreach(indexlist, cxt->alist)
1383         {
1384                 index = lfirst(indexlist);
1385
1386                 if (index->idxname == NULL && index->indexParams != NIL)
1387                 {
1388                         iparam = (IndexElem *) lfirst(index->indexParams);
1389                         /* we should never see an expression item here */
1390                         Assert(iparam->expr == NULL);
1391                         index->idxname = CreateIndexName(cxt->relation->relname,
1392                                                                                          iparam->name,
1393                                                                                          "key",
1394                                                                                          cxt->alist);
1395                 }
1396                 if (index->idxname == NULL)             /* should not happen */
1397                         elog(ERROR, "%s: failed to make implicit index name",
1398                                  cxt->stmtType);
1399
1400                 elog(NOTICE, "%s / %s%s will create implicit index '%s' for table '%s'",
1401                          cxt->stmtType,
1402                          (strcmp(cxt->stmtType, "ALTER TABLE") == 0) ? "ADD " : "",
1403                          (index->primary ? "PRIMARY KEY" : "UNIQUE"),
1404                          index->idxname, cxt->relation->relname);
1405         }
1406 }
1407
1408 static void
1409 transformFKConstraints(ParseState *pstate, CreateStmtContext *cxt,
1410                                            bool isAddConstraint)
1411 {
1412         if (cxt->fkconstraints == NIL)
1413                 return;
1414
1415         elog(NOTICE, "%s will create implicit trigger(s) for FOREIGN KEY check(s)",
1416                  cxt->stmtType);
1417
1418         /*
1419          * For ALTER TABLE ADD CONSTRAINT, nothing to do.  For CREATE TABLE or
1420          * ALTER TABLE ADD COLUMN, gin up an ALTER TABLE ADD CONSTRAINT command
1421          * to execute after the basic command is complete.
1422          *
1423          * Note: the ADD CONSTRAINT command must also execute after any index
1424          * creation commands.  Thus, this should run after
1425          * transformIndexConstraints, so that the CREATE INDEX commands are
1426          * already in cxt->alist.
1427          */
1428         if (!isAddConstraint)
1429         {
1430                 AlterTableStmt *alterstmt = makeNode(AlterTableStmt);
1431                 List       *fkclist;
1432
1433                 alterstmt->subtype = 'c'; /* preprocessed add constraint */
1434                 alterstmt->relation = cxt->relation;
1435                 alterstmt->name = NULL;
1436                 alterstmt->def = (Node *) cxt->fkconstraints;
1437
1438                 /* Don't need to scan the table contents in this case */
1439                 foreach(fkclist, cxt->fkconstraints)
1440                 {
1441                         FkConstraint *fkconstraint = (FkConstraint *) lfirst(fkclist);
1442
1443                         fkconstraint->skip_validation = true;
1444                 }
1445
1446                 cxt->alist = lappend(cxt->alist, (Node *) alterstmt);
1447         }
1448 }
1449
1450 /*
1451  * transformIndexStmt -
1452  *        transforms the qualification of the index statement
1453  */
1454 static Query *
1455 transformIndexStmt(ParseState *pstate, IndexStmt *stmt)
1456 {
1457         Query      *qry;
1458         RangeTblEntry *rte = NULL;
1459         List       *l;
1460
1461         qry = makeNode(Query);
1462         qry->commandType = CMD_UTILITY;
1463
1464         /* take care of the where clause */
1465         if (stmt->whereClause)
1466         {
1467                 /*
1468                  * Put the parent table into the rtable so that the WHERE clause
1469                  * can refer to its fields without qualification.  Note that this
1470                  * only works if the parent table already exists --- so we can't
1471                  * easily support predicates on indexes created implicitly by
1472                  * CREATE TABLE. Fortunately, that's not necessary.
1473                  */
1474                 rte = addRangeTableEntry(pstate, stmt->relation, NULL, false, true);
1475
1476                 /* no to join list, yes to namespace */
1477                 addRTEtoQuery(pstate, rte, false, true);
1478
1479                 stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
1480         }
1481
1482         /* take care of any index expressions */
1483         foreach(l, stmt->indexParams)
1484         {
1485                 IndexElem       *ielem = (IndexElem *) lfirst(l);
1486
1487                 if (ielem->expr)
1488                 {
1489                         /* Set up rtable as for predicate, see notes above */
1490                         if (rte == NULL)
1491                         {
1492                                 rte = addRangeTableEntry(pstate, stmt->relation, NULL,
1493                                                                                  false, true);
1494                                 /* no to join list, yes to namespace */
1495                                 addRTEtoQuery(pstate, rte, false, true);
1496                         }
1497                         ielem->expr = transformExpr(pstate, ielem->expr);
1498                         /*
1499                          * We check only that the result type is legitimate; this is
1500                          * for consistency with what transformWhereClause() checks for
1501                          * the predicate.  DefineIndex() will make more checks.
1502                          */
1503                         if (expression_returns_set(ielem->expr))
1504                                 elog(ERROR, "index expression may not return a set");
1505                 }
1506         }
1507
1508         qry->hasSubLinks = pstate->p_hasSubLinks;
1509         stmt->rangetable = pstate->p_rtable;
1510
1511         qry->utilityStmt = (Node *) stmt;
1512
1513         return qry;
1514 }
1515
1516 /*
1517  * transformRuleStmt -
1518  *        transform a Create Rule Statement. The actions is a list of parse
1519  *        trees which is transformed into a list of query trees.
1520  */
1521 static Query *
1522 transformRuleStmt(ParseState *pstate, RuleStmt *stmt,
1523                                   List **extras_before, List **extras_after)
1524 {
1525         Query      *qry;
1526         RangeTblEntry *oldrte;
1527         RangeTblEntry *newrte;
1528
1529         qry = makeNode(Query);
1530         qry->commandType = CMD_UTILITY;
1531         qry->utilityStmt = (Node *) stmt;
1532
1533         /*
1534          * To avoid deadlock, make sure the first thing we do is grab
1535          * AccessExclusiveLock on the target relation.  This will be needed by
1536          * DefineQueryRewrite(), and we don't want to grab a lesser lock
1537          * beforehand.  We don't need to hold a refcount on the relcache
1538          * entry, however.
1539          */
1540         heap_close(heap_openrv(stmt->relation, AccessExclusiveLock),
1541                            NoLock);
1542
1543         /*
1544          * NOTE: 'OLD' must always have a varno equal to 1 and 'NEW' equal to
1545          * 2.  Set up their RTEs in the main pstate for use in parsing the
1546          * rule qualification.
1547          */
1548         Assert(pstate->p_rtable == NIL);
1549         oldrte = addRangeTableEntry(pstate, stmt->relation,
1550                                                                 makeAlias("*OLD*", NIL),
1551                                                                 false, true);
1552         newrte = addRangeTableEntry(pstate, stmt->relation,
1553                                                                 makeAlias("*NEW*", NIL),
1554                                                                 false, true);
1555         /* Must override addRangeTableEntry's default access-check flags */
1556         oldrte->checkForRead = false;
1557         newrte->checkForRead = false;
1558
1559         /*
1560          * They must be in the namespace too for lookup purposes, but only add
1561          * the one(s) that are relevant for the current kind of rule.  In an
1562          * UPDATE rule, quals must refer to OLD.field or NEW.field to be
1563          * unambiguous, but there's no need to be so picky for INSERT &
1564          * DELETE. (Note we marked the RTEs "inFromCl = true" above to allow
1565          * unqualified references to their fields.)  We do not add them to the
1566          * joinlist.
1567          */
1568         switch (stmt->event)
1569         {
1570                 case CMD_SELECT:
1571                         addRTEtoQuery(pstate, oldrte, false, true);
1572                         break;
1573                 case CMD_UPDATE:
1574                         addRTEtoQuery(pstate, oldrte, false, true);
1575                         addRTEtoQuery(pstate, newrte, false, true);
1576                         break;
1577                 case CMD_INSERT:
1578                         addRTEtoQuery(pstate, newrte, false, true);
1579                         break;
1580                 case CMD_DELETE:
1581                         addRTEtoQuery(pstate, oldrte, false, true);
1582                         break;
1583                 default:
1584                         elog(ERROR, "transformRuleStmt: unexpected event type %d",
1585                                  (int) stmt->event);
1586                         break;
1587         }
1588
1589         /* take care of the where clause */
1590         stmt->whereClause = transformWhereClause(pstate, stmt->whereClause);
1591
1592         if (length(pstate->p_rtable) != 2)      /* naughty, naughty... */
1593                 elog(ERROR, "Rule WHERE condition may not contain references to other relations");
1594
1595         /* aggregates not allowed (but subselects are okay) */
1596         if (pstate->p_hasAggs)
1597                 elog(ERROR, "Rule WHERE condition may not contain aggregate functions");
1598
1599         /* save info about sublinks in where clause */
1600         qry->hasSubLinks = pstate->p_hasSubLinks;
1601
1602         /*
1603          * 'instead nothing' rules with a qualification need a query
1604          * rangetable so the rewrite handler can add the negated rule
1605          * qualification to the original query. We create a query with the new
1606          * command type CMD_NOTHING here that is treated specially by the
1607          * rewrite system.
1608          */
1609         if (stmt->actions == NIL)
1610         {
1611                 Query      *nothing_qry = makeNode(Query);
1612
1613                 nothing_qry->commandType = CMD_NOTHING;
1614                 nothing_qry->rtable = pstate->p_rtable;
1615                 nothing_qry->jointree = makeFromExpr(NIL, NULL);                /* no join wanted */
1616
1617                 stmt->actions = makeList1(nothing_qry);
1618         }
1619         else
1620         {
1621                 List       *oldactions;
1622                 List       *newactions = NIL;
1623
1624                 /*
1625                  * transform each statement, like parse_sub_analyze()
1626                  */
1627                 foreach(oldactions, stmt->actions)
1628                 {
1629                         Node       *action = (Node *) lfirst(oldactions);
1630                         ParseState *sub_pstate = make_parsestate(pstate->parentParseState);
1631                         Query      *sub_qry,
1632                                            *top_subqry;
1633                         bool            has_old,
1634                                                 has_new;
1635
1636                         /*
1637                          * Set up OLD/NEW in the rtable for this statement.  The
1638                          * entries are marked not inFromCl because we don't want them
1639                          * to be referred to by unqualified field names nor "*" in the
1640                          * rule actions.  We must add them to the namespace, however,
1641                          * or they won't be accessible at all.  We decide later
1642                          * whether to put them in the joinlist.
1643                          */
1644                         oldrte = addRangeTableEntry(sub_pstate, stmt->relation,
1645                                                                                 makeAlias("*OLD*", NIL),
1646                                                                                 false, false);
1647                         newrte = addRangeTableEntry(sub_pstate, stmt->relation,
1648                                                                                 makeAlias("*NEW*", NIL),
1649                                                                                 false, false);
1650                         oldrte->checkForRead = false;
1651                         newrte->checkForRead = false;
1652                         addRTEtoQuery(sub_pstate, oldrte, false, true);
1653                         addRTEtoQuery(sub_pstate, newrte, false, true);
1654
1655                         /* Transform the rule action statement */
1656                         top_subqry = transformStmt(sub_pstate, action,
1657                                                                            extras_before, extras_after);
1658
1659                         /*
1660                          * We cannot support utility-statement actions (eg NOTIFY)
1661                          * with nonempty rule WHERE conditions, because there's no way
1662                          * to make the utility action execute conditionally.
1663                          */
1664                         if (top_subqry->commandType == CMD_UTILITY &&
1665                                 stmt->whereClause != NULL)
1666                                 elog(ERROR, "Rules with WHERE conditions may only have SELECT, INSERT, UPDATE, or DELETE actions");
1667
1668                         /*
1669                          * If the action is INSERT...SELECT, OLD/NEW have been pushed
1670                          * down into the SELECT, and that's what we need to look at.
1671                          * (Ugly kluge ... try to fix this when we redesign
1672                          * querytrees.)
1673                          */
1674                         sub_qry = getInsertSelectQuery(top_subqry, NULL);
1675
1676                         /*
1677                          * Validate action's use of OLD/NEW, qual too
1678                          */
1679                         has_old =
1680                                 rangeTableEntry_used((Node *) sub_qry, PRS2_OLD_VARNO, 0) ||
1681                                 rangeTableEntry_used(stmt->whereClause, PRS2_OLD_VARNO, 0);
1682                         has_new =
1683                                 rangeTableEntry_used((Node *) sub_qry, PRS2_NEW_VARNO, 0) ||
1684                                 rangeTableEntry_used(stmt->whereClause, PRS2_NEW_VARNO, 0);
1685
1686                         switch (stmt->event)
1687                         {
1688                                 case CMD_SELECT:
1689                                         if (has_old)
1690                                                 elog(ERROR, "ON SELECT rule may not use OLD");
1691                                         if (has_new)
1692                                                 elog(ERROR, "ON SELECT rule may not use NEW");
1693                                         break;
1694                                 case CMD_UPDATE:
1695                                         /* both are OK */
1696                                         break;
1697                                 case CMD_INSERT:
1698                                         if (has_old)
1699                                                 elog(ERROR, "ON INSERT rule may not use OLD");
1700                                         break;
1701                                 case CMD_DELETE:
1702                                         if (has_new)
1703                                                 elog(ERROR, "ON DELETE rule may not use NEW");
1704                                         break;
1705                                 default:
1706                                         elog(ERROR, "transformRuleStmt: unexpected event type %d",
1707                                                  (int) stmt->event);
1708                                         break;
1709                         }
1710
1711                         /*
1712                          * For efficiency's sake, add OLD to the rule action's
1713                          * jointree only if it was actually referenced in the
1714                          * statement or qual.
1715                          *
1716                          * For INSERT, NEW is not really a relation (only a reference to
1717                          * the to-be-inserted tuple) and should never be added to the
1718                          * jointree.
1719                          *
1720                          * For UPDATE, we treat NEW as being another kind of reference to
1721                          * OLD, because it represents references to *transformed*
1722                          * tuples of the existing relation.  It would be wrong to
1723                          * enter NEW separately in the jointree, since that would
1724                          * cause a double join of the updated relation.  It's also
1725                          * wrong to fail to make a jointree entry if only NEW and not
1726                          * OLD is mentioned.
1727                          */
1728                         if (has_old || (has_new && stmt->event == CMD_UPDATE))
1729                         {
1730                                 /* hack so we can use addRTEtoQuery() */
1731                                 sub_pstate->p_rtable = sub_qry->rtable;
1732                                 sub_pstate->p_joinlist = sub_qry->jointree->fromlist;
1733                                 addRTEtoQuery(sub_pstate, oldrte, true, false);
1734                                 sub_qry->jointree->fromlist = sub_pstate->p_joinlist;
1735                         }
1736
1737                         newactions = lappend(newactions, top_subqry);
1738
1739                         release_pstate_resources(sub_pstate);
1740                         pfree(sub_pstate);
1741                 }
1742
1743                 stmt->actions = newactions;
1744         }
1745
1746         return qry;
1747 }
1748
1749
1750 /*
1751  * transformSelectStmt -
1752  *        transforms a Select Statement
1753  *
1754  * Note: this is also used for DECLARE CURSOR statements.
1755  */
1756 static Query *
1757 transformSelectStmt(ParseState *pstate, SelectStmt *stmt)
1758 {
1759         Query      *qry = makeNode(Query);
1760         Node       *qual;
1761
1762         qry->commandType = CMD_SELECT;
1763
1764         /* make FOR UPDATE clause available to addRangeTableEntry */
1765         pstate->p_forUpdate = stmt->forUpdate;
1766
1767         /* process the FROM clause */
1768         transformFromClause(pstate, stmt->fromClause);
1769
1770         /* transform targetlist */
1771         qry->targetList = transformTargetList(pstate, stmt->targetList);
1772
1773         /* handle any SELECT INTO/CREATE TABLE AS spec */
1774         qry->into = stmt->into;
1775         if (stmt->intoColNames)
1776                 applyColumnNames(qry->targetList, stmt->intoColNames);
1777
1778         /* mark column origins */
1779         markTargetListOrigins(pstate, qry->targetList);
1780
1781         /* transform WHERE */
1782         qual = transformWhereClause(pstate, stmt->whereClause);
1783
1784         /*
1785          * Initial processing of HAVING clause is just like WHERE clause.
1786          * Additional work will be done in optimizer/plan/planner.c.
1787          */
1788         qry->havingQual = transformWhereClause(pstate, stmt->havingClause);
1789
1790         /*
1791          * Transform sorting/grouping stuff.  Do ORDER BY first because both
1792          * transformGroupClause and transformDistinctClause need the results.
1793          */
1794         qry->sortClause = transformSortClause(pstate,
1795                                                                                   stmt->sortClause,
1796                                                                                   qry->targetList,
1797                                                                                   true /* fix unknowns */);
1798
1799         qry->groupClause = transformGroupClause(pstate,
1800                                                                                         stmt->groupClause,
1801                                                                                         qry->targetList,
1802                                                                                         qry->sortClause);
1803
1804         qry->distinctClause = transformDistinctClause(pstate,
1805                                                                                                   stmt->distinctClause,
1806                                                                                                   qry->targetList,
1807                                                                                                   &qry->sortClause);
1808
1809         qry->limitOffset = stmt->limitOffset;
1810         qry->limitCount = stmt->limitCount;
1811
1812         qry->rtable = pstate->p_rtable;
1813         qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1814
1815         qry->hasSubLinks = pstate->p_hasSubLinks;
1816         qry->hasAggs = pstate->p_hasAggs;
1817         if (pstate->p_hasAggs || qry->groupClause)
1818                 parseCheckAggregates(pstate, qry);
1819
1820         if (stmt->forUpdate != NIL)
1821                 transformForUpdate(qry, stmt->forUpdate);
1822
1823         return qry;
1824 }
1825
1826 /*
1827  * transformSetOperationsStmt -
1828  *        transforms a set-operations tree
1829  *
1830  * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1831  * structure to it.  We must transform each leaf SELECT and build up a top-
1832  * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1833  * The tree of set operations is converted into the setOperations field of
1834  * the top-level Query.
1835  */
1836 static Query *
1837 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1838 {
1839         Query      *qry = makeNode(Query);
1840         SelectStmt *leftmostSelect;
1841         int                     leftmostRTI;
1842         Query      *leftmostQuery;
1843         SetOperationStmt *sostmt;
1844         RangeVar   *into;
1845         List       *intoColNames;
1846         List       *sortClause;
1847         Node       *limitOffset;
1848         Node       *limitCount;
1849         List       *forUpdate;
1850         Node       *node;
1851         List       *lefttl,
1852                            *dtlist,
1853                            *targetvars,
1854                            *targetnames,
1855                            *sv_namespace,
1856                            *sv_rtable;
1857         RangeTblEntry *jrte;
1858         RangeTblRef *jrtr;
1859         int                     tllen;
1860
1861         qry->commandType = CMD_SELECT;
1862
1863         /*
1864          * Find leftmost leaf SelectStmt; extract the one-time-only items from
1865          * it and from the top-level node.
1866          */
1867         leftmostSelect = stmt->larg;
1868         while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1869                 leftmostSelect = leftmostSelect->larg;
1870         Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1871                    leftmostSelect->larg == NULL);
1872         into = leftmostSelect->into;
1873         intoColNames = leftmostSelect->intoColNames;
1874
1875         /* clear them to prevent complaints in transformSetOperationTree() */
1876         leftmostSelect->into = NULL;
1877         leftmostSelect->intoColNames = NIL;
1878
1879         /*
1880          * These are not one-time, exactly, but we want to process them here
1881          * and not let transformSetOperationTree() see them --- else it'll
1882          * just recurse right back here!
1883          */
1884         sortClause = stmt->sortClause;
1885         limitOffset = stmt->limitOffset;
1886         limitCount = stmt->limitCount;
1887         forUpdate = stmt->forUpdate;
1888
1889         stmt->sortClause = NIL;
1890         stmt->limitOffset = NULL;
1891         stmt->limitCount = NULL;
1892         stmt->forUpdate = NIL;
1893
1894         /* We don't support forUpdate with set ops at the moment. */
1895         if (forUpdate)
1896                 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
1897
1898         /*
1899          * Recursively transform the components of the tree.
1900          */
1901         sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
1902         Assert(sostmt && IsA(sostmt, SetOperationStmt));
1903         qry->setOperations = (Node *) sostmt;
1904
1905         /*
1906          * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1907          */
1908         node = sostmt->larg;
1909         while (node && IsA(node, SetOperationStmt))
1910                 node = ((SetOperationStmt *) node)->larg;
1911         Assert(node && IsA(node, RangeTblRef));
1912         leftmostRTI = ((RangeTblRef *) node)->rtindex;
1913         leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1914         Assert(leftmostQuery != NULL);
1915
1916         /*
1917          * Generate dummy targetlist for outer query using column names of
1918          * leftmost select and common datatypes of topmost set operation. Also
1919          * make lists of the dummy vars and their names for use in parsing
1920          * ORDER BY.
1921          *
1922          * Note: we use leftmostRTI as the varno of the dummy variables.
1923          * It shouldn't matter too much which RT index they have, as long
1924          * as they have one that corresponds to a real RT entry; else funny
1925          * things may happen when the tree is mashed by rule rewriting.
1926          */
1927         qry->targetList = NIL;
1928         targetvars = NIL;
1929         targetnames = NIL;
1930         lefttl = leftmostQuery->targetList;
1931         foreach(dtlist, sostmt->colTypes)
1932         {
1933                 Oid                     colType = lfirsto(dtlist);
1934                 Resdom     *leftResdom = ((TargetEntry *) lfirst(lefttl))->resdom;
1935                 char       *colName = pstrdup(leftResdom->resname);
1936                 Resdom     *resdom;
1937                 Expr       *expr;
1938
1939                 resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
1940                                                         colType,
1941                                                         -1,
1942                                                         colName,
1943                                                         false);
1944                 expr = (Expr *) makeVar(leftmostRTI,
1945                                                                 leftResdom->resno,
1946                                                                 colType,
1947                                                                 -1,
1948                                                                 0);
1949                 qry->targetList = lappend(qry->targetList,
1950                                                                   makeTargetEntry(resdom, expr));
1951                 targetvars = lappend(targetvars, expr);
1952                 targetnames = lappend(targetnames, makeString(colName));
1953                 lefttl = lnext(lefttl);
1954         }
1955
1956         /*
1957          * Handle SELECT INTO/CREATE TABLE AS.
1958          *
1959          * Any column names from CREATE TABLE AS need to be attached to both
1960          * the top level and the leftmost subquery.  We do not do this earlier
1961          * because we do *not* want the targetnames list to be affected.
1962          */
1963         qry->into = into;
1964         if (intoColNames)
1965         {
1966                 applyColumnNames(qry->targetList, intoColNames);
1967                 applyColumnNames(leftmostQuery->targetList, intoColNames);
1968         }
1969
1970         /*
1971          * As a first step towards supporting sort clauses that are
1972          * expressions using the output columns, generate a namespace entry
1973          * that makes the output columns visible.  A Join RTE node is handy
1974          * for this, since we can easily control the Vars generated upon
1975          * matches.
1976          *
1977          * Note: we don't yet do anything useful with such cases, but at least
1978          * "ORDER BY upper(foo)" will draw the right error message rather than
1979          * "foo not found".
1980          */
1981         jrte = addRangeTableEntryForJoin(NULL,
1982                                                                          targetnames,
1983                                                                          JOIN_INNER,
1984                                                                          targetvars,
1985                                                                          NULL,
1986                                                                          true);
1987         jrtr = makeNode(RangeTblRef);
1988         jrtr->rtindex = 1;                      /* only entry in dummy rtable */
1989
1990         sv_rtable = pstate->p_rtable;
1991         pstate->p_rtable = makeList1(jrte);
1992
1993         sv_namespace = pstate->p_namespace;
1994         pstate->p_namespace = makeList1(jrtr);
1995
1996         /*
1997          * For now, we don't support resjunk sort clauses on the output of a
1998          * setOperation tree --- you can only use the SQL92-spec options of
1999          * selecting an output column by name or number.  Enforce by checking
2000          * that transformSortClause doesn't add any items to tlist.
2001          */
2002         tllen = length(qry->targetList);
2003
2004         qry->sortClause = transformSortClause(pstate,
2005                                                                                   sortClause,
2006                                                                                   qry->targetList,
2007                                                                                   false /* no unknowns expected */);
2008
2009         pstate->p_namespace = sv_namespace;
2010         pstate->p_rtable = sv_rtable;
2011
2012         if (tllen != length(qry->targetList))
2013                 elog(ERROR, "ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns");
2014
2015         qry->limitOffset = limitOffset;
2016         qry->limitCount = limitCount;
2017
2018         qry->rtable = pstate->p_rtable;
2019         qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2020
2021         qry->hasSubLinks = pstate->p_hasSubLinks;
2022         qry->hasAggs = pstate->p_hasAggs;
2023         if (pstate->p_hasAggs || qry->groupClause)
2024                 parseCheckAggregates(pstate, qry);
2025
2026         if (forUpdate != NIL)
2027                 transformForUpdate(qry, forUpdate);
2028
2029         return qry;
2030 }
2031
2032 /*
2033  * transformSetOperationTree
2034  *              Recursively transform leaves and internal nodes of a set-op tree
2035  */
2036 static Node *
2037 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2038 {
2039         bool            isLeaf;
2040
2041         Assert(stmt && IsA(stmt, SelectStmt));
2042
2043         /*
2044          * Validity-check both leaf and internal SELECTs for disallowed ops.
2045          */
2046         if (stmt->into)
2047                 elog(ERROR, "INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT");
2048         /* We don't support forUpdate with set ops at the moment. */
2049         if (stmt->forUpdate)
2050                 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
2051
2052         /*
2053          * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2054          * clauses attached, we need to treat it like a leaf node to generate
2055          * an independent sub-Query tree.  Otherwise, it can be represented by
2056          * a SetOperationStmt node underneath the parent Query.
2057          */
2058         if (stmt->op == SETOP_NONE)
2059         {
2060                 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2061                 isLeaf = true;
2062         }
2063         else
2064         {
2065                 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2066                 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2067                         stmt->forUpdate)
2068                         isLeaf = true;
2069                 else
2070                         isLeaf = false;
2071         }
2072
2073         if (isLeaf)
2074         {
2075                 /* Process leaf SELECT */
2076                 List       *selectList;
2077                 Query      *selectQuery;
2078                 char            selectName[32];
2079                 RangeTblEntry *rte;
2080                 RangeTblRef *rtr;
2081
2082                 /*
2083                  * Transform SelectStmt into a Query.
2084                  *
2085                  * Note: previously transformed sub-queries don't affect the parsing
2086                  * of this sub-query, because they are not in the toplevel
2087                  * pstate's namespace list.
2088                  */
2089                 selectList = parse_sub_analyze((Node *) stmt, pstate);
2090
2091                 Assert(length(selectList) == 1);
2092                 selectQuery = (Query *) lfirst(selectList);
2093                 Assert(IsA(selectQuery, Query));
2094
2095                 /*
2096                  * Check for bogus references to Vars on the current query level
2097                  * (but upper-level references are okay).
2098                  * Normally this can't happen because the namespace will be empty,
2099                  * but it could happen if we are inside a rule.
2100                  */
2101                 if (pstate->p_namespace)
2102                 {
2103                         if (contain_vars_of_level((Node *) selectQuery, 1))
2104                                 elog(ERROR, "UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level");
2105                 }
2106
2107                 /*
2108                  * Make the leaf query be a subquery in the top-level rangetable.
2109                  */
2110                 snprintf(selectName, sizeof(selectName), "*SELECT* %d", length(pstate->p_rtable) + 1);
2111                 rte = addRangeTableEntryForSubquery(pstate,
2112                                                                                         selectQuery,
2113                                                                                         makeAlias(selectName, NIL),
2114                                                                                         false);
2115
2116                 /*
2117                  * Return a RangeTblRef to replace the SelectStmt in the set-op
2118                  * tree.
2119                  */
2120                 rtr = makeNode(RangeTblRef);
2121                 /* assume new rte is at end */
2122                 rtr->rtindex = length(pstate->p_rtable);
2123                 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2124                 return (Node *) rtr;
2125         }
2126         else
2127         {
2128                 /* Process an internal node (set operation node) */
2129                 SetOperationStmt *op = makeNode(SetOperationStmt);
2130                 List       *lcoltypes;
2131                 List       *rcoltypes;
2132                 const char *context;
2133
2134                 context = (stmt->op == SETOP_UNION ? "UNION" :
2135                                    (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2136                                         "EXCEPT"));
2137
2138                 op->op = stmt->op;
2139                 op->all = stmt->all;
2140
2141                 /*
2142                  * Recursively transform the child nodes.
2143                  */
2144                 op->larg = transformSetOperationTree(pstate, stmt->larg);
2145                 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2146
2147                 /*
2148                  * Verify that the two children have the same number of non-junk
2149                  * columns, and determine the types of the merged output columns.
2150                  */
2151                 lcoltypes = getSetColTypes(pstate, op->larg);
2152                 rcoltypes = getSetColTypes(pstate, op->rarg);
2153                 if (length(lcoltypes) != length(rcoltypes))
2154                         elog(ERROR, "Each %s query must have the same number of columns",
2155                                  context);
2156                 op->colTypes = NIL;
2157                 while (lcoltypes != NIL)
2158                 {
2159                         Oid                     lcoltype = lfirsto(lcoltypes);
2160                         Oid                     rcoltype = lfirsto(rcoltypes);
2161                         Oid                     rescoltype;
2162
2163                         rescoltype = select_common_type(makeListo2(lcoltype, rcoltype),
2164                                                                                         context);
2165                         op->colTypes = lappendo(op->colTypes, rescoltype);
2166                         lcoltypes = lnext(lcoltypes);
2167                         rcoltypes = lnext(rcoltypes);
2168                 }
2169
2170                 return (Node *) op;
2171         }
2172 }
2173
2174 /*
2175  * getSetColTypes
2176  *              Get output column types of an (already transformed) set-op node
2177  */
2178 static List *
2179 getSetColTypes(ParseState *pstate, Node *node)
2180 {
2181         if (IsA(node, RangeTblRef))
2182         {
2183                 RangeTblRef *rtr = (RangeTblRef *) node;
2184                 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2185                 Query      *selectQuery = rte->subquery;
2186                 List       *result = NIL;
2187                 List       *tl;
2188
2189                 Assert(selectQuery != NULL);
2190                 /* Get types of non-junk columns */
2191                 foreach(tl, selectQuery->targetList)
2192                 {
2193                         TargetEntry *tle = (TargetEntry *) lfirst(tl);
2194                         Resdom     *resnode = tle->resdom;
2195
2196                         if (resnode->resjunk)
2197                                 continue;
2198                         result = lappendo(result, resnode->restype);
2199                 }
2200                 return result;
2201         }
2202         else if (IsA(node, SetOperationStmt))
2203         {
2204                 SetOperationStmt *op = (SetOperationStmt *) node;
2205
2206                 /* Result already computed during transformation of node */
2207                 Assert(op->colTypes != NIL);
2208                 return op->colTypes;
2209         }
2210         else
2211         {
2212                 elog(ERROR, "getSetColTypes: unexpected node %d",
2213                          (int) nodeTag(node));
2214                 return NIL;                             /* keep compiler quiet */
2215         }
2216 }
2217
2218 /* Attach column names from a ColumnDef list to a TargetEntry list */
2219 static void
2220 applyColumnNames(List *dst, List *src)
2221 {
2222         if (length(src) > length(dst))
2223                 elog(ERROR, "CREATE TABLE AS specifies too many column names");
2224
2225         while (src != NIL && dst != NIL)
2226         {
2227                 TargetEntry *d = (TargetEntry *) lfirst(dst);
2228                 ColumnDef  *s = (ColumnDef *) lfirst(src);
2229
2230                 Assert(d->resdom && !d->resdom->resjunk);
2231
2232                 d->resdom->resname = pstrdup(s->colname);
2233
2234                 dst = lnext(dst);
2235                 src = lnext(src);
2236         }
2237 }
2238
2239
2240 /*
2241  * transformUpdateStmt -
2242  *        transforms an update statement
2243  */
2244 static Query *
2245 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2246 {
2247         Query      *qry = makeNode(Query);
2248         Node       *qual;
2249         List       *origTargetList;
2250         List       *tl;
2251
2252         qry->commandType = CMD_UPDATE;
2253         pstate->p_is_update = true;
2254
2255         qry->resultRelation = setTargetTable(pstate, stmt->relation,
2256                                                           interpretInhOption(stmt->relation->inhOpt),
2257                                                                                  true);
2258
2259         /*
2260          * the FROM clause is non-standard SQL syntax. We used to be able to
2261          * do this with REPLACE in POSTQUEL so we keep the feature.
2262          */
2263         transformFromClause(pstate, stmt->fromClause);
2264
2265         qry->targetList = transformTargetList(pstate, stmt->targetList);
2266
2267         qual = transformWhereClause(pstate, stmt->whereClause);
2268
2269         qry->rtable = pstate->p_rtable;
2270         qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2271
2272         qry->hasSubLinks = pstate->p_hasSubLinks;
2273         qry->hasAggs = pstate->p_hasAggs;
2274         if (pstate->p_hasAggs)
2275                 parseCheckAggregates(pstate, qry);
2276
2277         /*
2278          * Now we are done with SELECT-like processing, and can get on with
2279          * transforming the target list to match the UPDATE target columns.
2280          */
2281
2282         /* Prepare to assign non-conflicting resnos to resjunk attributes */
2283         if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2284                 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2285
2286         /* Prepare non-junk columns for assignment to target table */
2287         origTargetList = stmt->targetList;
2288         foreach(tl, qry->targetList)
2289         {
2290                 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2291                 Resdom     *resnode = tle->resdom;
2292                 ResTarget  *origTarget;
2293
2294                 if (resnode->resjunk)
2295                 {
2296                         /*
2297                          * Resjunk nodes need no additional processing, but be sure
2298                          * they have names and resnos that do not match any target
2299                          * columns; else rewriter or planner might get confused.
2300                          */
2301                         resnode->resname = "?resjunk?";
2302                         resnode->resno = (AttrNumber) pstate->p_next_resno++;
2303                         continue;
2304                 }
2305                 if (origTargetList == NIL)
2306                         elog(ERROR, "UPDATE target count mismatch --- internal error");
2307                 origTarget = (ResTarget *) lfirst(origTargetList);
2308                 updateTargetListEntry(pstate, tle, origTarget->name,
2309                                                           attnameAttNum(pstate->p_target_relation,
2310                                                                                         origTarget->name, true),
2311                                                           origTarget->indirection);
2312                 origTargetList = lnext(origTargetList);
2313         }
2314         if (origTargetList != NIL)
2315                 elog(ERROR, "UPDATE target count mismatch --- internal error");
2316
2317         return qry;
2318 }
2319
2320 /*
2321  * tranformAlterTableStmt -
2322  *      transform an Alter Table Statement
2323  */
2324 static Query *
2325 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2326                                                 List **extras_before, List **extras_after)
2327 {
2328         Relation        rel;
2329         CreateStmtContext cxt;
2330         Query      *qry;
2331
2332         /*
2333          * The only subtypes that currently require parse transformation
2334          * handling are 'A'dd column and Add 'C'onstraint.      These largely
2335          * re-use code from CREATE TABLE.
2336          *
2337          * If we need to do any parse transformation, get exclusive lock on
2338          * the relation to make sure it won't change before we execute the
2339          * command.
2340          */
2341         switch (stmt->subtype)
2342         {
2343                 case 'A':
2344                         rel = heap_openrv(stmt->relation, AccessExclusiveLock);
2345
2346                         cxt.stmtType = "ALTER TABLE";
2347                         cxt.relation = stmt->relation;
2348                         cxt.inhRelations = NIL;
2349                         cxt.relOid = RelationGetRelid(rel);
2350                         cxt.hasoids = SearchSysCacheExists(ATTNUM,
2351                                                                                         ObjectIdGetDatum(cxt.relOid),
2352                                                                   Int16GetDatum(ObjectIdAttributeNumber),
2353                                                                                            0, 0);
2354                         cxt.columns = NIL;
2355                         cxt.ckconstraints = NIL;
2356                         cxt.fkconstraints = NIL;
2357                         cxt.ixconstraints = NIL;
2358                         cxt.blist = NIL;
2359                         cxt.alist = NIL;
2360                         cxt.pkey = NULL;
2361
2362                         Assert(IsA(stmt->def, ColumnDef));
2363                         transformColumnDefinition(pstate, &cxt,
2364                                                                           (ColumnDef *) stmt->def);
2365
2366                         transformIndexConstraints(pstate, &cxt);
2367                         transformFKConstraints(pstate, &cxt, false);
2368
2369                         ((ColumnDef *) stmt->def)->constraints = cxt.ckconstraints;
2370                         *extras_before = nconc(*extras_before, cxt.blist);
2371                         *extras_after = nconc(cxt.alist, *extras_after);
2372
2373                         heap_close(rel, NoLock); /* close rel, keep lock */
2374                         break;
2375
2376                 case 'C':
2377                         rel = heap_openrv(stmt->relation, AccessExclusiveLock);
2378
2379                         cxt.stmtType = "ALTER TABLE";
2380                         cxt.relation = stmt->relation;
2381                         cxt.inhRelations = NIL;
2382                         cxt.relOid = RelationGetRelid(rel);
2383                         cxt.hasoids = SearchSysCacheExists(ATTNUM,
2384                                                                                         ObjectIdGetDatum(cxt.relOid),
2385                                                                   Int16GetDatum(ObjectIdAttributeNumber),
2386                                                                                            0, 0);
2387                         cxt.columns = NIL;
2388                         cxt.ckconstraints = NIL;
2389                         cxt.fkconstraints = NIL;
2390                         cxt.ixconstraints = NIL;
2391                         cxt.blist = NIL;
2392                         cxt.alist = NIL;
2393                         cxt.pkey = NULL;
2394
2395                         if (IsA(stmt->def, Constraint))
2396                                 transformTableConstraint(pstate, &cxt,
2397                                                                                  (Constraint *) stmt->def);
2398                         else if (IsA(stmt->def, FkConstraint))
2399                                 cxt.fkconstraints = lappend(cxt.fkconstraints, stmt->def);
2400                         else
2401                                 elog(ERROR, "Unexpected node type in ALTER TABLE ADD CONSTRAINT");
2402
2403                         transformIndexConstraints(pstate, &cxt);
2404                         transformFKConstraints(pstate, &cxt, true);
2405
2406                         Assert(cxt.columns == NIL);
2407                         /* fkconstraints should be put into my own stmt in this case */
2408                         stmt->def = (Node *) nconc(cxt.ckconstraints, cxt.fkconstraints);
2409                         *extras_before = nconc(*extras_before, cxt.blist);
2410                         *extras_after = nconc(cxt.alist, *extras_after);
2411
2412                         heap_close(rel, NoLock); /* close rel, keep lock */
2413                         break;
2414
2415                 case 'c':
2416
2417                         /*
2418                          * Already-transformed ADD CONSTRAINT, so just make it look
2419                          * like the standard case.
2420                          */
2421                         stmt->subtype = 'C';
2422                         break;
2423
2424                 default:
2425                         break;
2426         }
2427
2428         qry = makeNode(Query);
2429         qry->commandType = CMD_UTILITY;
2430         qry->utilityStmt = (Node *) stmt;
2431
2432         return qry;
2433 }
2434
2435 static Query *
2436 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2437 {
2438         Query      *result = makeNode(Query);
2439         List       *extras_before = NIL,
2440                            *extras_after = NIL;
2441
2442         result->commandType = CMD_UTILITY;
2443         result->utilityStmt = (Node *) stmt;
2444
2445         /*
2446          * Don't allow both SCROLL and NO SCROLL to be specified
2447          */
2448         if ((stmt->options & CURSOR_OPT_SCROLL) &&
2449                 (stmt->options & CURSOR_OPT_NO_SCROLL))
2450                 elog(ERROR, "Cannot specify both SCROLL and NO SCROLL");
2451
2452         stmt->query = (Node *) transformStmt(pstate, stmt->query,
2453                                                                                  &extras_before, &extras_after);
2454
2455         /* Shouldn't get any extras, since grammar only allows SelectStmt */
2456         if (extras_before || extras_after)
2457                 elog(ERROR, "transformDeclareCursorStmt: internal error");
2458
2459         return result;
2460 }
2461
2462
2463 static Query *
2464 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
2465 {
2466         Query      *result = makeNode(Query);
2467         List       *argtype_oids = NIL;         /* argtype OIDs in a list */
2468         Oid                *argtoids = NULL;            /* and as an array */
2469         int                     nargs;
2470         List       *queries;
2471
2472         result->commandType = CMD_UTILITY;
2473         result->utilityStmt = (Node *) stmt;
2474
2475         /* Transform list of TypeNames to list (and array) of type OIDs */
2476         nargs = length(stmt->argtypes);
2477
2478         if (nargs)
2479         {
2480                 List       *l;
2481                 int                     i = 0;
2482
2483                 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
2484
2485                 foreach(l, stmt->argtypes)
2486                 {
2487                         TypeName   *tn = lfirst(l);
2488                         Oid                     toid = typenameTypeId(tn);
2489
2490                         argtype_oids = lappendo(argtype_oids, toid);
2491                         argtoids[i++] = toid;
2492                 }
2493         }
2494
2495         stmt->argtype_oids = argtype_oids;
2496
2497         /*
2498          * Analyze the statement using these parameter types (any parameters
2499          * passed in from above us will not be visible to it).
2500          */
2501         queries = parse_analyze((Node *) stmt->query, argtoids, nargs);
2502
2503         /*
2504          * Shouldn't get any extra statements, since grammar only allows
2505          * OptimizableStmt
2506          */
2507         if (length(queries) != 1)
2508                 elog(ERROR, "transformPrepareStmt: internal error");
2509
2510         stmt->query = lfirst(queries);
2511
2512         return result;
2513 }
2514
2515 static Query *
2516 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
2517 {
2518         Query      *result = makeNode(Query);
2519         List       *paramtypes;
2520
2521         result->commandType = CMD_UTILITY;
2522         result->utilityStmt = (Node *) stmt;
2523
2524         paramtypes = FetchPreparedStatementParams(stmt->name);
2525
2526         if (stmt->params || paramtypes)
2527         {
2528                 int                     nparams = length(stmt->params);
2529                 int                     nexpected = length(paramtypes);
2530                 List       *l;
2531                 int                     i = 1;
2532
2533                 if (nparams != nexpected)
2534                         elog(ERROR, "Wrong number of parameters, expected %d but got %d",
2535                                  nexpected, nparams);
2536
2537                 foreach(l, stmt->params)
2538                 {
2539                         Node       *expr = lfirst(l);
2540                         Oid                     expected_type_id,
2541                                                 given_type_id;
2542
2543                         expr = transformExpr(pstate, expr);
2544
2545                         /* Cannot contain subselects or aggregates */
2546                         if (pstate->p_hasSubLinks)
2547                                 elog(ERROR, "Cannot use subselects in EXECUTE parameters");
2548                         if (pstate->p_hasAggs)
2549                                 elog(ERROR, "Cannot use aggregates in EXECUTE parameters");
2550
2551                         given_type_id = exprType(expr);
2552                         expected_type_id = lfirsto(paramtypes);
2553
2554                         expr = coerce_to_target_type(pstate, expr, given_type_id,
2555                                                                                  expected_type_id, -1,
2556                                                                                  COERCION_ASSIGNMENT,
2557                                                                                  COERCE_IMPLICIT_CAST);
2558
2559                         if (expr == NULL)
2560                                 elog(ERROR, "Parameter $%d of type %s cannot be coerced into the expected type %s"
2561                                          "\n\tYou will need to rewrite or cast the expression",
2562                                          i,
2563                                          format_type_be(given_type_id),
2564                                          format_type_be(expected_type_id));
2565
2566                         lfirst(l) = expr;
2567
2568                         paramtypes = lnext(paramtypes);
2569                         i++;
2570                 }
2571         }
2572
2573         return result;
2574 }
2575
2576 /* exported so planner can check again after rewriting, query pullup, etc */
2577 void
2578 CheckSelectForUpdate(Query *qry)
2579 {
2580         if (qry->setOperations)
2581                 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
2582         if (qry->distinctClause != NIL)
2583                 elog(ERROR, "SELECT FOR UPDATE is not allowed with DISTINCT clause");
2584         if (qry->groupClause != NIL)
2585                 elog(ERROR, "SELECT FOR UPDATE is not allowed with GROUP BY clause");
2586         if (qry->hasAggs)
2587                 elog(ERROR, "SELECT FOR UPDATE is not allowed with AGGREGATE");
2588 }
2589
2590 static void
2591 transformForUpdate(Query *qry, List *forUpdate)
2592 {
2593         List       *rowMarks = qry->rowMarks;
2594         List       *l;
2595         List       *rt;
2596         Index           i;
2597
2598         CheckSelectForUpdate(qry);
2599
2600         if (lfirst(forUpdate) == NULL)
2601         {
2602                 /* all tables used in query */
2603                 i = 0;
2604                 foreach(rt, qry->rtable)
2605                 {
2606                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2607
2608                         ++i;
2609                         if (rte->rtekind == RTE_SUBQUERY)
2610                         {
2611                                 /* FOR UPDATE of subquery is propagated to subquery's rels */
2612                                 transformForUpdate(rte->subquery, makeList1(NULL));
2613                         }
2614                         else
2615                         {
2616                                 if (!intMember(i, rowMarks))    /* avoid duplicates */
2617                                         rowMarks = lappendi(rowMarks, i);
2618                                 rte->checkForWrite = true;
2619                         }
2620                 }
2621         }
2622         else
2623         {
2624                 /* just the named tables */
2625                 foreach(l, forUpdate)
2626                 {
2627                         char       *relname = strVal(lfirst(l));
2628
2629                         i = 0;
2630                         foreach(rt, qry->rtable)
2631                         {
2632                                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2633
2634                                 ++i;
2635                                 if (strcmp(rte->eref->aliasname, relname) == 0)
2636                                 {
2637                                         if (rte->rtekind == RTE_SUBQUERY)
2638                                         {
2639                                                 /* propagate to subquery */
2640                                                 transformForUpdate(rte->subquery, makeList1(NULL));
2641                                         }
2642                                         else
2643                                         {
2644                                                 if (!intMember(i, rowMarks))    /* avoid duplicates */
2645                                                         rowMarks = lappendi(rowMarks, i);
2646                                                 rte->checkForWrite = true;
2647                                         }
2648                                         break;
2649                                 }
2650                         }
2651                         if (rt == NIL)
2652                                 elog(ERROR, "FOR UPDATE: relation \"%s\" not found in FROM clause",
2653                                          relname);
2654                 }
2655         }
2656
2657         qry->rowMarks = rowMarks;
2658 }
2659
2660
2661 /*
2662  * relationHasPrimaryKey -
2663  *
2664  *      See whether an existing relation has a primary key.
2665  */
2666 static bool
2667 relationHasPrimaryKey(Oid relationOid)
2668 {
2669         bool            result = false;
2670         Relation        rel;
2671         List       *indexoidlist,
2672                            *indexoidscan;
2673
2674         rel = heap_open(relationOid, AccessShareLock);
2675
2676         /*
2677          * Get the list of index OIDs for the table from the relcache, and
2678          * look up each one in the pg_index syscache until we find one marked
2679          * primary key (hopefully there isn't more than one such).
2680          */
2681         indexoidlist = RelationGetIndexList(rel);
2682
2683         foreach(indexoidscan, indexoidlist)
2684         {
2685                 Oid                     indexoid = lfirsto(indexoidscan);
2686                 HeapTuple       indexTuple;
2687
2688                 indexTuple = SearchSysCache(INDEXRELID,
2689                                                                         ObjectIdGetDatum(indexoid),
2690                                                                         0, 0, 0);
2691                 if (!HeapTupleIsValid(indexTuple))
2692                         elog(ERROR, "relationHasPrimaryKey: index %u not found",
2693                                  indexoid);
2694                 result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary;
2695                 ReleaseSysCache(indexTuple);
2696                 if (result)
2697                         break;
2698         }
2699
2700         freeList(indexoidlist);
2701
2702         heap_close(rel, AccessShareLock);
2703
2704         return result;
2705 }
2706
2707 /*
2708  * Preprocess a list of column constraint clauses
2709  * to attach constraint attributes to their primary constraint nodes
2710  * and detect inconsistent/misplaced constraint attributes.
2711  *
2712  * NOTE: currently, attributes are only supported for FOREIGN KEY primary
2713  * constraints, but someday they ought to be supported for other constraints.
2714  */
2715 static void
2716 transformConstraintAttrs(List *constraintList)
2717 {
2718         Node       *lastprimarynode = NULL;
2719         bool            saw_deferrability = false;
2720         bool            saw_initially = false;
2721         List       *clist;
2722
2723         foreach(clist, constraintList)
2724         {
2725                 Node       *node = lfirst(clist);
2726
2727                 if (!IsA(node, Constraint))
2728                 {
2729                         lastprimarynode = node;
2730                         /* reset flags for new primary node */
2731                         saw_deferrability = false;
2732                         saw_initially = false;
2733                 }
2734                 else
2735                 {
2736                         Constraint *con = (Constraint *) node;
2737
2738                         switch (con->contype)
2739                         {
2740                                 case CONSTR_ATTR_DEFERRABLE:
2741                                         if (lastprimarynode == NULL ||
2742                                                 !IsA(lastprimarynode, FkConstraint))
2743                                                 elog(ERROR, "Misplaced DEFERRABLE clause");
2744                                         if (saw_deferrability)
2745                                                 elog(ERROR, "Multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed");
2746                                         saw_deferrability = true;
2747                                         ((FkConstraint *) lastprimarynode)->deferrable = true;
2748                                         break;
2749                                 case CONSTR_ATTR_NOT_DEFERRABLE:
2750                                         if (lastprimarynode == NULL ||
2751                                                 !IsA(lastprimarynode, FkConstraint))
2752                                                 elog(ERROR, "Misplaced NOT DEFERRABLE clause");
2753                                         if (saw_deferrability)
2754                                                 elog(ERROR, "Multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed");
2755                                         saw_deferrability = true;
2756                                         ((FkConstraint *) lastprimarynode)->deferrable = false;
2757                                         if (saw_initially &&
2758                                                 ((FkConstraint *) lastprimarynode)->initdeferred)
2759                                                 elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2760                                         break;
2761                                 case CONSTR_ATTR_DEFERRED:
2762                                         if (lastprimarynode == NULL ||
2763                                                 !IsA(lastprimarynode, FkConstraint))
2764                                                 elog(ERROR, "Misplaced INITIALLY DEFERRED clause");
2765                                         if (saw_initially)
2766                                                 elog(ERROR, "Multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed");
2767                                         saw_initially = true;
2768                                         ((FkConstraint *) lastprimarynode)->initdeferred = true;
2769
2770                                         /*
2771                                          * If only INITIALLY DEFERRED appears, assume
2772                                          * DEFERRABLE
2773                                          */
2774                                         if (!saw_deferrability)
2775                                                 ((FkConstraint *) lastprimarynode)->deferrable = true;
2776                                         else if (!((FkConstraint *) lastprimarynode)->deferrable)
2777                                                 elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2778                                         break;
2779                                 case CONSTR_ATTR_IMMEDIATE:
2780                                         if (lastprimarynode == NULL ||
2781                                                 !IsA(lastprimarynode, FkConstraint))
2782                                                 elog(ERROR, "Misplaced INITIALLY IMMEDIATE clause");
2783                                         if (saw_initially)
2784                                                 elog(ERROR, "Multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed");
2785                                         saw_initially = true;
2786                                         ((FkConstraint *) lastprimarynode)->initdeferred = false;
2787                                         break;
2788                                 default:
2789                                         /* Otherwise it's not an attribute */
2790                                         lastprimarynode = node;
2791                                         /* reset flags for new primary node */
2792                                         saw_deferrability = false;
2793                                         saw_initially = false;
2794                                         break;
2795                         }
2796                 }
2797         }
2798 }
2799
2800 /* Build a FromExpr node */
2801 static FromExpr *
2802 makeFromExpr(List *fromlist, Node *quals)
2803 {
2804         FromExpr   *f = makeNode(FromExpr);
2805
2806         f->fromlist = fromlist;
2807         f->quals = quals;
2808         return f;
2809 }
2810
2811 /*
2812  * Special handling of type definition for a column
2813  */
2814 static void
2815 transformColumnType(ParseState *pstate, ColumnDef *column)
2816 {
2817         TypeName   *typename = column->typename;
2818         Type            ctype = typenameType(typename);
2819
2820         /*
2821          * Is this the name of a complex type? If so, implement it as a set.
2822          *
2823          * XXX this is a hangover from ancient Berkeley code that probably
2824          * doesn't work anymore anyway.
2825          */
2826         if (typeTypeRelid(ctype) != InvalidOid)
2827         {
2828                 /*
2829                  * (Eventually add in here that the set can only contain one
2830                  * element.)
2831                  */
2832                 typename->setof = true;
2833         }
2834
2835         ReleaseSysCache(ctype);
2836 }
2837
2838 /*
2839  * analyzeCreateSchemaStmt -
2840  *        analyzes the "create schema" statement
2841  *
2842  * Split the schema element list into individual commands and place
2843  * them in the result list in an order such that there are no
2844  * forward references (e.g. GRANT to a table created later in the list).
2845  *
2846  * SQL92 also allows constraints to make forward references, so thumb through
2847  * the table columns and move forward references to a posterior alter-table
2848  * command.
2849  *
2850  * The result is a list of parse nodes that still need to be analyzed ---
2851  * but we can't analyze the later commands until we've executed the earlier
2852  * ones, because of possible inter-object references.
2853  *
2854  * Note: Called from commands/command.c
2855  */
2856 List *
2857 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
2858 {
2859         CreateSchemaStmtContext cxt;
2860         List       *result;
2861         List       *elements;
2862
2863         cxt.stmtType = "CREATE SCHEMA";
2864         cxt.schemaname = stmt->schemaname;
2865         cxt.authid = stmt->authid;
2866         cxt.tables = NIL;
2867         cxt.views = NIL;
2868         cxt.grants = NIL;
2869         cxt.fwconstraints = NIL;
2870         cxt.alters = NIL;
2871         cxt.blist = NIL;
2872         cxt.alist = NIL;
2873
2874         /*
2875          * Run through each schema element in the schema element list.
2876          * Separate statements by type, and do preliminary analysis.
2877          */
2878         foreach(elements, stmt->schemaElts)
2879         {
2880                 Node       *element = lfirst(elements);
2881
2882                 switch (nodeTag(element))
2883                 {
2884                         case T_CreateStmt:
2885                                 {
2886                                         CreateStmt *elp = (CreateStmt *) element;
2887
2888                                         if (elp->relation->schemaname == NULL)
2889                                                 elp->relation->schemaname = cxt.schemaname;
2890                                         else if (strcmp(cxt.schemaname, elp->relation->schemaname) != 0)
2891                                                 elog(ERROR, "New table specifies a schema (%s)"
2892                                                          " different from the one being created (%s)",
2893                                                          elp->relation->schemaname, cxt.schemaname);
2894
2895                                         /*
2896                                          * XXX todo: deal with constraints
2897                                          */
2898
2899                                         cxt.tables = lappend(cxt.tables, element);
2900                                 }
2901                                 break;
2902
2903                         case T_ViewStmt:
2904                                 {
2905                                         ViewStmt   *elp = (ViewStmt *) element;
2906
2907                                         if (elp->view->schemaname == NULL)
2908                                                 elp->view->schemaname = cxt.schemaname;
2909                                         else if (strcmp(cxt.schemaname, elp->view->schemaname) != 0)
2910                                                 elog(ERROR, "New view specifies a schema (%s)"
2911                                                          " different from the one being created (%s)",
2912                                                          elp->view->schemaname, cxt.schemaname);
2913
2914                                         /*
2915                                          * XXX todo: deal with references between views
2916                                          */
2917
2918                                         cxt.views = lappend(cxt.views, element);
2919                                 }
2920                                 break;
2921
2922                         case T_GrantStmt:
2923                                 cxt.grants = lappend(cxt.grants, element);
2924                                 break;
2925
2926                         default:
2927                                 elog(ERROR, "parser: unsupported schema node (internal error)");
2928                 }
2929         }
2930
2931         result = NIL;
2932         result = nconc(result, cxt.tables);
2933         result = nconc(result, cxt.views);
2934         result = nconc(result, cxt.grants);
2935
2936         return result;
2937 }
2938
2939 /*
2940  * Traverse a fully-analyzed tree to verify that parameter symbols
2941  * match their types.  We need this because some Params might still
2942  * be UNKNOWN, if there wasn't anything to force their coercion,
2943  * and yet other instances seen later might have gotten coerced.
2944  */
2945 static bool
2946 check_parameter_resolution_walker(Node *node,
2947                                                                   check_parameter_resolution_context *context)
2948 {
2949         if (node == NULL)
2950                 return false;
2951         if (IsA(node, Param))
2952         {
2953                 Param      *param = (Param *) node;
2954
2955                 if (param->paramkind == PARAM_NUM)
2956                 {
2957                         int                     paramno = param->paramid;
2958
2959                         if (paramno <= 0 ||             /* shouldn't happen, but... */
2960                                 paramno > context->numParams)
2961                                 elog(ERROR, "Parameter '$%d' is out of range", paramno);
2962
2963                         if (param->paramtype != context->paramTypes[paramno-1])
2964                                 elog(ERROR, "Could not determine datatype of parameter $%d",
2965                                          paramno);
2966                 }
2967                 return false;
2968         }
2969         if (IsA(node, Query))
2970         {
2971                 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2972                 return query_tree_walker((Query *) node,
2973                                                                  check_parameter_resolution_walker,
2974                                                                  (void *) context, 0);
2975         }
2976         return expression_tree_walker(node, check_parameter_resolution_walker,
2977                                                                   (void *) context);
2978 }