]> granicus.if.org Git - postgresql/blob - src/backend/parser/analyze.c
95b209e4acb2fca56b81c005fc7572ec90ae727a
[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.274 2003/06/15 16:42:07 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
1798         qry->groupClause = transformGroupClause(pstate,
1799                                                                                         stmt->groupClause,
1800                                                                                         qry->targetList,
1801                                                                                         qry->sortClause);
1802
1803         qry->distinctClause = transformDistinctClause(pstate,
1804                                                                                                   stmt->distinctClause,
1805                                                                                                   qry->targetList,
1806                                                                                                   &qry->sortClause);
1807
1808         qry->limitOffset = stmt->limitOffset;
1809         qry->limitCount = stmt->limitCount;
1810
1811         qry->rtable = pstate->p_rtable;
1812         qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
1813
1814         qry->hasSubLinks = pstate->p_hasSubLinks;
1815         qry->hasAggs = pstate->p_hasAggs;
1816         if (pstate->p_hasAggs || qry->groupClause)
1817                 parseCheckAggregates(pstate, qry);
1818
1819         if (stmt->forUpdate != NIL)
1820                 transformForUpdate(qry, stmt->forUpdate);
1821
1822         return qry;
1823 }
1824
1825 /*
1826  * transformSetOperationsStmt -
1827  *        transforms a set-operations tree
1828  *
1829  * A set-operation tree is just a SELECT, but with UNION/INTERSECT/EXCEPT
1830  * structure to it.  We must transform each leaf SELECT and build up a top-
1831  * level Query that contains the leaf SELECTs as subqueries in its rangetable.
1832  * The tree of set operations is converted into the setOperations field of
1833  * the top-level Query.
1834  */
1835 static Query *
1836 transformSetOperationStmt(ParseState *pstate, SelectStmt *stmt)
1837 {
1838         Query      *qry = makeNode(Query);
1839         SelectStmt *leftmostSelect;
1840         int                     leftmostRTI;
1841         Query      *leftmostQuery;
1842         SetOperationStmt *sostmt;
1843         RangeVar   *into;
1844         List       *intoColNames;
1845         List       *sortClause;
1846         Node       *limitOffset;
1847         Node       *limitCount;
1848         List       *forUpdate;
1849         Node       *node;
1850         List       *lefttl,
1851                            *dtlist,
1852                            *targetvars,
1853                            *targetnames,
1854                            *sv_namespace,
1855                            *sv_rtable;
1856         RangeTblEntry *jrte;
1857         RangeTblRef *jrtr;
1858         int                     tllen;
1859
1860         qry->commandType = CMD_SELECT;
1861
1862         /*
1863          * Find leftmost leaf SelectStmt; extract the one-time-only items from
1864          * it and from the top-level node.
1865          */
1866         leftmostSelect = stmt->larg;
1867         while (leftmostSelect && leftmostSelect->op != SETOP_NONE)
1868                 leftmostSelect = leftmostSelect->larg;
1869         Assert(leftmostSelect && IsA(leftmostSelect, SelectStmt) &&
1870                    leftmostSelect->larg == NULL);
1871         into = leftmostSelect->into;
1872         intoColNames = leftmostSelect->intoColNames;
1873
1874         /* clear them to prevent complaints in transformSetOperationTree() */
1875         leftmostSelect->into = NULL;
1876         leftmostSelect->intoColNames = NIL;
1877
1878         /*
1879          * These are not one-time, exactly, but we want to process them here
1880          * and not let transformSetOperationTree() see them --- else it'll
1881          * just recurse right back here!
1882          */
1883         sortClause = stmt->sortClause;
1884         limitOffset = stmt->limitOffset;
1885         limitCount = stmt->limitCount;
1886         forUpdate = stmt->forUpdate;
1887
1888         stmt->sortClause = NIL;
1889         stmt->limitOffset = NULL;
1890         stmt->limitCount = NULL;
1891         stmt->forUpdate = NIL;
1892
1893         /* We don't support forUpdate with set ops at the moment. */
1894         if (forUpdate)
1895                 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
1896
1897         /*
1898          * Recursively transform the components of the tree.
1899          */
1900         sostmt = (SetOperationStmt *) transformSetOperationTree(pstate, stmt);
1901         Assert(sostmt && IsA(sostmt, SetOperationStmt));
1902         qry->setOperations = (Node *) sostmt;
1903
1904         /*
1905          * Re-find leftmost SELECT (now it's a sub-query in rangetable)
1906          */
1907         node = sostmt->larg;
1908         while (node && IsA(node, SetOperationStmt))
1909                 node = ((SetOperationStmt *) node)->larg;
1910         Assert(node && IsA(node, RangeTblRef));
1911         leftmostRTI = ((RangeTblRef *) node)->rtindex;
1912         leftmostQuery = rt_fetch(leftmostRTI, pstate->p_rtable)->subquery;
1913         Assert(leftmostQuery != NULL);
1914
1915         /*
1916          * Generate dummy targetlist for outer query using column names of
1917          * leftmost select and common datatypes of topmost set operation. Also
1918          * make lists of the dummy vars and their names for use in parsing
1919          * ORDER BY.
1920          *
1921          * Note: we use leftmostRTI as the varno of the dummy variables.
1922          * It shouldn't matter too much which RT index they have, as long
1923          * as they have one that corresponds to a real RT entry; else funny
1924          * things may happen when the tree is mashed by rule rewriting.
1925          */
1926         qry->targetList = NIL;
1927         targetvars = NIL;
1928         targetnames = NIL;
1929         lefttl = leftmostQuery->targetList;
1930         foreach(dtlist, sostmt->colTypes)
1931         {
1932                 Oid                     colType = lfirsto(dtlist);
1933                 Resdom     *leftResdom = ((TargetEntry *) lfirst(lefttl))->resdom;
1934                 char       *colName = pstrdup(leftResdom->resname);
1935                 Resdom     *resdom;
1936                 Expr       *expr;
1937
1938                 resdom = makeResdom((AttrNumber) pstate->p_next_resno++,
1939                                                         colType,
1940                                                         -1,
1941                                                         colName,
1942                                                         false);
1943                 expr = (Expr *) makeVar(leftmostRTI,
1944                                                                 leftResdom->resno,
1945                                                                 colType,
1946                                                                 -1,
1947                                                                 0);
1948                 qry->targetList = lappend(qry->targetList,
1949                                                                   makeTargetEntry(resdom, expr));
1950                 targetvars = lappend(targetvars, expr);
1951                 targetnames = lappend(targetnames, makeString(colName));
1952                 lefttl = lnext(lefttl);
1953         }
1954
1955         /*
1956          * Handle SELECT INTO/CREATE TABLE AS.
1957          *
1958          * Any column names from CREATE TABLE AS need to be attached to both
1959          * the top level and the leftmost subquery.  We do not do this earlier
1960          * because we do *not* want the targetnames list to be affected.
1961          */
1962         qry->into = into;
1963         if (intoColNames)
1964         {
1965                 applyColumnNames(qry->targetList, intoColNames);
1966                 applyColumnNames(leftmostQuery->targetList, intoColNames);
1967         }
1968
1969         /*
1970          * As a first step towards supporting sort clauses that are
1971          * expressions using the output columns, generate a namespace entry
1972          * that makes the output columns visible.  A Join RTE node is handy
1973          * for this, since we can easily control the Vars generated upon
1974          * matches.
1975          *
1976          * Note: we don't yet do anything useful with such cases, but at least
1977          * "ORDER BY upper(foo)" will draw the right error message rather than
1978          * "foo not found".
1979          */
1980         jrte = addRangeTableEntryForJoin(NULL,
1981                                                                          targetnames,
1982                                                                          JOIN_INNER,
1983                                                                          targetvars,
1984                                                                          NULL,
1985                                                                          true);
1986         jrtr = makeNode(RangeTblRef);
1987         jrtr->rtindex = 1;                      /* only entry in dummy rtable */
1988
1989         sv_rtable = pstate->p_rtable;
1990         pstate->p_rtable = makeList1(jrte);
1991
1992         sv_namespace = pstate->p_namespace;
1993         pstate->p_namespace = makeList1(jrtr);
1994
1995         /*
1996          * For now, we don't support resjunk sort clauses on the output of a
1997          * setOperation tree --- you can only use the SQL92-spec options of
1998          * selecting an output column by name or number.  Enforce by checking
1999          * that transformSortClause doesn't add any items to tlist.
2000          */
2001         tllen = length(qry->targetList);
2002
2003         qry->sortClause = transformSortClause(pstate,
2004                                                                                   sortClause,
2005                                                                                   qry->targetList);
2006
2007         pstate->p_namespace = sv_namespace;
2008         pstate->p_rtable = sv_rtable;
2009
2010         if (tllen != length(qry->targetList))
2011                 elog(ERROR, "ORDER BY on a UNION/INTERSECT/EXCEPT result must be on one of the result columns");
2012
2013         qry->limitOffset = limitOffset;
2014         qry->limitCount = limitCount;
2015
2016         qry->rtable = pstate->p_rtable;
2017         qry->jointree = makeFromExpr(pstate->p_joinlist, NULL);
2018
2019         qry->hasSubLinks = pstate->p_hasSubLinks;
2020         qry->hasAggs = pstate->p_hasAggs;
2021         if (pstate->p_hasAggs || qry->groupClause)
2022                 parseCheckAggregates(pstate, qry);
2023
2024         if (forUpdate != NIL)
2025                 transformForUpdate(qry, forUpdate);
2026
2027         return qry;
2028 }
2029
2030 /*
2031  * transformSetOperationTree
2032  *              Recursively transform leaves and internal nodes of a set-op tree
2033  */
2034 static Node *
2035 transformSetOperationTree(ParseState *pstate, SelectStmt *stmt)
2036 {
2037         bool            isLeaf;
2038
2039         Assert(stmt && IsA(stmt, SelectStmt));
2040
2041         /*
2042          * Validity-check both leaf and internal SELECTs for disallowed ops.
2043          */
2044         if (stmt->into)
2045                 elog(ERROR, "INTO is only allowed on first SELECT of UNION/INTERSECT/EXCEPT");
2046         /* We don't support forUpdate with set ops at the moment. */
2047         if (stmt->forUpdate)
2048                 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
2049
2050         /*
2051          * If an internal node of a set-op tree has ORDER BY, UPDATE, or LIMIT
2052          * clauses attached, we need to treat it like a leaf node to generate
2053          * an independent sub-Query tree.  Otherwise, it can be represented by
2054          * a SetOperationStmt node underneath the parent Query.
2055          */
2056         if (stmt->op == SETOP_NONE)
2057         {
2058                 Assert(stmt->larg == NULL && stmt->rarg == NULL);
2059                 isLeaf = true;
2060         }
2061         else
2062         {
2063                 Assert(stmt->larg != NULL && stmt->rarg != NULL);
2064                 if (stmt->sortClause || stmt->limitOffset || stmt->limitCount ||
2065                         stmt->forUpdate)
2066                         isLeaf = true;
2067                 else
2068                         isLeaf = false;
2069         }
2070
2071         if (isLeaf)
2072         {
2073                 /* Process leaf SELECT */
2074                 List       *selectList;
2075                 Query      *selectQuery;
2076                 char            selectName[32];
2077                 RangeTblEntry *rte;
2078                 RangeTblRef *rtr;
2079
2080                 /*
2081                  * Transform SelectStmt into a Query.
2082                  *
2083                  * Note: previously transformed sub-queries don't affect the parsing
2084                  * of this sub-query, because they are not in the toplevel
2085                  * pstate's namespace list.
2086                  */
2087                 selectList = parse_sub_analyze((Node *) stmt, pstate);
2088
2089                 Assert(length(selectList) == 1);
2090                 selectQuery = (Query *) lfirst(selectList);
2091                 Assert(IsA(selectQuery, Query));
2092
2093                 /*
2094                  * Check for bogus references to Vars on the current query level
2095                  * (but upper-level references are okay).
2096                  * Normally this can't happen because the namespace will be empty,
2097                  * but it could happen if we are inside a rule.
2098                  */
2099                 if (pstate->p_namespace)
2100                 {
2101                         if (contain_vars_of_level((Node *) selectQuery, 1))
2102                                 elog(ERROR, "UNION/INTERSECT/EXCEPT member statement may not refer to other relations of same query level");
2103                 }
2104
2105                 /*
2106                  * Make the leaf query be a subquery in the top-level rangetable.
2107                  */
2108                 snprintf(selectName, sizeof(selectName), "*SELECT* %d", length(pstate->p_rtable) + 1);
2109                 rte = addRangeTableEntryForSubquery(pstate,
2110                                                                                         selectQuery,
2111                                                                                         makeAlias(selectName, NIL),
2112                                                                                         false);
2113
2114                 /*
2115                  * Return a RangeTblRef to replace the SelectStmt in the set-op
2116                  * tree.
2117                  */
2118                 rtr = makeNode(RangeTblRef);
2119                 /* assume new rte is at end */
2120                 rtr->rtindex = length(pstate->p_rtable);
2121                 Assert(rte == rt_fetch(rtr->rtindex, pstate->p_rtable));
2122                 return (Node *) rtr;
2123         }
2124         else
2125         {
2126                 /* Process an internal node (set operation node) */
2127                 SetOperationStmt *op = makeNode(SetOperationStmt);
2128                 List       *lcoltypes;
2129                 List       *rcoltypes;
2130                 const char *context;
2131
2132                 context = (stmt->op == SETOP_UNION ? "UNION" :
2133                                    (stmt->op == SETOP_INTERSECT ? "INTERSECT" :
2134                                         "EXCEPT"));
2135
2136                 op->op = stmt->op;
2137                 op->all = stmt->all;
2138
2139                 /*
2140                  * Recursively transform the child nodes.
2141                  */
2142                 op->larg = transformSetOperationTree(pstate, stmt->larg);
2143                 op->rarg = transformSetOperationTree(pstate, stmt->rarg);
2144
2145                 /*
2146                  * Verify that the two children have the same number of non-junk
2147                  * columns, and determine the types of the merged output columns.
2148                  */
2149                 lcoltypes = getSetColTypes(pstate, op->larg);
2150                 rcoltypes = getSetColTypes(pstate, op->rarg);
2151                 if (length(lcoltypes) != length(rcoltypes))
2152                         elog(ERROR, "Each %s query must have the same number of columns",
2153                                  context);
2154                 op->colTypes = NIL;
2155                 while (lcoltypes != NIL)
2156                 {
2157                         Oid                     lcoltype = lfirsto(lcoltypes);
2158                         Oid                     rcoltype = lfirsto(rcoltypes);
2159                         Oid                     rescoltype;
2160
2161                         rescoltype = select_common_type(makeListo2(lcoltype, rcoltype),
2162                                                                                         context);
2163                         op->colTypes = lappendo(op->colTypes, rescoltype);
2164                         lcoltypes = lnext(lcoltypes);
2165                         rcoltypes = lnext(rcoltypes);
2166                 }
2167
2168                 return (Node *) op;
2169         }
2170 }
2171
2172 /*
2173  * getSetColTypes
2174  *              Get output column types of an (already transformed) set-op node
2175  */
2176 static List *
2177 getSetColTypes(ParseState *pstate, Node *node)
2178 {
2179         if (IsA(node, RangeTblRef))
2180         {
2181                 RangeTblRef *rtr = (RangeTblRef *) node;
2182                 RangeTblEntry *rte = rt_fetch(rtr->rtindex, pstate->p_rtable);
2183                 Query      *selectQuery = rte->subquery;
2184                 List       *result = NIL;
2185                 List       *tl;
2186
2187                 Assert(selectQuery != NULL);
2188                 /* Get types of non-junk columns */
2189                 foreach(tl, selectQuery->targetList)
2190                 {
2191                         TargetEntry *tle = (TargetEntry *) lfirst(tl);
2192                         Resdom     *resnode = tle->resdom;
2193
2194                         if (resnode->resjunk)
2195                                 continue;
2196                         result = lappendo(result, resnode->restype);
2197                 }
2198                 return result;
2199         }
2200         else if (IsA(node, SetOperationStmt))
2201         {
2202                 SetOperationStmt *op = (SetOperationStmt *) node;
2203
2204                 /* Result already computed during transformation of node */
2205                 Assert(op->colTypes != NIL);
2206                 return op->colTypes;
2207         }
2208         else
2209         {
2210                 elog(ERROR, "getSetColTypes: unexpected node %d",
2211                          (int) nodeTag(node));
2212                 return NIL;                             /* keep compiler quiet */
2213         }
2214 }
2215
2216 /* Attach column names from a ColumnDef list to a TargetEntry list */
2217 static void
2218 applyColumnNames(List *dst, List *src)
2219 {
2220         if (length(src) > length(dst))
2221                 elog(ERROR, "CREATE TABLE AS specifies too many column names");
2222
2223         while (src != NIL && dst != NIL)
2224         {
2225                 TargetEntry *d = (TargetEntry *) lfirst(dst);
2226                 ColumnDef  *s = (ColumnDef *) lfirst(src);
2227
2228                 Assert(d->resdom && !d->resdom->resjunk);
2229
2230                 d->resdom->resname = pstrdup(s->colname);
2231
2232                 dst = lnext(dst);
2233                 src = lnext(src);
2234         }
2235 }
2236
2237
2238 /*
2239  * transformUpdateStmt -
2240  *        transforms an update statement
2241  */
2242 static Query *
2243 transformUpdateStmt(ParseState *pstate, UpdateStmt *stmt)
2244 {
2245         Query      *qry = makeNode(Query);
2246         Node       *qual;
2247         List       *origTargetList;
2248         List       *tl;
2249
2250         qry->commandType = CMD_UPDATE;
2251         pstate->p_is_update = true;
2252
2253         qry->resultRelation = setTargetTable(pstate, stmt->relation,
2254                                                           interpretInhOption(stmt->relation->inhOpt),
2255                                                                                  true);
2256
2257         /*
2258          * the FROM clause is non-standard SQL syntax. We used to be able to
2259          * do this with REPLACE in POSTQUEL so we keep the feature.
2260          */
2261         transformFromClause(pstate, stmt->fromClause);
2262
2263         qry->targetList = transformTargetList(pstate, stmt->targetList);
2264
2265         qual = transformWhereClause(pstate, stmt->whereClause);
2266
2267         qry->rtable = pstate->p_rtable;
2268         qry->jointree = makeFromExpr(pstate->p_joinlist, qual);
2269
2270         qry->hasSubLinks = pstate->p_hasSubLinks;
2271         qry->hasAggs = pstate->p_hasAggs;
2272         if (pstate->p_hasAggs)
2273                 parseCheckAggregates(pstate, qry);
2274
2275         /*
2276          * Now we are done with SELECT-like processing, and can get on with
2277          * transforming the target list to match the UPDATE target columns.
2278          */
2279
2280         /* Prepare to assign non-conflicting resnos to resjunk attributes */
2281         if (pstate->p_next_resno <= pstate->p_target_relation->rd_rel->relnatts)
2282                 pstate->p_next_resno = pstate->p_target_relation->rd_rel->relnatts + 1;
2283
2284         /* Prepare non-junk columns for assignment to target table */
2285         origTargetList = stmt->targetList;
2286         foreach(tl, qry->targetList)
2287         {
2288                 TargetEntry *tle = (TargetEntry *) lfirst(tl);
2289                 Resdom     *resnode = tle->resdom;
2290                 ResTarget  *origTarget;
2291
2292                 if (resnode->resjunk)
2293                 {
2294                         /*
2295                          * Resjunk nodes need no additional processing, but be sure
2296                          * they have names and resnos that do not match any target
2297                          * columns; else rewriter or planner might get confused.
2298                          */
2299                         resnode->resname = "?resjunk?";
2300                         resnode->resno = (AttrNumber) pstate->p_next_resno++;
2301                         continue;
2302                 }
2303                 if (origTargetList == NIL)
2304                         elog(ERROR, "UPDATE target count mismatch --- internal error");
2305                 origTarget = (ResTarget *) lfirst(origTargetList);
2306                 updateTargetListEntry(pstate, tle, origTarget->name,
2307                                                           attnameAttNum(pstate->p_target_relation,
2308                                                                                         origTarget->name, true),
2309                                                           origTarget->indirection);
2310                 origTargetList = lnext(origTargetList);
2311         }
2312         if (origTargetList != NIL)
2313                 elog(ERROR, "UPDATE target count mismatch --- internal error");
2314
2315         return qry;
2316 }
2317
2318 /*
2319  * tranformAlterTableStmt -
2320  *      transform an Alter Table Statement
2321  */
2322 static Query *
2323 transformAlterTableStmt(ParseState *pstate, AlterTableStmt *stmt,
2324                                                 List **extras_before, List **extras_after)
2325 {
2326         Relation        rel;
2327         CreateStmtContext cxt;
2328         Query      *qry;
2329
2330         /*
2331          * The only subtypes that currently require parse transformation
2332          * handling are 'A'dd column and Add 'C'onstraint.      These largely
2333          * re-use code from CREATE TABLE.
2334          *
2335          * If we need to do any parse transformation, get exclusive lock on
2336          * the relation to make sure it won't change before we execute the
2337          * command.
2338          */
2339         switch (stmt->subtype)
2340         {
2341                 case 'A':
2342                         rel = heap_openrv(stmt->relation, AccessExclusiveLock);
2343
2344                         cxt.stmtType = "ALTER TABLE";
2345                         cxt.relation = stmt->relation;
2346                         cxt.inhRelations = NIL;
2347                         cxt.relOid = RelationGetRelid(rel);
2348                         cxt.hasoids = SearchSysCacheExists(ATTNUM,
2349                                                                                         ObjectIdGetDatum(cxt.relOid),
2350                                                                   Int16GetDatum(ObjectIdAttributeNumber),
2351                                                                                            0, 0);
2352                         cxt.columns = NIL;
2353                         cxt.ckconstraints = NIL;
2354                         cxt.fkconstraints = NIL;
2355                         cxt.ixconstraints = NIL;
2356                         cxt.blist = NIL;
2357                         cxt.alist = NIL;
2358                         cxt.pkey = NULL;
2359
2360                         Assert(IsA(stmt->def, ColumnDef));
2361                         transformColumnDefinition(pstate, &cxt,
2362                                                                           (ColumnDef *) stmt->def);
2363
2364                         transformIndexConstraints(pstate, &cxt);
2365                         transformFKConstraints(pstate, &cxt, false);
2366
2367                         ((ColumnDef *) stmt->def)->constraints = cxt.ckconstraints;
2368                         *extras_before = nconc(*extras_before, cxt.blist);
2369                         *extras_after = nconc(cxt.alist, *extras_after);
2370
2371                         heap_close(rel, NoLock); /* close rel, keep lock */
2372                         break;
2373
2374                 case 'C':
2375                         rel = heap_openrv(stmt->relation, AccessExclusiveLock);
2376
2377                         cxt.stmtType = "ALTER TABLE";
2378                         cxt.relation = stmt->relation;
2379                         cxt.inhRelations = NIL;
2380                         cxt.relOid = RelationGetRelid(rel);
2381                         cxt.hasoids = SearchSysCacheExists(ATTNUM,
2382                                                                                         ObjectIdGetDatum(cxt.relOid),
2383                                                                   Int16GetDatum(ObjectIdAttributeNumber),
2384                                                                                            0, 0);
2385                         cxt.columns = NIL;
2386                         cxt.ckconstraints = NIL;
2387                         cxt.fkconstraints = NIL;
2388                         cxt.ixconstraints = NIL;
2389                         cxt.blist = NIL;
2390                         cxt.alist = NIL;
2391                         cxt.pkey = NULL;
2392
2393                         if (IsA(stmt->def, Constraint))
2394                                 transformTableConstraint(pstate, &cxt,
2395                                                                                  (Constraint *) stmt->def);
2396                         else if (IsA(stmt->def, FkConstraint))
2397                                 cxt.fkconstraints = lappend(cxt.fkconstraints, stmt->def);
2398                         else
2399                                 elog(ERROR, "Unexpected node type in ALTER TABLE ADD CONSTRAINT");
2400
2401                         transformIndexConstraints(pstate, &cxt);
2402                         transformFKConstraints(pstate, &cxt, true);
2403
2404                         Assert(cxt.columns == NIL);
2405                         /* fkconstraints should be put into my own stmt in this case */
2406                         stmt->def = (Node *) nconc(cxt.ckconstraints, cxt.fkconstraints);
2407                         *extras_before = nconc(*extras_before, cxt.blist);
2408                         *extras_after = nconc(cxt.alist, *extras_after);
2409
2410                         heap_close(rel, NoLock); /* close rel, keep lock */
2411                         break;
2412
2413                 case 'c':
2414
2415                         /*
2416                          * Already-transformed ADD CONSTRAINT, so just make it look
2417                          * like the standard case.
2418                          */
2419                         stmt->subtype = 'C';
2420                         break;
2421
2422                 default:
2423                         break;
2424         }
2425
2426         qry = makeNode(Query);
2427         qry->commandType = CMD_UTILITY;
2428         qry->utilityStmt = (Node *) stmt;
2429
2430         return qry;
2431 }
2432
2433 static Query *
2434 transformDeclareCursorStmt(ParseState *pstate, DeclareCursorStmt *stmt)
2435 {
2436         Query      *result = makeNode(Query);
2437         List       *extras_before = NIL,
2438                            *extras_after = NIL;
2439
2440         result->commandType = CMD_UTILITY;
2441         result->utilityStmt = (Node *) stmt;
2442
2443         /*
2444          * Don't allow both SCROLL and NO SCROLL to be specified
2445          */
2446         if ((stmt->options & CURSOR_OPT_SCROLL) &&
2447                 (stmt->options & CURSOR_OPT_NO_SCROLL))
2448                 elog(ERROR, "Cannot specify both SCROLL and NO SCROLL");
2449
2450         stmt->query = (Node *) transformStmt(pstate, stmt->query,
2451                                                                                  &extras_before, &extras_after);
2452
2453         /* Shouldn't get any extras, since grammar only allows SelectStmt */
2454         if (extras_before || extras_after)
2455                 elog(ERROR, "transformDeclareCursorStmt: internal error");
2456
2457         return result;
2458 }
2459
2460
2461 static Query *
2462 transformPrepareStmt(ParseState *pstate, PrepareStmt *stmt)
2463 {
2464         Query      *result = makeNode(Query);
2465         List       *argtype_oids = NIL;         /* argtype OIDs in a list */
2466         Oid                *argtoids = NULL;            /* and as an array */
2467         int                     nargs;
2468         List       *queries;
2469
2470         result->commandType = CMD_UTILITY;
2471         result->utilityStmt = (Node *) stmt;
2472
2473         /* Transform list of TypeNames to list (and array) of type OIDs */
2474         nargs = length(stmt->argtypes);
2475
2476         if (nargs)
2477         {
2478                 List       *l;
2479                 int                     i = 0;
2480
2481                 argtoids = (Oid *) palloc(nargs * sizeof(Oid));
2482
2483                 foreach(l, stmt->argtypes)
2484                 {
2485                         TypeName   *tn = lfirst(l);
2486                         Oid                     toid = typenameTypeId(tn);
2487
2488                         argtype_oids = lappendo(argtype_oids, toid);
2489                         argtoids[i++] = toid;
2490                 }
2491         }
2492
2493         stmt->argtype_oids = argtype_oids;
2494
2495         /*
2496          * Analyze the statement using these parameter types (any parameters
2497          * passed in from above us will not be visible to it).
2498          */
2499         queries = parse_analyze((Node *) stmt->query, argtoids, nargs);
2500
2501         /*
2502          * Shouldn't get any extra statements, since grammar only allows
2503          * OptimizableStmt
2504          */
2505         if (length(queries) != 1)
2506                 elog(ERROR, "transformPrepareStmt: internal error");
2507
2508         stmt->query = lfirst(queries);
2509
2510         return result;
2511 }
2512
2513 static Query *
2514 transformExecuteStmt(ParseState *pstate, ExecuteStmt *stmt)
2515 {
2516         Query      *result = makeNode(Query);
2517         List       *paramtypes;
2518
2519         result->commandType = CMD_UTILITY;
2520         result->utilityStmt = (Node *) stmt;
2521
2522         paramtypes = FetchPreparedStatementParams(stmt->name);
2523
2524         if (stmt->params || paramtypes)
2525         {
2526                 int                     nparams = length(stmt->params);
2527                 int                     nexpected = length(paramtypes);
2528                 List       *l;
2529                 int                     i = 1;
2530
2531                 if (nparams != nexpected)
2532                         elog(ERROR, "Wrong number of parameters, expected %d but got %d",
2533                                  nexpected, nparams);
2534
2535                 foreach(l, stmt->params)
2536                 {
2537                         Node       *expr = lfirst(l);
2538                         Oid                     expected_type_id,
2539                                                 given_type_id;
2540
2541                         expr = transformExpr(pstate, expr);
2542
2543                         /* Cannot contain subselects or aggregates */
2544                         if (pstate->p_hasSubLinks)
2545                                 elog(ERROR, "Cannot use subselects in EXECUTE parameters");
2546                         if (pstate->p_hasAggs)
2547                                 elog(ERROR, "Cannot use aggregates in EXECUTE parameters");
2548
2549                         given_type_id = exprType(expr);
2550                         expected_type_id = lfirsto(paramtypes);
2551
2552                         expr = coerce_to_target_type(pstate, expr, given_type_id,
2553                                                                                  expected_type_id, -1,
2554                                                                                  COERCION_ASSIGNMENT,
2555                                                                                  COERCE_IMPLICIT_CAST);
2556
2557                         if (expr == NULL)
2558                                 elog(ERROR, "Parameter $%d of type %s cannot be coerced into the expected type %s"
2559                                          "\n\tYou will need to rewrite or cast the expression",
2560                                          i,
2561                                          format_type_be(given_type_id),
2562                                          format_type_be(expected_type_id));
2563
2564                         lfirst(l) = expr;
2565
2566                         paramtypes = lnext(paramtypes);
2567                         i++;
2568                 }
2569         }
2570
2571         return result;
2572 }
2573
2574 /* exported so planner can check again after rewriting, query pullup, etc */
2575 void
2576 CheckSelectForUpdate(Query *qry)
2577 {
2578         if (qry->setOperations)
2579                 elog(ERROR, "SELECT FOR UPDATE is not allowed with UNION/INTERSECT/EXCEPT");
2580         if (qry->distinctClause != NIL)
2581                 elog(ERROR, "SELECT FOR UPDATE is not allowed with DISTINCT clause");
2582         if (qry->groupClause != NIL)
2583                 elog(ERROR, "SELECT FOR UPDATE is not allowed with GROUP BY clause");
2584         if (qry->hasAggs)
2585                 elog(ERROR, "SELECT FOR UPDATE is not allowed with AGGREGATE");
2586 }
2587
2588 static void
2589 transformForUpdate(Query *qry, List *forUpdate)
2590 {
2591         List       *rowMarks = qry->rowMarks;
2592         List       *l;
2593         List       *rt;
2594         Index           i;
2595
2596         CheckSelectForUpdate(qry);
2597
2598         if (lfirst(forUpdate) == NULL)
2599         {
2600                 /* all tables used in query */
2601                 i = 0;
2602                 foreach(rt, qry->rtable)
2603                 {
2604                         RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2605
2606                         ++i;
2607                         if (rte->rtekind == RTE_SUBQUERY)
2608                         {
2609                                 /* FOR UPDATE of subquery is propagated to subquery's rels */
2610                                 transformForUpdate(rte->subquery, makeList1(NULL));
2611                         }
2612                         else
2613                         {
2614                                 if (!intMember(i, rowMarks))    /* avoid duplicates */
2615                                         rowMarks = lappendi(rowMarks, i);
2616                                 rte->checkForWrite = true;
2617                         }
2618                 }
2619         }
2620         else
2621         {
2622                 /* just the named tables */
2623                 foreach(l, forUpdate)
2624                 {
2625                         char       *relname = strVal(lfirst(l));
2626
2627                         i = 0;
2628                         foreach(rt, qry->rtable)
2629                         {
2630                                 RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt);
2631
2632                                 ++i;
2633                                 if (strcmp(rte->eref->aliasname, relname) == 0)
2634                                 {
2635                                         if (rte->rtekind == RTE_SUBQUERY)
2636                                         {
2637                                                 /* propagate to subquery */
2638                                                 transformForUpdate(rte->subquery, makeList1(NULL));
2639                                         }
2640                                         else
2641                                         {
2642                                                 if (!intMember(i, rowMarks))    /* avoid duplicates */
2643                                                         rowMarks = lappendi(rowMarks, i);
2644                                                 rte->checkForWrite = true;
2645                                         }
2646                                         break;
2647                                 }
2648                         }
2649                         if (rt == NIL)
2650                                 elog(ERROR, "FOR UPDATE: relation \"%s\" not found in FROM clause",
2651                                          relname);
2652                 }
2653         }
2654
2655         qry->rowMarks = rowMarks;
2656 }
2657
2658
2659 /*
2660  * relationHasPrimaryKey -
2661  *
2662  *      See whether an existing relation has a primary key.
2663  */
2664 static bool
2665 relationHasPrimaryKey(Oid relationOid)
2666 {
2667         bool            result = false;
2668         Relation        rel;
2669         List       *indexoidlist,
2670                            *indexoidscan;
2671
2672         rel = heap_open(relationOid, AccessShareLock);
2673
2674         /*
2675          * Get the list of index OIDs for the table from the relcache, and
2676          * look up each one in the pg_index syscache until we find one marked
2677          * primary key (hopefully there isn't more than one such).
2678          */
2679         indexoidlist = RelationGetIndexList(rel);
2680
2681         foreach(indexoidscan, indexoidlist)
2682         {
2683                 Oid                     indexoid = lfirsto(indexoidscan);
2684                 HeapTuple       indexTuple;
2685
2686                 indexTuple = SearchSysCache(INDEXRELID,
2687                                                                         ObjectIdGetDatum(indexoid),
2688                                                                         0, 0, 0);
2689                 if (!HeapTupleIsValid(indexTuple))
2690                         elog(ERROR, "relationHasPrimaryKey: index %u not found",
2691                                  indexoid);
2692                 result = ((Form_pg_index) GETSTRUCT(indexTuple))->indisprimary;
2693                 ReleaseSysCache(indexTuple);
2694                 if (result)
2695                         break;
2696         }
2697
2698         freeList(indexoidlist);
2699
2700         heap_close(rel, AccessShareLock);
2701
2702         return result;
2703 }
2704
2705 /*
2706  * Preprocess a list of column constraint clauses
2707  * to attach constraint attributes to their primary constraint nodes
2708  * and detect inconsistent/misplaced constraint attributes.
2709  *
2710  * NOTE: currently, attributes are only supported for FOREIGN KEY primary
2711  * constraints, but someday they ought to be supported for other constraints.
2712  */
2713 static void
2714 transformConstraintAttrs(List *constraintList)
2715 {
2716         Node       *lastprimarynode = NULL;
2717         bool            saw_deferrability = false;
2718         bool            saw_initially = false;
2719         List       *clist;
2720
2721         foreach(clist, constraintList)
2722         {
2723                 Node       *node = lfirst(clist);
2724
2725                 if (!IsA(node, Constraint))
2726                 {
2727                         lastprimarynode = node;
2728                         /* reset flags for new primary node */
2729                         saw_deferrability = false;
2730                         saw_initially = false;
2731                 }
2732                 else
2733                 {
2734                         Constraint *con = (Constraint *) node;
2735
2736                         switch (con->contype)
2737                         {
2738                                 case CONSTR_ATTR_DEFERRABLE:
2739                                         if (lastprimarynode == NULL ||
2740                                                 !IsA(lastprimarynode, FkConstraint))
2741                                                 elog(ERROR, "Misplaced DEFERRABLE clause");
2742                                         if (saw_deferrability)
2743                                                 elog(ERROR, "Multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed");
2744                                         saw_deferrability = true;
2745                                         ((FkConstraint *) lastprimarynode)->deferrable = true;
2746                                         break;
2747                                 case CONSTR_ATTR_NOT_DEFERRABLE:
2748                                         if (lastprimarynode == NULL ||
2749                                                 !IsA(lastprimarynode, FkConstraint))
2750                                                 elog(ERROR, "Misplaced NOT DEFERRABLE clause");
2751                                         if (saw_deferrability)
2752                                                 elog(ERROR, "Multiple DEFERRABLE/NOT DEFERRABLE clauses not allowed");
2753                                         saw_deferrability = true;
2754                                         ((FkConstraint *) lastprimarynode)->deferrable = false;
2755                                         if (saw_initially &&
2756                                                 ((FkConstraint *) lastprimarynode)->initdeferred)
2757                                                 elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2758                                         break;
2759                                 case CONSTR_ATTR_DEFERRED:
2760                                         if (lastprimarynode == NULL ||
2761                                                 !IsA(lastprimarynode, FkConstraint))
2762                                                 elog(ERROR, "Misplaced INITIALLY DEFERRED clause");
2763                                         if (saw_initially)
2764                                                 elog(ERROR, "Multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed");
2765                                         saw_initially = true;
2766                                         ((FkConstraint *) lastprimarynode)->initdeferred = true;
2767
2768                                         /*
2769                                          * If only INITIALLY DEFERRED appears, assume
2770                                          * DEFERRABLE
2771                                          */
2772                                         if (!saw_deferrability)
2773                                                 ((FkConstraint *) lastprimarynode)->deferrable = true;
2774                                         else if (!((FkConstraint *) lastprimarynode)->deferrable)
2775                                                 elog(ERROR, "INITIALLY DEFERRED constraint must be DEFERRABLE");
2776                                         break;
2777                                 case CONSTR_ATTR_IMMEDIATE:
2778                                         if (lastprimarynode == NULL ||
2779                                                 !IsA(lastprimarynode, FkConstraint))
2780                                                 elog(ERROR, "Misplaced INITIALLY IMMEDIATE clause");
2781                                         if (saw_initially)
2782                                                 elog(ERROR, "Multiple INITIALLY IMMEDIATE/DEFERRED clauses not allowed");
2783                                         saw_initially = true;
2784                                         ((FkConstraint *) lastprimarynode)->initdeferred = false;
2785                                         break;
2786                                 default:
2787                                         /* Otherwise it's not an attribute */
2788                                         lastprimarynode = node;
2789                                         /* reset flags for new primary node */
2790                                         saw_deferrability = false;
2791                                         saw_initially = false;
2792                                         break;
2793                         }
2794                 }
2795         }
2796 }
2797
2798 /* Build a FromExpr node */
2799 static FromExpr *
2800 makeFromExpr(List *fromlist, Node *quals)
2801 {
2802         FromExpr   *f = makeNode(FromExpr);
2803
2804         f->fromlist = fromlist;
2805         f->quals = quals;
2806         return f;
2807 }
2808
2809 /*
2810  * Special handling of type definition for a column
2811  */
2812 static void
2813 transformColumnType(ParseState *pstate, ColumnDef *column)
2814 {
2815         TypeName   *typename = column->typename;
2816         Type            ctype = typenameType(typename);
2817
2818         /*
2819          * Is this the name of a complex type? If so, implement it as a set.
2820          *
2821          * XXX this is a hangover from ancient Berkeley code that probably
2822          * doesn't work anymore anyway.
2823          */
2824         if (typeTypeRelid(ctype) != InvalidOid)
2825         {
2826                 /*
2827                  * (Eventually add in here that the set can only contain one
2828                  * element.)
2829                  */
2830                 typename->setof = true;
2831         }
2832
2833         ReleaseSysCache(ctype);
2834 }
2835
2836 /*
2837  * analyzeCreateSchemaStmt -
2838  *        analyzes the "create schema" statement
2839  *
2840  * Split the schema element list into individual commands and place
2841  * them in the result list in an order such that there are no
2842  * forward references (e.g. GRANT to a table created later in the list).
2843  *
2844  * SQL92 also allows constraints to make forward references, so thumb through
2845  * the table columns and move forward references to a posterior alter-table
2846  * command.
2847  *
2848  * The result is a list of parse nodes that still need to be analyzed ---
2849  * but we can't analyze the later commands until we've executed the earlier
2850  * ones, because of possible inter-object references.
2851  *
2852  * Note: Called from commands/command.c
2853  */
2854 List *
2855 analyzeCreateSchemaStmt(CreateSchemaStmt *stmt)
2856 {
2857         CreateSchemaStmtContext cxt;
2858         List       *result;
2859         List       *elements;
2860
2861         cxt.stmtType = "CREATE SCHEMA";
2862         cxt.schemaname = stmt->schemaname;
2863         cxt.authid = stmt->authid;
2864         cxt.tables = NIL;
2865         cxt.views = NIL;
2866         cxt.grants = NIL;
2867         cxt.fwconstraints = NIL;
2868         cxt.alters = NIL;
2869         cxt.blist = NIL;
2870         cxt.alist = NIL;
2871
2872         /*
2873          * Run through each schema element in the schema element list.
2874          * Separate statements by type, and do preliminary analysis.
2875          */
2876         foreach(elements, stmt->schemaElts)
2877         {
2878                 Node       *element = lfirst(elements);
2879
2880                 switch (nodeTag(element))
2881                 {
2882                         case T_CreateStmt:
2883                                 {
2884                                         CreateStmt *elp = (CreateStmt *) element;
2885
2886                                         if (elp->relation->schemaname == NULL)
2887                                                 elp->relation->schemaname = cxt.schemaname;
2888                                         else if (strcmp(cxt.schemaname, elp->relation->schemaname) != 0)
2889                                                 elog(ERROR, "New table specifies a schema (%s)"
2890                                                          " different from the one being created (%s)",
2891                                                          elp->relation->schemaname, cxt.schemaname);
2892
2893                                         /*
2894                                          * XXX todo: deal with constraints
2895                                          */
2896
2897                                         cxt.tables = lappend(cxt.tables, element);
2898                                 }
2899                                 break;
2900
2901                         case T_ViewStmt:
2902                                 {
2903                                         ViewStmt   *elp = (ViewStmt *) element;
2904
2905                                         if (elp->view->schemaname == NULL)
2906                                                 elp->view->schemaname = cxt.schemaname;
2907                                         else if (strcmp(cxt.schemaname, elp->view->schemaname) != 0)
2908                                                 elog(ERROR, "New view specifies a schema (%s)"
2909                                                          " different from the one being created (%s)",
2910                                                          elp->view->schemaname, cxt.schemaname);
2911
2912                                         /*
2913                                          * XXX todo: deal with references between views
2914                                          */
2915
2916                                         cxt.views = lappend(cxt.views, element);
2917                                 }
2918                                 break;
2919
2920                         case T_GrantStmt:
2921                                 cxt.grants = lappend(cxt.grants, element);
2922                                 break;
2923
2924                         default:
2925                                 elog(ERROR, "parser: unsupported schema node (internal error)");
2926                 }
2927         }
2928
2929         result = NIL;
2930         result = nconc(result, cxt.tables);
2931         result = nconc(result, cxt.views);
2932         result = nconc(result, cxt.grants);
2933
2934         return result;
2935 }
2936
2937 /*
2938  * Traverse a fully-analyzed tree to verify that parameter symbols
2939  * match their types.  We need this because some Params might still
2940  * be UNKNOWN, if there wasn't anything to force their coercion,
2941  * and yet other instances seen later might have gotten coerced.
2942  */
2943 static bool
2944 check_parameter_resolution_walker(Node *node,
2945                                                                   check_parameter_resolution_context *context)
2946 {
2947         if (node == NULL)
2948                 return false;
2949         if (IsA(node, Param))
2950         {
2951                 Param      *param = (Param *) node;
2952
2953                 if (param->paramkind == PARAM_NUM)
2954                 {
2955                         int                     paramno = param->paramid;
2956
2957                         if (paramno <= 0 ||             /* shouldn't happen, but... */
2958                                 paramno > context->numParams)
2959                                 elog(ERROR, "Parameter '$%d' is out of range", paramno);
2960
2961                         if (param->paramtype != context->paramTypes[paramno-1])
2962                                 elog(ERROR, "Could not determine datatype of parameter $%d",
2963                                          paramno);
2964                 }
2965                 return false;
2966         }
2967         if (IsA(node, Query))
2968         {
2969                 /* Recurse into RTE subquery or not-yet-planned sublink subquery */
2970                 return query_tree_walker((Query *) node,
2971                                                                  check_parameter_resolution_walker,
2972                                                                  (void *) context, 0);
2973         }
2974         return expression_tree_walker(node, check_parameter_resolution_walker,
2975                                                                   (void *) context);
2976 }